repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
pyQode/pyqode.core
pyqode/core/managers/file.py
FileManager.get_mimetype
def get_mimetype(path): """ Guesses the mime type of a file. If mime type cannot be detected, plain text is assumed. :param path: path of the file :return: the corresponding mime type. """ filename = os.path.split(path)[1] mimetype = mimetypes.guess_type(filename)[0] if mimetype is None: mimetype = 'text/x-plain' _logger().debug('mimetype detected: %s', mimetype) return mimetype
python
def get_mimetype(path): """ Guesses the mime type of a file. If mime type cannot be detected, plain text is assumed. :param path: path of the file :return: the corresponding mime type. """ filename = os.path.split(path)[1] mimetype = mimetypes.guess_type(filename)[0] if mimetype is None: mimetype = 'text/x-plain' _logger().debug('mimetype detected: %s', mimetype) return mimetype
[ "def", "get_mimetype", "(", "path", ")", ":", "filename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", "mimetype", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "if", "mimetype", "is", "None", "...
Guesses the mime type of a file. If mime type cannot be detected, plain text is assumed. :param path: path of the file :return: the corresponding mime type.
[ "Guesses", "the", "mime", "type", "of", "a", "file", ".", "If", "mime", "type", "cannot", "be", "detected", "plain", "text", "is", "assumed", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/file.py#L186-L199
train
46,400
pyQode/pyqode.core
pyqode/core/managers/file.py
FileManager.open
def open(self, path, encoding=None, use_cached_encoding=True): """ Open a file and set its content on the editor widget. pyqode does not try to guess encoding. It's up to the client code to handle encodings. You can either use a charset detector to detect encoding or rely on a settings in your application. It is also up to you to handle UnicodeDecodeError, unless you've added class:`pyqode.core.panels.EncodingPanel` on the editor. pyqode automatically caches file encoding that you can later reuse it automatically. :param path: Path of the file to open. :param encoding: Default file encoding. Default is to use the locale encoding. :param use_cached_encoding: True to use the cached encoding instead of ``encoding``. Set it to True if you want to force reload with a new encoding. :raises: UnicodeDecodeError in case of error if no EncodingPanel were set on the editor. """ ret_val = False if encoding is None: encoding = locale.getpreferredencoding() self.opening = True settings = Cache() self._path = path # get encoding from cache if use_cached_encoding: try: cached_encoding = settings.get_file_encoding( path, preferred_encoding=encoding) except KeyError: pass else: encoding = cached_encoding enable_modes = os.path.getsize(path) < self._limit for m in self.editor.modes: if m.enabled: m.enabled = enable_modes # open file and get its content try: with open(path, 'Ur', encoding=encoding) as file: content = file.read() if self.autodetect_eol: self._eol = file.newlines if isinstance(self._eol, tuple): self._eol = self._eol[0] if self._eol is None: # empty file has no newlines self._eol = self.EOL.string(self.preferred_eol) else: self._eol = self.EOL.string(self.preferred_eol) except (UnicodeDecodeError, UnicodeError) as e: try: from pyqode.core.panels import EncodingPanel panel = self.editor.panels.get(EncodingPanel) except KeyError: raise e # panel not found, not automatic error management else: panel.on_open_failed(path, encoding) else: # success! Cache the encoding settings.set_file_encoding(path, encoding) self._encoding = encoding # replace tabs by spaces if self.replace_tabs_by_spaces: content = content.replace("\t", " " * self.editor.tab_length) # set plain text self.editor.setPlainText( content, self.get_mimetype(path), self.encoding) self.editor.setDocumentTitle(self.editor.file.name) ret_val = True _logger().debug('file open: %s', path) self.opening = False if self.restore_cursor: self._restore_cached_pos() self._check_for_readonly() return ret_val
python
def open(self, path, encoding=None, use_cached_encoding=True): """ Open a file and set its content on the editor widget. pyqode does not try to guess encoding. It's up to the client code to handle encodings. You can either use a charset detector to detect encoding or rely on a settings in your application. It is also up to you to handle UnicodeDecodeError, unless you've added class:`pyqode.core.panels.EncodingPanel` on the editor. pyqode automatically caches file encoding that you can later reuse it automatically. :param path: Path of the file to open. :param encoding: Default file encoding. Default is to use the locale encoding. :param use_cached_encoding: True to use the cached encoding instead of ``encoding``. Set it to True if you want to force reload with a new encoding. :raises: UnicodeDecodeError in case of error if no EncodingPanel were set on the editor. """ ret_val = False if encoding is None: encoding = locale.getpreferredencoding() self.opening = True settings = Cache() self._path = path # get encoding from cache if use_cached_encoding: try: cached_encoding = settings.get_file_encoding( path, preferred_encoding=encoding) except KeyError: pass else: encoding = cached_encoding enable_modes = os.path.getsize(path) < self._limit for m in self.editor.modes: if m.enabled: m.enabled = enable_modes # open file and get its content try: with open(path, 'Ur', encoding=encoding) as file: content = file.read() if self.autodetect_eol: self._eol = file.newlines if isinstance(self._eol, tuple): self._eol = self._eol[0] if self._eol is None: # empty file has no newlines self._eol = self.EOL.string(self.preferred_eol) else: self._eol = self.EOL.string(self.preferred_eol) except (UnicodeDecodeError, UnicodeError) as e: try: from pyqode.core.panels import EncodingPanel panel = self.editor.panels.get(EncodingPanel) except KeyError: raise e # panel not found, not automatic error management else: panel.on_open_failed(path, encoding) else: # success! Cache the encoding settings.set_file_encoding(path, encoding) self._encoding = encoding # replace tabs by spaces if self.replace_tabs_by_spaces: content = content.replace("\t", " " * self.editor.tab_length) # set plain text self.editor.setPlainText( content, self.get_mimetype(path), self.encoding) self.editor.setDocumentTitle(self.editor.file.name) ret_val = True _logger().debug('file open: %s', path) self.opening = False if self.restore_cursor: self._restore_cached_pos() self._check_for_readonly() return ret_val
[ "def", "open", "(", "self", ",", "path", ",", "encoding", "=", "None", ",", "use_cached_encoding", "=", "True", ")", ":", "ret_val", "=", "False", "if", "encoding", "is", "None", ":", "encoding", "=", "locale", ".", "getpreferredencoding", "(", ")", "sel...
Open a file and set its content on the editor widget. pyqode does not try to guess encoding. It's up to the client code to handle encodings. You can either use a charset detector to detect encoding or rely on a settings in your application. It is also up to you to handle UnicodeDecodeError, unless you've added class:`pyqode.core.panels.EncodingPanel` on the editor. pyqode automatically caches file encoding that you can later reuse it automatically. :param path: Path of the file to open. :param encoding: Default file encoding. Default is to use the locale encoding. :param use_cached_encoding: True to use the cached encoding instead of ``encoding``. Set it to True if you want to force reload with a new encoding. :raises: UnicodeDecodeError in case of error if no EncodingPanel were set on the editor.
[ "Open", "a", "file", "and", "set", "its", "content", "on", "the", "editor", "widget", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/file.py#L201-L281
train
46,401
pyQode/pyqode.core
pyqode/core/managers/file.py
FileManager.reload
def reload(self, encoding): """ Reload the file with another encoding. :param encoding: the new encoding to use to reload the file. """ assert os.path.exists(self.path) self.open(self.path, encoding=encoding, use_cached_encoding=False)
python
def reload(self, encoding): """ Reload the file with another encoding. :param encoding: the new encoding to use to reload the file. """ assert os.path.exists(self.path) self.open(self.path, encoding=encoding, use_cached_encoding=False)
[ "def", "reload", "(", "self", ",", "encoding", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", "self", ".", "open", "(", "self", ".", "path", ",", "encoding", "=", "encoding", ",", "use_cached_encoding", "=", "Fal...
Reload the file with another encoding. :param encoding: the new encoding to use to reload the file.
[ "Reload", "the", "file", "with", "another", "encoding", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/file.py#L297-L305
train
46,402
pyQode/pyqode.core
pyqode/core/managers/file.py
FileManager.save
def save(self, path=None, encoding=None, fallback_encoding=None): """ Save the editor content to a file. :param path: optional file path. Set it to None to save using the current path (save), set a new path to save as. :param encoding: optional encoding, will use the current file encoding if None. :param fallback_encoding: Fallback encoding to use in case of encoding error. None to use the locale preferred encoding """ if not self.editor.dirty and \ (encoding is None and encoding == self.encoding) and \ (path is None and path == self.path): # avoid saving if editor not dirty or if encoding or path did not # change return if fallback_encoding is None: fallback_encoding = locale.getpreferredencoding() _logger().log( 5, "saving %r with %r encoding", path, encoding) if path is None: if self.path: path = self.path else: _logger().debug( 'failed to save file, path argument cannot be None if ' 'FileManager.path is also None') return False # use cached encoding if None were specified if encoding is None: encoding = self._encoding self.saving = True self.editor.text_saving.emit(str(path)) # get file persmission on linux try: st_mode = os.stat(path).st_mode except (ImportError, TypeError, AttributeError, OSError): st_mode = None # perform a safe save: we first save to a temporary file, if the save # succeeded we just rename the temporary file to the final file name # and remove it. if self.safe_save: tmp_path = path + '~' else: tmp_path = path try: with open(tmp_path, 'wb') as file: file.write(self._get_text(encoding)) except UnicodeEncodeError: # fallback to utf-8 in case of error. with open(tmp_path, 'wb') as file: file.write(self._get_text(fallback_encoding)) except (IOError, OSError) as e: self._rm(tmp_path) self.saving = False self.editor.text_saved.emit(str(path)) raise e # cache update encoding Cache().set_file_encoding(path, encoding) self._encoding = encoding # remove path and rename temp file, if safe save is on if self.safe_save: self._rm(path) os.rename(tmp_path, path) self._rm(tmp_path) # reset dirty flags self.editor.document().setModified(False) # remember path for next save self._path = os.path.normpath(path) self.editor.text_saved.emit(str(path)) self.saving = False _logger().debug('file saved: %s', path) self._check_for_readonly() # restore file permission if st_mode: try: os.chmod(path, st_mode) except (ImportError, TypeError, AttributeError): pass
python
def save(self, path=None, encoding=None, fallback_encoding=None): """ Save the editor content to a file. :param path: optional file path. Set it to None to save using the current path (save), set a new path to save as. :param encoding: optional encoding, will use the current file encoding if None. :param fallback_encoding: Fallback encoding to use in case of encoding error. None to use the locale preferred encoding """ if not self.editor.dirty and \ (encoding is None and encoding == self.encoding) and \ (path is None and path == self.path): # avoid saving if editor not dirty or if encoding or path did not # change return if fallback_encoding is None: fallback_encoding = locale.getpreferredencoding() _logger().log( 5, "saving %r with %r encoding", path, encoding) if path is None: if self.path: path = self.path else: _logger().debug( 'failed to save file, path argument cannot be None if ' 'FileManager.path is also None') return False # use cached encoding if None were specified if encoding is None: encoding = self._encoding self.saving = True self.editor.text_saving.emit(str(path)) # get file persmission on linux try: st_mode = os.stat(path).st_mode except (ImportError, TypeError, AttributeError, OSError): st_mode = None # perform a safe save: we first save to a temporary file, if the save # succeeded we just rename the temporary file to the final file name # and remove it. if self.safe_save: tmp_path = path + '~' else: tmp_path = path try: with open(tmp_path, 'wb') as file: file.write(self._get_text(encoding)) except UnicodeEncodeError: # fallback to utf-8 in case of error. with open(tmp_path, 'wb') as file: file.write(self._get_text(fallback_encoding)) except (IOError, OSError) as e: self._rm(tmp_path) self.saving = False self.editor.text_saved.emit(str(path)) raise e # cache update encoding Cache().set_file_encoding(path, encoding) self._encoding = encoding # remove path and rename temp file, if safe save is on if self.safe_save: self._rm(path) os.rename(tmp_path, path) self._rm(tmp_path) # reset dirty flags self.editor.document().setModified(False) # remember path for next save self._path = os.path.normpath(path) self.editor.text_saved.emit(str(path)) self.saving = False _logger().debug('file saved: %s', path) self._check_for_readonly() # restore file permission if st_mode: try: os.chmod(path, st_mode) except (ImportError, TypeError, AttributeError): pass
[ "def", "save", "(", "self", ",", "path", "=", "None", ",", "encoding", "=", "None", ",", "fallback_encoding", "=", "None", ")", ":", "if", "not", "self", ".", "editor", ".", "dirty", "and", "(", "encoding", "is", "None", "and", "encoding", "==", "sel...
Save the editor content to a file. :param path: optional file path. Set it to None to save using the current path (save), set a new path to save as. :param encoding: optional encoding, will use the current file encoding if None. :param fallback_encoding: Fallback encoding to use in case of encoding error. None to use the locale preferred encoding
[ "Save", "the", "editor", "content", "to", "a", "file", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/file.py#L342-L425
train
46,403
pyQode/pyqode.core
pyqode/core/modes/filewatcher.py
FileWatcherMode._update_mtime
def _update_mtime(self): """ Updates modif time """ try: self._mtime = os.path.getmtime(self.editor.file.path) except OSError: # file_path does not exists. self._mtime = 0 self._timer.stop() except (TypeError, AttributeError): # file path is none, this happen if you use setPlainText instead of # openFile. This is perfectly fine, we just do not have anything to # watch try: self._timer.stop() except AttributeError: pass
python
def _update_mtime(self): """ Updates modif time """ try: self._mtime = os.path.getmtime(self.editor.file.path) except OSError: # file_path does not exists. self._mtime = 0 self._timer.stop() except (TypeError, AttributeError): # file path is none, this happen if you use setPlainText instead of # openFile. This is perfectly fine, we just do not have anything to # watch try: self._timer.stop() except AttributeError: pass
[ "def", "_update_mtime", "(", "self", ")", ":", "try", ":", "self", ".", "_mtime", "=", "os", ".", "path", ".", "getmtime", "(", "self", ".", "editor", ".", "file", ".", "path", ")", "except", "OSError", ":", "# file_path does not exists.", "self", ".", ...
Updates modif time
[ "Updates", "modif", "time" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/filewatcher.py#L96-L111
train
46,404
pyQode/pyqode.core
pyqode/core/modes/filewatcher.py
FileWatcherMode._check_file
def _check_file(self): """ Checks watched file moficiation time and permission changes. """ try: self.editor.toPlainText() except RuntimeError: self._timer.stop() return if self.editor and self.editor.file.path: if not os.path.exists(self.editor.file.path) and self._mtime: self._notify_deleted_file() else: mtime = os.path.getmtime(self.editor.file.path) if mtime > self._mtime: self._mtime = mtime self._notify_change() # check for permission change writeable = os.access(self.editor.file.path, os.W_OK) self.editor.setReadOnly(not writeable)
python
def _check_file(self): """ Checks watched file moficiation time and permission changes. """ try: self.editor.toPlainText() except RuntimeError: self._timer.stop() return if self.editor and self.editor.file.path: if not os.path.exists(self.editor.file.path) and self._mtime: self._notify_deleted_file() else: mtime = os.path.getmtime(self.editor.file.path) if mtime > self._mtime: self._mtime = mtime self._notify_change() # check for permission change writeable = os.access(self.editor.file.path, os.W_OK) self.editor.setReadOnly(not writeable)
[ "def", "_check_file", "(", "self", ")", ":", "try", ":", "self", ".", "editor", ".", "toPlainText", "(", ")", "except", "RuntimeError", ":", "self", ".", "_timer", ".", "stop", "(", ")", "return", "if", "self", ".", "editor", "and", "self", ".", "edi...
Checks watched file moficiation time and permission changes.
[ "Checks", "watched", "file", "moficiation", "time", "and", "permission", "changes", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/filewatcher.py#L113-L132
train
46,405
pyQode/pyqode.core
pyqode/core/modes/filewatcher.py
FileWatcherMode._notify
def _notify(self, title, message, expected_action=None): """ Notify user from external event """ if self.editor is None: return inital_value = self.editor.save_on_focus_out self.editor.save_on_focus_out = False self._flg_notify = True dlg_type = (QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) expected_action = ( lambda *x: None) if not expected_action else expected_action if (self._auto_reload or QtWidgets.QMessageBox.question( self.editor, title, message, dlg_type, QtWidgets.QMessageBox.Yes) == QtWidgets.QMessageBox.Yes): expected_action(self.editor.file.path) self._update_mtime() self.editor.save_on_focus_out = inital_value
python
def _notify(self, title, message, expected_action=None): """ Notify user from external event """ if self.editor is None: return inital_value = self.editor.save_on_focus_out self.editor.save_on_focus_out = False self._flg_notify = True dlg_type = (QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) expected_action = ( lambda *x: None) if not expected_action else expected_action if (self._auto_reload or QtWidgets.QMessageBox.question( self.editor, title, message, dlg_type, QtWidgets.QMessageBox.Yes) == QtWidgets.QMessageBox.Yes): expected_action(self.editor.file.path) self._update_mtime() self.editor.save_on_focus_out = inital_value
[ "def", "_notify", "(", "self", ",", "title", ",", "message", ",", "expected_action", "=", "None", ")", ":", "if", "self", ".", "editor", "is", "None", ":", "return", "inital_value", "=", "self", ".", "editor", ".", "save_on_focus_out", "self", ".", "edit...
Notify user from external event
[ "Notify", "user", "from", "external", "event" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/filewatcher.py#L134-L151
train
46,406
pyQode/pyqode.core
pyqode/core/modes/filewatcher.py
FileWatcherMode._notify_change
def _notify_change(self): """ Notify user from external change if autoReloadChangedFiles is False then reload the changed file in the editor """ def inner_action(*args): """ Inner action: open file """ # cache cursor position before reloading so that the cursor # position is restored automatically after reload has finished. # See OpenCobolIDE/OpenCobolIDE#97 Cache().set_cursor_position( self.editor.file.path, self.editor.textCursor().position()) if os.path.exists(self.editor.file.path): self.editor.file.open(self.editor.file.path) self.file_reloaded.emit() else: # file moved just after a change, see OpenCobolIDE/OpenCobolIDE#337 self._notify_deleted_file() args = (_("File changed"), _("The file <i>%s</i> has changed externally.\nDo you want to " "reload it?") % os.path.basename(self.editor.file.path)) kwargs = {"expected_action": inner_action} if self.editor.hasFocus() or self.auto_reload: self._notify(*args, **kwargs) else: # show the reload prompt as soon as the editor has focus self._notification_pending = True self._data = (args, kwargs)
python
def _notify_change(self): """ Notify user from external change if autoReloadChangedFiles is False then reload the changed file in the editor """ def inner_action(*args): """ Inner action: open file """ # cache cursor position before reloading so that the cursor # position is restored automatically after reload has finished. # See OpenCobolIDE/OpenCobolIDE#97 Cache().set_cursor_position( self.editor.file.path, self.editor.textCursor().position()) if os.path.exists(self.editor.file.path): self.editor.file.open(self.editor.file.path) self.file_reloaded.emit() else: # file moved just after a change, see OpenCobolIDE/OpenCobolIDE#337 self._notify_deleted_file() args = (_("File changed"), _("The file <i>%s</i> has changed externally.\nDo you want to " "reload it?") % os.path.basename(self.editor.file.path)) kwargs = {"expected_action": inner_action} if self.editor.hasFocus() or self.auto_reload: self._notify(*args, **kwargs) else: # show the reload prompt as soon as the editor has focus self._notification_pending = True self._data = (args, kwargs)
[ "def", "_notify_change", "(", "self", ")", ":", "def", "inner_action", "(", "*", "args", ")", ":", "\"\"\" Inner action: open file \"\"\"", "# cache cursor position before reloading so that the cursor", "# position is restored automatically after reload has finished.", "# See OpenCob...
Notify user from external change if autoReloadChangedFiles is False then reload the changed file in the editor
[ "Notify", "user", "from", "external", "change", "if", "autoReloadChangedFiles", "is", "False", "then", "reload", "the", "changed", "file", "in", "the", "editor" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/filewatcher.py#L153-L182
train
46,407
pyQode/pyqode.core
pyqode/core/modes/filewatcher.py
FileWatcherMode._check_for_pending
def _check_for_pending(self, *args, **kwargs): """ Checks if a notification is pending. """ if self._notification_pending and not self._processing: self._processing = True args, kwargs = self._data self._notify(*args, **kwargs) self._notification_pending = False self._processing = False
python
def _check_for_pending(self, *args, **kwargs): """ Checks if a notification is pending. """ if self._notification_pending and not self._processing: self._processing = True args, kwargs = self._data self._notify(*args, **kwargs) self._notification_pending = False self._processing = False
[ "def", "_check_for_pending", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_notification_pending", "and", "not", "self", ".", "_processing", ":", "self", ".", "_processing", "=", "True", "args", ",", "kwargs", "=",...
Checks if a notification is pending.
[ "Checks", "if", "a", "notification", "is", "pending", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/filewatcher.py#L184-L193
train
46,408
pyQode/pyqode.core
pyqode/core/modes/filewatcher.py
FileWatcherMode._notify_deleted_file
def _notify_deleted_file(self): """ Notify user from external file deletion. """ self.file_deleted.emit(self.editor) # file deleted, disable file watcher self.enabled = False
python
def _notify_deleted_file(self): """ Notify user from external file deletion. """ self.file_deleted.emit(self.editor) # file deleted, disable file watcher self.enabled = False
[ "def", "_notify_deleted_file", "(", "self", ")", ":", "self", ".", "file_deleted", ".", "emit", "(", "self", ".", "editor", ")", "# file deleted, disable file watcher", "self", ".", "enabled", "=", "False" ]
Notify user from external file deletion.
[ "Notify", "user", "from", "external", "file", "deletion", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/filewatcher.py#L195-L201
train
46,409
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/appengine.py
get_gae_versions
def get_gae_versions(): """Gets a list of all of the available Python SDK versions, sorted with the newest last.""" r = requests.get(SDK_RELEASES_URL) r.raise_for_status() releases = r.json().get('items', {}) # We only care about the Python releases, which all are in the format # "featured/google_appengine_{version}.zip". We'll extract the version # number so we can sort the list by version, and finally get the download # URL. versions_and_urls = [] for release in releases: match = PYTHON_RELEASE_RE.match(release['name']) if not match: continue versions_and_urls.append( ([int(x) for x in match.groups()], release['mediaLink'])) return sorted(versions_and_urls, key=lambda x: x[0])
python
def get_gae_versions(): """Gets a list of all of the available Python SDK versions, sorted with the newest last.""" r = requests.get(SDK_RELEASES_URL) r.raise_for_status() releases = r.json().get('items', {}) # We only care about the Python releases, which all are in the format # "featured/google_appengine_{version}.zip". We'll extract the version # number so we can sort the list by version, and finally get the download # URL. versions_and_urls = [] for release in releases: match = PYTHON_RELEASE_RE.match(release['name']) if not match: continue versions_and_urls.append( ([int(x) for x in match.groups()], release['mediaLink'])) return sorted(versions_and_urls, key=lambda x: x[0])
[ "def", "get_gae_versions", "(", ")", ":", "r", "=", "requests", ".", "get", "(", "SDK_RELEASES_URL", ")", "r", ".", "raise_for_status", "(", ")", "releases", "=", "r", ".", "json", "(", ")", ".", "get", "(", "'items'", ",", "{", "}", ")", "# We only ...
Gets a list of all of the available Python SDK versions, sorted with the newest last.
[ "Gets", "a", "list", "of", "all", "of", "the", "available", "Python", "SDK", "versions", "sorted", "with", "the", "newest", "last", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/appengine.py#L41-L63
train
46,410
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/appengine.py
is_existing_up_to_date
def is_existing_up_to_date(destination, latest_version): """Returns False if there is no existing install or if the existing install is out of date. Otherwise, returns True.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') if not os.path.exists(version_path): return False with open(version_path, 'r') as f: version_line = f.readline() match = SDK_RELEASE_RE.match(version_line) if not match: print('Unable to parse version from:', version_line) return False version = [int(x) for x in match.groups()] return version >= latest_version
python
def is_existing_up_to_date(destination, latest_version): """Returns False if there is no existing install or if the existing install is out of date. Otherwise, returns True.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') if not os.path.exists(version_path): return False with open(version_path, 'r') as f: version_line = f.readline() match = SDK_RELEASE_RE.match(version_line) if not match: print('Unable to parse version from:', version_line) return False version = [int(x) for x in match.groups()] return version >= latest_version
[ "def", "is_existing_up_to_date", "(", "destination", ",", "latest_version", ")", ":", "version_path", "=", "os", ".", "path", ".", "join", "(", "destination", ",", "'google_appengine'", ",", "'VERSION'", ")", "if", "not", "os", ".", "path", ".", "exists", "(...
Returns False if there is no existing install or if the existing install is out of date. Otherwise, returns True.
[ "Returns", "False", "if", "there", "is", "no", "existing", "install", "or", "if", "the", "existing", "install", "is", "out", "of", "date", ".", "Otherwise", "returns", "True", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/appengine.py#L66-L86
train
46,411
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/appengine.py
download_sdk
def download_sdk(url): """Downloads the SDK and returns a file-like object for the zip content.""" r = requests.get(url) r.raise_for_status() return StringIO(r.content)
python
def download_sdk(url): """Downloads the SDK and returns a file-like object for the zip content.""" r = requests.get(url) r.raise_for_status() return StringIO(r.content)
[ "def", "download_sdk", "(", "url", ")", ":", "r", "=", "requests", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "return", "StringIO", "(", "r", ".", "content", ")" ]
Downloads the SDK and returns a file-like object for the zip content.
[ "Downloads", "the", "SDK", "and", "returns", "a", "file", "-", "like", "object", "for", "the", "zip", "content", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/appengine.py#L89-L93
train
46,412
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/appengine.py
fixup_version
def fixup_version(destination, version): """Newer releases of the SDK do not have the version number set correctly in the VERSION file. Fix it up.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') with open(version_path, 'r') as f: version_data = f.read() version_data = version_data.replace( 'release: "0.0.0"', 'release: "{}"'.format('.'.join(str(x) for x in version))) with open(version_path, 'w') as f: f.write(version_data)
python
def fixup_version(destination, version): """Newer releases of the SDK do not have the version number set correctly in the VERSION file. Fix it up.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') with open(version_path, 'r') as f: version_data = f.read() version_data = version_data.replace( 'release: "0.0.0"', 'release: "{}"'.format('.'.join(str(x) for x in version))) with open(version_path, 'w') as f: f.write(version_data)
[ "def", "fixup_version", "(", "destination", ",", "version", ")", ":", "version_path", "=", "os", ".", "path", ".", "join", "(", "destination", ",", "'google_appengine'", ",", "'VERSION'", ")", "with", "open", "(", "version_path", ",", "'r'", ")", "as", "f"...
Newer releases of the SDK do not have the version number set correctly in the VERSION file. Fix it up.
[ "Newer", "releases", "of", "the", "SDK", "do", "not", "have", "the", "version", "number", "set", "correctly", "in", "the", "VERSION", "file", ".", "Fix", "it", "up", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/appengine.py#L105-L119
train
46,413
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/appengine.py
download_command
def download_command(args): """Downloads and extracts the latest App Engine SDK to the given destination.""" latest_two_versions = list(reversed(get_gae_versions()))[:2] zip = None version_number = None for version in latest_two_versions: if is_existing_up_to_date(args.destination, version[0]): print( 'App Engine SDK already exists and is up to date ' 'at {}.'.format(args.destination)) return try: print('Downloading App Engine SDK {}'.format( '.'.join([str(x) for x in version[0]]))) zip = download_sdk(version[1]) version_number = version[0] break except Exception as e: print('Failed to download: {}'.format(e)) continue if not zip: return print('Extracting SDK to {}'.format(args.destination)) extract_zip(zip, args.destination) fixup_version(args.destination, version_number) print('App Engine SDK installed.')
python
def download_command(args): """Downloads and extracts the latest App Engine SDK to the given destination.""" latest_two_versions = list(reversed(get_gae_versions()))[:2] zip = None version_number = None for version in latest_two_versions: if is_existing_up_to_date(args.destination, version[0]): print( 'App Engine SDK already exists and is up to date ' 'at {}.'.format(args.destination)) return try: print('Downloading App Engine SDK {}'.format( '.'.join([str(x) for x in version[0]]))) zip = download_sdk(version[1]) version_number = version[0] break except Exception as e: print('Failed to download: {}'.format(e)) continue if not zip: return print('Extracting SDK to {}'.format(args.destination)) extract_zip(zip, args.destination) fixup_version(args.destination, version_number) print('App Engine SDK installed.')
[ "def", "download_command", "(", "args", ")", ":", "latest_two_versions", "=", "list", "(", "reversed", "(", "get_gae_versions", "(", ")", ")", ")", "[", ":", "2", "]", "zip", "=", "None", "version_number", "=", "None", "for", "version", "in", "latest_two_v...
Downloads and extracts the latest App Engine SDK to the given destination.
[ "Downloads", "and", "extracts", "the", "latest", "App", "Engine", "SDK", "to", "the", "given", "destination", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/appengine.py#L122-L155
train
46,414
pyQode/pyqode.core
pyqode/core/cache.py
Cache.get_file_encoding
def get_file_encoding(self, file_path, preferred_encoding=None): """ Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding. """ _logger().debug('getting encoding for %s', file_path) try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} try: return map[file_path] except KeyError: encodings = self.preferred_encodings if preferred_encoding: encodings.insert(0, preferred_encoding) for encoding in encodings: _logger().debug('trying encoding: %s', encoding) try: with open(file_path, encoding=encoding) as f: f.read() except (UnicodeDecodeError, IOError, OSError): pass else: return encoding raise KeyError(file_path)
python
def get_file_encoding(self, file_path, preferred_encoding=None): """ Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding. """ _logger().debug('getting encoding for %s', file_path) try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} try: return map[file_path] except KeyError: encodings = self.preferred_encodings if preferred_encoding: encodings.insert(0, preferred_encoding) for encoding in encodings: _logger().debug('trying encoding: %s', encoding) try: with open(file_path, encoding=encoding) as f: f.read() except (UnicodeDecodeError, IOError, OSError): pass else: return encoding raise KeyError(file_path)
[ "def", "get_file_encoding", "(", "self", ",", "file_path", ",", "preferred_encoding", "=", "None", ")", ":", "_logger", "(", ")", ".", "debug", "(", "'getting encoding for %s'", ",", "file_path", ")", "try", ":", "map", "=", "json", ".", "loads", "(", "sel...
Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding.
[ "Gets", "an", "eventual", "cached", "encoding", "for", "file_path", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/cache.py#L72-L102
train
46,415
pyQode/pyqode.core
pyqode/core/cache.py
Cache.get_cursor_position
def get_cursor_position(self, file_path): """ Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0) """ try: map = json.loads(self._settings.value('cachedCursorPosition')) except TypeError: map = {} try: pos = map[file_path] except KeyError: pos = 0 if isinstance(pos, list): # changed in pyqode 2.6.3, now we store the cursor position # instead of the line and column (faster) pos = 0 return pos
python
def get_cursor_position(self, file_path): """ Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0) """ try: map = json.loads(self._settings.value('cachedCursorPosition')) except TypeError: map = {} try: pos = map[file_path] except KeyError: pos = 0 if isinstance(pos, list): # changed in pyqode 2.6.3, now we store the cursor position # instead of the line and column (faster) pos = 0 return pos
[ "def", "get_cursor_position", "(", "self", ",", "file_path", ")", ":", "try", ":", "map", "=", "json", ".", "loads", "(", "self", ".", "_settings", ".", "value", "(", "'cachedCursorPosition'", ")", ")", "except", "TypeError", ":", "map", "=", "{", "}", ...
Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0)
[ "Gets", "the", "cached", "cursor", "position", "for", "file_path" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/cache.py#L118-L137
train
46,416
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
_mid
def _mid(string, start, end=None): """ Returns a substring delimited by start and end position. """ if end is None: end = len(string) return string[start:start + end]
python
def _mid(string, start, end=None): """ Returns a substring delimited by start and end position. """ if end is None: end = len(string) return string[start:start + end]
[ "def", "_mid", "(", "string", ",", "start", ",", "end", "=", "None", ")", ":", "if", "end", "is", "None", ":", "end", "=", "len", "(", "string", ")", "return", "string", "[", "start", ":", "start", "+", "end", "]" ]
Returns a substring delimited by start and end position.
[ "Returns", "a", "substring", "delimited", "by", "start", "and", "end", "position", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L753-L759
train
46,417
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow.start_process
def start_process(self, program, arguments=None, working_dir=None, print_command=True, use_pseudo_terminal=True, env=None): """ Starts the child process. :param program: program to start :param arguments: list of program arguments :param working_dir: working directory of the child process :param print_command: True to print the full command (pgm + arguments) as the first line of the output window :param use_pseudo_terminal: True to use a pseudo terminal on Unix (pty), False to avoid using a pty wrapper. When using a pty wrapper, both stdout and stderr are merged together. :param environ: environment variables to set on the child process. If None, os.environ will be used. """ # clear previous output self.clear() self.setReadOnly(False) if arguments is None: arguments = [] if sys.platform != 'win32' and use_pseudo_terminal: pgm = sys.executable args = [pty_wrapper.__file__, program] + arguments self.flg_use_pty = use_pseudo_terminal else: pgm = program args = arguments self.flg_use_pty = False # pty not available on windows self._process.setProcessEnvironment(self._setup_process_environment(env)) if working_dir: self._process.setWorkingDirectory(working_dir) if print_command: self._formatter.append_message('\x1b[0m%s %s\n' % (program, ' '.join(arguments)), output_format=OutputFormat.CustomFormat) self._process.start(pgm, args)
python
def start_process(self, program, arguments=None, working_dir=None, print_command=True, use_pseudo_terminal=True, env=None): """ Starts the child process. :param program: program to start :param arguments: list of program arguments :param working_dir: working directory of the child process :param print_command: True to print the full command (pgm + arguments) as the first line of the output window :param use_pseudo_terminal: True to use a pseudo terminal on Unix (pty), False to avoid using a pty wrapper. When using a pty wrapper, both stdout and stderr are merged together. :param environ: environment variables to set on the child process. If None, os.environ will be used. """ # clear previous output self.clear() self.setReadOnly(False) if arguments is None: arguments = [] if sys.platform != 'win32' and use_pseudo_terminal: pgm = sys.executable args = [pty_wrapper.__file__, program] + arguments self.flg_use_pty = use_pseudo_terminal else: pgm = program args = arguments self.flg_use_pty = False # pty not available on windows self._process.setProcessEnvironment(self._setup_process_environment(env)) if working_dir: self._process.setWorkingDirectory(working_dir) if print_command: self._formatter.append_message('\x1b[0m%s %s\n' % (program, ' '.join(arguments)), output_format=OutputFormat.CustomFormat) self._process.start(pgm, args)
[ "def", "start_process", "(", "self", ",", "program", ",", "arguments", "=", "None", ",", "working_dir", "=", "None", ",", "print_command", "=", "True", ",", "use_pseudo_terminal", "=", "True", ",", "env", "=", "None", ")", ":", "# clear previous output", "se...
Starts the child process. :param program: program to start :param arguments: list of program arguments :param working_dir: working directory of the child process :param print_command: True to print the full command (pgm + arguments) as the first line of the output window :param use_pseudo_terminal: True to use a pseudo terminal on Unix (pty), False to avoid using a pty wrapper. When using a pty wrapper, both stdout and stderr are merged together. :param environ: environment variables to set on the child process. If None, os.environ will be used.
[ "Starts", "the", "child", "process", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L143-L179
train
46,418
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow.stop_process
def stop_process(self): """ Stops the child process. """ self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
python
def stop_process(self): """ Stops the child process. """ self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
[ "def", "stop_process", "(", "self", ")", ":", "self", ".", "_process", ".", "terminate", "(", ")", "if", "not", "self", ".", "_process", ".", "waitForFinished", "(", "100", ")", ":", "self", ".", "_process", ".", "kill", "(", ")" ]
Stops the child process.
[ "Stops", "the", "child", "process", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L181-L187
train
46,419
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow.create_color_scheme
def create_color_scheme(background=None, foreground=None, error=None, custom=None, red=None, green=None, yellow=None, blue=None, magenta=None, cyan=None): """ Utility function that creates a color scheme instance, with default values. The default colors are chosen based on the current palette. :param background: background color :param foreground: foreground color :param error: color of error messages (stderr) :param custom: color of custom messages (e.g. to print the full command or the process exit code) :param red: value of the red ANSI color :param green: value of the green ANSI color :param yellow: value of the yellow ANSI color :param blue: value of the blue ANSI color :param magenta: value of the magenta ANSI color :param cyan: value of the cyan ANSI color :return: A ColorScheme instance. """ if background is None: background = qApp.palette().base().color() if foreground is None: foreground = qApp.palette().text().color() is_light = background.lightness() >= 128 if error is None: if is_light: error = QColor('dark red') else: error = QColor('#FF5555') if red is None: red = QColor(error) if green is None: if is_light: green = QColor('dark green') else: green = QColor('#55FF55') if yellow is None: if is_light: yellow = QColor('#aaaa00') else: yellow = QColor('#FFFF55') if blue is None: if is_light: blue = QColor('dark blue') else: blue = QColor('#5555FF') if magenta is None: if is_light: magenta = QColor('dark magenta') else: magenta = QColor('#FF55FF') if cyan is None: if is_light: cyan = QColor('dark cyan') else: cyan = QColor('#55FFFF') if custom is None: custom = QColor('orange') return OutputWindow.ColorScheme(background, foreground, error, custom, red, green, yellow, blue, magenta, cyan)
python
def create_color_scheme(background=None, foreground=None, error=None, custom=None, red=None, green=None, yellow=None, blue=None, magenta=None, cyan=None): """ Utility function that creates a color scheme instance, with default values. The default colors are chosen based on the current palette. :param background: background color :param foreground: foreground color :param error: color of error messages (stderr) :param custom: color of custom messages (e.g. to print the full command or the process exit code) :param red: value of the red ANSI color :param green: value of the green ANSI color :param yellow: value of the yellow ANSI color :param blue: value of the blue ANSI color :param magenta: value of the magenta ANSI color :param cyan: value of the cyan ANSI color :return: A ColorScheme instance. """ if background is None: background = qApp.palette().base().color() if foreground is None: foreground = qApp.palette().text().color() is_light = background.lightness() >= 128 if error is None: if is_light: error = QColor('dark red') else: error = QColor('#FF5555') if red is None: red = QColor(error) if green is None: if is_light: green = QColor('dark green') else: green = QColor('#55FF55') if yellow is None: if is_light: yellow = QColor('#aaaa00') else: yellow = QColor('#FFFF55') if blue is None: if is_light: blue = QColor('dark blue') else: blue = QColor('#5555FF') if magenta is None: if is_light: magenta = QColor('dark magenta') else: magenta = QColor('#FF55FF') if cyan is None: if is_light: cyan = QColor('dark cyan') else: cyan = QColor('#55FFFF') if custom is None: custom = QColor('orange') return OutputWindow.ColorScheme(background, foreground, error, custom, red, green, yellow, blue, magenta, cyan)
[ "def", "create_color_scheme", "(", "background", "=", "None", ",", "foreground", "=", "None", ",", "error", "=", "None", ",", "custom", "=", "None", ",", "red", "=", "None", ",", "green", "=", "None", ",", "yellow", "=", "None", ",", "blue", "=", "No...
Utility function that creates a color scheme instance, with default values. The default colors are chosen based on the current palette. :param background: background color :param foreground: foreground color :param error: color of error messages (stderr) :param custom: color of custom messages (e.g. to print the full command or the process exit code) :param red: value of the red ANSI color :param green: value of the green ANSI color :param yellow: value of the yellow ANSI color :param blue: value of the blue ANSI color :param magenta: value of the magenta ANSI color :param cyan: value of the cyan ANSI color :return: A ColorScheme instance.
[ "Utility", "function", "that", "creates", "a", "color", "scheme", "instance", "with", "default", "values", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L196-L255
train
46,420
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow.closeEvent
def closeEvent(self, event): """ Terminates the child process on close. """ self.stop_process() self.backend.stop() try: self.modes.remove('_LinkHighlighter') except KeyError: pass # already removed super(OutputWindow, self).closeEvent(event)
python
def closeEvent(self, event): """ Terminates the child process on close. """ self.stop_process() self.backend.stop() try: self.modes.remove('_LinkHighlighter') except KeyError: pass # already removed super(OutputWindow, self).closeEvent(event)
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "self", ".", "stop_process", "(", ")", "self", ".", "backend", ".", "stop", "(", ")", "try", ":", "self", ".", "modes", ".", "remove", "(", "'_LinkHighlighter'", ")", "except", "KeyError", ":", ...
Terminates the child process on close.
[ "Terminates", "the", "child", "process", "on", "close", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L263-L273
train
46,421
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow.keyPressEvent
def keyPressEvent(self, event): """ Handle key press event using the defined input handler. """ if self._process.state() != self._process.Running: return tc = self.textCursor() sel_start = tc.selectionStart() sel_end = tc.selectionEnd() tc.setPosition(self._formatter._last_cursor_pos) self.setTextCursor(tc) if self.input_handler.key_press_event(event): tc.setPosition(sel_start) tc.setPosition(sel_end, tc.KeepAnchor) self.setTextCursor(tc) super(OutputWindow, self).keyPressEvent(event) self._formatter._last_cursor_pos = self.textCursor().position()
python
def keyPressEvent(self, event): """ Handle key press event using the defined input handler. """ if self._process.state() != self._process.Running: return tc = self.textCursor() sel_start = tc.selectionStart() sel_end = tc.selectionEnd() tc.setPosition(self._formatter._last_cursor_pos) self.setTextCursor(tc) if self.input_handler.key_press_event(event): tc.setPosition(sel_start) tc.setPosition(sel_end, tc.KeepAnchor) self.setTextCursor(tc) super(OutputWindow, self).keyPressEvent(event) self._formatter._last_cursor_pos = self.textCursor().position()
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "_process", ".", "state", "(", ")", "!=", "self", ".", "_process", ".", "Running", ":", "return", "tc", "=", "self", ".", "textCursor", "(", ")", "sel_start", "=", "tc", ...
Handle key press event using the defined input handler.
[ "Handle", "key", "press", "event", "using", "the", "defined", "input", "handler", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L275-L291
train
46,422
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow.mouseMoveEvent
def mouseMoveEvent(self, event): """ Handle mouse over file link. """ c = self.cursorForPosition(event.pos()) block = c.block() self._link_match = None self.viewport().setCursor(QtCore.Qt.IBeamCursor) for match in self.link_regex.finditer(block.text()): if not match: continue start, end = match.span() if start <= c.positionInBlock() <= end: self._link_match = match self.viewport().setCursor(QtCore.Qt.PointingHandCursor) break self._last_hovered_block = block super(OutputWindow, self).mouseMoveEvent(event)
python
def mouseMoveEvent(self, event): """ Handle mouse over file link. """ c = self.cursorForPosition(event.pos()) block = c.block() self._link_match = None self.viewport().setCursor(QtCore.Qt.IBeamCursor) for match in self.link_regex.finditer(block.text()): if not match: continue start, end = match.span() if start <= c.positionInBlock() <= end: self._link_match = match self.viewport().setCursor(QtCore.Qt.PointingHandCursor) break self._last_hovered_block = block super(OutputWindow, self).mouseMoveEvent(event)
[ "def", "mouseMoveEvent", "(", "self", ",", "event", ")", ":", "c", "=", "self", ".", "cursorForPosition", "(", "event", ".", "pos", "(", ")", ")", "block", "=", "c", ".", "block", "(", ")", "self", ".", "_link_match", "=", "None", "self", ".", "vie...
Handle mouse over file link.
[ "Handle", "mouse", "over", "file", "link", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L293-L311
train
46,423
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow.mousePressEvent
def mousePressEvent(self, event): """ Handle file link clicks. """ super(OutputWindow, self).mousePressEvent(event) if self._link_match: path = self._link_match.group('url') line = self._link_match.group('line') if line is not None: line = int(line) - 1 else: line = 0 self.open_file_requested.emit(path, line)
python
def mousePressEvent(self, event): """ Handle file link clicks. """ super(OutputWindow, self).mousePressEvent(event) if self._link_match: path = self._link_match.group('url') line = self._link_match.group('line') if line is not None: line = int(line) - 1 else: line = 0 self.open_file_requested.emit(path, line)
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "super", "(", "OutputWindow", ",", "self", ")", ".", "mousePressEvent", "(", "event", ")", "if", "self", ".", "_link_match", ":", "path", "=", "self", ".", "_link_match", ".", "group", "(", ...
Handle file link clicks.
[ "Handle", "file", "link", "clicks", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L313-L325
train
46,424
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow._setup_process_environment
def _setup_process_environment(self, env): """ Sets up the process environment. """ environ = self._process.processEnvironment() if env is None: env = {} for k, v in os.environ.items(): environ.insert(k, v) for k, v in env.items(): environ.insert(k, v) if sys.platform != 'win32': environ.insert('TERM', 'xterm') environ.insert('LINES', '24') environ.insert('COLUMNS', '450') environ.insert('PYTHONUNBUFFERED', '1') environ.insert('QT_LOGGING_TO_CONSOLE', '1') return environ
python
def _setup_process_environment(self, env): """ Sets up the process environment. """ environ = self._process.processEnvironment() if env is None: env = {} for k, v in os.environ.items(): environ.insert(k, v) for k, v in env.items(): environ.insert(k, v) if sys.platform != 'win32': environ.insert('TERM', 'xterm') environ.insert('LINES', '24') environ.insert('COLUMNS', '450') environ.insert('PYTHONUNBUFFERED', '1') environ.insert('QT_LOGGING_TO_CONSOLE', '1') return environ
[ "def", "_setup_process_environment", "(", "self", ",", "env", ")", ":", "environ", "=", "self", ".", "_process", ".", "processEnvironment", "(", ")", "if", "env", "is", "None", ":", "env", "=", "{", "}", "for", "k", ",", "v", "in", "os", ".", "enviro...
Sets up the process environment.
[ "Sets", "up", "the", "process", "environment", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L362-L379
train
46,425
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow._on_process_error
def _on_process_error(self, error): """ Display child process error in the text edit. """ if self is None: return err = PROCESS_ERROR_STRING[error] self._formatter.append_message(err + '\r\n', output_format=OutputFormat.ErrorMessageFormat)
python
def _on_process_error(self, error): """ Display child process error in the text edit. """ if self is None: return err = PROCESS_ERROR_STRING[error] self._formatter.append_message(err + '\r\n', output_format=OutputFormat.ErrorMessageFormat)
[ "def", "_on_process_error", "(", "self", ",", "error", ")", ":", "if", "self", "is", "None", ":", "return", "err", "=", "PROCESS_ERROR_STRING", "[", "error", "]", "self", ".", "_formatter", ".", "append_message", "(", "err", "+", "'\\r\\n'", ",", "output_f...
Display child process error in the text edit.
[ "Display", "child", "process", "error", "in", "the", "text", "edit", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L381-L388
train
46,426
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow._on_process_finished
def _on_process_finished(self): """ Write the process finished message and emit the `finished` signal. """ exit_code = self._process.exitCode() if self._process.exitStatus() != self._process.NormalExit: exit_code = 139 self._formatter.append_message('\x1b[0m\nProcess finished with exit code %d' % exit_code, output_format=OutputFormat.CustomFormat) self.setReadOnly(True) self.process_finished.emit()
python
def _on_process_finished(self): """ Write the process finished message and emit the `finished` signal. """ exit_code = self._process.exitCode() if self._process.exitStatus() != self._process.NormalExit: exit_code = 139 self._formatter.append_message('\x1b[0m\nProcess finished with exit code %d' % exit_code, output_format=OutputFormat.CustomFormat) self.setReadOnly(True) self.process_finished.emit()
[ "def", "_on_process_finished", "(", "self", ")", ":", "exit_code", "=", "self", ".", "_process", ".", "exitCode", "(", ")", "if", "self", ".", "_process", ".", "exitStatus", "(", ")", "!=", "self", ".", "_process", ".", "NormalExit", ":", "exit_code", "=...
Write the process finished message and emit the `finished` signal.
[ "Write", "the", "process", "finished", "message", "and", "emit", "the", "finished", "signal", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L390-L400
train
46,427
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow._read_stdout
def _read_stdout(self): """ Reads the child process' stdout and process it. """ output = self._decode(self._process.readAllStandardOutput().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.NormalMessageFormat) else: self.insertPlainText(output)
python
def _read_stdout(self): """ Reads the child process' stdout and process it. """ output = self._decode(self._process.readAllStandardOutput().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.NormalMessageFormat) else: self.insertPlainText(output)
[ "def", "_read_stdout", "(", "self", ")", ":", "output", "=", "self", ".", "_decode", "(", "self", ".", "_process", ".", "readAllStandardOutput", "(", ")", ".", "data", "(", ")", ")", "if", "self", ".", "_formatter", ":", "self", ".", "_formatter", ".",...
Reads the child process' stdout and process it.
[ "Reads", "the", "child", "process", "stdout", "and", "process", "it", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L414-L422
train
46,428
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputWindow._read_stderr
def _read_stderr(self): """ Reads the child process' stderr and process it. """ output = self._decode(self._process.readAllStandardError().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.ErrorMessageFormat) else: self.insertPlainText(output)
python
def _read_stderr(self): """ Reads the child process' stderr and process it. """ output = self._decode(self._process.readAllStandardError().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.ErrorMessageFormat) else: self.insertPlainText(output)
[ "def", "_read_stderr", "(", "self", ")", ":", "output", "=", "self", ".", "_decode", "(", "self", ".", "_process", ".", "readAllStandardError", "(", ")", ".", "data", "(", ")", ")", "if", "self", ".", "_formatter", ":", "self", ".", "_formatter", ".", ...
Reads the child process' stderr and process it.
[ "Reads", "the", "child", "process", "stderr", "and", "process", "it", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L424-L432
train
46,429
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
AnsiEscapeCodeParser._set_format_scope
def _set_format_scope(self, fmt): """ Opens the format scope. """ self._prev_fmt = QtGui.QTextCharFormat(fmt) self._prev_fmt_closed = False
python
def _set_format_scope(self, fmt): """ Opens the format scope. """ self._prev_fmt = QtGui.QTextCharFormat(fmt) self._prev_fmt_closed = False
[ "def", "_set_format_scope", "(", "self", ",", "fmt", ")", ":", "self", ".", "_prev_fmt", "=", "QtGui", ".", "QTextCharFormat", "(", "fmt", ")", "self", ".", "_prev_fmt_closed", "=", "False" ]
Opens the format scope.
[ "Opens", "the", "format", "scope", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L745-L750
train
46,430
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
ImmediateInputHandler.key_press_event
def key_press_event(self, event): """ Directly writes the ascii code of the key to the process' stdin. :retuns: False to prevent the event from being propagated to the parent widget. """ if event.key() == QtCore.Qt.Key_Return: cursor = self.edit.textCursor() cursor.movePosition(cursor.EndOfBlock) self.edit.setTextCursor(cursor) code = _qkey_to_ascii(event) if code: self.process.writeData(code) return False return True
python
def key_press_event(self, event): """ Directly writes the ascii code of the key to the process' stdin. :retuns: False to prevent the event from being propagated to the parent widget. """ if event.key() == QtCore.Qt.Key_Return: cursor = self.edit.textCursor() cursor.movePosition(cursor.EndOfBlock) self.edit.setTextCursor(cursor) code = _qkey_to_ascii(event) if code: self.process.writeData(code) return False return True
[ "def", "key_press_event", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "==", "QtCore", ".", "Qt", ".", "Key_Return", ":", "cursor", "=", "self", ".", "edit", ".", "textCursor", "(", ")", "cursor", ".", "movePosition", "("...
Directly writes the ascii code of the key to the process' stdin. :retuns: False to prevent the event from being propagated to the parent widget.
[ "Directly", "writes", "the", "ascii", "code", "of", "the", "key", "to", "the", "process", "stdin", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L805-L819
train
46,431
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
CommandHistory.add_command
def add_command(self, command): """ Adds a command to the history and reset history index. """ try: self._history.remove(command) except ValueError: pass self._history.insert(0, command) self._index = -1
python
def add_command(self, command): """ Adds a command to the history and reset history index. """ try: self._history.remove(command) except ValueError: pass self._history.insert(0, command) self._index = -1
[ "def", "add_command", "(", "self", ",", "command", ")", ":", "try", ":", "self", ".", "_history", ".", "remove", "(", "command", ")", "except", "ValueError", ":", "pass", "self", ".", "_history", ".", "insert", "(", "0", ",", "command", ")", "self", ...
Adds a command to the history and reset history index.
[ "Adds", "a", "command", "to", "the", "history", "and", "reset", "history", "index", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L930-L939
train
46,432
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
CommandHistory.scroll_up
def scroll_up(self): """ Returns the previous command, if any. """ self._index += 1 nb_commands = len(self._history) if self._index >= nb_commands: self._index = nb_commands - 1 try: return self._history[self._index] except IndexError: return ''
python
def scroll_up(self): """ Returns the previous command, if any. """ self._index += 1 nb_commands = len(self._history) if self._index >= nb_commands: self._index = nb_commands - 1 try: return self._history[self._index] except IndexError: return ''
[ "def", "scroll_up", "(", "self", ")", ":", "self", ".", "_index", "+=", "1", "nb_commands", "=", "len", "(", "self", ".", "_history", ")", "if", "self", ".", "_index", ">=", "nb_commands", ":", "self", ".", "_index", "=", "nb_commands", "-", "1", "tr...
Returns the previous command, if any.
[ "Returns", "the", "previous", "command", "if", "any", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L941-L952
train
46,433
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
CommandHistory.scroll_down
def scroll_down(self): """ Returns the next command if any. """ self._index -= 1 if self._index < 0: self._index = -1 return '' try: return self._history[self._index] except IndexError: return ''
python
def scroll_down(self): """ Returns the next command if any. """ self._index -= 1 if self._index < 0: self._index = -1 return '' try: return self._history[self._index] except IndexError: return ''
[ "def", "scroll_down", "(", "self", ")", ":", "self", ".", "_index", "-=", "1", "if", "self", ".", "_index", "<", "0", ":", "self", ".", "_index", "=", "-", "1", "return", "''", "try", ":", "return", "self", ".", "_history", "[", "self", ".", "_in...
Returns the next command if any.
[ "Returns", "the", "next", "command", "if", "any", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L954-L965
train
46,434
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
BufferedInputHandler._insert_command
def _insert_command(self, command): """ Insert command by replacing the current input buffer and display it on the text edit. """ self._clear_user_buffer() tc = self.edit.textCursor() tc.insertText(command) self.edit.setTextCursor(tc)
python
def _insert_command(self, command): """ Insert command by replacing the current input buffer and display it on the text edit. """ self._clear_user_buffer() tc = self.edit.textCursor() tc.insertText(command) self.edit.setTextCursor(tc)
[ "def", "_insert_command", "(", "self", ",", "command", ")", ":", "self", ".", "_clear_user_buffer", "(", ")", "tc", "=", "self", ".", "edit", ".", "textCursor", "(", ")", "tc", ".", "insertText", "(", "command", ")", "self", ".", "edit", ".", "setTextC...
Insert command by replacing the current input buffer and display it on the text edit.
[ "Insert", "command", "by", "replacing", "the", "current", "input", "buffer", "and", "display", "it", "on", "the", "text", "edit", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L978-L985
train
46,435
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter.append_message
def append_message(self, text, output_format=OutputFormat.NormalMessageFormat): """ Parses and append message to the text edit. """ self._append_message(text, self._formats[output_format])
python
def append_message(self, text, output_format=OutputFormat.NormalMessageFormat): """ Parses and append message to the text edit. """ self._append_message(text, self._formats[output_format])
[ "def", "append_message", "(", "self", ",", "text", ",", "output_format", "=", "OutputFormat", ".", "NormalMessageFormat", ")", ":", "self", ".", "_append_message", "(", "text", ",", "self", ".", "_formats", "[", "output_format", "]", ")" ]
Parses and append message to the text edit.
[ "Parses", "and", "append", "message", "to", "the", "text", "edit", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1128-L1132
train
46,436
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._append_message
def _append_message(self, text, char_format): """ Parses text and executes parsed operations. """ self._cursor = self._text_edit.textCursor() operations = self._parser.parse_text(FormattedText(text, char_format)) for i, operation in enumerate(operations): try: func = getattr(self, '_%s' % operation.command) except AttributeError: print('command not implemented: %r - %r' % ( operation.command, operation.data)) else: try: func(operation.data) except Exception: _logger().exception('exception while running %r', operation) # uncomment next line for debugging commands self._text_edit.repaint()
python
def _append_message(self, text, char_format): """ Parses text and executes parsed operations. """ self._cursor = self._text_edit.textCursor() operations = self._parser.parse_text(FormattedText(text, char_format)) for i, operation in enumerate(operations): try: func = getattr(self, '_%s' % operation.command) except AttributeError: print('command not implemented: %r - %r' % ( operation.command, operation.data)) else: try: func(operation.data) except Exception: _logger().exception('exception while running %r', operation) # uncomment next line for debugging commands self._text_edit.repaint()
[ "def", "_append_message", "(", "self", ",", "text", ",", "char_format", ")", ":", "self", ".", "_cursor", "=", "self", ".", "_text_edit", ".", "textCursor", "(", ")", "operations", "=", "self", ".", "_parser", ".", "parse_text", "(", "FormattedText", "(", ...
Parses text and executes parsed operations.
[ "Parses", "text", "and", "executes", "parsed", "operations", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1141-L1159
train
46,437
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._init_formats
def _init_formats(self): """ Initialise default formats. """ theme = self._color_scheme # normal message format fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.foreground) fmt.setBackground(theme.background) self._formats[OutputFormat.NormalMessageFormat] = fmt # error message fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.error) fmt.setBackground(theme.background) self._formats[OutputFormat.ErrorMessageFormat] = fmt # debug message fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.custom) fmt.setBackground(theme.background) self._formats[OutputFormat.CustomFormat] = fmt
python
def _init_formats(self): """ Initialise default formats. """ theme = self._color_scheme # normal message format fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.foreground) fmt.setBackground(theme.background) self._formats[OutputFormat.NormalMessageFormat] = fmt # error message fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.error) fmt.setBackground(theme.background) self._formats[OutputFormat.ErrorMessageFormat] = fmt # debug message fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.custom) fmt.setBackground(theme.background) self._formats[OutputFormat.CustomFormat] = fmt
[ "def", "_init_formats", "(", "self", ")", ":", "theme", "=", "self", ".", "_color_scheme", "# normal message format", "fmt", "=", "QtGui", ".", "QTextCharFormat", "(", ")", "fmt", ".", "setForeground", "(", "theme", ".", "foreground", ")", "fmt", ".", "setBa...
Initialise default formats.
[ "Initialise", "default", "formats", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1161-L1182
train
46,438
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._draw_chars
def _draw_chars(self, data, to_draw): """ Draw the specified charachters using the specified format. """ i = 0 while not self._cursor.atBlockEnd() and i < len(to_draw) and len(to_draw) > 1: self._cursor.deleteChar() i += 1 self._cursor.insertText(to_draw, data.fmt)
python
def _draw_chars(self, data, to_draw): """ Draw the specified charachters using the specified format. """ i = 0 while not self._cursor.atBlockEnd() and i < len(to_draw) and len(to_draw) > 1: self._cursor.deleteChar() i += 1 self._cursor.insertText(to_draw, data.fmt)
[ "def", "_draw_chars", "(", "self", ",", "data", ",", "to_draw", ")", ":", "i", "=", "0", "while", "not", "self", ".", "_cursor", ".", "atBlockEnd", "(", ")", "and", "i", "<", "len", "(", "to_draw", ")", "and", "len", "(", "to_draw", ")", ">", "1"...
Draw the specified charachters using the specified format.
[ "Draw", "the", "specified", "charachters", "using", "the", "specified", "format", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1236-L1244
train
46,439
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._linefeed
def _linefeed(self): """ Performs a line feed. """ last_line = self._cursor.blockNumber() == self._text_edit.blockCount() - 1 if self._cursor.atEnd() or last_line: if last_line: self._cursor.movePosition(self._cursor.EndOfBlock) self._cursor.insertText('\n') else: self._cursor.movePosition(self._cursor.Down) self._cursor.movePosition(self._cursor.StartOfBlock) self._text_edit.setTextCursor(self._cursor)
python
def _linefeed(self): """ Performs a line feed. """ last_line = self._cursor.blockNumber() == self._text_edit.blockCount() - 1 if self._cursor.atEnd() or last_line: if last_line: self._cursor.movePosition(self._cursor.EndOfBlock) self._cursor.insertText('\n') else: self._cursor.movePosition(self._cursor.Down) self._cursor.movePosition(self._cursor.StartOfBlock) self._text_edit.setTextCursor(self._cursor)
[ "def", "_linefeed", "(", "self", ")", ":", "last_line", "=", "self", ".", "_cursor", ".", "blockNumber", "(", ")", "==", "self", ".", "_text_edit", ".", "blockCount", "(", ")", "-", "1", "if", "self", ".", "_cursor", ".", "atEnd", "(", ")", "or", "...
Performs a line feed.
[ "Performs", "a", "line", "feed", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1246-L1258
train
46,440
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._cursor_down
def _cursor_down(self, value): """ Moves the cursor down by ``value``. """ self._cursor.clearSelection() if self._cursor.atEnd(): self._cursor.insertText('\n') else: self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, value) self._last_cursor_pos = self._cursor.position()
python
def _cursor_down(self, value): """ Moves the cursor down by ``value``. """ self._cursor.clearSelection() if self._cursor.atEnd(): self._cursor.insertText('\n') else: self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, value) self._last_cursor_pos = self._cursor.position()
[ "def", "_cursor_down", "(", "self", ",", "value", ")", ":", "self", ".", "_cursor", ".", "clearSelection", "(", ")", "if", "self", ".", "_cursor", ".", "atEnd", "(", ")", ":", "self", ".", "_cursor", ".", "insertText", "(", "'\\n'", ")", "else", ":",...
Moves the cursor down by ``value``.
[ "Moves", "the", "cursor", "down", "by", "value", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1260-L1269
train
46,441
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._cursor_up
def _cursor_up(self, value): """ Moves the cursor up by ``value``. """ value = int(value) if value == 0: value = 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.Up, self._cursor.MoveAnchor, value) self._last_cursor_pos = self._cursor.position()
python
def _cursor_up(self, value): """ Moves the cursor up by ``value``. """ value = int(value) if value == 0: value = 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.Up, self._cursor.MoveAnchor, value) self._last_cursor_pos = self._cursor.position()
[ "def", "_cursor_up", "(", "self", ",", "value", ")", ":", "value", "=", "int", "(", "value", ")", "if", "value", "==", "0", ":", "value", "=", "1", "self", ".", "_cursor", ".", "clearSelection", "(", ")", "self", ".", "_cursor", ".", "movePosition", ...
Moves the cursor up by ``value``.
[ "Moves", "the", "cursor", "up", "by", "value", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1271-L1280
train
46,442
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._cursor_position
def _cursor_position(self, data): """ Moves the cursor position. """ column, line = self._get_line_and_col(data) self._move_cursor_to_line(line) self._move_cursor_to_column(column) self._last_cursor_pos = self._cursor.position()
python
def _cursor_position(self, data): """ Moves the cursor position. """ column, line = self._get_line_and_col(data) self._move_cursor_to_line(line) self._move_cursor_to_column(column) self._last_cursor_pos = self._cursor.position()
[ "def", "_cursor_position", "(", "self", ",", "data", ")", ":", "column", ",", "line", "=", "self", ".", "_get_line_and_col", "(", "data", ")", "self", ".", "_move_cursor_to_line", "(", "line", ")", "self", ".", "_move_cursor_to_column", "(", "column", ")", ...
Moves the cursor position.
[ "Moves", "the", "cursor", "position", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1282-L1289
train
46,443
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._move_cursor_to_column
def _move_cursor_to_column(self, column): """ Moves the cursor to the specified column, if possible. """ last_col = len(self._cursor.block().text()) self._cursor.movePosition(self._cursor.EndOfBlock) to_insert = '' for i in range(column - last_col): to_insert += ' ' if to_insert: self._cursor.insertText(to_insert) self._cursor.movePosition(self._cursor.StartOfBlock) self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, column) self._last_cursor_pos = self._cursor.position()
python
def _move_cursor_to_column(self, column): """ Moves the cursor to the specified column, if possible. """ last_col = len(self._cursor.block().text()) self._cursor.movePosition(self._cursor.EndOfBlock) to_insert = '' for i in range(column - last_col): to_insert += ' ' if to_insert: self._cursor.insertText(to_insert) self._cursor.movePosition(self._cursor.StartOfBlock) self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, column) self._last_cursor_pos = self._cursor.position()
[ "def", "_move_cursor_to_column", "(", "self", ",", "column", ")", ":", "last_col", "=", "len", "(", "self", ".", "_cursor", ".", "block", "(", ")", ".", "text", "(", ")", ")", "self", ".", "_cursor", ".", "movePosition", "(", "self", ".", "_cursor", ...
Moves the cursor to the specified column, if possible.
[ "Moves", "the", "cursor", "to", "the", "specified", "column", "if", "possible", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1291-L1304
train
46,444
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._move_cursor_to_line
def _move_cursor_to_line(self, line): """ Moves the cursor to the specified line, if possible. """ last_line = self._text_edit.document().blockCount() - 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.End) to_insert = '' for i in range(line - last_line): to_insert += '\n' if to_insert: self._cursor.insertText(to_insert) self._cursor.movePosition(self._cursor.Start) self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, line) self._last_cursor_pos = self._cursor.position()
python
def _move_cursor_to_line(self, line): """ Moves the cursor to the specified line, if possible. """ last_line = self._text_edit.document().blockCount() - 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.End) to_insert = '' for i in range(line - last_line): to_insert += '\n' if to_insert: self._cursor.insertText(to_insert) self._cursor.movePosition(self._cursor.Start) self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, line) self._last_cursor_pos = self._cursor.position()
[ "def", "_move_cursor_to_line", "(", "self", ",", "line", ")", ":", "last_line", "=", "self", ".", "_text_edit", ".", "document", "(", ")", ".", "blockCount", "(", ")", "-", "1", "self", ".", "_cursor", ".", "clearSelection", "(", ")", "self", ".", "_cu...
Moves the cursor to the specified line, if possible.
[ "Moves", "the", "cursor", "to", "the", "specified", "line", "if", "possible", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1306-L1320
train
46,445
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._erase_in_line
def _erase_in_line(self, value): """ Erases charachters in line. """ initial_pos = self._cursor.position() if value == 0: # delete end of line self._cursor.movePosition(self._cursor.EndOfBlock, self._cursor.KeepAnchor) elif value == 1: # delete start of line self._cursor.movePosition(self._cursor.StartOfBlock, self._cursor.KeepAnchor) else: # delete whole line self._cursor.movePosition(self._cursor.StartOfBlock) self._cursor.movePosition(self._cursor.EndOfBlock, self._cursor.KeepAnchor) self._cursor.insertText(' ' * len(self._cursor.selectedText())) self._cursor.setPosition(initial_pos) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
python
def _erase_in_line(self, value): """ Erases charachters in line. """ initial_pos = self._cursor.position() if value == 0: # delete end of line self._cursor.movePosition(self._cursor.EndOfBlock, self._cursor.KeepAnchor) elif value == 1: # delete start of line self._cursor.movePosition(self._cursor.StartOfBlock, self._cursor.KeepAnchor) else: # delete whole line self._cursor.movePosition(self._cursor.StartOfBlock) self._cursor.movePosition(self._cursor.EndOfBlock, self._cursor.KeepAnchor) self._cursor.insertText(' ' * len(self._cursor.selectedText())) self._cursor.setPosition(initial_pos) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
[ "def", "_erase_in_line", "(", "self", ",", "value", ")", ":", "initial_pos", "=", "self", ".", "_cursor", ".", "position", "(", ")", "if", "value", "==", "0", ":", "# delete end of line", "self", ".", "_cursor", ".", "movePosition", "(", "self", ".", "_c...
Erases charachters in line.
[ "Erases", "charachters", "in", "line", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1355-L1373
train
46,446
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._erase_display
def _erase_display(self, value): """ Erases display. """ if value == 0: # delete end of line self._cursor.movePosition(self._cursor.End, self._cursor.KeepAnchor) elif value == 1: # delete start of line self._cursor.movePosition(self._cursor.Start, self._cursor.KeepAnchor) else: # delete whole line self._cursor.movePosition(self._cursor.Start) self._cursor.movePosition(self._cursor.End, self._cursor.KeepAnchor) self._cursor.removeSelectedText() self._last_cursor_pos = self._cursor.position()
python
def _erase_display(self, value): """ Erases display. """ if value == 0: # delete end of line self._cursor.movePosition(self._cursor.End, self._cursor.KeepAnchor) elif value == 1: # delete start of line self._cursor.movePosition(self._cursor.Start, self._cursor.KeepAnchor) else: # delete whole line self._cursor.movePosition(self._cursor.Start) self._cursor.movePosition(self._cursor.End, self._cursor.KeepAnchor) self._cursor.removeSelectedText() self._last_cursor_pos = self._cursor.position()
[ "def", "_erase_display", "(", "self", ",", "value", ")", ":", "if", "value", "==", "0", ":", "# delete end of line", "self", ".", "_cursor", ".", "movePosition", "(", "self", ".", "_cursor", ".", "End", ",", "self", ".", "_cursor", ".", "KeepAnchor", ")"...
Erases display.
[ "Erases", "display", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1375-L1390
train
46,447
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._cursor_back
def _cursor_back(self, value): """ Moves the cursor back. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Left, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
python
def _cursor_back(self, value): """ Moves the cursor back. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Left, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
[ "def", "_cursor_back", "(", "self", ",", "value", ")", ":", "if", "value", "<=", "0", ":", "value", "=", "1", "self", ".", "_cursor", ".", "movePosition", "(", "self", ".", "_cursor", ".", "Left", ",", "self", ".", "_cursor", ".", "MoveAnchor", ",", ...
Moves the cursor back.
[ "Moves", "the", "cursor", "back", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1392-L1400
train
46,448
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._cursor_forward
def _cursor_forward(self, value): """ Moves the cursor forward. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
python
def _cursor_forward(self, value): """ Moves the cursor forward. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
[ "def", "_cursor_forward", "(", "self", ",", "value", ")", ":", "if", "value", "<=", "0", ":", "value", "=", "1", "self", ".", "_cursor", ".", "movePosition", "(", "self", ".", "_cursor", ".", "Right", ",", "self", ".", "_cursor", ".", "MoveAnchor", "...
Moves the cursor forward.
[ "Moves", "the", "cursor", "forward", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1402-L1410
train
46,449
pyQode/pyqode.core
pyqode/core/widgets/output_window.py
OutputFormatter._delete_chars
def _delete_chars(self, value): """ Deletes the specified number of charachters. """ value = int(value) if value <= 0: value = 1 for i in range(value): self._cursor.deleteChar() self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
python
def _delete_chars(self, value): """ Deletes the specified number of charachters. """ value = int(value) if value <= 0: value = 1 for i in range(value): self._cursor.deleteChar() self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.position()
[ "def", "_delete_chars", "(", "self", ",", "value", ")", ":", "value", "=", "int", "(", "value", ")", "if", "value", "<=", "0", ":", "value", "=", "1", "for", "i", "in", "range", "(", "value", ")", ":", "self", ".", "_cursor", ".", "deleteChar", "...
Deletes the specified number of charachters.
[ "Deletes", "the", "specified", "number", "of", "charachters", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/output_window.py#L1412-L1422
train
46,450
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
get_package_info
def get_package_info(package): """Gets the PyPI information for a given package.""" url = 'https://pypi.python.org/pypi/{}/json'.format(package) r = requests.get(url) r.raise_for_status() return r.json()
python
def get_package_info(package): """Gets the PyPI information for a given package.""" url = 'https://pypi.python.org/pypi/{}/json'.format(package) r = requests.get(url) r.raise_for_status() return r.json()
[ "def", "get_package_info", "(", "package", ")", ":", "url", "=", "'https://pypi.python.org/pypi/{}/json'", ".", "format", "(", "package", ")", "r", "=", "requests", ".", "get", "(", "url", ")", "r", ".", "raise_for_status", "(", ")", "return", "r", ".", "j...
Gets the PyPI information for a given package.
[ "Gets", "the", "PyPI", "information", "for", "a", "given", "package", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L30-L35
train
46,451
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
read_requirements
def read_requirements(req_file): """Reads a requirements file. Args: req_file (str): Filename of requirements file """ items = list(parse_requirements(req_file, session={})) result = [] for item in items: # Get line number from item line_number = item.comes_from.split(req_file + ' (line ')[1][:-1] if item.req: item.req.marker = item.markers result.append((item.req, line_number)) else: result.append((item, line_number)) return result
python
def read_requirements(req_file): """Reads a requirements file. Args: req_file (str): Filename of requirements file """ items = list(parse_requirements(req_file, session={})) result = [] for item in items: # Get line number from item line_number = item.comes_from.split(req_file + ' (line ')[1][:-1] if item.req: item.req.marker = item.markers result.append((item.req, line_number)) else: result.append((item, line_number)) return result
[ "def", "read_requirements", "(", "req_file", ")", ":", "items", "=", "list", "(", "parse_requirements", "(", "req_file", ",", "session", "=", "{", "}", ")", ")", "result", "=", "[", "]", "for", "item", "in", "items", ":", "# Get line number from item", "li...
Reads a requirements file. Args: req_file (str): Filename of requirements file
[ "Reads", "a", "requirements", "file", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L38-L56
train
46,452
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
_is_version_range
def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' else: # "foo > 2.0, < 3.0" return True
python
def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' else: # "foo > 2.0, < 3.0" return True
[ "def", "_is_version_range", "(", "req", ")", ":", "assert", "len", "(", "req", ".", "specifier", ")", ">", "0", "specs", "=", "list", "(", "req", ".", "specifier", ")", "if", "len", "(", "specs", ")", "==", "1", ":", "# \"foo > 2.0\" or \"foo == 2.4.3\""...
Returns true if requirements specify a version range.
[ "Returns", "true", "if", "requirements", "specify", "a", "version", "range", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L72-L82
train
46,453
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
update_req
def update_req(req): """Updates a given req object with the latest version.""" if not req.name: return req, None info = get_package_info(req.name) if info['info'].get('_pypi_hidden'): print('{} is hidden on PyPI and will not be updated.'.format(req)) return req, None if _is_pinned(req) and _is_version_range(req): print('{} is pinned to a range and will not be updated.'.format(req)) return req, None newest_version = _get_newest_version(info) current_spec = next(iter(req.specifier)) if req.specifier else None current_version = current_spec.version if current_spec else None new_spec = Specifier(u'=={}'.format(newest_version)) if not current_spec or current_spec._spec != new_spec._spec: req.specifier = new_spec update_info = ( req.name, current_version, newest_version) return req, update_info return req, None
python
def update_req(req): """Updates a given req object with the latest version.""" if not req.name: return req, None info = get_package_info(req.name) if info['info'].get('_pypi_hidden'): print('{} is hidden on PyPI and will not be updated.'.format(req)) return req, None if _is_pinned(req) and _is_version_range(req): print('{} is pinned to a range and will not be updated.'.format(req)) return req, None newest_version = _get_newest_version(info) current_spec = next(iter(req.specifier)) if req.specifier else None current_version = current_spec.version if current_spec else None new_spec = Specifier(u'=={}'.format(newest_version)) if not current_spec or current_spec._spec != new_spec._spec: req.specifier = new_spec update_info = ( req.name, current_version, newest_version) return req, update_info return req, None
[ "def", "update_req", "(", "req", ")", ":", "if", "not", "req", ".", "name", ":", "return", "req", ",", "None", "info", "=", "get_package_info", "(", "req", ".", "name", ")", "if", "info", "[", "'info'", "]", ".", "get", "(", "'_pypi_hidden'", ")", ...
Updates a given req object with the latest version.
[ "Updates", "a", "given", "req", "object", "with", "the", "latest", "version", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L85-L112
train
46,454
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
write_requirements
def write_requirements(reqs_linenum, req_file): """Writes a list of req objects out to a given file.""" with open(req_file, 'r') as input: lines = input.readlines() for req in reqs_linenum: line_num = int(req[1]) if hasattr(req[0], 'link'): lines[line_num - 1] = '{}\n'.format(req[0].link) else: lines[line_num - 1] = '{}\n'.format(req[0]) with open(req_file, 'w') as output: output.writelines(lines)
python
def write_requirements(reqs_linenum, req_file): """Writes a list of req objects out to a given file.""" with open(req_file, 'r') as input: lines = input.readlines() for req in reqs_linenum: line_num = int(req[1]) if hasattr(req[0], 'link'): lines[line_num - 1] = '{}\n'.format(req[0].link) else: lines[line_num - 1] = '{}\n'.format(req[0]) with open(req_file, 'w') as output: output.writelines(lines)
[ "def", "write_requirements", "(", "reqs_linenum", ",", "req_file", ")", ":", "with", "open", "(", "req_file", ",", "'r'", ")", "as", "input", ":", "lines", "=", "input", ".", "readlines", "(", ")", "for", "req", "in", "reqs_linenum", ":", "line_num", "="...
Writes a list of req objects out to a given file.
[ "Writes", "a", "list", "of", "req", "objects", "out", "to", "a", "given", "file", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L115-L129
train
46,455
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
check_req
def check_req(req): """Checks if a given req is the latest version available.""" if not isinstance(req, Requirement): return None info = get_package_info(req.name) newest_version = _get_newest_version(info) if _is_pinned(req) and _is_version_range(req): return None current_spec = next(iter(req.specifier)) if req.specifier else None current_version = current_spec.version if current_spec else None if current_version != newest_version: return req.name, current_version, newest_version
python
def check_req(req): """Checks if a given req is the latest version available.""" if not isinstance(req, Requirement): return None info = get_package_info(req.name) newest_version = _get_newest_version(info) if _is_pinned(req) and _is_version_range(req): return None current_spec = next(iter(req.specifier)) if req.specifier else None current_version = current_spec.version if current_spec else None if current_version != newest_version: return req.name, current_version, newest_version
[ "def", "check_req", "(", "req", ")", ":", "if", "not", "isinstance", "(", "req", ",", "Requirement", ")", ":", "return", "None", "info", "=", "get_package_info", "(", "req", ".", "name", ")", "newest_version", "=", "_get_newest_version", "(", "info", ")", ...
Checks if a given req is the latest version available.
[ "Checks", "if", "a", "given", "req", "is", "the", "latest", "version", "available", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L132-L146
train
46,456
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
check_requirements_file
def check_requirements_file(req_file, skip_packages): """Return list of outdated requirements. Args: req_file (str): Filename of requirements file skip_packages (list): List of package names to ignore. """ reqs = read_requirements(req_file) if skip_packages is not None: reqs = [req for req in reqs if req.name not in skip_packages] outdated_reqs = filter(None, [check_req(req) for req in reqs]) return outdated_reqs
python
def check_requirements_file(req_file, skip_packages): """Return list of outdated requirements. Args: req_file (str): Filename of requirements file skip_packages (list): List of package names to ignore. """ reqs = read_requirements(req_file) if skip_packages is not None: reqs = [req for req in reqs if req.name not in skip_packages] outdated_reqs = filter(None, [check_req(req) for req in reqs]) return outdated_reqs
[ "def", "check_requirements_file", "(", "req_file", ",", "skip_packages", ")", ":", "reqs", "=", "read_requirements", "(", "req_file", ")", "if", "skip_packages", "is", "not", "None", ":", "reqs", "=", "[", "req", "for", "req", "in", "reqs", "if", "req", "....
Return list of outdated requirements. Args: req_file (str): Filename of requirements file skip_packages (list): List of package names to ignore.
[ "Return", "list", "of", "outdated", "requirements", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L162-L173
train
46,457
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
update_command
def update_command(args): """Updates all dependencies the specified requirements file.""" updated = update_requirements_file( args.requirements_file, args.skip_packages) if updated: print('Updated requirements in {}:'.format(args.requirements_file)) for item in updated: print(' * {} from {} to {}.'.format(*item)) else: print('All dependencies in {} are up-to-date.'.format( args.requirements_file))
python
def update_command(args): """Updates all dependencies the specified requirements file.""" updated = update_requirements_file( args.requirements_file, args.skip_packages) if updated: print('Updated requirements in {}:'.format(args.requirements_file)) for item in updated: print(' * {} from {} to {}.'.format(*item)) else: print('All dependencies in {} are up-to-date.'.format( args.requirements_file))
[ "def", "update_command", "(", "args", ")", ":", "updated", "=", "update_requirements_file", "(", "args", ".", "requirements_file", ",", "args", ".", "skip_packages", ")", "if", "updated", ":", "print", "(", "'Updated requirements in {}:'", ".", "format", "(", "a...
Updates all dependencies the specified requirements file.
[ "Updates", "all", "dependencies", "the", "specified", "requirements", "file", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L176-L188
train
46,458
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
check_command
def check_command(args): """Checks that all dependencies in the specified requirements file are up to date.""" outdated = check_requirements_file(args.requirements_file, args.skip_packages) if outdated: print('Requirements in {} are out of date:'.format( args.requirements_file)) for item in outdated: print(' * {} is {} latest is {}.'.format(*item)) sys.exit(1) else: print('Requirements in {} are up to date.'.format( args.requirements_file))
python
def check_command(args): """Checks that all dependencies in the specified requirements file are up to date.""" outdated = check_requirements_file(args.requirements_file, args.skip_packages) if outdated: print('Requirements in {} are out of date:'.format( args.requirements_file)) for item in outdated: print(' * {} is {} latest is {}.'.format(*item)) sys.exit(1) else: print('Requirements in {} are up to date.'.format( args.requirements_file))
[ "def", "check_command", "(", "args", ")", ":", "outdated", "=", "check_requirements_file", "(", "args", ".", "requirements_file", ",", "args", ".", "skip_packages", ")", "if", "outdated", ":", "print", "(", "'Requirements in {} are out of date:'", ".", "format", "...
Checks that all dependencies in the specified requirements file are up to date.
[ "Checks", "that", "all", "dependencies", "in", "the", "specified", "requirements", "file", "are", "up", "to", "date", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L191-L207
train
46,459
pyQode/pyqode.core
pyqode/core/panels/encodings.py
EncodingPanel.paintEvent
def paintEvent(self, event): """ Fills the panel background. """ super(EncodingPanel, self).paintEvent(event) if self.isVisible(): # fill background painter = QtGui.QPainter(self) self._background_brush = QtGui.QBrush(self._color) painter.fillRect(event.rect(), self._background_brush)
python
def paintEvent(self, event): """ Fills the panel background. """ super(EncodingPanel, self).paintEvent(event) if self.isVisible(): # fill background painter = QtGui.QPainter(self) self._background_brush = QtGui.QBrush(self._color) painter.fillRect(event.rect(), self._background_brush)
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "super", "(", "EncodingPanel", ",", "self", ")", ".", "paintEvent", "(", "event", ")", "if", "self", ".", "isVisible", "(", ")", ":", "# fill background", "painter", "=", "QtGui", ".", "QPainter",...
Fills the panel background.
[ "Fills", "the", "panel", "background", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/encodings.py#L157-L164
train
46,460
pyQode/pyqode.core
pyqode/core/api/syntax_highlighter.py
ColorScheme._get_format_from_style
def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() items = list(style.style_for_token(token).items()) for key, value in items: if value is None and key == 'color': # make sure to use a default visible color for the foreground # brush value = drift_color(self.background, 1000).name() if value: if key == 'color': result.setForeground(self._get_brush(value)) elif key == 'bgcolor': result.setBackground(self._get_brush(value)) elif key == 'bold': result.setFontWeight(QtGui.QFont.Bold) elif key == 'italic': result.setFontItalic(value) elif key == 'underline': result.setUnderlineStyle( QtGui.QTextCharFormat.SingleUnderline) elif key == 'sans': result.setFontStyleHint(QtGui.QFont.SansSerif) elif key == 'roman': result.setFontStyleHint(QtGui.QFont.Times) elif key == 'mono': result.setFontStyleHint(QtGui.QFont.TypeWriter) if token in [Token.Literal.String, Token.Literal.String.Doc, Token.Comment]: # mark strings, comments and docstrings regions for further queries result.setObjectType(result.UserObject) return result
python
def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() items = list(style.style_for_token(token).items()) for key, value in items: if value is None and key == 'color': # make sure to use a default visible color for the foreground # brush value = drift_color(self.background, 1000).name() if value: if key == 'color': result.setForeground(self._get_brush(value)) elif key == 'bgcolor': result.setBackground(self._get_brush(value)) elif key == 'bold': result.setFontWeight(QtGui.QFont.Bold) elif key == 'italic': result.setFontItalic(value) elif key == 'underline': result.setUnderlineStyle( QtGui.QTextCharFormat.SingleUnderline) elif key == 'sans': result.setFontStyleHint(QtGui.QFont.SansSerif) elif key == 'roman': result.setFontStyleHint(QtGui.QFont.Times) elif key == 'mono': result.setFontStyleHint(QtGui.QFont.TypeWriter) if token in [Token.Literal.String, Token.Literal.String.Doc, Token.Comment]: # mark strings, comments and docstrings regions for further queries result.setObjectType(result.UserObject) return result
[ "def", "_get_format_from_style", "(", "self", ",", "token", ",", "style", ")", ":", "result", "=", "QtGui", ".", "QTextCharFormat", "(", ")", "items", "=", "list", "(", "style", ".", "style_for_token", "(", "token", ")", ".", "items", "(", ")", ")", "f...
Returns a QTextCharFormat for token by reading a Pygments style.
[ "Returns", "a", "QTextCharFormat", "for", "token", "by", "reading", "a", "Pygments", "style", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/syntax_highlighter.py#L144-L176
train
46,461
pyQode/pyqode.core
pyqode/core/api/syntax_highlighter.py
SyntaxHighlighter.rehighlight
def rehighlight(self): """ Rehighlight the entire document, may be slow. """ start = time.time() QtWidgets.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) try: super(SyntaxHighlighter, self).rehighlight() except RuntimeError: # cloned widget, no need to rehighlight the same document twice ;) pass QtWidgets.QApplication.restoreOverrideCursor() end = time.time() _logger().debug('rehighlight duration: %fs' % (end - start))
python
def rehighlight(self): """ Rehighlight the entire document, may be slow. """ start = time.time() QtWidgets.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) try: super(SyntaxHighlighter, self).rehighlight() except RuntimeError: # cloned widget, no need to rehighlight the same document twice ;) pass QtWidgets.QApplication.restoreOverrideCursor() end = time.time() _logger().debug('rehighlight duration: %fs' % (end - start))
[ "def", "rehighlight", "(", "self", ")", ":", "start", "=", "time", ".", "time", "(", ")", "QtWidgets", ".", "QApplication", ".", "setOverrideCursor", "(", "QtGui", ".", "QCursor", "(", "QtCore", ".", "Qt", ".", "WaitCursor", ")", ")", "try", ":", "supe...
Rehighlight the entire document, may be slow.
[ "Rehighlight", "the", "entire", "document", "may", "be", "slow", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/syntax_highlighter.py#L349-L363
train
46,462
pyQode/pyqode.core
pyqode/core/panels/line_number.py
LineNumberPanel.line_number_area_width
def line_number_area_width(self): """ Computes the lineNumber area width depending on the number of lines in the document :return: Widtg """ digits = 1 count = max(1, self.editor.blockCount()) while count >= 10: count /= 10 digits += 1 space = 5 + self.editor.fontMetrics().width("9") * digits return space
python
def line_number_area_width(self): """ Computes the lineNumber area width depending on the number of lines in the document :return: Widtg """ digits = 1 count = max(1, self.editor.blockCount()) while count >= 10: count /= 10 digits += 1 space = 5 + self.editor.fontMetrics().width("9") * digits return space
[ "def", "line_number_area_width", "(", "self", ")", ":", "digits", "=", "1", "count", "=", "max", "(", "1", ",", "self", ".", "editor", ".", "blockCount", "(", ")", ")", "while", "count", ">=", "10", ":", "count", "/=", "10", "digits", "+=", "1", "s...
Computes the lineNumber area width depending on the number of lines in the document :return: Widtg
[ "Computes", "the", "lineNumber", "area", "width", "depending", "on", "the", "number", "of", "lines", "in", "the", "document" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/line_number.py#L30-L43
train
46,463
pyQode/pyqode.core
pyqode/core/widgets/outline.py
OutlineTreeWidget.set_editor
def set_editor(self, editor): """ Sets the current editor. The widget display the structure of that editor. :param editor: CodeEdit """ try: self._editor.cursorPositionChanged.disconnect(self.sync) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass try: self._outline_mode.document_changed.disconnect( self._on_changed) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass try: self._folding_panel.trigger_state_changed.disconnect( self._on_block_state_changed) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass if editor: self._editor = weakref.proxy(editor) else: self._editor = None if editor is not None: editor.cursorPositionChanged.connect(self.sync) try: self._folding_panel = weakref.proxy( editor.panels.get(FoldingPanel)) except KeyError: pass else: self._folding_panel.trigger_state_changed.connect( self._on_block_state_changed) try: analyser = editor.modes.get(OutlineMode) except KeyError: self._outline_mode = None else: self._outline_mode = weakref.proxy(analyser) analyser.document_changed.connect(self._on_changed) self._on_changed()
python
def set_editor(self, editor): """ Sets the current editor. The widget display the structure of that editor. :param editor: CodeEdit """ try: self._editor.cursorPositionChanged.disconnect(self.sync) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass try: self._outline_mode.document_changed.disconnect( self._on_changed) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass try: self._folding_panel.trigger_state_changed.disconnect( self._on_block_state_changed) except (AttributeError, TypeError, RuntimeError, ReferenceError): pass if editor: self._editor = weakref.proxy(editor) else: self._editor = None if editor is not None: editor.cursorPositionChanged.connect(self.sync) try: self._folding_panel = weakref.proxy( editor.panels.get(FoldingPanel)) except KeyError: pass else: self._folding_panel.trigger_state_changed.connect( self._on_block_state_changed) try: analyser = editor.modes.get(OutlineMode) except KeyError: self._outline_mode = None else: self._outline_mode = weakref.proxy(analyser) analyser.document_changed.connect(self._on_changed) self._on_changed()
[ "def", "set_editor", "(", "self", ",", "editor", ")", ":", "try", ":", "self", ".", "_editor", ".", "cursorPositionChanged", ".", "disconnect", "(", "self", ".", "sync", ")", "except", "(", "AttributeError", ",", "TypeError", ",", "RuntimeError", ",", "Ref...
Sets the current editor. The widget display the structure of that editor. :param editor: CodeEdit
[ "Sets", "the", "current", "editor", ".", "The", "widget", "display", "the", "structure", "of", "that", "editor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/outline.py#L62-L105
train
46,464
pyQode/pyqode.core
pyqode/core/widgets/outline.py
OutlineTreeWidget._on_changed
def _on_changed(self): """ Update the tree items """ self._updating = True to_collapse = [] self.clear() if self._editor and self._outline_mode and self._folding_panel: items, to_collapse = self.to_tree_widget_items( self._outline_mode.definitions, to_collapse=to_collapse) if len(items): self.addTopLevelItems(items) self.expandAll() for item in reversed(to_collapse): self.collapseItem(item) self._updating = False return # no data root = QtWidgets.QTreeWidgetItem() root.setText(0, _('No data')) root.setIcon(0, icons.icon( 'dialog-information', ':/pyqode-icons/rc/dialog-info.png', 'fa.info-circle')) self.addTopLevelItem(root) self._updating = False self.sync()
python
def _on_changed(self): """ Update the tree items """ self._updating = True to_collapse = [] self.clear() if self._editor and self._outline_mode and self._folding_panel: items, to_collapse = self.to_tree_widget_items( self._outline_mode.definitions, to_collapse=to_collapse) if len(items): self.addTopLevelItems(items) self.expandAll() for item in reversed(to_collapse): self.collapseItem(item) self._updating = False return # no data root = QtWidgets.QTreeWidgetItem() root.setText(0, _('No data')) root.setIcon(0, icons.icon( 'dialog-information', ':/pyqode-icons/rc/dialog-info.png', 'fa.info-circle')) self.addTopLevelItem(root) self._updating = False self.sync()
[ "def", "_on_changed", "(", "self", ")", ":", "self", ".", "_updating", "=", "True", "to_collapse", "=", "[", "]", "self", ".", "clear", "(", ")", "if", "self", ".", "_editor", "and", "self", ".", "_outline_mode", "and", "self", ".", "_folding_panel", "...
Update the tree items
[ "Update", "the", "tree", "items" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/outline.py#L136-L162
train
46,465
pyQode/pyqode.core
pyqode/core/widgets/outline.py
OutlineTreeWidget._on_item_clicked
def _on_item_clicked(self, item): """ Go to the item position in the editor. """ if item: name = item.data(0, QtCore.Qt.UserRole) if name: go = name.block.blockNumber() helper = TextHelper(self._editor) if helper.current_line_nbr() != go: helper.goto_line(go, column=name.column) self._editor.setFocus()
python
def _on_item_clicked(self, item): """ Go to the item position in the editor. """ if item: name = item.data(0, QtCore.Qt.UserRole) if name: go = name.block.blockNumber() helper = TextHelper(self._editor) if helper.current_line_nbr() != go: helper.goto_line(go, column=name.column) self._editor.setFocus()
[ "def", "_on_item_clicked", "(", "self", ",", "item", ")", ":", "if", "item", ":", "name", "=", "item", ".", "data", "(", "0", ",", "QtCore", ".", "Qt", ".", "UserRole", ")", "if", "name", ":", "go", "=", "name", ".", "block", ".", "blockNumber", ...
Go to the item position in the editor.
[ "Go", "to", "the", "item", "position", "in", "the", "editor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/outline.py#L164-L175
train
46,466
pyQode/pyqode.core
pyqode/core/widgets/outline.py
OutlineTreeWidget.to_tree_widget_items
def to_tree_widget_items(self, definitions, to_collapse=None): """ Converts the list of top level definitions to a list of top level tree items. """ def flatten(definitions): """ Flattens the document structure tree as a simple sequential list. """ ret_val = [] for de in definitions: ret_val.append(de) for sub_d in de.children: ret_val.append(sub_d) ret_val += flatten(sub_d.children) return ret_val def convert(name, editor, to_collapse): ti = QtWidgets.QTreeWidgetItem() ti.setText(0, name.name) if isinstance(name.icon, list): icon = QtGui.QIcon.fromTheme( name.icon[0], QtGui.QIcon(name.icon[1])) else: icon = QtGui.QIcon(name.icon) ti.setIcon(0, icon) name.block = editor.document().findBlockByNumber(name.line) ti.setData(0, QtCore.Qt.UserRole, name) ti.setToolTip(0, name.description) name.tree_item = ti block_data = name.block.userData() if block_data is None: block_data = TextBlockUserData() name.block.setUserData(block_data) block_data.tree_item = ti if to_collapse is not None and \ TextBlockHelper.is_collapsed(name.block): to_collapse.append(ti) for ch in name.children: ti_ch, to_collapse = convert(ch, editor, to_collapse) if ti_ch: ti.addChild(ti_ch) return ti, to_collapse self._definitions = definitions self._flattened_defs = flatten(self._definitions) items = [] for d in definitions: value, to_collapse = convert(d, self._editor, to_collapse) items.append(value) if to_collapse is not None: return items, to_collapse return items
python
def to_tree_widget_items(self, definitions, to_collapse=None): """ Converts the list of top level definitions to a list of top level tree items. """ def flatten(definitions): """ Flattens the document structure tree as a simple sequential list. """ ret_val = [] for de in definitions: ret_val.append(de) for sub_d in de.children: ret_val.append(sub_d) ret_val += flatten(sub_d.children) return ret_val def convert(name, editor, to_collapse): ti = QtWidgets.QTreeWidgetItem() ti.setText(0, name.name) if isinstance(name.icon, list): icon = QtGui.QIcon.fromTheme( name.icon[0], QtGui.QIcon(name.icon[1])) else: icon = QtGui.QIcon(name.icon) ti.setIcon(0, icon) name.block = editor.document().findBlockByNumber(name.line) ti.setData(0, QtCore.Qt.UserRole, name) ti.setToolTip(0, name.description) name.tree_item = ti block_data = name.block.userData() if block_data is None: block_data = TextBlockUserData() name.block.setUserData(block_data) block_data.tree_item = ti if to_collapse is not None and \ TextBlockHelper.is_collapsed(name.block): to_collapse.append(ti) for ch in name.children: ti_ch, to_collapse = convert(ch, editor, to_collapse) if ti_ch: ti.addChild(ti_ch) return ti, to_collapse self._definitions = definitions self._flattened_defs = flatten(self._definitions) items = [] for d in definitions: value, to_collapse = convert(d, self._editor, to_collapse) items.append(value) if to_collapse is not None: return items, to_collapse return items
[ "def", "to_tree_widget_items", "(", "self", ",", "definitions", ",", "to_collapse", "=", "None", ")", ":", "def", "flatten", "(", "definitions", ")", ":", "\"\"\"\n Flattens the document structure tree as a simple sequential list.\n \"\"\"", "ret_val", "...
Converts the list of top level definitions to a list of top level tree items.
[ "Converts", "the", "list", "of", "top", "level", "definitions", "to", "a", "list", "of", "top", "level", "tree", "items", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/outline.py#L177-L233
train
46,467
pyQode/pyqode.core
pyqode/core/modes/matcher.py
SymbolMatcherMode.do_symbols_matching
def do_symbols_matching(self): """ Performs symbols matching. """ self._clear_decorations() current_block = self.editor.textCursor().block() data = get_block_symbol_data(self.editor, current_block) pos = self.editor.textCursor().block().position() for symbol in [PAREN, SQUARE, BRACE]: self._match(symbol, data, pos)
python
def do_symbols_matching(self): """ Performs symbols matching. """ self._clear_decorations() current_block = self.editor.textCursor().block() data = get_block_symbol_data(self.editor, current_block) pos = self.editor.textCursor().block().position() for symbol in [PAREN, SQUARE, BRACE]: self._match(symbol, data, pos)
[ "def", "do_symbols_matching", "(", "self", ")", ":", "self", ".", "_clear_decorations", "(", ")", "current_block", "=", "self", ".", "editor", ".", "textCursor", "(", ")", ".", "block", "(", ")", "data", "=", "get_block_symbol_data", "(", "self", ".", "edi...
Performs symbols matching.
[ "Performs", "symbols", "matching", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/matcher.py#L229-L238
train
46,468
pyQode/pyqode.core
pyqode/core/widgets/prompt_line_edit.py
PromptLineEdit.set_button_visible
def set_button_visible(self, visible): """ Sets the clear button as ``visible`` :param visible: Visible state (True = visible, False = hidden). """ self.button.setVisible(visible) left, top, right, bottom = self.getTextMargins() if visible: right = self._margin + self._spacing else: right = 0 self.setTextMargins(left, top, right, bottom)
python
def set_button_visible(self, visible): """ Sets the clear button as ``visible`` :param visible: Visible state (True = visible, False = hidden). """ self.button.setVisible(visible) left, top, right, bottom = self.getTextMargins() if visible: right = self._margin + self._spacing else: right = 0 self.setTextMargins(left, top, right, bottom)
[ "def", "set_button_visible", "(", "self", ",", "visible", ")", ":", "self", ".", "button", ".", "setVisible", "(", "visible", ")", "left", ",", "top", ",", "right", ",", "bottom", "=", "self", ".", "getTextMargins", "(", ")", "if", "visible", ":", "rig...
Sets the clear button as ``visible`` :param visible: Visible state (True = visible, False = hidden).
[ "Sets", "the", "clear", "button", "as", "visible" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/prompt_line_edit.py#L98-L110
train
46,469
pyQode/pyqode.core
pyqode/core/backend/server.py
import_class
def import_class(klass): """ Imports a class from a fully qualified name string. :param klass: class string, e.g. "pyqode.core.backend.workers.CodeCompletionWorker" :return: The corresponding class """ path = klass.rfind(".") class_name = klass[path + 1: len(klass)] try: module = __import__(klass[0:path], globals(), locals(), [class_name]) klass = getattr(module, class_name) except ImportError as e: raise ImportError('%s: %s' % (klass, str(e))) except AttributeError: raise ImportError(klass) else: return klass
python
def import_class(klass): """ Imports a class from a fully qualified name string. :param klass: class string, e.g. "pyqode.core.backend.workers.CodeCompletionWorker" :return: The corresponding class """ path = klass.rfind(".") class_name = klass[path + 1: len(klass)] try: module = __import__(klass[0:path], globals(), locals(), [class_name]) klass = getattr(module, class_name) except ImportError as e: raise ImportError('%s: %s' % (klass, str(e))) except AttributeError: raise ImportError(klass) else: return klass
[ "def", "import_class", "(", "klass", ")", ":", "path", "=", "klass", ".", "rfind", "(", "\".\"", ")", "class_name", "=", "klass", "[", "path", "+", "1", ":", "len", "(", "klass", ")", "]", "try", ":", "module", "=", "__import__", "(", "klass", "[",...
Imports a class from a fully qualified name string. :param klass: class string, e.g. "pyqode.core.backend.workers.CodeCompletionWorker" :return: The corresponding class
[ "Imports", "a", "class", "from", "a", "fully", "qualified", "name", "string", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/backend/server.py#L33-L52
train
46,470
pyQode/pyqode.core
pyqode/core/backend/server.py
serve_forever
def serve_forever(args=None): """ Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments. """ class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) sys.stdout = Unbuffered(sys.stdout) sys.stderr = Unbuffered(sys.stderr) server = JsonServer(args=args) server.serve_forever()
python
def serve_forever(args=None): """ Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments. """ class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) sys.stdout = Unbuffered(sys.stdout) sys.stderr = Unbuffered(sys.stderr) server = JsonServer(args=args) server.serve_forever()
[ "def", "serve_forever", "(", "args", "=", "None", ")", ":", "class", "Unbuffered", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "stream", ")", ":", "self", ".", "stream", "=", "stream", "def", "write", "(", "self", ",", "data", ")", ...
Creates the server and serves forever :param args: Optional args if you decided to use your own argument parser. Default is None to let the JsonServer setup its own parser and parse command line arguments.
[ "Creates", "the", "server", "and", "serves", "forever" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/backend/server.py#L207-L230
train
46,471
pyQode/pyqode.core
pyqode/core/modes/case_converter.py
CaseConverterMode._create_actions
def _create_actions(self): """ Create associated actions """ self.action_to_lower = QtWidgets.QAction(self.editor) self.action_to_lower.triggered.connect(self.to_lower) self.action_to_upper = QtWidgets.QAction(self.editor) self.action_to_upper.triggered.connect(self.to_upper) self.action_to_lower.setText(_('Convert to lower case')) self.action_to_lower.setShortcut('Ctrl+U') self.action_to_upper.setText(_('Convert to UPPER CASE')) self.action_to_upper.setShortcut('Ctrl+Shift+U') self.menu = QtWidgets.QMenu(_('Case'), self.editor) self.menu.addAction(self.action_to_lower) self.menu.addAction(self.action_to_upper) self._actions_created = True
python
def _create_actions(self): """ Create associated actions """ self.action_to_lower = QtWidgets.QAction(self.editor) self.action_to_lower.triggered.connect(self.to_lower) self.action_to_upper = QtWidgets.QAction(self.editor) self.action_to_upper.triggered.connect(self.to_upper) self.action_to_lower.setText(_('Convert to lower case')) self.action_to_lower.setShortcut('Ctrl+U') self.action_to_upper.setText(_('Convert to UPPER CASE')) self.action_to_upper.setShortcut('Ctrl+Shift+U') self.menu = QtWidgets.QMenu(_('Case'), self.editor) self.menu.addAction(self.action_to_lower) self.menu.addAction(self.action_to_upper) self._actions_created = True
[ "def", "_create_actions", "(", "self", ")", ":", "self", ".", "action_to_lower", "=", "QtWidgets", ".", "QAction", "(", "self", ".", "editor", ")", "self", ".", "action_to_lower", ".", "triggered", ".", "connect", "(", "self", ".", "to_lower", ")", "self",...
Create associated actions
[ "Create", "associated", "actions" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/case_converter.py#L37-L50
train
46,472
pyQode/pyqode.core
pyqode/core/modes/wordclick.py
WordClickMode._select_word_cursor
def _select_word_cursor(self): """ Selects the word under the mouse cursor. """ cursor = TextHelper(self.editor).word_under_mouse_cursor() if (self._previous_cursor_start != cursor.selectionStart() and self._previous_cursor_end != cursor.selectionEnd()): self._remove_decoration() self._add_decoration(cursor) self._previous_cursor_start = cursor.selectionStart() self._previous_cursor_end = cursor.selectionEnd()
python
def _select_word_cursor(self): """ Selects the word under the mouse cursor. """ cursor = TextHelper(self.editor).word_under_mouse_cursor() if (self._previous_cursor_start != cursor.selectionStart() and self._previous_cursor_end != cursor.selectionEnd()): self._remove_decoration() self._add_decoration(cursor) self._previous_cursor_start = cursor.selectionStart() self._previous_cursor_end = cursor.selectionEnd()
[ "def", "_select_word_cursor", "(", "self", ")", ":", "cursor", "=", "TextHelper", "(", "self", ".", "editor", ")", ".", "word_under_mouse_cursor", "(", ")", "if", "(", "self", ".", "_previous_cursor_start", "!=", "cursor", ".", "selectionStart", "(", ")", "a...
Selects the word under the mouse cursor.
[ "Selects", "the", "word", "under", "the", "mouse", "cursor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/wordclick.py#L60-L68
train
46,473
pyQode/pyqode.core
pyqode/core/modes/wordclick.py
WordClickMode._on_mouse_released
def _on_mouse_released(self, event): """ mouse pressed callback """ if event.button() == 1 and self._deco: cursor = TextHelper(self.editor).word_under_mouse_cursor() if cursor and cursor.selectedText(): self._timer.request_job( self.word_clicked.emit, cursor)
python
def _on_mouse_released(self, event): """ mouse pressed callback """ if event.button() == 1 and self._deco: cursor = TextHelper(self.editor).word_under_mouse_cursor() if cursor and cursor.selectedText(): self._timer.request_job( self.word_clicked.emit, cursor)
[ "def", "_on_mouse_released", "(", "self", ",", "event", ")", ":", "if", "event", ".", "button", "(", ")", "==", "1", "and", "self", ".", "_deco", ":", "cursor", "=", "TextHelper", "(", "self", ".", "editor", ")", ".", "word_under_mouse_cursor", "(", ")...
mouse pressed callback
[ "mouse", "pressed", "callback" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/wordclick.py#L94-L100
train
46,474
pyQode/pyqode.core
pyqode/core/modes/wordclick.py
WordClickMode._remove_decoration
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
python
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
[ "def", "_remove_decoration", "(", "self", ")", ":", "if", "self", ".", "_deco", "is", "not", "None", ":", "self", ".", "editor", ".", "decorations", ".", "remove", "(", "self", ".", "_deco", ")", "self", ".", "_deco", "=", "None" ]
Removes the word under cursor's decoration
[ "Removes", "the", "word", "under", "cursor", "s", "decoration" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/wordclick.py#L119-L125
train
46,475
pyQode/pyqode.core
pyqode/core/panels/global_checker.py
GlobalCheckerPanel._draw_messages
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)
python
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)
[ "def", "_draw_messages", "(", "self", ",", "painter", ")", ":", "checker_modes", "=", "[", "]", "for", "m", "in", "self", ".", "editor", ".", "modes", ":", "if", "isinstance", "(", "m", ",", "modes", ".", "CheckerMode", ")", ":", "checker_modes", ".", ...
Draw messages from all subclass of CheckerMode currently installed on the editor. :type painter: QtGui.QPainter
[ "Draw", "messages", "from", "all", "subclass", "of", "CheckerMode", "currently", "installed", "on", "the", "editor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/global_checker.py#L21-L41
train
46,476
pyQode/pyqode.core
pyqode/core/panels/global_checker.py
GlobalCheckerPanel._draw_visible_area
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)
python
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)
[ "def", "_draw_visible_area", "(", "self", ",", "painter", ")", ":", "if", "self", ".", "editor", ".", "visible_blocks", ":", "start", "=", "self", ".", "editor", ".", "visible_blocks", "[", "0", "]", "[", "-", "1", "]", "end", "=", "self", ".", "edit...
Draw the visible area. This method does not take folded blocks into account. :type painter: QtGui.QPainter
[ "Draw", "the", "visible", "area", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/global_checker.py#L43-L64
train
46,477
pyQode/pyqode.core
pyqode/core/panels/global_checker.py
GlobalCheckerPanel.get_marker_height
def get_marker_height(self): """ Gets the height of message marker. """ return self.editor.viewport().height() / TextHelper( self.editor).line_count()
python
def get_marker_height(self): """ Gets the height of message marker. """ return self.editor.viewport().height() / TextHelper( self.editor).line_count()
[ "def", "get_marker_height", "(", "self", ")", ":", "return", "self", ".", "editor", ".", "viewport", "(", ")", ".", "height", "(", ")", "/", "TextHelper", "(", "self", ".", "editor", ")", ".", "line_count", "(", ")" ]
Gets the height of message marker.
[ "Gets", "the", "height", "of", "message", "marker", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/global_checker.py#L85-L90
train
46,478
pyQode/pyqode.core
pyqode/core/widgets/file_icons_provider.py
FileIconProvider.mimetype_icon
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')
python
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')
[ "def", "mimetype_icon", "(", "path", ",", "fallback", "=", "None", ")", ":", "mime", "=", "mimetypes", ".", "guess_type", "(", "path", ")", "[", "0", "]", "if", "mime", ":", "icon", "=", "mime", ".", "replace", "(", "'/'", ",", "'-'", ")", "# if sy...
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.
[ "Tries", "to", "create", "an", "icon", "from", "theme", "using", "the", "file", "mimetype", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/file_icons_provider.py#L13-L37
train
46,479
psphere-project/psphere
examples/connect.py
main
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()
python
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()
[ "def", "main", "(", "options", ")", ":", "client", "=", "Client", "(", "server", "=", "options", ".", "server", ",", "username", "=", "options", ".", "username", ",", "password", "=", "options", ".", "password", ")", "print", "(", "'Successfully connected ...
A simple connection test to login and print the server time.
[ "A", "simple", "connection", "test", "to", "login", "and", "print", "the", "server", "time", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/examples/connect.py#L21-L28
train
46,480
pyQode/pyqode.core
pyqode/core/tools/console.py
main
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)
python
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)
[ "def", "main", "(", ")", ":", "global", "program", ",", "args", ",", "ret", "print", "(", "os", ".", "getcwd", "(", ")", ")", "ret", "=", "0", "if", "'--help'", "in", "sys", ".", "argv", "or", "'-h'", "in", "sys", ".", "argv", "or", "len", "(",...
pyqode-console main function.
[ "pyqode", "-", "console", "main", "function", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/tools/console.py#L23-L45
train
46,481
fmenabe/python-dokuwiki
doc/source/conf.py
linkcode_resolve
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
python
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
[ "def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "module_name", "=", "info", "[", "'module'", "]", "fullname", "=", "info", "[", "'fullname'", "]", "attribute_name", "=", "fullname", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "b...
A simple function to find matching source code.
[ "A", "simple", "function", "to", "find", "matching", "source", "code", "." ]
7b5b13b764912b36f49a03a445c88f0934260eb1
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/doc/source/conf.py#L48-L96
train
46,482
pyQode/pyqode.core
pyqode/core/managers/backend.py
BackendManager.pick_free_port
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
python
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
[ "def", "pick_free_port", "(", ")", ":", "test_socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "test_socket", ".", "bind", "(", "(", "'127.0.0.1'", ",", "0", ")", ")", "free_port", "=", "int", ...
Picks a free port
[ "Picks", "a", "free", "port" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/backend.py#L57-L63
train
46,483
pyQode/pyqode.core
pyqode/core/managers/backend.py
BackendManager.start
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()
python
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()
[ "def", "start", "(", "self", ",", "script", ",", "interpreter", "=", "sys", ".", "executable", ",", "args", "=", "None", ",", "error_callback", "=", "None", ",", "reuse", "=", "False", ")", ":", "self", ".", "_shared", "=", "reuse", "if", "reuse", "a...
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).
[ "Starts", "the", "backend", "process", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/backend.py#L65-L126
train
46,484
pyQode/pyqode.core
pyqode/core/managers/backend.py
BackendManager.stop
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')
python
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')
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_process", "is", "None", ":", "return", "if", "self", ".", "_shared", ":", "BackendManager", ".", "SHARE_COUNT", "-=", "1", "if", "BackendManager", ".", "SHARE_COUNT", ":", "return", "comm", "(", ...
Stops the backend process.
[ "Stops", "the", "backend", "process", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/backend.py#L128-L159
train
46,485
pyQode/pyqode.core
pyqode/core/managers/backend.py
BackendManager.running
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
python
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
[ "def", "running", "(", "self", ")", ":", "try", ":", "return", "(", "self", ".", "_process", "is", "not", "None", "and", "self", ".", "_process", ".", "state", "(", ")", "!=", "self", ".", "_process", ".", "NotRunning", ")", "except", "RuntimeError", ...
Tells whether the backend process is running. :return: True if the process is running, otherwise False
[ "Tells", "whether", "the", "backend", "process", "is", "running", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/backend.py#L211-L221
train
46,486
pyQode/pyqode.core
pyqode/core/widgets/menu_recents.py
MenuRecentFiles.update_actions
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)
python
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)
[ "def", "update_actions", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "recent_files_actions", "[", ":", "]", "=", "[", "]", "for", "file", "in", "self", ".", "manager", ".", "get_recent_files", "(", ")", ":", "action", "=", "Qt...
Updates the list of actions.
[ "Updates", "the", "list", "of", "actions", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/menu_recents.py#L168-L196
train
46,487
pyQode/pyqode.core
pyqode/core/widgets/menu_recents.py
MenuRecentFiles.clear_recent_files
def clear_recent_files(self): """ Clear recent files and menu. """ self.manager.clear() self.update_actions() self.clear_requested.emit()
python
def clear_recent_files(self): """ Clear recent files and menu. """ self.manager.clear() self.update_actions() self.clear_requested.emit()
[ "def", "clear_recent_files", "(", "self", ")", ":", "self", ".", "manager", ".", "clear", "(", ")", "self", ".", "update_actions", "(", ")", "self", ".", "clear_requested", ".", "emit", "(", ")" ]
Clear recent files and menu.
[ "Clear", "recent", "files", "and", "menu", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/menu_recents.py#L198-L202
train
46,488
pyQode/pyqode.core
pyqode/core/widgets/menu_recents.py
MenuRecentFiles._on_action_triggered
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()
python
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()
[ "def", "_on_action_triggered", "(", "self", ")", ":", "action", "=", "self", ".", "sender", "(", ")", "assert", "isinstance", "(", "action", ",", "QtWidgets", ".", "QAction", ")", "path", "=", "action", ".", "data", "(", ")", "self", ".", "open_requested...
Emits open_requested when a recent file action has been triggered.
[ "Emits", "open_requested", "when", "a", "recent", "file", "action", "has", "been", "triggered", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/menu_recents.py#L204-L212
train
46,489
pyQode/pyqode.core
pyqode/core/icons.py
icon
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
python
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
[ "def", "icon", "(", "theme_name", "=", "''", ",", "path", "=", "''", ",", "qta_name", "=", "''", ",", "qta_options", "=", "None", ",", "use_qta", "=", "None", ")", ":", "ret_val", "=", "None", "if", "use_qta", "is", "None", ":", "use_qta", "=", "US...
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
[ "Creates", "an", "icon", "from", "qtawesome", "from", "theme", "or", "from", "path", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/icons.py#L29-L57
train
46,490
pyQode/pyqode.core
pyqode/core/api/decoration.py
TextDecoration.set_outline
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))
python
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))
[ "def", "set_outline", "(", "self", ",", "color", ")", ":", "self", ".", "format", ".", "setProperty", "(", "QtGui", ".", "QTextFormat", ".", "OutlinePen", ",", "QtGui", ".", "QPen", "(", "color", ")", ")" ]
Uses an outline rectangle. :param color: Color of the outline rect :type color: QtGui.QColor
[ "Uses", "an", "outline", "rectangle", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/decoration.py#L114-L122
train
46,491
doloopwhile/Python-CoffeeScript
coffeescript/__init__.py
Compiler.compile
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})
python
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})
[ "def", "compile", "(", "self", ",", "script", ",", "bare", "=", "False", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_context'", ")", ":", "self", ".", "_context", "=", "self", ".", "_runtime", ".", "compile", "(", "self", ".", "_compiler_s...
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).
[ "compile", "a", "CoffeeScript", "code", "to", "a", "JavaScript", "code", "." ]
9ca0c861c7c2e5c4ecd2dad7dc9010a15a4fb404
https://github.com/doloopwhile/Python-CoffeeScript/blob/9ca0c861c7c2e5c4ecd2dad7dc9010a15a4fb404/coffeescript/__init__.py#L73-L82
train
46,492
doloopwhile/Python-CoffeeScript
coffeescript/__init__.py
Compiler.compile_file
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)
python
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)
[ "def", "compile_file", "(", "self", ",", "filename", ",", "encoding", "=", "\"utf-8\"", ",", "bare", "=", "False", ")", ":", "if", "isinstance", "(", "filename", ",", "_BaseString", ")", ":", "filename", "=", "[", "filename", "]", "scripts", "=", "[", ...
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).
[ "compile", "a", "CoffeeScript", "script", "file", "to", "a", "JavaScript", "code", "." ]
9ca0c861c7c2e5c4ecd2dad7dc9010a15a4fb404
https://github.com/doloopwhile/Python-CoffeeScript/blob/9ca0c861c7c2e5c4ecd2dad7dc9010a15a4fb404/coffeescript/__init__.py#L84-L101
train
46,493
pyQode/pyqode.core
examples/notepad/notepad/main_window.py
MainWindow.setup_actions
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)
python
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)
[ "def", "setup_actions", "(", "self", ")", ":", "self", ".", "actionOpen", ".", "triggered", ".", "connect", "(", "self", ".", "on_open", ")", "self", ".", "actionNew", ".", "triggered", ".", "connect", "(", "self", ".", "on_new", ")", "self", ".", "act...
Connects slots to signals
[ "Connects", "slots", "to", "signals" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/examples/notepad/notepad/main_window.py#L54-L63
train
46,494
pyQode/pyqode.core
examples/notepad/notepad/main_window.py
MainWindow.setup_recent_files_menu
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)
python
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)
[ "def", "setup_recent_files_menu", "(", "self", ")", ":", "self", ".", "recent_files_manager", "=", "widgets", ".", "RecentFilesManager", "(", "'pyQode'", ",", "'notepad'", ")", "self", ".", "menu_recents", "=", "widgets", ".", "MenuRecentFiles", "(", "self", "."...
Setup the recent files menu and manager
[ "Setup", "the", "recent", "files", "menu", "and", "manager" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/examples/notepad/notepad/main_window.py#L65-L74
train
46,495
pyQode/pyqode.core
examples/notepad/notepad/main_window.py
MainWindow.setup_mimetypes
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())
python
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())
[ "def", "setup_mimetypes", "(", "self", ")", ":", "# setup some specific mimetypes", "mimetypes", ".", "add_type", "(", "'text/xml'", ",", "'.ui'", ")", "# qt designer forms forms", "mimetypes", ".", "add_type", "(", "'text/x-rst'", ",", "'.rst'", ")", "# rst docs", ...
Setup additional mime types.
[ "Setup", "additional", "mime", "types", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/examples/notepad/notepad/main_window.py#L76-L93
train
46,496
pyQode/pyqode.core
examples/notepad/notepad/main_window.py
MainWindow.open_file
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()
python
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()
[ "def", "open_file", "(", "self", ",", "path", ")", ":", "if", "path", ":", "editor", "=", "self", ".", "tabWidget", ".", "open_document", "(", "path", ")", "editor", ".", "cursorPositionChanged", ".", "connect", "(", "self", ".", "on_cursor_pos_changed", "...
Creates a new GenericCodeEdit, opens the requested file and adds it to the tab widget. :param path: Path of the file to open
[ "Creates", "a", "new", "GenericCodeEdit", "opens", "the", "requested", "file", "and", "adds", "it", "to", "the", "tab", "widget", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/examples/notepad/notepad/main_window.py#L144-L156
train
46,497
pyQode/pyqode.core
examples/notepad/notepad/main_window.py
MainWindow.on_new
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()
python
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()
[ "def", "on_new", "(", "self", ")", ":", "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
[ "Add", "a", "new", "empty", "code", "editor", "to", "the", "tab", "widget" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/examples/notepad/notepad/main_window.py#L158-L164
train
46,498
pyQode/pyqode.core
examples/notepad/notepad/main_window.py
MainWindow.on_open
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)
python
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)
[ "def", "on_open", "(", "self", ")", ":", "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.
[ "Shows", "an", "open", "file", "dialog", "and", "open", "the", "file", "if", "the", "dialog", "was", "accepted", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/examples/notepad/notepad/main_window.py#L166-L175
train
46,499