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
examples/notepad/notepad/main_window.py
MainWindow.on_save_as
def on_save_as(self): """ Save the current editor document as. """ self.tabWidget.save_current_as() self._update_status_bar(self.tabWidget.current_widget())
python
def on_save_as(self): """ Save the current editor document as. """ self.tabWidget.save_current_as() self._update_status_bar(self.tabWidget.current_widget())
[ "def", "on_save_as", "(", "self", ")", ":", "self", ".", "tabWidget", ".", "save_current_as", "(", ")", "self", ".", "_update_status_bar", "(", "self", ".", "tabWidget", ".", "current_widget", "(", ")", ")" ]
Save the current editor document as.
[ "Save", "the", "current", "editor", "document", "as", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/examples/notepad/notepad/main_window.py#L181-L186
train
46,500
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
BaseTabWidget.close_all
def close_all(self): """ Closes all editors """ if self._try_close_dirty_tabs(): while self.count(): widget = self.widget(0) self.remove_tab(0) self.tab_closed.emit(widget) return True return False
python
def close_all(self): """ Closes all editors """ if self._try_close_dirty_tabs(): while self.count(): widget = self.widget(0) self.remove_tab(0) self.tab_closed.emit(widget) return True return False
[ "def", "close_all", "(", "self", ")", ":", "if", "self", ".", "_try_close_dirty_tabs", "(", ")", ":", "while", "self", ".", "count", "(", ")", ":", "widget", "=", "self", ".", "widget", "(", "0", ")", "self", ".", "remove_tab", "(", "0", ")", "self...
Closes all editors
[ "Closes", "all", "editors" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L215-L225
train
46,501
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
BaseTabWidget._close_widget
def _close_widget(widget): """ Closes the given widgets and handles cases where the widget has been clone or is a clone of another widget """ if widget is None: return try: widget.document().setParent(None) widget.syntax_highlighter.setParent(None) except AttributeError: pass # not a QPlainTextEdit subclass # handled cloned widgets clones = [] if hasattr(widget, 'original') and widget.original: # cloned widget needs to be removed from the original widget.original.clones.remove(widget) try: widget.setDocument(None) except AttributeError: # not a QTextEdit/QPlainTextEdit pass elif hasattr(widget, 'clones'): clones = widget.clones try: # only clear current editor if it does not have any other clones widget.close(clear=len(clones) == 0) except (AttributeError, TypeError): # not a CodeEdit widget.close() return clones
python
def _close_widget(widget): """ Closes the given widgets and handles cases where the widget has been clone or is a clone of another widget """ if widget is None: return try: widget.document().setParent(None) widget.syntax_highlighter.setParent(None) except AttributeError: pass # not a QPlainTextEdit subclass # handled cloned widgets clones = [] if hasattr(widget, 'original') and widget.original: # cloned widget needs to be removed from the original widget.original.clones.remove(widget) try: widget.setDocument(None) except AttributeError: # not a QTextEdit/QPlainTextEdit pass elif hasattr(widget, 'clones'): clones = widget.clones try: # only clear current editor if it does not have any other clones widget.close(clear=len(clones) == 0) except (AttributeError, TypeError): # not a CodeEdit widget.close() return clones
[ "def", "_close_widget", "(", "widget", ")", ":", "if", "widget", "is", "None", ":", "return", "try", ":", "widget", ".", "document", "(", ")", ".", "setParent", "(", "None", ")", "widget", ".", "syntax_highlighter", ".", "setParent", "(", "None", ")", ...
Closes the given widgets and handles cases where the widget has been clone or is a clone of another widget
[ "Closes", "the", "given", "widgets", "and", "handles", "cases", "where", "the", "widget", "has", "been", "clone", "or", "is", "a", "clone", "of", "another", "widget" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L453-L483
train
46,502
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
BaseTabWidget.remove_tab
def remove_tab(self, index): """ Overrides removeTab to emit tab_closed and last_tab_closed signals. :param index: index of the tab to remove. """ widget = self.widget(index) try: document = widget.document() except AttributeError: document = None # not a QPlainTextEdit clones = self._close_widget(widget) self.tab_closed.emit(widget) self.removeTab(index) self._restore_original(clones) widget._original_tab_widget._tabs.remove(widget) if self.count() == 0: self.last_tab_closed.emit() if SplittableTabWidget.tab_under_menu == widget: SplittableTabWidget.tab_under_menu = None if not clones: widget.setParent(None) else: try: clones[0].syntax_highlighter.setDocument(document) except AttributeError: pass
python
def remove_tab(self, index): """ Overrides removeTab to emit tab_closed and last_tab_closed signals. :param index: index of the tab to remove. """ widget = self.widget(index) try: document = widget.document() except AttributeError: document = None # not a QPlainTextEdit clones = self._close_widget(widget) self.tab_closed.emit(widget) self.removeTab(index) self._restore_original(clones) widget._original_tab_widget._tabs.remove(widget) if self.count() == 0: self.last_tab_closed.emit() if SplittableTabWidget.tab_under_menu == widget: SplittableTabWidget.tab_under_menu = None if not clones: widget.setParent(None) else: try: clones[0].syntax_highlighter.setDocument(document) except AttributeError: pass
[ "def", "remove_tab", "(", "self", ",", "index", ")", ":", "widget", "=", "self", ".", "widget", "(", "index", ")", "try", ":", "document", "=", "widget", ".", "document", "(", ")", "except", "AttributeError", ":", "document", "=", "None", "# not a QPlain...
Overrides removeTab to emit tab_closed and last_tab_closed signals. :param index: index of the tab to remove.
[ "Overrides", "removeTab", "to", "emit", "tab_closed", "and", "last_tab_closed", "signals", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L497-L523
train
46,503
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
BaseTabWidget._on_split_requested
def _on_split_requested(self): """ Emits the split requested signal with the desired orientation. """ orientation = self.sender().text() widget = self.widget(self.tab_under_menu()) if 'horizontally' in orientation: self.split_requested.emit( widget, QtCore.Qt.Horizontal) else: self.split_requested.emit( widget, QtCore.Qt.Vertical)
python
def _on_split_requested(self): """ Emits the split requested signal with the desired orientation. """ orientation = self.sender().text() widget = self.widget(self.tab_under_menu()) if 'horizontally' in orientation: self.split_requested.emit( widget, QtCore.Qt.Horizontal) else: self.split_requested.emit( widget, QtCore.Qt.Vertical)
[ "def", "_on_split_requested", "(", "self", ")", ":", "orientation", "=", "self", ".", "sender", "(", ")", ".", "text", "(", ")", "widget", "=", "self", ".", "widget", "(", "self", ".", "tab_under_menu", "(", ")", ")", "if", "'horizontally'", "in", "ori...
Emits the split requested signal with the desired orientation.
[ "Emits", "the", "split", "requested", "signal", "with", "the", "desired", "orientation", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L525-L536
train
46,504
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
BaseTabWidget.addTab
def addTab(self, tab, *args): """ Adds a tab to the tab widget, this function set the parent_tab_widget attribute on the tab instance. """ tab.parent_tab_widget = self super(BaseTabWidget, self).addTab(tab, *args)
python
def addTab(self, tab, *args): """ Adds a tab to the tab widget, this function set the parent_tab_widget attribute on the tab instance. """ tab.parent_tab_widget = self super(BaseTabWidget, self).addTab(tab, *args)
[ "def", "addTab", "(", "self", ",", "tab", ",", "*", "args", ")", ":", "tab", ".", "parent_tab_widget", "=", "self", "super", "(", "BaseTabWidget", ",", "self", ")", ".", "addTab", "(", "tab", ",", "*", "args", ")" ]
Adds a tab to the tab widget, this function set the parent_tab_widget attribute on the tab instance.
[ "Adds", "a", "tab", "to", "the", "tab", "widget", "this", "function", "set", "the", "parent_tab_widget", "attribute", "on", "the", "tab", "instance", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L571-L577
train
46,505
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
SplittableTabWidget.add_context_action
def add_context_action(self, action): """ Adds a custom context menu action :param action: action to add. """ self.main_tab_widget.context_actions.append(action) for child_splitter in self.child_splitters: child_splitter.add_context_action(action)
python
def add_context_action(self, action): """ Adds a custom context menu action :param action: action to add. """ self.main_tab_widget.context_actions.append(action) for child_splitter in self.child_splitters: child_splitter.add_context_action(action)
[ "def", "add_context_action", "(", "self", ",", "action", ")", ":", "self", ".", "main_tab_widget", ".", "context_actions", ".", "append", "(", "action", ")", "for", "child_splitter", "in", "self", ".", "child_splitters", ":", "child_splitter", ".", "add_context_...
Adds a custom context menu action :param action: action to add.
[ "Adds", "a", "custom", "context", "menu", "action" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L749-L757
train
46,506
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
SplittableTabWidget.add_tab
def add_tab(self, tab, title='', icon=None): """ Adds a tab to main tab widget. :param tab: Widget to add as a new tab of the main tab widget. :param title: Tab title :param icon: Tab icon """ if icon: tab._icon = icon if not hasattr(tab, 'clones'): tab.clones = [] if not hasattr(tab, 'original'): tab.original = None if icon: self.main_tab_widget.addTab(tab, icon, title) else: self.main_tab_widget.addTab(tab, title) self.main_tab_widget.setCurrentIndex( self.main_tab_widget.indexOf(tab)) self.main_tab_widget.show() tab._uuid = self._uuid try: scroll_bar = tab.horizontalScrollBar() except AttributeError: # not a QPlainTextEdit class pass else: scroll_bar.setValue(0) tab.setFocus() tab._original_tab_widget = self self._tabs.append(tab) self._on_focus_changed(None, tab)
python
def add_tab(self, tab, title='', icon=None): """ Adds a tab to main tab widget. :param tab: Widget to add as a new tab of the main tab widget. :param title: Tab title :param icon: Tab icon """ if icon: tab._icon = icon if not hasattr(tab, 'clones'): tab.clones = [] if not hasattr(tab, 'original'): tab.original = None if icon: self.main_tab_widget.addTab(tab, icon, title) else: self.main_tab_widget.addTab(tab, title) self.main_tab_widget.setCurrentIndex( self.main_tab_widget.indexOf(tab)) self.main_tab_widget.show() tab._uuid = self._uuid try: scroll_bar = tab.horizontalScrollBar() except AttributeError: # not a QPlainTextEdit class pass else: scroll_bar.setValue(0) tab.setFocus() tab._original_tab_widget = self self._tabs.append(tab) self._on_focus_changed(None, tab)
[ "def", "add_tab", "(", "self", ",", "tab", ",", "title", "=", "''", ",", "icon", "=", "None", ")", ":", "if", "icon", ":", "tab", ".", "_icon", "=", "icon", "if", "not", "hasattr", "(", "tab", ",", "'clones'", ")", ":", "tab", ".", "clones", "=...
Adds a tab to main tab widget. :param tab: Widget to add as a new tab of the main tab widget. :param title: Tab title :param icon: Tab icon
[ "Adds", "a", "tab", "to", "main", "tab", "widget", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L759-L791
train
46,507
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
SplittableTabWidget.split
def split(self, widget, orientation): """ Split the the current widget in new SplittableTabWidget. :param widget: widget to split :param orientation: orientation of the splitter :return: the new splitter """ if widget.original: base = widget.original else: base = widget clone = base.split() if not clone: return if orientation == int(QtCore.Qt.Horizontal): orientation = QtCore.Qt.Horizontal else: orientation = QtCore.Qt.Vertical self.setOrientation(orientation) splitter = self._make_splitter() splitter.show() self.addWidget(splitter) self.child_splitters.append(splitter) if clone not in base.clones: # code editors maintain the list of clones internally but some # other widgets (user widgets) might not. base.clones.append(clone) clone.original = base splitter._parent_splitter = self splitter.last_tab_closed.connect(self._on_last_child_tab_closed) splitter.tab_detached.connect(self.tab_detached.emit) if hasattr(base, '_icon'): icon = base._icon else: icon = None # same group of tab splitter (user might have a group for editors and # another group for consoles or whatever). splitter._uuid = self._uuid splitter.add_tab(clone, title=self.main_tab_widget.tabText( self.main_tab_widget.indexOf(widget)), icon=icon) self.setSizes([1 for i in range(self.count())]) return splitter
python
def split(self, widget, orientation): """ Split the the current widget in new SplittableTabWidget. :param widget: widget to split :param orientation: orientation of the splitter :return: the new splitter """ if widget.original: base = widget.original else: base = widget clone = base.split() if not clone: return if orientation == int(QtCore.Qt.Horizontal): orientation = QtCore.Qt.Horizontal else: orientation = QtCore.Qt.Vertical self.setOrientation(orientation) splitter = self._make_splitter() splitter.show() self.addWidget(splitter) self.child_splitters.append(splitter) if clone not in base.clones: # code editors maintain the list of clones internally but some # other widgets (user widgets) might not. base.clones.append(clone) clone.original = base splitter._parent_splitter = self splitter.last_tab_closed.connect(self._on_last_child_tab_closed) splitter.tab_detached.connect(self.tab_detached.emit) if hasattr(base, '_icon'): icon = base._icon else: icon = None # same group of tab splitter (user might have a group for editors and # another group for consoles or whatever). splitter._uuid = self._uuid splitter.add_tab(clone, title=self.main_tab_widget.tabText( self.main_tab_widget.indexOf(widget)), icon=icon) self.setSizes([1 for i in range(self.count())]) return splitter
[ "def", "split", "(", "self", ",", "widget", ",", "orientation", ")", ":", "if", "widget", ".", "original", ":", "base", "=", "widget", ".", "original", "else", ":", "base", "=", "widget", "clone", "=", "base", ".", "split", "(", ")", "if", "not", "...
Split the the current widget in new SplittableTabWidget. :param widget: widget to split :param orientation: orientation of the splitter :return: the new splitter
[ "Split", "the", "the", "current", "widget", "in", "new", "SplittableTabWidget", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L836-L878
train
46,508
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
SplittableTabWidget.widgets
def widgets(self, include_clones=False): """ Recursively gets the list of widgets. :param include_clones: True to retrieve all tabs, including clones, otherwise only original widgets are returned. """ widgets = [] for i in range(self.main_tab_widget.count()): widget = self.main_tab_widget.widget(i) try: if widget.original is None or include_clones: widgets.append(widget) except AttributeError: pass for child in self.child_splitters: widgets += child.widgets(include_clones=include_clones) return widgets
python
def widgets(self, include_clones=False): """ Recursively gets the list of widgets. :param include_clones: True to retrieve all tabs, including clones, otherwise only original widgets are returned. """ widgets = [] for i in range(self.main_tab_widget.count()): widget = self.main_tab_widget.widget(i) try: if widget.original is None or include_clones: widgets.append(widget) except AttributeError: pass for child in self.child_splitters: widgets += child.widgets(include_clones=include_clones) return widgets
[ "def", "widgets", "(", "self", ",", "include_clones", "=", "False", ")", ":", "widgets", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "main_tab_widget", ".", "count", "(", ")", ")", ":", "widget", "=", "self", ".", "main_tab_widget", "...
Recursively gets the list of widgets. :param include_clones: True to retrieve all tabs, including clones, otherwise only original widgets are returned.
[ "Recursively", "gets", "the", "list", "of", "widgets", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L900-L917
train
46,509
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
CodeEditTabWidget.get_filter
def get_filter(cls, mimetype): """ Returns a filter string for the file dialog. The filter is based on the mime type. :param mimetype: path from which the filter must be derived. :return: Filter string """ filters = ' '.join( ['*%s' % ext for ext in mimetypes.guess_all_extensions(mimetype)]) return '%s (%s)' % (mimetype, filters)
python
def get_filter(cls, mimetype): """ Returns a filter string for the file dialog. The filter is based on the mime type. :param mimetype: path from which the filter must be derived. :return: Filter string """ filters = ' '.join( ['*%s' % ext for ext in mimetypes.guess_all_extensions(mimetype)]) return '%s (%s)' % (mimetype, filters)
[ "def", "get_filter", "(", "cls", ",", "mimetype", ")", ":", "filters", "=", "' '", ".", "join", "(", "[", "'*%s'", "%", "ext", "for", "ext", "in", "mimetypes", ".", "guess_all_extensions", "(", "mimetype", ")", "]", ")", "return", "'%s (%s)'", "%", "("...
Returns a filter string for the file dialog. The filter is based on the mime type. :param mimetype: path from which the filter must be derived. :return: Filter string
[ "Returns", "a", "filter", "string", "for", "the", "file", "dialog", ".", "The", "filter", "is", "based", "on", "the", "mime", "type", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L993-L1003
train
46,510
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
CodeEditTabWidget.addTab
def addTab(self, widget, *args): """ Re-implements addTab to connect to the dirty changed signal and setup some helper attributes. :param widget: widget to add :param args: optional addtional arguments (name and/or icon). """ widget.dirty_changed.connect(self._on_dirty_changed) super(CodeEditTabWidget, self).addTab(widget, *args)
python
def addTab(self, widget, *args): """ Re-implements addTab to connect to the dirty changed signal and setup some helper attributes. :param widget: widget to add :param args: optional addtional arguments (name and/or icon). """ widget.dirty_changed.connect(self._on_dirty_changed) super(CodeEditTabWidget, self).addTab(widget, *args)
[ "def", "addTab", "(", "self", ",", "widget", ",", "*", "args", ")", ":", "widget", ".", "dirty_changed", ".", "connect", "(", "self", ".", "_on_dirty_changed", ")", "super", "(", "CodeEditTabWidget", ",", "self", ")", ".", "addTab", "(", "widget", ",", ...
Re-implements addTab to connect to the dirty changed signal and setup some helper attributes. :param widget: widget to add :param args: optional addtional arguments (name and/or icon).
[ "Re", "-", "implements", "addTab", "to", "connect", "to", "the", "dirty", "changed", "signal", "and", "setup", "some", "helper", "attributes", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L1005-L1014
train
46,511
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
CodeEditTabWidget._ask_path
def _ask_path(cls, editor): """ Shows a QFileDialog and ask for a save filename. :return: save filename """ try: filter = cls.get_filter(editor.mimetypes[0]) except IndexError: filter = _('All files (*)') return QtWidgets.QFileDialog.getSaveFileName( editor, _('Save file as'), cls.default_directory, filter)
python
def _ask_path(cls, editor): """ Shows a QFileDialog and ask for a save filename. :return: save filename """ try: filter = cls.get_filter(editor.mimetypes[0]) except IndexError: filter = _('All files (*)') return QtWidgets.QFileDialog.getSaveFileName( editor, _('Save file as'), cls.default_directory, filter)
[ "def", "_ask_path", "(", "cls", ",", "editor", ")", ":", "try", ":", "filter", "=", "cls", ".", "get_filter", "(", "editor", ".", "mimetypes", "[", "0", "]", ")", "except", "IndexError", ":", "filter", "=", "_", "(", "'All files (*)'", ")", "return", ...
Shows a QFileDialog and ask for a save filename. :return: save filename
[ "Shows", "a", "QFileDialog", "and", "ask", "for", "a", "save", "filename", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L1034-L1045
train
46,512
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
CodeEditTabWidget.save_widget
def save_widget(cls, editor): """ Implements SplittableTabWidget.save_widget to actually save the code editor widget. If the editor.file.path is None or empty or the file does not exist, a save as dialog is shown (save as). :param editor: editor widget to save. :return: False if there was a problem saving the editor (e.g. the save as dialog has been canceled by the user, or a permission error,...) """ if editor.original: editor = editor.original if editor.file.path is None or not os.path.exists(editor.file.path): # save as path, filter = cls._ask_path(editor) if not path: return False if not os.path.splitext(path)[1]: if len(editor.mimetypes): path += mimetypes.guess_extension(editor.mimetypes[0]) try: _logger().debug('saving %r as %r', editor.file._old_path, path) except AttributeError: _logger().debug('saving %r as %r', editor.file.path, path) editor.file._path = path else: path = editor.file.path try: editor.file.save(path) except Exception as e: QtWidgets.QMessageBox.warning(editor, "Failed to save file", 'Failed to save %r.\n\nError="%s"' % (path, e)) else: tw = editor.parent_tab_widget text = tw.tabText(tw.indexOf(editor)).replace('*', '') tw.setTabText(tw.indexOf(editor), text) for clone in [editor] + editor.clones: if clone != editor: tw = clone.parent_tab_widget tw.setTabText(tw.indexOf(clone), text) return True
python
def save_widget(cls, editor): """ Implements SplittableTabWidget.save_widget to actually save the code editor widget. If the editor.file.path is None or empty or the file does not exist, a save as dialog is shown (save as). :param editor: editor widget to save. :return: False if there was a problem saving the editor (e.g. the save as dialog has been canceled by the user, or a permission error,...) """ if editor.original: editor = editor.original if editor.file.path is None or not os.path.exists(editor.file.path): # save as path, filter = cls._ask_path(editor) if not path: return False if not os.path.splitext(path)[1]: if len(editor.mimetypes): path += mimetypes.guess_extension(editor.mimetypes[0]) try: _logger().debug('saving %r as %r', editor.file._old_path, path) except AttributeError: _logger().debug('saving %r as %r', editor.file.path, path) editor.file._path = path else: path = editor.file.path try: editor.file.save(path) except Exception as e: QtWidgets.QMessageBox.warning(editor, "Failed to save file", 'Failed to save %r.\n\nError="%s"' % (path, e)) else: tw = editor.parent_tab_widget text = tw.tabText(tw.indexOf(editor)).replace('*', '') tw.setTabText(tw.indexOf(editor), text) for clone in [editor] + editor.clones: if clone != editor: tw = clone.parent_tab_widget tw.setTabText(tw.indexOf(clone), text) return True
[ "def", "save_widget", "(", "cls", ",", "editor", ")", ":", "if", "editor", ".", "original", ":", "editor", "=", "editor", ".", "original", "if", "editor", ".", "file", ".", "path", "is", "None", "or", "not", "os", ".", "path", ".", "exists", "(", "...
Implements SplittableTabWidget.save_widget to actually save the code editor widget. If the editor.file.path is None or empty or the file does not exist, a save as dialog is shown (save as). :param editor: editor widget to save. :return: False if there was a problem saving the editor (e.g. the save as dialog has been canceled by the user, or a permission error,...)
[ "Implements", "SplittableTabWidget", ".", "save_widget", "to", "actually", "save", "the", "code", "editor", "widget", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L1048-L1090
train
46,513
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
SplittableCodeEditTabWidget.save_current_as
def save_current_as(self): """ Save current widget as. """ if not self.current_widget(): return mem = self.current_widget().file.path self.current_widget().file._path = None self.current_widget().file._old_path = mem CodeEditTabWidget.default_directory = os.path.dirname(mem) widget = self.current_widget() try: success = self.main_tab_widget.save_widget(widget) except Exception as e: QtWidgets.QMessageBox.warning( self, _('Failed to save file as'), _('Failed to save file as %s\nError=%s') % ( widget.file.path, str(e))) widget.file._path = mem else: if not success: widget.file._path = mem else: CodeEditTabWidget.default_directory = os.path.expanduser('~') self.document_saved.emit(widget.file.path, '') # rename tab tw = widget.parent_tab_widget tw.setTabText(tw.indexOf(widget), os.path.split(widget.file.path)[1]) return self.current_widget().file.path
python
def save_current_as(self): """ Save current widget as. """ if not self.current_widget(): return mem = self.current_widget().file.path self.current_widget().file._path = None self.current_widget().file._old_path = mem CodeEditTabWidget.default_directory = os.path.dirname(mem) widget = self.current_widget() try: success = self.main_tab_widget.save_widget(widget) except Exception as e: QtWidgets.QMessageBox.warning( self, _('Failed to save file as'), _('Failed to save file as %s\nError=%s') % ( widget.file.path, str(e))) widget.file._path = mem else: if not success: widget.file._path = mem else: CodeEditTabWidget.default_directory = os.path.expanduser('~') self.document_saved.emit(widget.file.path, '') # rename tab tw = widget.parent_tab_widget tw.setTabText(tw.indexOf(widget), os.path.split(widget.file.path)[1]) return self.current_widget().file.path
[ "def", "save_current_as", "(", "self", ")", ":", "if", "not", "self", ".", "current_widget", "(", ")", ":", "return", "mem", "=", "self", ".", "current_widget", "(", ")", ".", "file", ".", "path", "self", ".", "current_widget", "(", ")", ".", "file", ...
Save current widget as.
[ "Save", "current", "widget", "as", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L1204-L1235
train
46,514
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
SplittableCodeEditTabWidget.save_current
def save_current(self): """ Save current editor. If the editor.file.path is None, a save as dialog will be shown. """ if self.current_widget() is not None: editor = self.current_widget() self._save(editor)
python
def save_current(self): """ Save current editor. If the editor.file.path is None, a save as dialog will be shown. """ if self.current_widget() is not None: editor = self.current_widget() self._save(editor)
[ "def", "save_current", "(", "self", ")", ":", "if", "self", ".", "current_widget", "(", ")", "is", "not", "None", ":", "editor", "=", "self", ".", "current_widget", "(", ")", "self", ".", "_save", "(", "editor", ")" ]
Save current editor. If the editor.file.path is None, a save as dialog will be shown.
[ "Save", "current", "editor", ".", "If", "the", "editor", ".", "file", ".", "path", "is", "None", "a", "save", "as", "dialog", "will", "be", "shown", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L1237-L1244
train
46,515
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
SplittableCodeEditTabWidget.closeEvent
def closeEvent(self, event): """ Saves dirty editors on close and cancel the event if the user choosed to continue to work. :param event: close event """ dirty_widgets = [] for w in self.widgets(include_clones=False): if w.dirty: dirty_widgets.append(w) filenames = [] for w in dirty_widgets: if os.path.exists(w.file.path): filenames.append(w.file.path) else: filenames.append(w.documentTitle()) if len(filenames) == 0: self.close_all() return dlg = DlgUnsavedFiles(self, files=filenames) if dlg.exec_() == dlg.Accepted: if not dlg.discarded: for item in dlg.listWidget.selectedItems(): filename = item.text() widget = None for widget in dirty_widgets: if widget.file.path == filename or \ widget.documentTitle() == filename: break tw = widget.parent_tab_widget tw.save_widget(widget) tw.remove_tab(tw.indexOf(widget)) self.close_all() else: event.ignore()
python
def closeEvent(self, event): """ Saves dirty editors on close and cancel the event if the user choosed to continue to work. :param event: close event """ dirty_widgets = [] for w in self.widgets(include_clones=False): if w.dirty: dirty_widgets.append(w) filenames = [] for w in dirty_widgets: if os.path.exists(w.file.path): filenames.append(w.file.path) else: filenames.append(w.documentTitle()) if len(filenames) == 0: self.close_all() return dlg = DlgUnsavedFiles(self, files=filenames) if dlg.exec_() == dlg.Accepted: if not dlg.discarded: for item in dlg.listWidget.selectedItems(): filename = item.text() widget = None for widget in dirty_widgets: if widget.file.path == filename or \ widget.documentTitle() == filename: break tw = widget.parent_tab_widget tw.save_widget(widget) tw.remove_tab(tw.indexOf(widget)) self.close_all() else: event.ignore()
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "dirty_widgets", "=", "[", "]", "for", "w", "in", "self", ".", "widgets", "(", "include_clones", "=", "False", ")", ":", "if", "w", ".", "dirty", ":", "dirty_widgets", ".", "append", "(", "w",...
Saves dirty editors on close and cancel the event if the user choosed to continue to work. :param event: close event
[ "Saves", "dirty", "editors", "on", "close", "and", "cancel", "the", "event", "if", "the", "user", "choosed", "to", "continue", "to", "work", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L1483-L1518
train
46,516
pyQode/pyqode.core
pyqode/core/modes/code_completion.py
CodeCompletionMode._hide_popup
def _hide_popup(self): """ Hides the completer popup """ debug('hide popup') if (self._completer.popup() is not None and self._completer.popup().isVisible()): self._completer.popup().hide() self._last_cursor_column = -1 self._last_cursor_line = -1 QtWidgets.QToolTip.hideText()
python
def _hide_popup(self): """ Hides the completer popup """ debug('hide popup') if (self._completer.popup() is not None and self._completer.popup().isVisible()): self._completer.popup().hide() self._last_cursor_column = -1 self._last_cursor_line = -1 QtWidgets.QToolTip.hideText()
[ "def", "_hide_popup", "(", "self", ")", ":", "debug", "(", "'hide popup'", ")", "if", "(", "self", ".", "_completer", ".", "popup", "(", ")", "is", "not", "None", "and", "self", ".", "_completer", ".", "popup", "(", ")", ".", "isVisible", "(", ")", ...
Hides the completer popup
[ "Hides", "the", "completer", "popup" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/code_completion.py#L534-L544
train
46,517
pyQode/pyqode.core
pyqode/core/modes/code_completion.py
CodeCompletionMode._update_model
def _update_model(self, completions): """ Creates a QStandardModel that holds the suggestion from the completion models for the QCompleter :param completionPrefix: """ # build the completion model cc_model = QtGui.QStandardItemModel() self._tooltips.clear() for completion in completions: name = completion['name'] item = QtGui.QStandardItem() item.setData(name, QtCore.Qt.DisplayRole) if 'tooltip' in completion and completion['tooltip']: self._tooltips[name] = completion['tooltip'] if 'icon' in completion: icon = completion['icon'] if isinstance(icon, list): icon = QtGui.QIcon.fromTheme(icon[0], QtGui.QIcon(icon[1])) else: icon = QtGui.QIcon(icon) item.setData(QtGui.QIcon(icon), QtCore.Qt.DecorationRole) cc_model.appendRow(item) try: self._completer.setModel(cc_model) except RuntimeError: self._create_completer() self._completer.setModel(cc_model) return cc_model
python
def _update_model(self, completions): """ Creates a QStandardModel that holds the suggestion from the completion models for the QCompleter :param completionPrefix: """ # build the completion model cc_model = QtGui.QStandardItemModel() self._tooltips.clear() for completion in completions: name = completion['name'] item = QtGui.QStandardItem() item.setData(name, QtCore.Qt.DisplayRole) if 'tooltip' in completion and completion['tooltip']: self._tooltips[name] = completion['tooltip'] if 'icon' in completion: icon = completion['icon'] if isinstance(icon, list): icon = QtGui.QIcon.fromTheme(icon[0], QtGui.QIcon(icon[1])) else: icon = QtGui.QIcon(icon) item.setData(QtGui.QIcon(icon), QtCore.Qt.DecorationRole) cc_model.appendRow(item) try: self._completer.setModel(cc_model) except RuntimeError: self._create_completer() self._completer.setModel(cc_model) return cc_model
[ "def", "_update_model", "(", "self", ",", "completions", ")", ":", "# build the completion model", "cc_model", "=", "QtGui", ".", "QStandardItemModel", "(", ")", "self", ".", "_tooltips", ".", "clear", "(", ")", "for", "completion", "in", "completions", ":", "...
Creates a QStandardModel that holds the suggestion from the completion models for the QCompleter :param completionPrefix:
[ "Creates", "a", "QStandardModel", "that", "holds", "the", "suggestion", "from", "the", "completion", "models", "for", "the", "QCompleter" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/code_completion.py#L602-L632
train
46,518
psphere-project/psphere
psphere/soap.py
create
def create(client, _type, **kwargs): """Create a suds object of the requested _type.""" obj = client.factory.create("ns0:%s" % _type) for key, value in kwargs.items(): setattr(obj, key, value) return obj
python
def create(client, _type, **kwargs): """Create a suds object of the requested _type.""" obj = client.factory.create("ns0:%s" % _type) for key, value in kwargs.items(): setattr(obj, key, value) return obj
[ "def", "create", "(", "client", ",", "_type", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "client", ".", "factory", ".", "create", "(", "\"ns0:%s\"", "%", "_type", ")", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "...
Create a suds object of the requested _type.
[ "Create", "a", "suds", "object", "of", "the", "requested", "_type", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/soap.py#L48-L53
train
46,519
psphere-project/psphere
psphere/soap.py
invoke
def invoke(client, method, **kwargs): """Invoke a method on the underlying soap service.""" try: # Proxy the method to the suds service result = getattr(client.service, method)(**kwargs) except AttributeError: logger.critical("Unknown method: %s", method) raise except URLError as e: logger.debug(pprint(e)) logger.debug("A URL related error occurred while invoking the '%s' " "method on the VIM server, this can be caused by " "name resolution or connection problems.", method) logger.debug("The underlying error is: %s", e.reason[1]) raise except suds.client.TransportError as e: logger.debug(pprint(e)) logger.debug("TransportError: %s", e) except suds.WebFault as e: # Get the type of fault logger.critical("SUDS Fault: %s" % e.fault.faultstring) if len(e.fault.faultstring) > 0: raise detail = e.document.childAtPath("/Envelope/Body/Fault/detail") fault_type = detail.getChildren()[0].name fault = create(fault_type) if isinstance(e.fault.detail[0], list): for attr in e.fault.detail[0]: setattr(fault, attr[0], attr[1]) else: fault["text"] = e.fault.detail[0] raise VimFault(fault) return result
python
def invoke(client, method, **kwargs): """Invoke a method on the underlying soap service.""" try: # Proxy the method to the suds service result = getattr(client.service, method)(**kwargs) except AttributeError: logger.critical("Unknown method: %s", method) raise except URLError as e: logger.debug(pprint(e)) logger.debug("A URL related error occurred while invoking the '%s' " "method on the VIM server, this can be caused by " "name resolution or connection problems.", method) logger.debug("The underlying error is: %s", e.reason[1]) raise except suds.client.TransportError as e: logger.debug(pprint(e)) logger.debug("TransportError: %s", e) except suds.WebFault as e: # Get the type of fault logger.critical("SUDS Fault: %s" % e.fault.faultstring) if len(e.fault.faultstring) > 0: raise detail = e.document.childAtPath("/Envelope/Body/Fault/detail") fault_type = detail.getChildren()[0].name fault = create(fault_type) if isinstance(e.fault.detail[0], list): for attr in e.fault.detail[0]: setattr(fault, attr[0], attr[1]) else: fault["text"] = e.fault.detail[0] raise VimFault(fault) return result
[ "def", "invoke", "(", "client", ",", "method", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# Proxy the method to the suds service", "result", "=", "getattr", "(", "client", ".", "service", ",", "method", ")", "(", "*", "*", "kwargs", ")", "except", "...
Invoke a method on the underlying soap service.
[ "Invoke", "a", "method", "on", "the", "underlying", "soap", "service", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/soap.py#L56-L91
train
46,520
bmwcarit/zubbi
zubbi/utils.py
prettydate
def prettydate(date): now = datetime.now(timezone.utc) """ Return the relative timeframe between the given date and now. e.g. 'Just now', 'x days ago', 'x hours ago', ... When the difference is greater than 7 days, the timestamp will be returned instead. """ diff = now - date # Show the timestamp rather than the relative timeframe when the difference # is greater than 7 days if diff.days > 7: return date.strftime("%d. %b %Y") return arrow.get(date).humanize()
python
def prettydate(date): now = datetime.now(timezone.utc) """ Return the relative timeframe between the given date and now. e.g. 'Just now', 'x days ago', 'x hours ago', ... When the difference is greater than 7 days, the timestamp will be returned instead. """ diff = now - date # Show the timestamp rather than the relative timeframe when the difference # is greater than 7 days if diff.days > 7: return date.strftime("%d. %b %Y") return arrow.get(date).humanize()
[ "def", "prettydate", "(", "date", ")", ":", "now", "=", "datetime", ".", "now", "(", "timezone", ".", "utc", ")", "diff", "=", "now", "-", "date", "# Show the timestamp rather than the relative timeframe when the difference", "# is greater than 7 days", "if", "diff", ...
Return the relative timeframe between the given date and now. e.g. 'Just now', 'x days ago', 'x hours ago', ... When the difference is greater than 7 days, the timestamp will be returned instead.
[ "Return", "the", "relative", "timeframe", "between", "the", "given", "date", "and", "now", "." ]
b99dfd6113c0351f13876f4172648c2eb63468ba
https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/utils.py#L44-L59
train
46,521
psphere-project/psphere
examples/vidiscovery.py
Discovery.discovery
def discovery(self, compute_resource): """An example that discovers hosts and VMs in the inventory.""" # Find the first ClusterComputeResource if compute_resource is None: cr_list = ComputeResource.all(self.client) print("ERROR: You must specify a ComputeResource.") print("Available ComputeResource's:") for cr in cr_list: print(cr.name) sys.exit(1) try: ccr = ComputeResource.get(self.client, name=compute_resource) except ObjectNotFoundError: print("ERROR: Could not find ComputeResource with name %s" % compute_resource) sys.exit(1) print('Cluster: %s (%s hosts)' % (ccr.name, len(ccr.host))) ccr.preload("host", properties=["name", "vm"]) for host in ccr.host: print(' Host: %s (%s VMs)' % (host.name, len(host.vm))) # Get the vm views in one fell swoop host.preload("vm", properties=["name"]) for vm in host.vm: print(' VM: %s' % vm.name)
python
def discovery(self, compute_resource): """An example that discovers hosts and VMs in the inventory.""" # Find the first ClusterComputeResource if compute_resource is None: cr_list = ComputeResource.all(self.client) print("ERROR: You must specify a ComputeResource.") print("Available ComputeResource's:") for cr in cr_list: print(cr.name) sys.exit(1) try: ccr = ComputeResource.get(self.client, name=compute_resource) except ObjectNotFoundError: print("ERROR: Could not find ComputeResource with name %s" % compute_resource) sys.exit(1) print('Cluster: %s (%s hosts)' % (ccr.name, len(ccr.host))) ccr.preload("host", properties=["name", "vm"]) for host in ccr.host: print(' Host: %s (%s VMs)' % (host.name, len(host.vm))) # Get the vm views in one fell swoop host.preload("vm", properties=["name"]) for vm in host.vm: print(' VM: %s' % vm.name)
[ "def", "discovery", "(", "self", ",", "compute_resource", ")", ":", "# Find the first ClusterComputeResource", "if", "compute_resource", "is", "None", ":", "cr_list", "=", "ComputeResource", ".", "all", "(", "self", ".", "client", ")", "print", "(", "\"ERROR: You ...
An example that discovers hosts and VMs in the inventory.
[ "An", "example", "that", "discovers", "hosts", "and", "VMs", "in", "the", "inventory", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/examples/vidiscovery.py#L27-L53
train
46,522
bmwcarit/zubbi
zubbi/scraper/connections/github.py
GitHubConnection._get_app_auth_headers
def _get_app_auth_headers(self): """Set the correct auth headers to authenticate against GitHub.""" now = datetime.now(timezone.utc) expiry = now + timedelta(minutes=5) data = {"iat": now, "exp": expiry, "iss": self.app_id} app_token = jwt.encode(data, self.app_key, algorithm="RS256").decode("utf-8") headers = { "Accept": PREVIEW_JSON_ACCEPT, "Authorization": "Bearer {}".format(app_token), } return headers
python
def _get_app_auth_headers(self): """Set the correct auth headers to authenticate against GitHub.""" now = datetime.now(timezone.utc) expiry = now + timedelta(minutes=5) data = {"iat": now, "exp": expiry, "iss": self.app_id} app_token = jwt.encode(data, self.app_key, algorithm="RS256").decode("utf-8") headers = { "Accept": PREVIEW_JSON_ACCEPT, "Authorization": "Bearer {}".format(app_token), } return headers
[ "def", "_get_app_auth_headers", "(", "self", ")", ":", "now", "=", "datetime", ".", "now", "(", "timezone", ".", "utc", ")", "expiry", "=", "now", "+", "timedelta", "(", "minutes", "=", "5", ")", "data", "=", "{", "\"iat\"", ":", "now", ",", "\"exp\"...
Set the correct auth headers to authenticate against GitHub.
[ "Set", "the", "correct", "auth", "headers", "to", "authenticate", "against", "GitHub", "." ]
b99dfd6113c0351f13876f4172648c2eb63468ba
https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/scraper/connections/github.py#L66-L79
train
46,523
bmwcarit/zubbi
zubbi/scraper/connections/github.py
GitHubConnection._get_installation_key
def _get_installation_key( self, project, user_id=None, install_id=None, reprime=False ): """Get the auth token for a project or installation id.""" installation_id = install_id if project is not None: installation_id = self.installation_map.get(project, {}).get( "installation_id" ) if not installation_id: if reprime: # prime installation map and try again without refreshing self._prime_install_map() return self._get_installation_key( project, user_id=user_id, install_id=install_id, reprime=False ) LOGGER.debug("No installation ID available for project %s", project) return "" # Look up the token from cache now = datetime.now(timezone.utc) token, expiry = self.installation_token_cache.get(installation_id, (None, None)) # Request new token if the available one is expired or could not be found if (not expiry) or (not token) or (now >= expiry): LOGGER.debug("Requesting new token for installation %s", installation_id) headers = self._get_app_auth_headers() url = "{}/installations/{}/access_tokens".format( self.api_url, installation_id ) json_data = {"user_id": user_id} if user_id else None response = requests.post(url, headers=headers, json=json_data) response.raise_for_status() data = response.json() token = data["token"] expiry = datetime.strptime(data["expires_at"], "%Y-%m-%dT%H:%M:%SZ") # Update time zone of expiration date to make it comparable with now() expiry = expiry.replace(tzinfo=timezone.utc) # Assume, that the token expires two minutes earlier, to not # get lost during the checkout/scraping? expiry -= timedelta(minutes=2) self.installation_token_cache[installation_id] = (token, expiry) return token
python
def _get_installation_key( self, project, user_id=None, install_id=None, reprime=False ): """Get the auth token for a project or installation id.""" installation_id = install_id if project is not None: installation_id = self.installation_map.get(project, {}).get( "installation_id" ) if not installation_id: if reprime: # prime installation map and try again without refreshing self._prime_install_map() return self._get_installation_key( project, user_id=user_id, install_id=install_id, reprime=False ) LOGGER.debug("No installation ID available for project %s", project) return "" # Look up the token from cache now = datetime.now(timezone.utc) token, expiry = self.installation_token_cache.get(installation_id, (None, None)) # Request new token if the available one is expired or could not be found if (not expiry) or (not token) or (now >= expiry): LOGGER.debug("Requesting new token for installation %s", installation_id) headers = self._get_app_auth_headers() url = "{}/installations/{}/access_tokens".format( self.api_url, installation_id ) json_data = {"user_id": user_id} if user_id else None response = requests.post(url, headers=headers, json=json_data) response.raise_for_status() data = response.json() token = data["token"] expiry = datetime.strptime(data["expires_at"], "%Y-%m-%dT%H:%M:%SZ") # Update time zone of expiration date to make it comparable with now() expiry = expiry.replace(tzinfo=timezone.utc) # Assume, that the token expires two minutes earlier, to not # get lost during the checkout/scraping? expiry -= timedelta(minutes=2) self.installation_token_cache[installation_id] = (token, expiry) return token
[ "def", "_get_installation_key", "(", "self", ",", "project", ",", "user_id", "=", "None", ",", "install_id", "=", "None", ",", "reprime", "=", "False", ")", ":", "installation_id", "=", "install_id", "if", "project", "is", "not", "None", ":", "installation_i...
Get the auth token for a project or installation id.
[ "Get", "the", "auth", "token", "for", "a", "project", "or", "installation", "id", "." ]
b99dfd6113c0351f13876f4172648c2eb63468ba
https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/scraper/connections/github.py#L81-L131
train
46,524
bmwcarit/zubbi
zubbi/scraper/connections/github.py
GitHubConnection._prime_install_map
def _prime_install_map(self): """Fetch all installations and look up the ID for each.""" url = "{}/app/installations".format(self.api_url) headers = self._get_app_auth_headers() LOGGER.debug("Fetching installations for GitHub app") response = requests.get(url, headers=headers) response.raise_for_status() data = response.json() for install in data: install_id = install.get("id") token = self._get_installation_key(project=None, install_id=install_id) headers = { "Accept": PREVIEW_JSON_ACCEPT, "Authorization": "token {}".format(token), } url = "{}/installation/repositories?per_page=100".format(self.api_url) while url: LOGGER.debug("Fetching repos for installation %s", install_id) response = requests.get(url, headers=headers) response.raise_for_status() repos = response.json() # Store all projects in the installation map for repo in repos.get("repositories", []): # TODO (fschmidt): Store the installation's # permissions (could come in handy for later features) project_name = repo["full_name"] self.installation_map[project_name] = { "installation_id": install_id, "default_branch": repo["default_branch"], } # Check if we need to do further page calls url = response.links.get("next", {}).get("url")
python
def _prime_install_map(self): """Fetch all installations and look up the ID for each.""" url = "{}/app/installations".format(self.api_url) headers = self._get_app_auth_headers() LOGGER.debug("Fetching installations for GitHub app") response = requests.get(url, headers=headers) response.raise_for_status() data = response.json() for install in data: install_id = install.get("id") token = self._get_installation_key(project=None, install_id=install_id) headers = { "Accept": PREVIEW_JSON_ACCEPT, "Authorization": "token {}".format(token), } url = "{}/installation/repositories?per_page=100".format(self.api_url) while url: LOGGER.debug("Fetching repos for installation %s", install_id) response = requests.get(url, headers=headers) response.raise_for_status() repos = response.json() # Store all projects in the installation map for repo in repos.get("repositories", []): # TODO (fschmidt): Store the installation's # permissions (could come in handy for later features) project_name = repo["full_name"] self.installation_map[project_name] = { "installation_id": install_id, "default_branch": repo["default_branch"], } # Check if we need to do further page calls url = response.links.get("next", {}).get("url")
[ "def", "_prime_install_map", "(", "self", ")", ":", "url", "=", "\"{}/app/installations\"", ".", "format", "(", "self", ".", "api_url", ")", "headers", "=", "self", ".", "_get_app_auth_headers", "(", ")", "LOGGER", ".", "debug", "(", "\"Fetching installations fo...
Fetch all installations and look up the ID for each.
[ "Fetch", "all", "installations", "and", "look", "up", "the", "ID", "for", "each", "." ]
b99dfd6113c0351f13876f4172648c2eb63468ba
https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/scraper/connections/github.py#L133-L170
train
46,525
pyQode/pyqode.core
pyqode/core/modes/line_highlighter.py
LineHighlighterMode._clear_deco
def _clear_deco(self): """ Clear line decoration """ if self._decoration: self.editor.decorations.remove(self._decoration) self._decoration = None
python
def _clear_deco(self): """ Clear line decoration """ if self._decoration: self.editor.decorations.remove(self._decoration) self._decoration = None
[ "def", "_clear_deco", "(", "self", ")", ":", "if", "self", ".", "_decoration", ":", "self", ".", "editor", ".", "decorations", ".", "remove", "(", "self", ".", "_decoration", ")", "self", ".", "_decoration", "=", "None" ]
Clear line decoration
[ "Clear", "line", "decoration" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/line_highlighter.py#L68-L72
train
46,526
pyQode/pyqode.core
pyqode/core/widgets/tabs.py
TabWidget.save_current
def save_current(self, path=None): """ Save current editor content. Leave file to None to erase the previous file content. If the current editor's file_path is None and path is None, the function will call ``QtWidgets.QFileDialog.getSaveFileName`` to get a valid save filename. :param path: path of the file to save, leave it None to overwrite existing file. """ try: if not path and not self._current.file.path: path, filter = QtWidgets.QFileDialog.getSaveFileName( self, _('Choose destination path')) if not path: return False old_path = self._current.file.path code_edit = self._current self._save_editor(code_edit, path) path = code_edit.file.path # path (and icon) may have changed if path and old_path != path: self._ensure_unique_name(code_edit, code_edit.file.name) self.setTabText(self.currentIndex(), code_edit._tab_name) ext = os.path.splitext(path)[1] old_ext = os.path.splitext(old_path)[1] if ext != old_ext or not old_path: icon = QtWidgets.QFileIconProvider().icon( QtCore.QFileInfo(code_edit.file.path)) self.setTabIcon(self.currentIndex(), icon) return True except AttributeError: # not an editor widget pass return False
python
def save_current(self, path=None): """ Save current editor content. Leave file to None to erase the previous file content. If the current editor's file_path is None and path is None, the function will call ``QtWidgets.QFileDialog.getSaveFileName`` to get a valid save filename. :param path: path of the file to save, leave it None to overwrite existing file. """ try: if not path and not self._current.file.path: path, filter = QtWidgets.QFileDialog.getSaveFileName( self, _('Choose destination path')) if not path: return False old_path = self._current.file.path code_edit = self._current self._save_editor(code_edit, path) path = code_edit.file.path # path (and icon) may have changed if path and old_path != path: self._ensure_unique_name(code_edit, code_edit.file.name) self.setTabText(self.currentIndex(), code_edit._tab_name) ext = os.path.splitext(path)[1] old_ext = os.path.splitext(old_path)[1] if ext != old_ext or not old_path: icon = QtWidgets.QFileIconProvider().icon( QtCore.QFileInfo(code_edit.file.path)) self.setTabIcon(self.currentIndex(), icon) return True except AttributeError: # not an editor widget pass return False
[ "def", "save_current", "(", "self", ",", "path", "=", "None", ")", ":", "try", ":", "if", "not", "path", "and", "not", "self", ".", "_current", ".", "file", ".", "path", ":", "path", ",", "filter", "=", "QtWidgets", ".", "QFileDialog", ".", "getSaveF...
Save current editor content. Leave file to None to erase the previous file content. If the current editor's file_path is None and path is None, the function will call ``QtWidgets.QFileDialog.getSaveFileName`` to get a valid save filename. :param path: path of the file to save, leave it None to overwrite existing file.
[ "Save", "current", "editor", "content", ".", "Leave", "file", "to", "None", "to", "erase", "the", "previous", "file", "content", ".", "If", "the", "current", "editor", "s", "file_path", "is", "None", "and", "path", "is", "None", "the", "function", "will", ...
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L126-L160
train
46,527
pyQode/pyqode.core
pyqode/core/widgets/tabs.py
TabWidget.index_from_filename
def index_from_filename(self, path): """ Checks if the path is already open in an editor tab. :param path: path to check :returns: The tab index if found or -1 """ if path: for i in range(self.count()): widget = self.widget(i) try: if widget.file.path == path: return i except AttributeError: pass # not an editor widget return -1
python
def index_from_filename(self, path): """ Checks if the path is already open in an editor tab. :param path: path to check :returns: The tab index if found or -1 """ if path: for i in range(self.count()): widget = self.widget(i) try: if widget.file.path == path: return i except AttributeError: pass # not an editor widget return -1
[ "def", "index_from_filename", "(", "self", ",", "path", ")", ":", "if", "path", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ":", "widget", "=", "self", ".", "widget", "(", "i", ")", "try", ":", "if", "widget", ".", ...
Checks if the path is already open in an editor tab. :param path: path to check :returns: The tab index if found or -1
[ "Checks", "if", "the", "path", "is", "already", "open", "in", "an", "editor", "tab", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L191-L206
train
46,528
pyQode/pyqode.core
pyqode/core/widgets/tabs.py
TabWidget.add_code_edit
def add_code_edit(self, code_edit, name=None): """ Adds a code edit tab, sets its text as the editor.file.name and sets it as the active tab. The widget is only added if there is no other editor tab open with the same filename, else the already open tab is set as current. If the widget file path is empty, i.e. this is a new document that has not been saved to disk, you may provided a formatted string such as 'New document %d.txt' for the document name. The int format will be automatically replaced by the number of new documents (e.g. 'New document 1.txt' then 'New document 2.txt' and so on). If you prefer to use your own code to manage the file names, just ensure that the names are unique. :param code_edit: The code editor widget tab to append :type code_edit: pyqode.core.api.CodeEdit :param name: Name of the tab. Will use code_edit.file.name if None is supplied. Default is None. If this is a new document, you should either pass a unique name or a formatted string (with a '%d' format) :return: Tab index """ # new empty editor widget (no path set) if code_edit.file.path == '': cnt = 0 for i in range(self.count()): tab = self.widget(i) if tab.file.path.startswith(name[:name.find('%')]): cnt += 1 name %= (cnt + 1) code_edit.file._path = name index = self.index_from_filename(code_edit.file.path) if index != -1: # already open, just show it self.setCurrentIndex(index) # no need to keep this instance self._del_code_edit(code_edit) return -1 self._ensure_unique_name(code_edit, name) index = self.addTab(code_edit, code_edit.file.icon, code_edit._tab_name) self.setCurrentIndex(index) self.setTabText(index, code_edit._tab_name) try: code_edit.setFocus() except TypeError: # PySide code_edit.setFocus() try: file_watcher = code_edit.modes.get(FileWatcherMode) except (KeyError, AttributeError): # not installed pass else: file_watcher.file_deleted.connect(self._on_file_deleted) return index
python
def add_code_edit(self, code_edit, name=None): """ Adds a code edit tab, sets its text as the editor.file.name and sets it as the active tab. The widget is only added if there is no other editor tab open with the same filename, else the already open tab is set as current. If the widget file path is empty, i.e. this is a new document that has not been saved to disk, you may provided a formatted string such as 'New document %d.txt' for the document name. The int format will be automatically replaced by the number of new documents (e.g. 'New document 1.txt' then 'New document 2.txt' and so on). If you prefer to use your own code to manage the file names, just ensure that the names are unique. :param code_edit: The code editor widget tab to append :type code_edit: pyqode.core.api.CodeEdit :param name: Name of the tab. Will use code_edit.file.name if None is supplied. Default is None. If this is a new document, you should either pass a unique name or a formatted string (with a '%d' format) :return: Tab index """ # new empty editor widget (no path set) if code_edit.file.path == '': cnt = 0 for i in range(self.count()): tab = self.widget(i) if tab.file.path.startswith(name[:name.find('%')]): cnt += 1 name %= (cnt + 1) code_edit.file._path = name index = self.index_from_filename(code_edit.file.path) if index != -1: # already open, just show it self.setCurrentIndex(index) # no need to keep this instance self._del_code_edit(code_edit) return -1 self._ensure_unique_name(code_edit, name) index = self.addTab(code_edit, code_edit.file.icon, code_edit._tab_name) self.setCurrentIndex(index) self.setTabText(index, code_edit._tab_name) try: code_edit.setFocus() except TypeError: # PySide code_edit.setFocus() try: file_watcher = code_edit.modes.get(FileWatcherMode) except (KeyError, AttributeError): # not installed pass else: file_watcher.file_deleted.connect(self._on_file_deleted) return index
[ "def", "add_code_edit", "(", "self", ",", "code_edit", ",", "name", "=", "None", ")", ":", "# new empty editor widget (no path set)", "if", "code_edit", ".", "file", ".", "path", "==", "''", ":", "cnt", "=", "0", "for", "i", "in", "range", "(", "self", "...
Adds a code edit tab, sets its text as the editor.file.name and sets it as the active tab. The widget is only added if there is no other editor tab open with the same filename, else the already open tab is set as current. If the widget file path is empty, i.e. this is a new document that has not been saved to disk, you may provided a formatted string such as 'New document %d.txt' for the document name. The int format will be automatically replaced by the number of new documents (e.g. 'New document 1.txt' then 'New document 2.txt' and so on). If you prefer to use your own code to manage the file names, just ensure that the names are unique. :param code_edit: The code editor widget tab to append :type code_edit: pyqode.core.api.CodeEdit :param name: Name of the tab. Will use code_edit.file.name if None is supplied. Default is None. If this is a new document, you should either pass a unique name or a formatted string (with a '%d' format) :return: Tab index
[ "Adds", "a", "code", "edit", "tab", "sets", "its", "text", "as", "the", "editor", ".", "file", ".", "name", "and", "sets", "it", "as", "the", "active", "tab", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L217-L275
train
46,529
pyQode/pyqode.core
pyqode/core/widgets/tabs.py
TabWidget.addTab
def addTab(self, elem, icon, name): """ Extends QTabWidget.addTab to keep an internal list of added tabs. :param elem: tab widget :param icon: tab icon :param name: tab name """ self._widgets.append(elem) return super(TabWidget, self).addTab(elem, icon, name)
python
def addTab(self, elem, icon, name): """ Extends QTabWidget.addTab to keep an internal list of added tabs. :param elem: tab widget :param icon: tab icon :param name: tab name """ self._widgets.append(elem) return super(TabWidget, self).addTab(elem, icon, name)
[ "def", "addTab", "(", "self", ",", "elem", ",", "icon", ",", "name", ")", ":", "self", ".", "_widgets", ".", "append", "(", "elem", ")", "return", "super", "(", "TabWidget", ",", "self", ")", ".", "addTab", "(", "elem", ",", "icon", ",", "name", ...
Extends QTabWidget.addTab to keep an internal list of added tabs. :param elem: tab widget :param icon: tab icon :param name: tab name
[ "Extends", "QTabWidget", ".", "addTab", "to", "keep", "an", "internal", "list", "of", "added", "tabs", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L277-L286
train
46,530
pyQode/pyqode.core
pyqode/core/widgets/tabs.py
TabWidget._name_exists
def _name_exists(self, name): """ Checks if we already have an opened tab with the same name. """ for i in range(self.count()): if self.tabText(i) == name: return True return False
python
def _name_exists(self, name): """ Checks if we already have an opened tab with the same name. """ for i in range(self.count()): if self.tabText(i) == name: return True return False
[ "def", "_name_exists", "(", "self", ",", "name", ")", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ":", "if", "self", ".", "tabText", "(", "i", ")", "==", "name", ":", "return", "True", "return", "False" ]
Checks if we already have an opened tab with the same name.
[ "Checks", "if", "we", "already", "have", "an", "opened", "tab", "with", "the", "same", "name", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L288-L295
train
46,531
pyQode/pyqode.core
pyqode/core/widgets/tabs.py
TabWidget._rename_duplicate_tabs
def _rename_duplicate_tabs(self, current, name, path): """ Rename tabs whose title is the same as the name """ for i in range(self.count()): if self.widget(i)._tab_name == name and self.widget(i) != current: file_path = self.widget(i).file.path if file_path: parent_dir = os.path.split(os.path.abspath( os.path.join(file_path, os.pardir)))[1] new_name = os.path.join(parent_dir, name) self.setTabText(i, new_name) self.widget(i)._tab_name = new_name break if path: parent_dir = os.path.split(os.path.abspath( os.path.join(path, os.pardir)))[1] return os.path.join(parent_dir, name) else: return name
python
def _rename_duplicate_tabs(self, current, name, path): """ Rename tabs whose title is the same as the name """ for i in range(self.count()): if self.widget(i)._tab_name == name and self.widget(i) != current: file_path = self.widget(i).file.path if file_path: parent_dir = os.path.split(os.path.abspath( os.path.join(file_path, os.pardir)))[1] new_name = os.path.join(parent_dir, name) self.setTabText(i, new_name) self.widget(i)._tab_name = new_name break if path: parent_dir = os.path.split(os.path.abspath( os.path.join(path, os.pardir)))[1] return os.path.join(parent_dir, name) else: return name
[ "def", "_rename_duplicate_tabs", "(", "self", ",", "current", ",", "name", ",", "path", ")", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ":", "if", "self", ".", "widget", "(", "i", ")", ".", "_tab_name", "==", "name", ...
Rename tabs whose title is the same as the name
[ "Rename", "tabs", "whose", "title", "is", "the", "same", "as", "the", "name" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L310-L329
train
46,532
pyQode/pyqode.core
pyqode/core/widgets/tabs.py
TabWidget.removeTab
def removeTab(self, index): """ Removes tab at index ``index``. This method will emits tab_closed for the removed tab. :param index: index of the tab to remove. """ widget = self.widget(index) try: self._widgets.remove(widget) except ValueError: pass self.tab_closed.emit(widget) self._del_code_edit(widget) QTabWidget.removeTab(self, index) if widget == self._current: self._current = None
python
def removeTab(self, index): """ Removes tab at index ``index``. This method will emits tab_closed for the removed tab. :param index: index of the tab to remove. """ widget = self.widget(index) try: self._widgets.remove(widget) except ValueError: pass self.tab_closed.emit(widget) self._del_code_edit(widget) QTabWidget.removeTab(self, index) if widget == self._current: self._current = None
[ "def", "removeTab", "(", "self", ",", "index", ")", ":", "widget", "=", "self", ".", "widget", "(", "index", ")", "try", ":", "self", ".", "_widgets", ".", "remove", "(", "widget", ")", "except", "ValueError", ":", "pass", "self", ".", "tab_closed", ...
Removes tab at index ``index``. This method will emits tab_closed for the removed tab. :param index: index of the tab to remove.
[ "Removes", "tab", "at", "index", "index", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L349-L366
train
46,533
pyQode/pyqode.core
pyqode/core/widgets/tabs.py
TabWidget._try_close_dirty_tabs
def _try_close_dirty_tabs(self, exept=None): """ Tries to close dirty tabs. Uses DlgUnsavedFiles to ask the user what he wants to do. """ widgets, filenames = self._collect_dirty_tabs(exept=exept) if not len(filenames): return True dlg = DlgUnsavedFiles(self, files=filenames) if dlg.exec_() == dlg.Accepted: if not dlg.discarded: for item in dlg.listWidget.selectedItems(): filename = item.text() widget = None for widget in widgets: if widget.file.path == filename: break if widget != exept: self._save_editor(widget) self.removeTab(self.indexOf(widget)) return True return False
python
def _try_close_dirty_tabs(self, exept=None): """ Tries to close dirty tabs. Uses DlgUnsavedFiles to ask the user what he wants to do. """ widgets, filenames = self._collect_dirty_tabs(exept=exept) if not len(filenames): return True dlg = DlgUnsavedFiles(self, files=filenames) if dlg.exec_() == dlg.Accepted: if not dlg.discarded: for item in dlg.listWidget.selectedItems(): filename = item.text() widget = None for widget in widgets: if widget.file.path == filename: break if widget != exept: self._save_editor(widget) self.removeTab(self.indexOf(widget)) return True return False
[ "def", "_try_close_dirty_tabs", "(", "self", ",", "exept", "=", "None", ")", ":", "widgets", ",", "filenames", "=", "self", ".", "_collect_dirty_tabs", "(", "exept", "=", "exept", ")", "if", "not", "len", "(", "filenames", ")", ":", "return", "True", "dl...
Tries to close dirty tabs. Uses DlgUnsavedFiles to ask the user what he wants to do.
[ "Tries", "to", "close", "dirty", "tabs", ".", "Uses", "DlgUnsavedFiles", "to", "ask", "the", "user", "what", "he", "wants", "to", "do", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L389-L410
train
46,534
pyQode/pyqode.core
pyqode/core/dialogs/encodings.py
DlgPreferredEncodingsEditor.edit_encoding
def edit_encoding(cls, parent): """ Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings. :param parent: parent widget :return: True in case of succes, False otherwise """ dlg = cls(parent) if dlg.exec_() == dlg.Accepted: settings = Cache() settings.preferred_encodings = dlg.get_preferred_encodings() return True return False
python
def edit_encoding(cls, parent): """ Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings. :param parent: parent widget :return: True in case of succes, False otherwise """ dlg = cls(parent) if dlg.exec_() == dlg.Accepted: settings = Cache() settings.preferred_encodings = dlg.get_preferred_encodings() return True return False
[ "def", "edit_encoding", "(", "cls", ",", "parent", ")", ":", "dlg", "=", "cls", "(", "parent", ")", "if", "dlg", ".", "exec_", "(", ")", "==", "dlg", ".", "Accepted", ":", "settings", "=", "Cache", "(", ")", "settings", ".", "preferred_encodings", "=...
Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings. :param parent: parent widget :return: True in case of succes, False otherwise
[ "Static", "helper", "method", "that", "shows", "the", "encoding", "editor", "dialog", "If", "the", "dialog", "was", "accepted", "the", "new", "encodings", "are", "added", "to", "the", "settings", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/dialogs/encodings.py#L123-L137
train
46,535
pyQode/pyqode.core
pyqode/core/dialogs/encodings.py
DlgEncodingsChoice.choose_encoding
def choose_encoding(cls, parent, path, encoding): """ Show the encodings dialog and returns the user choice. :param parent: parent widget. :param path: file path :param encoding: current file encoding :return: selected encoding """ dlg = cls(parent, path, encoding) dlg.exec_() return dlg.ui.comboBoxEncodings.current_encoding
python
def choose_encoding(cls, parent, path, encoding): """ Show the encodings dialog and returns the user choice. :param parent: parent widget. :param path: file path :param encoding: current file encoding :return: selected encoding """ dlg = cls(parent, path, encoding) dlg.exec_() return dlg.ui.comboBoxEncodings.current_encoding
[ "def", "choose_encoding", "(", "cls", ",", "parent", ",", "path", ",", "encoding", ")", ":", "dlg", "=", "cls", "(", "parent", ",", "path", ",", "encoding", ")", "dlg", ".", "exec_", "(", ")", "return", "dlg", ".", "ui", ".", "comboBoxEncodings", "."...
Show the encodings dialog and returns the user choice. :param parent: parent widget. :param path: file path :param encoding: current file encoding :return: selected encoding
[ "Show", "the", "encodings", "dialog", "and", "returns", "the", "user", "choice", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/dialogs/encodings.py#L162-L173
train
46,536
pyQode/pyqode.core
pyqode/core/widgets/pty_wrapper.py
pty_wrapper_main
def pty_wrapper_main(): """ Main function of the pty wrapper script """ # make sure we can import _pty even if pyqode is not installed (this is the case in HackEdit where pyqode has # been vendored). sys.path.insert(0, os.path.dirname(__file__)) import _pty # fixme: find a way to use a pty and keep stdout and stderr as separate channels _pty.spawn(sys.argv[1:])
python
def pty_wrapper_main(): """ Main function of the pty wrapper script """ # make sure we can import _pty even if pyqode is not installed (this is the case in HackEdit where pyqode has # been vendored). sys.path.insert(0, os.path.dirname(__file__)) import _pty # fixme: find a way to use a pty and keep stdout and stderr as separate channels _pty.spawn(sys.argv[1:])
[ "def", "pty_wrapper_main", "(", ")", ":", "# make sure we can import _pty even if pyqode is not installed (this is the case in HackEdit where pyqode has", "# been vendored).", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "path", ".", "dirname", "(", "__file_...
Main function of the pty wrapper script
[ "Main", "function", "of", "the", "pty", "wrapper", "script" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/pty_wrapper.py#L5-L15
train
46,537
pyQode/pyqode.core
pyqode/core/modes/extended_selection.py
ExtendedSelectionMode.create_menu
def create_menu(self): """ Creates the extended selection menu. """ # setup menu menu = QtWidgets.QMenu(self.editor) menu.setTitle(_('Select')) menu.menuAction().setIcon(QtGui.QIcon.fromTheme('edit-select')) # setup actions menu.addAction(self.action_select_word) menu.addAction(self.action_select_extended_word) menu.addAction(self.action_select_matched) menu.addAction(self.action_select_line) menu.addSeparator() menu.addAction(self.editor.action_select_all) icon = QtGui.QIcon.fromTheme( 'edit-select-all', QtGui.QIcon( ':/pyqode-icons/rc/edit-select-all.png')) self.editor.action_select_all.setIcon(icon) return menu
python
def create_menu(self): """ Creates the extended selection menu. """ # setup menu menu = QtWidgets.QMenu(self.editor) menu.setTitle(_('Select')) menu.menuAction().setIcon(QtGui.QIcon.fromTheme('edit-select')) # setup actions menu.addAction(self.action_select_word) menu.addAction(self.action_select_extended_word) menu.addAction(self.action_select_matched) menu.addAction(self.action_select_line) menu.addSeparator() menu.addAction(self.editor.action_select_all) icon = QtGui.QIcon.fromTheme( 'edit-select-all', QtGui.QIcon( ':/pyqode-icons/rc/edit-select-all.png')) self.editor.action_select_all.setIcon(icon) return menu
[ "def", "create_menu", "(", "self", ")", ":", "# setup menu", "menu", "=", "QtWidgets", ".", "QMenu", "(", "self", ".", "editor", ")", "menu", ".", "setTitle", "(", "_", "(", "'Select'", ")", ")", "menu", ".", "menuAction", "(", ")", ".", "setIcon", "...
Creates the extended selection menu.
[ "Creates", "the", "extended", "selection", "menu", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/extended_selection.py#L72-L91
train
46,538
pyQode/pyqode.core
pyqode/core/share.py
Definition.to_dict
def to_dict(self): """ Serializes a definition to a dictionary, ready for json. Children are serialised recursively. """ ddict = {'name': self.name, 'icon': self.icon, 'line': self.line, 'column': self.column, 'children': [], 'description': self.description, 'user_data': self.user_data, 'path': self.file_path} for child in self.children: ddict['children'].append(child.to_dict()) return ddict
python
def to_dict(self): """ Serializes a definition to a dictionary, ready for json. Children are serialised recursively. """ ddict = {'name': self.name, 'icon': self.icon, 'line': self.line, 'column': self.column, 'children': [], 'description': self.description, 'user_data': self.user_data, 'path': self.file_path} for child in self.children: ddict['children'].append(child.to_dict()) return ddict
[ "def", "to_dict", "(", "self", ")", ":", "ddict", "=", "{", "'name'", ":", "self", ".", "name", ",", "'icon'", ":", "self", ".", "icon", ",", "'line'", ":", "self", ".", "line", ",", "'column'", ":", "self", ".", "column", ",", "'children'", ":", ...
Serializes a definition to a dictionary, ready for json. Children are serialised recursively.
[ "Serializes", "a", "definition", "to", "a", "dictionary", "ready", "for", "json", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/share.py#L43-L55
train
46,539
pyQode/pyqode.core
pyqode/core/share.py
Definition.from_dict
def from_dict(ddict): """ Deserializes a definition from a simple dict. """ d = Definition(ddict['name'], ddict['line'], ddict['column'], ddict['icon'], ddict['description'], ddict['user_data'], ddict['path']) for child_dict in ddict['children']: d.children.append(Definition.from_dict(child_dict)) return d
python
def from_dict(ddict): """ Deserializes a definition from a simple dict. """ d = Definition(ddict['name'], ddict['line'], ddict['column'], ddict['icon'], ddict['description'], ddict['user_data'], ddict['path']) for child_dict in ddict['children']: d.children.append(Definition.from_dict(child_dict)) return d
[ "def", "from_dict", "(", "ddict", ")", ":", "d", "=", "Definition", "(", "ddict", "[", "'name'", "]", ",", "ddict", "[", "'line'", "]", ",", "ddict", "[", "'column'", "]", ",", "ddict", "[", "'icon'", "]", ",", "ddict", "[", "'description'", "]", "...
Deserializes a definition from a simple dict.
[ "Deserializes", "a", "definition", "from", "a", "simple", "dict", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/share.py#L58-L67
train
46,540
pyQode/pyqode.core
pyqode/core/modes/indenter.py
IndenterMode.indent_selection
def indent_selection(self, cursor): """ Indent selected text :param cursor: QTextCursor """ doc = self.editor.document() tab_len = self.editor.tab_length cursor.beginEditBlock() nb_lines = len(cursor.selection().toPlainText().splitlines()) c = self.editor.textCursor() if c.atBlockStart() and c.position() == c.selectionEnd(): nb_lines += 1 block = doc.findBlock(cursor.selectionStart()) i = 0 # indent every lines while i < nb_lines: nb_space_to_add = tab_len cursor = QtGui.QTextCursor(block) cursor.movePosition(cursor.StartOfLine, cursor.MoveAnchor) if self.editor.use_spaces_instead_of_tabs: for _ in range(nb_space_to_add): cursor.insertText(" ") else: cursor.insertText('\t') block = block.next() i += 1 cursor.endEditBlock()
python
def indent_selection(self, cursor): """ Indent selected text :param cursor: QTextCursor """ doc = self.editor.document() tab_len = self.editor.tab_length cursor.beginEditBlock() nb_lines = len(cursor.selection().toPlainText().splitlines()) c = self.editor.textCursor() if c.atBlockStart() and c.position() == c.selectionEnd(): nb_lines += 1 block = doc.findBlock(cursor.selectionStart()) i = 0 # indent every lines while i < nb_lines: nb_space_to_add = tab_len cursor = QtGui.QTextCursor(block) cursor.movePosition(cursor.StartOfLine, cursor.MoveAnchor) if self.editor.use_spaces_instead_of_tabs: for _ in range(nb_space_to_add): cursor.insertText(" ") else: cursor.insertText('\t') block = block.next() i += 1 cursor.endEditBlock()
[ "def", "indent_selection", "(", "self", ",", "cursor", ")", ":", "doc", "=", "self", ".", "editor", ".", "document", "(", ")", "tab_len", "=", "self", ".", "editor", ".", "tab_length", "cursor", ".", "beginEditBlock", "(", ")", "nb_lines", "=", "len", ...
Indent selected text :param cursor: QTextCursor
[ "Indent", "selected", "text" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/indenter.py#L41-L68
train
46,541
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.show_tooltip
def show_tooltip(self, pos, tooltip, _sender_deco=None): """ Show a tool tip at the specified position :param pos: Tooltip position :param tooltip: Tooltip text :param _sender_deco: TextDecoration which is the sender of the show tooltip request. (for internal use only). """ if _sender_deco is not None and _sender_deco not in self.decorations: return QtWidgets.QToolTip.showText(pos, tooltip[0: 1024], self)
python
def show_tooltip(self, pos, tooltip, _sender_deco=None): """ Show a tool tip at the specified position :param pos: Tooltip position :param tooltip: Tooltip text :param _sender_deco: TextDecoration which is the sender of the show tooltip request. (for internal use only). """ if _sender_deco is not None and _sender_deco not in self.decorations: return QtWidgets.QToolTip.showText(pos, tooltip[0: 1024], self)
[ "def", "show_tooltip", "(", "self", ",", "pos", ",", "tooltip", ",", "_sender_deco", "=", "None", ")", ":", "if", "_sender_deco", "is", "not", "None", "and", "_sender_deco", "not", "in", "self", ".", "decorations", ":", "return", "QtWidgets", ".", "QToolTi...
Show a tool tip at the specified position :param pos: Tooltip position :param tooltip: Tooltip text :param _sender_deco: TextDecoration which is the sender of the show tooltip request. (for internal use only).
[ "Show", "a", "tool", "tip", "at", "the", "specified", "position" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L603-L615
train
46,542
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.setPlainText
def setPlainText(self, txt, mime_type, encoding): """ Extends setPlainText to force the user to setup an encoding and a mime type. Emits the new_text_set signal. :param txt: The new text to set. :param mime_type: Associated mimetype. Setting the mime will update the pygments lexer. :param encoding: text encoding """ self.file.mimetype = mime_type self.file._encoding = encoding self._original_text = txt self._modified_lines.clear() import time t = time.time() super(CodeEdit, self).setPlainText(txt) _logger().log(5, 'setPlainText duration: %fs' % (time.time() - t)) self.new_text_set.emit() self.redoAvailable.emit(False) self.undoAvailable.emit(False)
python
def setPlainText(self, txt, mime_type, encoding): """ Extends setPlainText to force the user to setup an encoding and a mime type. Emits the new_text_set signal. :param txt: The new text to set. :param mime_type: Associated mimetype. Setting the mime will update the pygments lexer. :param encoding: text encoding """ self.file.mimetype = mime_type self.file._encoding = encoding self._original_text = txt self._modified_lines.clear() import time t = time.time() super(CodeEdit, self).setPlainText(txt) _logger().log(5, 'setPlainText duration: %fs' % (time.time() - t)) self.new_text_set.emit() self.redoAvailable.emit(False) self.undoAvailable.emit(False)
[ "def", "setPlainText", "(", "self", ",", "txt", ",", "mime_type", ",", "encoding", ")", ":", "self", ".", "file", ".", "mimetype", "=", "mime_type", "self", ".", "file", ".", "_encoding", "=", "encoding", "self", ".", "_original_text", "=", "txt", "self"...
Extends setPlainText to force the user to setup an encoding and a mime type. Emits the new_text_set signal. :param txt: The new text to set. :param mime_type: Associated mimetype. Setting the mime will update the pygments lexer. :param encoding: text encoding
[ "Extends", "setPlainText", "to", "force", "the", "user", "to", "setup", "an", "encoding", "and", "a", "mime", "type", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L617-L639
train
46,543
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.add_action
def add_action(self, action, sub_menu='Advanced'): """ Adds an action to the editor's context menu. :param action: QAction to add to the context menu. :param sub_menu: The name of a sub menu where to put the action. 'Advanced' by default. If None or empty, the action will be added at the root of the submenu. """ if sub_menu: try: mnu = self._sub_menus[sub_menu] except KeyError: mnu = QtWidgets.QMenu(sub_menu) self.add_menu(mnu) self._sub_menus[sub_menu] = mnu finally: mnu.addAction(action) else: self._actions.append(action) action.setShortcutContext(QtCore.Qt.WidgetShortcut) self.addAction(action)
python
def add_action(self, action, sub_menu='Advanced'): """ Adds an action to the editor's context menu. :param action: QAction to add to the context menu. :param sub_menu: The name of a sub menu where to put the action. 'Advanced' by default. If None or empty, the action will be added at the root of the submenu. """ if sub_menu: try: mnu = self._sub_menus[sub_menu] except KeyError: mnu = QtWidgets.QMenu(sub_menu) self.add_menu(mnu) self._sub_menus[sub_menu] = mnu finally: mnu.addAction(action) else: self._actions.append(action) action.setShortcutContext(QtCore.Qt.WidgetShortcut) self.addAction(action)
[ "def", "add_action", "(", "self", ",", "action", ",", "sub_menu", "=", "'Advanced'", ")", ":", "if", "sub_menu", ":", "try", ":", "mnu", "=", "self", ".", "_sub_menus", "[", "sub_menu", "]", "except", "KeyError", ":", "mnu", "=", "QtWidgets", ".", "QMe...
Adds an action to the editor's context menu. :param action: QAction to add to the context menu. :param sub_menu: The name of a sub menu where to put the action. 'Advanced' by default. If None or empty, the action will be added at the root of the submenu.
[ "Adds", "an", "action", "to", "the", "editor", "s", "context", "menu", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L641-L662
train
46,544
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.insert_action
def insert_action(self, action, prev_action): """ Inserts an action to the editor's context menu. :param action: action to insert :param prev_action: the action after which the new action must be inserted or the insert index """ if isinstance(prev_action, QtWidgets.QAction): index = self._actions.index(prev_action) else: index = prev_action action.setShortcutContext(QtCore.Qt.WidgetShortcut) self._actions.insert(index, action)
python
def insert_action(self, action, prev_action): """ Inserts an action to the editor's context menu. :param action: action to insert :param prev_action: the action after which the new action must be inserted or the insert index """ if isinstance(prev_action, QtWidgets.QAction): index = self._actions.index(prev_action) else: index = prev_action action.setShortcutContext(QtCore.Qt.WidgetShortcut) self._actions.insert(index, action)
[ "def", "insert_action", "(", "self", ",", "action", ",", "prev_action", ")", ":", "if", "isinstance", "(", "prev_action", ",", "QtWidgets", ".", "QAction", ")", ":", "index", "=", "self", ".", "_actions", ".", "index", "(", "prev_action", ")", "else", ":...
Inserts an action to the editor's context menu. :param action: action to insert :param prev_action: the action after which the new action must be inserted or the insert index
[ "Inserts", "an", "action", "to", "the", "editor", "s", "context", "menu", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L664-L677
train
46,545
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.add_separator
def add_separator(self, sub_menu='Advanced'): """ Adds a sepqrator to the editor's context menu. :return: The sepator that has been added. :rtype: QtWidgets.QAction """ action = QtWidgets.QAction(self) action.setSeparator(True) if sub_menu: try: mnu = self._sub_menus[sub_menu] except KeyError: pass else: mnu.addAction(action) else: self._actions.append(action) return action
python
def add_separator(self, sub_menu='Advanced'): """ Adds a sepqrator to the editor's context menu. :return: The sepator that has been added. :rtype: QtWidgets.QAction """ action = QtWidgets.QAction(self) action.setSeparator(True) if sub_menu: try: mnu = self._sub_menus[sub_menu] except KeyError: pass else: mnu.addAction(action) else: self._actions.append(action) return action
[ "def", "add_separator", "(", "self", ",", "sub_menu", "=", "'Advanced'", ")", ":", "action", "=", "QtWidgets", ".", "QAction", "(", "self", ")", "action", ".", "setSeparator", "(", "True", ")", "if", "sub_menu", ":", "try", ":", "mnu", "=", "self", "."...
Adds a sepqrator to the editor's context menu. :return: The sepator that has been added. :rtype: QtWidgets.QAction
[ "Adds", "a", "sepqrator", "to", "the", "editor", "s", "context", "menu", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L686-L704
train
46,546
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.add_menu
def add_menu(self, menu): """ Adds a sub-menu to the editor context menu. Menu are put at the bottom of the context menu. .. note:: to add a menu in the middle of the context menu, you can always add its menuAction(). :param menu: menu to add """ self._menus.append(menu) self._menus = sorted(list(set(self._menus)), key=lambda x: x.title()) for action in menu.actions(): action.setShortcutContext(QtCore.Qt.WidgetShortcut) self.addActions(menu.actions())
python
def add_menu(self, menu): """ Adds a sub-menu to the editor context menu. Menu are put at the bottom of the context menu. .. note:: to add a menu in the middle of the context menu, you can always add its menuAction(). :param menu: menu to add """ self._menus.append(menu) self._menus = sorted(list(set(self._menus)), key=lambda x: x.title()) for action in menu.actions(): action.setShortcutContext(QtCore.Qt.WidgetShortcut) self.addActions(menu.actions())
[ "def", "add_menu", "(", "self", ",", "menu", ")", ":", "self", ".", "_menus", ".", "append", "(", "menu", ")", "self", ".", "_menus", "=", "sorted", "(", "list", "(", "set", "(", "self", ".", "_menus", ")", ")", ",", "key", "=", "lambda", "x", ...
Adds a sub-menu to the editor context menu. Menu are put at the bottom of the context menu. .. note:: to add a menu in the middle of the context menu, you can always add its menuAction(). :param menu: menu to add
[ "Adds", "a", "sub", "-", "menu", "to", "the", "editor", "context", "menu", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L727-L742
train
46,547
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.duplicate_line
def duplicate_line(self): """ Duplicates the line under the cursor. If multiple lines are selected, only the last one is duplicated. """ cursor = self.textCursor() assert isinstance(cursor, QtGui.QTextCursor) has_selection = True if not cursor.hasSelection(): cursor.select(cursor.LineUnderCursor) has_selection = False line = cursor.selectedText() line = '\n'.join(line.split('\u2029')) end = cursor.selectionEnd() cursor.setPosition(end) cursor.beginEditBlock() cursor.insertText('\n') cursor.insertText(line) cursor.endEditBlock() if has_selection: pos = cursor.position() cursor.setPosition(end + 1) cursor.setPosition(pos, cursor.KeepAnchor) self.setTextCursor(cursor)
python
def duplicate_line(self): """ Duplicates the line under the cursor. If multiple lines are selected, only the last one is duplicated. """ cursor = self.textCursor() assert isinstance(cursor, QtGui.QTextCursor) has_selection = True if not cursor.hasSelection(): cursor.select(cursor.LineUnderCursor) has_selection = False line = cursor.selectedText() line = '\n'.join(line.split('\u2029')) end = cursor.selectionEnd() cursor.setPosition(end) cursor.beginEditBlock() cursor.insertText('\n') cursor.insertText(line) cursor.endEditBlock() if has_selection: pos = cursor.position() cursor.setPosition(end + 1) cursor.setPosition(pos, cursor.KeepAnchor) self.setTextCursor(cursor)
[ "def", "duplicate_line", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "assert", "isinstance", "(", "cursor", ",", "QtGui", ".", "QTextCursor", ")", "has_selection", "=", "True", "if", "not", "cursor", ".", "hasSelection", "(",...
Duplicates the line under the cursor. If multiple lines are selected, only the last one is duplicated.
[ "Duplicates", "the", "line", "under", "the", "cursor", ".", "If", "multiple", "lines", "are", "selected", "only", "the", "last", "one", "is", "duplicated", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L812-L835
train
46,548
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.cut
def cut(self): """ Cuts the selected text or the whole line if no text was selected. """ tc = self.textCursor() helper = TextHelper(self) tc.beginEditBlock() no_selection = False sText = tc.selection().toPlainText() if not helper.current_line_text() and sText.count("\n") > 1: tc.deleteChar() else: if not self.textCursor().hasSelection(): no_selection = True TextHelper(self).select_whole_line() super(CodeEdit, self).cut() if no_selection: tc.deleteChar() tc.endEditBlock() self.setTextCursor(tc)
python
def cut(self): """ Cuts the selected text or the whole line if no text was selected. """ tc = self.textCursor() helper = TextHelper(self) tc.beginEditBlock() no_selection = False sText = tc.selection().toPlainText() if not helper.current_line_text() and sText.count("\n") > 1: tc.deleteChar() else: if not self.textCursor().hasSelection(): no_selection = True TextHelper(self).select_whole_line() super(CodeEdit, self).cut() if no_selection: tc.deleteChar() tc.endEditBlock() self.setTextCursor(tc)
[ "def", "cut", "(", "self", ")", ":", "tc", "=", "self", ".", "textCursor", "(", ")", "helper", "=", "TextHelper", "(", "self", ")", "tc", ".", "beginEditBlock", "(", ")", "no_selection", "=", "False", "sText", "=", "tc", ".", "selection", "(", ")", ...
Cuts the selected text or the whole line if no text was selected.
[ "Cuts", "the", "selected", "text", "or", "the", "whole", "line", "if", "no", "text", "was", "selected", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L869-L888
train
46,549
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.resizeEvent
def resizeEvent(self, e): """ Overrides resize event to resize the editor's panels. :param e: resize event """ super(CodeEdit, self).resizeEvent(e) self.panels.resize()
python
def resizeEvent(self, e): """ Overrides resize event to resize the editor's panels. :param e: resize event """ super(CodeEdit, self).resizeEvent(e) self.panels.resize()
[ "def", "resizeEvent", "(", "self", ",", "e", ")", ":", "super", "(", "CodeEdit", ",", "self", ")", ".", "resizeEvent", "(", "e", ")", "self", ".", "panels", ".", "resize", "(", ")" ]
Overrides resize event to resize the editor's panels. :param e: resize event
[ "Overrides", "resize", "event", "to", "resize", "the", "editor", "s", "panels", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L921-L928
train
46,550
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.paintEvent
def paintEvent(self, e): """ Overrides paint event to update the list of visible blocks and emit the painted event. :param e: paint event """ self._update_visible_blocks(e) super(CodeEdit, self).paintEvent(e) self.painted.emit(e)
python
def paintEvent(self, e): """ Overrides paint event to update the list of visible blocks and emit the painted event. :param e: paint event """ self._update_visible_blocks(e) super(CodeEdit, self).paintEvent(e) self.painted.emit(e)
[ "def", "paintEvent", "(", "self", ",", "e", ")", ":", "self", ".", "_update_visible_blocks", "(", "e", ")", "super", "(", "CodeEdit", ",", "self", ")", ".", "paintEvent", "(", "e", ")", "self", ".", "painted", ".", "emit", "(", "e", ")" ]
Overrides paint event to update the list of visible blocks and emit the painted event. :param e: paint event
[ "Overrides", "paint", "event", "to", "update", "the", "list", "of", "visible", "blocks", "and", "emit", "the", "painted", "event", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L934-L943
train
46,551
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.keyPressEvent
def keyPressEvent(self, event): """ Overrides the keyPressEvent to emit the key_pressed signal. Also takes care of indenting and handling smarter home key. :param event: QKeyEvent """ if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_pressed.emit(event) state = event.isAccepted() if not event.isAccepted(): if event.key() == QtCore.Qt.Key_Tab and event.modifiers() == \ QtCore.Qt.NoModifier: self.indent() event.accept() elif event.key() == QtCore.Qt.Key_Backtab and \ event.modifiers() == QtCore.Qt.NoModifier: self.un_indent() event.accept() elif event.key() == QtCore.Qt.Key_Home and \ int(event.modifiers()) & QtCore.Qt.ControlModifier == 0: self._do_home_key( event, int(event.modifiers()) & QtCore.Qt.ShiftModifier) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).keyPressEvent(event) new_state = event.isAccepted() event.setAccepted(state) self.post_key_pressed.emit(event) event.setAccepted(new_state)
python
def keyPressEvent(self, event): """ Overrides the keyPressEvent to emit the key_pressed signal. Also takes care of indenting and handling smarter home key. :param event: QKeyEvent """ if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_pressed.emit(event) state = event.isAccepted() if not event.isAccepted(): if event.key() == QtCore.Qt.Key_Tab and event.modifiers() == \ QtCore.Qt.NoModifier: self.indent() event.accept() elif event.key() == QtCore.Qt.Key_Backtab and \ event.modifiers() == QtCore.Qt.NoModifier: self.un_indent() event.accept() elif event.key() == QtCore.Qt.Key_Home and \ int(event.modifiers()) & QtCore.Qt.ControlModifier == 0: self._do_home_key( event, int(event.modifiers()) & QtCore.Qt.ShiftModifier) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).keyPressEvent(event) new_state = event.isAccepted() event.setAccepted(state) self.post_key_pressed.emit(event) event.setAccepted(new_state)
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "isReadOnly", "(", ")", ":", "return", "initial_state", "=", "event", ".", "isAccepted", "(", ")", "event", ".", "ignore", "(", ")", "self", ".", "key_pressed", ".", "emit"...
Overrides the keyPressEvent to emit the key_pressed signal. Also takes care of indenting and handling smarter home key. :param event: QKeyEvent
[ "Overrides", "the", "keyPressEvent", "to", "emit", "the", "key_pressed", "signal", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L945-L978
train
46,552
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.keyReleaseEvent
def keyReleaseEvent(self, event): """ Overrides keyReleaseEvent to emit the key_released signal. :param event: QKeyEvent """ if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_released.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).keyReleaseEvent(event)
python
def keyReleaseEvent(self, event): """ Overrides keyReleaseEvent to emit the key_released signal. :param event: QKeyEvent """ if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_released.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).keyReleaseEvent(event)
[ "def", "keyReleaseEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "isReadOnly", "(", ")", ":", "return", "initial_state", "=", "event", ".", "isAccepted", "(", ")", "event", ".", "ignore", "(", ")", "self", ".", "key_released", ".", "em...
Overrides keyReleaseEvent to emit the key_released signal. :param event: QKeyEvent
[ "Overrides", "keyReleaseEvent", "to", "emit", "the", "key_released", "signal", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L980-L993
train
46,553
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.focusInEvent
def focusInEvent(self, event): """ Overrides focusInEvent to emits the focused_in signal :param event: QFocusEvent """ self.focused_in.emit(event) super(CodeEdit, self).focusInEvent(event)
python
def focusInEvent(self, event): """ Overrides focusInEvent to emits the focused_in signal :param event: QFocusEvent """ self.focused_in.emit(event) super(CodeEdit, self).focusInEvent(event)
[ "def", "focusInEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focused_in", ".", "emit", "(", "event", ")", "super", "(", "CodeEdit", ",", "self", ")", ".", "focusInEvent", "(", "event", ")" ]
Overrides focusInEvent to emits the focused_in signal :param event: QFocusEvent
[ "Overrides", "focusInEvent", "to", "emits", "the", "focused_in", "signal" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1003-L1010
train
46,554
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.mousePressEvent
def mousePressEvent(self, event): """ Overrides mousePressEvent to emits mouse_pressed signal :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_pressed.emit(event) if event.button() == QtCore.Qt.LeftButton: cursor = self.cursorForPosition(event.pos()) for sel in self.decorations: if sel.cursor.blockNumber() == cursor.blockNumber(): if sel.contains_cursor(cursor): sel.signals.clicked.emit(sel) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).mousePressEvent(event)
python
def mousePressEvent(self, event): """ Overrides mousePressEvent to emits mouse_pressed signal :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_pressed.emit(event) if event.button() == QtCore.Qt.LeftButton: cursor = self.cursorForPosition(event.pos()) for sel in self.decorations: if sel.cursor.blockNumber() == cursor.blockNumber(): if sel.contains_cursor(cursor): sel.signals.clicked.emit(sel) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).mousePressEvent(event)
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "initial_state", "=", "event", ".", "isAccepted", "(", ")", "event", ".", "ignore", "(", ")", "self", ".", "mouse_pressed", ".", "emit", "(", "event", ")", "if", "event", ".", "button", "("...
Overrides mousePressEvent to emits mouse_pressed signal :param event: QMouseEvent
[ "Overrides", "mousePressEvent", "to", "emits", "mouse_pressed", "signal" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1018-L1035
train
46,555
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.mouseReleaseEvent
def mouseReleaseEvent(self, event): """ Emits mouse_released signal. :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_released.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).mouseReleaseEvent(event)
python
def mouseReleaseEvent(self, event): """ Emits mouse_released signal. :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_released.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).mouseReleaseEvent(event)
[ "def", "mouseReleaseEvent", "(", "self", ",", "event", ")", ":", "initial_state", "=", "event", ".", "isAccepted", "(", ")", "event", ".", "ignore", "(", ")", "self", ".", "mouse_released", ".", "emit", "(", "event", ")", "if", "not", "event", ".", "is...
Emits mouse_released signal. :param event: QMouseEvent
[ "Emits", "mouse_released", "signal", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1037-L1048
train
46,556
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.wheelEvent
def wheelEvent(self, event): """ Emits the mouse_wheel_activated signal. :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_wheel_activated.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).wheelEvent(event)
python
def wheelEvent(self, event): """ Emits the mouse_wheel_activated signal. :param event: QMouseEvent """ initial_state = event.isAccepted() event.ignore() self.mouse_wheel_activated.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).wheelEvent(event)
[ "def", "wheelEvent", "(", "self", ",", "event", ")", ":", "initial_state", "=", "event", ".", "isAccepted", "(", ")", "event", ".", "ignore", "(", ")", "self", ".", "mouse_wheel_activated", ".", "emit", "(", "event", ")", "if", "not", "event", ".", "is...
Emits the mouse_wheel_activated signal. :param event: QMouseEvent
[ "Emits", "the", "mouse_wheel_activated", "signal", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1050-L1061
train
46,557
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.mouseMoveEvent
def mouseMoveEvent(self, event): """ Overrides mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event. :param event: QMouseEvent """ cursor = self.cursorForPosition(event.pos()) self._last_mouse_pos = event.pos() block_found = False for sel in self.decorations: if sel.contains_cursor(cursor) and sel.tooltip: if (self._prev_tooltip_block_nbr != cursor.blockNumber() or not QtWidgets.QToolTip.isVisible()): pos = event.pos() # add left margin pos.setX(pos.x() + self.panels.margin_size()) # add top margin pos.setY(pos.y() + self.panels.margin_size(0)) self._tooltips_runner.request_job( self.show_tooltip, self.mapToGlobal(pos), sel.tooltip[0: 1024], sel) self._prev_tooltip_block_nbr = cursor.blockNumber() block_found = True break if not block_found and self._prev_tooltip_block_nbr != -1: QtWidgets.QToolTip.hideText() self._prev_tooltip_block_nbr = -1 self._tooltips_runner.cancel_requests() self.mouse_moved.emit(event) super(CodeEdit, self).mouseMoveEvent(event)
python
def mouseMoveEvent(self, event): """ Overrides mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event. :param event: QMouseEvent """ cursor = self.cursorForPosition(event.pos()) self._last_mouse_pos = event.pos() block_found = False for sel in self.decorations: if sel.contains_cursor(cursor) and sel.tooltip: if (self._prev_tooltip_block_nbr != cursor.blockNumber() or not QtWidgets.QToolTip.isVisible()): pos = event.pos() # add left margin pos.setX(pos.x() + self.panels.margin_size()) # add top margin pos.setY(pos.y() + self.panels.margin_size(0)) self._tooltips_runner.request_job( self.show_tooltip, self.mapToGlobal(pos), sel.tooltip[0: 1024], sel) self._prev_tooltip_block_nbr = cursor.blockNumber() block_found = True break if not block_found and self._prev_tooltip_block_nbr != -1: QtWidgets.QToolTip.hideText() self._prev_tooltip_block_nbr = -1 self._tooltips_runner.cancel_requests() self.mouse_moved.emit(event) super(CodeEdit, self).mouseMoveEvent(event)
[ "def", "mouseMoveEvent", "(", "self", ",", "event", ")", ":", "cursor", "=", "self", ".", "cursorForPosition", "(", "event", ".", "pos", "(", ")", ")", "self", ".", "_last_mouse_pos", "=", "event", ".", "pos", "(", ")", "block_found", "=", "False", "fo...
Overrides mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event. :param event: QMouseEvent
[ "Overrides", "mouseMovedEvent", "to", "display", "any", "decoration", "tooltip", "and", "emits", "the", "mouse_moved", "event", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1063-L1093
train
46,558
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.showEvent
def showEvent(self, event): """ Overrides showEvent to update the viewport margins """ super(CodeEdit, self).showEvent(event) self.panels.refresh()
python
def showEvent(self, event): """ Overrides showEvent to update the viewport margins """ super(CodeEdit, self).showEvent(event) self.panels.refresh()
[ "def", "showEvent", "(", "self", ",", "event", ")", ":", "super", "(", "CodeEdit", ",", "self", ")", ".", "showEvent", "(", "event", ")", "self", ".", "panels", ".", "refresh", "(", ")" ]
Overrides showEvent to update the viewport margins
[ "Overrides", "showEvent", "to", "update", "the", "viewport", "margins" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1095-L1098
train
46,559
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit.get_context_menu
def get_context_menu(self): """ Gets the editor context menu. :return: QMenu """ mnu = QtWidgets.QMenu() mnu.addActions(self._actions) mnu.addSeparator() for menu in self._menus: mnu.addMenu(menu) return mnu
python
def get_context_menu(self): """ Gets the editor context menu. :return: QMenu """ mnu = QtWidgets.QMenu() mnu.addActions(self._actions) mnu.addSeparator() for menu in self._menus: mnu.addMenu(menu) return mnu
[ "def", "get_context_menu", "(", "self", ")", ":", "mnu", "=", "QtWidgets", ".", "QMenu", "(", ")", "mnu", ".", "addActions", "(", "self", ".", "_actions", ")", "mnu", ".", "addSeparator", "(", ")", "for", "menu", "in", "self", ".", "_menus", ":", "mn...
Gets the editor context menu. :return: QMenu
[ "Gets", "the", "editor", "context", "menu", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1112-L1123
train
46,560
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit._show_context_menu
def _show_context_menu(self, point): """ Shows the context menu """ tc = self.textCursor() nc = self.cursorForPosition(point) if not nc.position() in range(tc.selectionStart(), tc.selectionEnd()): self.setTextCursor(nc) self._mnu = self.get_context_menu() if len(self._mnu.actions()) > 1 and self.show_context_menu: self._mnu.popup(self.mapToGlobal(point))
python
def _show_context_menu(self, point): """ Shows the context menu """ tc = self.textCursor() nc = self.cursorForPosition(point) if not nc.position() in range(tc.selectionStart(), tc.selectionEnd()): self.setTextCursor(nc) self._mnu = self.get_context_menu() if len(self._mnu.actions()) > 1 and self.show_context_menu: self._mnu.popup(self.mapToGlobal(point))
[ "def", "_show_context_menu", "(", "self", ",", "point", ")", ":", "tc", "=", "self", ".", "textCursor", "(", ")", "nc", "=", "self", ".", "cursorForPosition", "(", "point", ")", "if", "not", "nc", ".", "position", "(", ")", "in", "range", "(", "tc", ...
Shows the context menu
[ "Shows", "the", "context", "menu" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1125-L1133
train
46,561
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit._set_whitespaces_flags
def _set_whitespaces_flags(self, show): """ Sets show white spaces flag """ doc = self.document() options = doc.defaultTextOption() if show: options.setFlags(options.flags() | QtGui.QTextOption.ShowTabsAndSpaces) else: options.setFlags( options.flags() & ~QtGui.QTextOption.ShowTabsAndSpaces) doc.setDefaultTextOption(options)
python
def _set_whitespaces_flags(self, show): """ Sets show white spaces flag """ doc = self.document() options = doc.defaultTextOption() if show: options.setFlags(options.flags() | QtGui.QTextOption.ShowTabsAndSpaces) else: options.setFlags( options.flags() & ~QtGui.QTextOption.ShowTabsAndSpaces) doc.setDefaultTextOption(options)
[ "def", "_set_whitespaces_flags", "(", "self", ",", "show", ")", ":", "doc", "=", "self", ".", "document", "(", ")", "options", "=", "doc", ".", "defaultTextOption", "(", ")", "if", "show", ":", "options", ".", "setFlags", "(", "options", ".", "flags", ...
Sets show white spaces flag
[ "Sets", "show", "white", "spaces", "flag" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1135-L1145
train
46,562
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit._init_style
def _init_style(self): """ Inits style options """ self._background = QtGui.QColor('white') self._foreground = QtGui.QColor('black') self._whitespaces_foreground = QtGui.QColor('light gray') app = QtWidgets.QApplication.instance() self._sel_background = app.palette().highlight().color() self._sel_foreground = app.palette().highlightedText().color() self._font_size = 10 self.font_name = ""
python
def _init_style(self): """ Inits style options """ self._background = QtGui.QColor('white') self._foreground = QtGui.QColor('black') self._whitespaces_foreground = QtGui.QColor('light gray') app = QtWidgets.QApplication.instance() self._sel_background = app.palette().highlight().color() self._sel_foreground = app.palette().highlightedText().color() self._font_size = 10 self.font_name = ""
[ "def", "_init_style", "(", "self", ")", ":", "self", ".", "_background", "=", "QtGui", ".", "QColor", "(", "'white'", ")", "self", ".", "_foreground", "=", "QtGui", ".", "QColor", "(", "'black'", ")", "self", ".", "_whitespaces_foreground", "=", "QtGui", ...
Inits style options
[ "Inits", "style", "options" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1263-L1272
train
46,563
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit._update_visible_blocks
def _update_visible_blocks(self, *args): """ Updates the list of visible blocks """ self._visible_blocks[:] = [] block = self.firstVisibleBlock() block_nbr = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated( self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) ebottom_top = 0 ebottom_bottom = self.height() while block.isValid(): visible = (top >= ebottom_top and bottom <= ebottom_bottom) if not visible: break if block.isVisible(): self._visible_blocks.append((top, block_nbr, block)) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) block_nbr = block.blockNumber()
python
def _update_visible_blocks(self, *args): """ Updates the list of visible blocks """ self._visible_blocks[:] = [] block = self.firstVisibleBlock() block_nbr = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated( self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) ebottom_top = 0 ebottom_bottom = self.height() while block.isValid(): visible = (top >= ebottom_top and bottom <= ebottom_bottom) if not visible: break if block.isVisible(): self._visible_blocks.append((top, block_nbr, block)) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) block_nbr = block.blockNumber()
[ "def", "_update_visible_blocks", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_visible_blocks", "[", ":", "]", "=", "[", "]", "block", "=", "self", ".", "firstVisibleBlock", "(", ")", "block_nbr", "=", "block", ".", "blockNumber", "(", ")", "...
Updates the list of visible blocks
[ "Updates", "the", "list", "of", "visible", "blocks" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1274-L1293
train
46,564
pyQode/pyqode.core
pyqode/core/api/code_edit.py
CodeEdit._on_text_changed
def _on_text_changed(self): """ Adjust dirty flag depending on editor's content """ if not self._cleaning: ln = TextHelper(self).cursor_position()[0] self._modified_lines.add(ln)
python
def _on_text_changed(self): """ Adjust dirty flag depending on editor's content """ if not self._cleaning: ln = TextHelper(self).cursor_position()[0] self._modified_lines.add(ln)
[ "def", "_on_text_changed", "(", "self", ")", ":", "if", "not", "self", ".", "_cleaning", ":", "ln", "=", "TextHelper", "(", "self", ")", ".", "cursor_position", "(", ")", "[", "0", "]", "self", ".", "_modified_lines", ".", "add", "(", "ln", ")" ]
Adjust dirty flag depending on editor's content
[ "Adjust", "dirty", "flag", "depending", "on", "editor", "s", "content" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1295-L1299
train
46,565
bmwcarit/zubbi
zubbi/extensions.py
cached
def cached(key, timeout=3600): """Cache the return value of the decorated function with the given key. Key can be a String or a function. If key is a function, it must have the same arguments as the decorated function, otherwise it cannot be called successfully. """ def decorator(f): @wraps(f) def wrapped(*args, **kwargs): cache = get_cache() # Check if key is a function if callable(key): cache_key = key(*args, **kwargs) else: cache_key = key # Try to get the value from cache cached_val = cache.get(cache_key) if cached_val is None: # Call the original function and cache the result cached_val = f(*args, **kwargs) cache.set(cache_key, cached_val, timeout) return cached_val return wrapped return decorator
python
def cached(key, timeout=3600): """Cache the return value of the decorated function with the given key. Key can be a String or a function. If key is a function, it must have the same arguments as the decorated function, otherwise it cannot be called successfully. """ def decorator(f): @wraps(f) def wrapped(*args, **kwargs): cache = get_cache() # Check if key is a function if callable(key): cache_key = key(*args, **kwargs) else: cache_key = key # Try to get the value from cache cached_val = cache.get(cache_key) if cached_val is None: # Call the original function and cache the result cached_val = f(*args, **kwargs) cache.set(cache_key, cached_val, timeout) return cached_val return wrapped return decorator
[ "def", "cached", "(", "key", ",", "timeout", "=", "3600", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cache", "=", "get_cache", "(", ")",...
Cache the return value of the decorated function with the given key. Key can be a String or a function. If key is a function, it must have the same arguments as the decorated function, otherwise it cannot be called successfully.
[ "Cache", "the", "return", "value", "of", "the", "decorated", "function", "with", "the", "given", "key", "." ]
b99dfd6113c0351f13876f4172648c2eb63468ba
https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/extensions.py#L23-L50
train
46,566
pyQode/pyqode.core
pyqode/core/widgets/errors_table.py
ErrorsTable._copy_cell_text
def _copy_cell_text(self): """ Copies the description of the selected message to the clipboard """ txt = self.currentItem().text() QtWidgets.QApplication.clipboard().setText(txt)
python
def _copy_cell_text(self): """ Copies the description of the selected message to the clipboard """ txt = self.currentItem().text() QtWidgets.QApplication.clipboard().setText(txt)
[ "def", "_copy_cell_text", "(", "self", ")", ":", "txt", "=", "self", ".", "currentItem", "(", ")", ".", "text", "(", ")", "QtWidgets", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "txt", ")" ]
Copies the description of the selected message to the clipboard
[ "Copies", "the", "description", "of", "the", "selected", "message", "to", "the", "clipboard" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L68-L73
train
46,567
pyQode/pyqode.core
pyqode/core/widgets/errors_table.py
ErrorsTable.clear
def clear(self): """ Clears the tables and the message list """ QtWidgets.QTableWidget.clear(self) self.setRowCount(0) self.setColumnCount(4) self.setHorizontalHeaderLabels( ["Type", "File name", "Line", "Description"])
python
def clear(self): """ Clears the tables and the message list """ QtWidgets.QTableWidget.clear(self) self.setRowCount(0) self.setColumnCount(4) self.setHorizontalHeaderLabels( ["Type", "File name", "Line", "Description"])
[ "def", "clear", "(", "self", ")", ":", "QtWidgets", ".", "QTableWidget", ".", "clear", "(", "self", ")", "self", ".", "setRowCount", "(", "0", ")", "self", ".", "setColumnCount", "(", "4", ")", "self", ".", "setHorizontalHeaderLabels", "(", "[", "\"Type\...
Clears the tables and the message list
[ "Clears", "the", "tables", "and", "the", "message", "list" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L79-L87
train
46,568
pyQode/pyqode.core
pyqode/core/widgets/errors_table.py
ErrorsTable.add_message
def add_message(self, msg): """ Adds a checker message to the table. :param msg: The message to append :type msg: pyqode.core.modes.CheckerMessage """ row = self.rowCount() self.insertRow(row) # type item = QtWidgets.QTableWidgetItem( self._make_icon(msg.status), msg.status_string) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_TYPE, item) # filename item = QtWidgets.QTableWidgetItem( QtCore.QFileInfo(msg.path).fileName()) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_FILE_NAME, item) # line if msg.line < 0: item = QtWidgets.QTableWidgetItem("-") else: item = QtWidgets.QTableWidgetItem(str(msg.line + 1)) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_LINE_NBR, item) # desc item = QtWidgets.QTableWidgetItem(msg.description) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_MSG, item)
python
def add_message(self, msg): """ Adds a checker message to the table. :param msg: The message to append :type msg: pyqode.core.modes.CheckerMessage """ row = self.rowCount() self.insertRow(row) # type item = QtWidgets.QTableWidgetItem( self._make_icon(msg.status), msg.status_string) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_TYPE, item) # filename item = QtWidgets.QTableWidgetItem( QtCore.QFileInfo(msg.path).fileName()) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_FILE_NAME, item) # line if msg.line < 0: item = QtWidgets.QTableWidgetItem("-") else: item = QtWidgets.QTableWidgetItem(str(msg.line + 1)) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_LINE_NBR, item) # desc item = QtWidgets.QTableWidgetItem(msg.description) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self.setItem(row, COL_MSG, item)
[ "def", "add_message", "(", "self", ",", "msg", ")", ":", "row", "=", "self", ".", "rowCount", "(", ")", "self", ".", "insertRow", "(", "row", ")", "# type", "item", "=", "QtWidgets", ".", "QTableWidgetItem", "(", "self", ".", "_make_icon", "(", "msg", ...
Adds a checker message to the table. :param msg: The message to append :type msg: pyqode.core.modes.CheckerMessage
[ "Adds", "a", "checker", "message", "to", "the", "table", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L106-L143
train
46,569
pyQode/pyqode.core
pyqode/core/widgets/errors_table.py
ErrorsTable._on_item_activated
def _on_item_activated(self, item): """ Emits the message activated signal """ msg = item.data(QtCore.Qt.UserRole) self.msg_activated.emit(msg)
python
def _on_item_activated(self, item): """ Emits the message activated signal """ msg = item.data(QtCore.Qt.UserRole) self.msg_activated.emit(msg)
[ "def", "_on_item_activated", "(", "self", ",", "item", ")", ":", "msg", "=", "item", ".", "data", "(", "QtCore", ".", "Qt", ".", "UserRole", ")", "self", ".", "msg_activated", ".", "emit", "(", "msg", ")" ]
Emits the message activated signal
[ "Emits", "the", "message", "activated", "signal" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L145-L150
train
46,570
pyQode/pyqode.core
pyqode/core/widgets/errors_table.py
ErrorsTable.showDetails
def showDetails(self): """ Shows the error details. """ msg = self.currentItem().data(QtCore.Qt.UserRole) desc = msg.description desc = desc.replace('\r\n', '\n').replace('\r', '\n') desc = desc.replace('\n', '<br/>') QtWidgets.QMessageBox.information( self, _('Message details'), _("""<p><b>Description:</b><br/>%s</p> <p><b>File:</b><br/>%s</p> <p><b>Line:</b><br/>%d</p> """) % (desc, msg.path, msg.line + 1, ))
python
def showDetails(self): """ Shows the error details. """ msg = self.currentItem().data(QtCore.Qt.UserRole) desc = msg.description desc = desc.replace('\r\n', '\n').replace('\r', '\n') desc = desc.replace('\n', '<br/>') QtWidgets.QMessageBox.information( self, _('Message details'), _("""<p><b>Description:</b><br/>%s</p> <p><b>File:</b><br/>%s</p> <p><b>Line:</b><br/>%d</p> """) % (desc, msg.path, msg.line + 1, ))
[ "def", "showDetails", "(", "self", ")", ":", "msg", "=", "self", ".", "currentItem", "(", ")", ".", "data", "(", "QtCore", ".", "Qt", ".", "UserRole", ")", "desc", "=", "msg", ".", "description", "desc", "=", "desc", ".", "replace", "(", "'\\r\\n'", ...
Shows the error details.
[ "Shows", "the", "error", "details", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L152-L165
train
46,571
pyQode/pyqode.core
pyqode/core/dialogs/goto.py
DlgGotoLine.get_line
def get_line(cls, parent, current_line, line_count): """ Gets user selected line. :param parent: Parent widget :param current_line: Current line number :param line_count: Number of lines in the current text document. :returns: tuple(line, status) status is False if the dialog has been rejected. """ dlg = DlgGotoLine(parent, current_line + 1, line_count) if dlg.exec_() == dlg.Accepted: return dlg.spinBox.value() - 1, True return current_line, False
python
def get_line(cls, parent, current_line, line_count): """ Gets user selected line. :param parent: Parent widget :param current_line: Current line number :param line_count: Number of lines in the current text document. :returns: tuple(line, status) status is False if the dialog has been rejected. """ dlg = DlgGotoLine(parent, current_line + 1, line_count) if dlg.exec_() == dlg.Accepted: return dlg.spinBox.value() - 1, True return current_line, False
[ "def", "get_line", "(", "cls", ",", "parent", ",", "current_line", ",", "line_count", ")", ":", "dlg", "=", "DlgGotoLine", "(", "parent", ",", "current_line", "+", "1", ",", "line_count", ")", "if", "dlg", ".", "exec_", "(", ")", "==", "dlg", ".", "A...
Gets user selected line. :param parent: Parent widget :param current_line: Current line number :param line_count: Number of lines in the current text document. :returns: tuple(line, status) status is False if the dialog has been rejected.
[ "Gets", "user", "selected", "line", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/dialogs/goto.py#L28-L42
train
46,572
pyQode/pyqode.core
pyqode/core/panels/search_and_replace.py
SearchAndReplacePanel.close_panel
def close_panel(self): """ Closes the panel """ self.hide() self.lineEditReplace.clear() self.lineEditSearch.clear()
python
def close_panel(self): """ Closes the panel """ self.hide() self.lineEditReplace.clear() self.lineEditSearch.clear()
[ "def", "close_panel", "(", "self", ")", ":", "self", ".", "hide", "(", ")", "self", ".", "lineEditReplace", ".", "clear", "(", ")", "self", ".", "lineEditSearch", ".", "clear", "(", ")" ]
Closes the panel
[ "Closes", "the", "panel" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L267-L273
train
46,573
pyQode/pyqode.core
pyqode/core/panels/search_and_replace.py
SearchAndReplacePanel.request_search
def request_search(self, txt=None): """ Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead. """ if self.checkBoxRegex.isChecked(): try: re.compile(self.lineEditSearch.text(), re.DOTALL) except sre_constants.error as e: self._show_error(e) return else: self._show_error(None) if txt is None or isinstance(txt, int): txt = self.lineEditSearch.text() if txt: self.job_runner.request_job( self._exec_search, txt, self._search_flags()) else: self.job_runner.cancel_requests() self._clear_occurrences() self._on_search_finished()
python
def request_search(self, txt=None): """ Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead. """ if self.checkBoxRegex.isChecked(): try: re.compile(self.lineEditSearch.text(), re.DOTALL) except sre_constants.error as e: self._show_error(e) return else: self._show_error(None) if txt is None or isinstance(txt, int): txt = self.lineEditSearch.text() if txt: self.job_runner.request_job( self._exec_search, txt, self._search_flags()) else: self.job_runner.cancel_requests() self._clear_occurrences() self._on_search_finished()
[ "def", "request_search", "(", "self", ",", "txt", "=", "None", ")", ":", "if", "self", ".", "checkBoxRegex", ".", "isChecked", "(", ")", ":", "try", ":", "re", ".", "compile", "(", "self", ".", "lineEditSearch", ".", "text", "(", ")", ",", "re", "....
Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead.
[ "Requests", "a", "search", "operation", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L309-L333
train
46,574
pyQode/pyqode.core
pyqode/core/panels/search_and_replace.py
SearchAndReplacePanel.select_next
def select_next(self): """ Selects the next occurrence. :return: True in case of success, false if no occurrence could be selected. """ current_occurence = self._current_occurrence() occurrences = self.get_occurences() if not occurrences: return current = self._occurrences[current_occurence] cursor_pos = self.editor.textCursor().position() if cursor_pos not in range(current[0], current[1] + 1) or \ current_occurence == -1: # search first occurrence that occurs after the cursor position current_occurence = 0 for i, (start, end) in enumerate(self._occurrences): if end > cursor_pos: current_occurence = i break else: if (current_occurence == -1 or current_occurence >= len(occurrences) - 1): current_occurence = 0 else: current_occurence += 1 self._set_current_occurrence(current_occurence) try: cursor = self.editor.textCursor() cursor.setPosition(occurrences[current_occurence][0]) cursor.setPosition(occurrences[current_occurence][1], cursor.KeepAnchor) self.editor.setTextCursor(cursor) return True except IndexError: return False
python
def select_next(self): """ Selects the next occurrence. :return: True in case of success, false if no occurrence could be selected. """ current_occurence = self._current_occurrence() occurrences = self.get_occurences() if not occurrences: return current = self._occurrences[current_occurence] cursor_pos = self.editor.textCursor().position() if cursor_pos not in range(current[0], current[1] + 1) or \ current_occurence == -1: # search first occurrence that occurs after the cursor position current_occurence = 0 for i, (start, end) in enumerate(self._occurrences): if end > cursor_pos: current_occurence = i break else: if (current_occurence == -1 or current_occurence >= len(occurrences) - 1): current_occurence = 0 else: current_occurence += 1 self._set_current_occurrence(current_occurence) try: cursor = self.editor.textCursor() cursor.setPosition(occurrences[current_occurence][0]) cursor.setPosition(occurrences[current_occurence][1], cursor.KeepAnchor) self.editor.setTextCursor(cursor) return True except IndexError: return False
[ "def", "select_next", "(", "self", ")", ":", "current_occurence", "=", "self", ".", "_current_occurrence", "(", ")", "occurrences", "=", "self", ".", "get_occurences", "(", ")", "if", "not", "occurrences", ":", "return", "current", "=", "self", ".", "_occurr...
Selects the next occurrence. :return: True in case of success, false if no occurrence could be selected.
[ "Selects", "the", "next", "occurrence", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L367-L403
train
46,575
pyQode/pyqode.core
pyqode/core/panels/search_and_replace.py
SearchAndReplacePanel.replace
def replace(self, text=None): """ Replaces the selected occurrence. :param text: The replacement text. If it is None, the lineEditReplace's text is used instead. :return True if the text could be replace properly, False if there is no more occurrences to replace. """ if text is None or isinstance(text, bool): text = self.lineEditReplace.text() current_occurences = self._current_occurrence() occurrences = self.get_occurences() if current_occurences == -1: self.select_next() current_occurences = self._current_occurrence() try: # prevent search request due to editor textChanged try: self.editor.textChanged.disconnect(self.request_search) except (RuntimeError, TypeError): # already disconnected pass occ = occurrences[current_occurences] cursor = self.editor.textCursor() cursor.setPosition(occ[0]) cursor.setPosition(occ[1], cursor.KeepAnchor) len_to_replace = len(cursor.selectedText()) len_replacement = len(text) offset = len_replacement - len_to_replace cursor.insertText(text) self.editor.setTextCursor(cursor) self._remove_occurrence(current_occurences, offset) current_occurences -= 1 self._set_current_occurrence(current_occurences) self.select_next() self.cpt_occurences = len(self.get_occurences()) self._update_label_matches() self._update_buttons() return True except IndexError: return False finally: self.editor.textChanged.connect(self.request_search)
python
def replace(self, text=None): """ Replaces the selected occurrence. :param text: The replacement text. If it is None, the lineEditReplace's text is used instead. :return True if the text could be replace properly, False if there is no more occurrences to replace. """ if text is None or isinstance(text, bool): text = self.lineEditReplace.text() current_occurences = self._current_occurrence() occurrences = self.get_occurences() if current_occurences == -1: self.select_next() current_occurences = self._current_occurrence() try: # prevent search request due to editor textChanged try: self.editor.textChanged.disconnect(self.request_search) except (RuntimeError, TypeError): # already disconnected pass occ = occurrences[current_occurences] cursor = self.editor.textCursor() cursor.setPosition(occ[0]) cursor.setPosition(occ[1], cursor.KeepAnchor) len_to_replace = len(cursor.selectedText()) len_replacement = len(text) offset = len_replacement - len_to_replace cursor.insertText(text) self.editor.setTextCursor(cursor) self._remove_occurrence(current_occurences, offset) current_occurences -= 1 self._set_current_occurrence(current_occurences) self.select_next() self.cpt_occurences = len(self.get_occurences()) self._update_label_matches() self._update_buttons() return True except IndexError: return False finally: self.editor.textChanged.connect(self.request_search)
[ "def", "replace", "(", "self", ",", "text", "=", "None", ")", ":", "if", "text", "is", "None", "or", "isinstance", "(", "text", ",", "bool", ")", ":", "text", "=", "self", ".", "lineEditReplace", ".", "text", "(", ")", "current_occurences", "=", "sel...
Replaces the selected occurrence. :param text: The replacement text. If it is None, the lineEditReplace's text is used instead. :return True if the text could be replace properly, False if there is no more occurrences to replace.
[ "Replaces", "the", "selected", "occurrence", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L443-L487
train
46,576
pyQode/pyqode.core
pyqode/core/panels/search_and_replace.py
SearchAndReplacePanel.replace_all
def replace_all(self, text=None): """ Replaces all occurrences in the editor's document. :param text: The replacement text. If None, the content of the lineEdit replace will be used instead """ cursor = self.editor.textCursor() cursor.beginEditBlock() remains = self.replace(text=text) while remains: remains = self.replace(text=text) cursor.endEditBlock()
python
def replace_all(self, text=None): """ Replaces all occurrences in the editor's document. :param text: The replacement text. If None, the content of the lineEdit replace will be used instead """ cursor = self.editor.textCursor() cursor.beginEditBlock() remains = self.replace(text=text) while remains: remains = self.replace(text=text) cursor.endEditBlock()
[ "def", "replace_all", "(", "self", ",", "text", "=", "None", ")", ":", "cursor", "=", "self", ".", "editor", ".", "textCursor", "(", ")", "cursor", ".", "beginEditBlock", "(", ")", "remains", "=", "self", ".", "replace", "(", "text", "=", "text", ")"...
Replaces all occurrences in the editor's document. :param text: The replacement text. If None, the content of the lineEdit replace will be used instead
[ "Replaces", "all", "occurrences", "in", "the", "editor", "s", "document", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L489-L501
train
46,577
pyQode/pyqode.core
pyqode/core/panels/search_and_replace.py
SearchAndReplacePanel._create_decoration
def _create_decoration(self, selection_start, selection_end): """ Creates the text occurences decoration """ deco = TextDecoration(self.editor.document(), selection_start, selection_end) deco.set_background(QtGui.QBrush(self.background)) deco.set_outline(self._outline) deco.set_foreground(QtCore.Qt.black) deco.draw_order = 1 return deco
python
def _create_decoration(self, selection_start, selection_end): """ Creates the text occurences decoration """ deco = TextDecoration(self.editor.document(), selection_start, selection_end) deco.set_background(QtGui.QBrush(self.background)) deco.set_outline(self._outline) deco.set_foreground(QtCore.Qt.black) deco.draw_order = 1 return deco
[ "def", "_create_decoration", "(", "self", ",", "selection_start", ",", "selection_end", ")", ":", "deco", "=", "TextDecoration", "(", "self", ".", "editor", ".", "document", "(", ")", ",", "selection_start", ",", "selection_end", ")", "deco", ".", "set_backgro...
Creates the text occurences decoration
[ "Creates", "the", "text", "occurences", "decoration" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L599-L607
train
46,578
pyQode/pyqode.core
pyqode/core/api/client.py
JsonTcpClient._send_request
def _send_request(self): """ Sends the request to the backend. """ if isinstance(self._worker, str): classname = self._worker else: classname = '%s.%s' % (self._worker.__module__, self._worker.__name__) self.request_id = str(uuid.uuid4()) self.send({'request_id': self.request_id, 'worker': classname, 'data': self._args})
python
def _send_request(self): """ Sends the request to the backend. """ if isinstance(self._worker, str): classname = self._worker else: classname = '%s.%s' % (self._worker.__module__, self._worker.__name__) self.request_id = str(uuid.uuid4()) self.send({'request_id': self.request_id, 'worker': classname, 'data': self._args})
[ "def", "_send_request", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_worker", ",", "str", ")", ":", "classname", "=", "self", ".", "_worker", "else", ":", "classname", "=", "'%s.%s'", "%", "(", "self", ".", "_worker", ".", "__module__...
Sends the request to the backend.
[ "Sends", "the", "request", "to", "the", "backend", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L210-L221
train
46,579
pyQode/pyqode.core
pyqode/core/api/client.py
JsonTcpClient._connect
def _connect(self): """ Connects our client socket to the backend socket """ if self is None: return comm('connecting to 127.0.0.1:%d', self._port) address = QtNetwork.QHostAddress('127.0.0.1') self.connectToHost(address, self._port) if sys.platform == 'darwin': self.waitForConnected()
python
def _connect(self): """ Connects our client socket to the backend socket """ if self is None: return comm('connecting to 127.0.0.1:%d', self._port) address = QtNetwork.QHostAddress('127.0.0.1') self.connectToHost(address, self._port) if sys.platform == 'darwin': self.waitForConnected()
[ "def", "_connect", "(", "self", ")", ":", "if", "self", "is", "None", ":", "return", "comm", "(", "'connecting to 127.0.0.1:%d'", ",", "self", ".", "_port", ")", "address", "=", "QtNetwork", ".", "QHostAddress", "(", "'127.0.0.1'", ")", "self", ".", "conne...
Connects our client socket to the backend socket
[ "Connects", "our", "client", "socket", "to", "the", "backend", "socket" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L248-L256
train
46,580
pyQode/pyqode.core
pyqode/core/api/client.py
JsonTcpClient._on_ready_read
def _on_ready_read(self): """ Read bytes when ready read """ while self.bytesAvailable(): if not self._header_complete: self._read_header() else: self._read_payload()
python
def _on_ready_read(self): """ Read bytes when ready read """ while self.bytesAvailable(): if not self._header_complete: self._read_header() else: self._read_payload()
[ "def", "_on_ready_read", "(", "self", ")", ":", "while", "self", ".", "bytesAvailable", "(", ")", ":", "if", "not", "self", ".", "_header_complete", ":", "self", ".", "_read_header", "(", ")", "else", ":", "self", ".", "_read_payload", "(", ")" ]
Read bytes when ready read
[ "Read", "bytes", "when", "ready", "read" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L334-L340
train
46,581
pyQode/pyqode.core
pyqode/core/api/client.py
BackendProcess._on_process_started
def _on_process_started(self): """ Logs process started """ comm('backend process started') if self is None: return self.starting = False self.running = True
python
def _on_process_started(self): """ Logs process started """ comm('backend process started') if self is None: return self.starting = False self.running = True
[ "def", "_on_process_started", "(", "self", ")", ":", "comm", "(", "'backend process started'", ")", "if", "self", "is", "None", ":", "return", "self", ".", "starting", "=", "False", "self", ".", "running", "=", "True" ]
Logs process started
[ "Logs", "process", "started" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L362-L368
train
46,582
pyQode/pyqode.core
pyqode/core/api/client.py
BackendProcess._on_process_error
def _on_process_error(self, error): """ Logs process error """ if self is None: return if error not in PROCESS_ERROR_STRING: error = -1 if not self._prevent_logs: _logger().warning(PROCESS_ERROR_STRING[error])
python
def _on_process_error(self, error): """ Logs process error """ if self is None: return if error not in PROCESS_ERROR_STRING: error = -1 if not self._prevent_logs: _logger().warning(PROCESS_ERROR_STRING[error])
[ "def", "_on_process_error", "(", "self", ",", "error", ")", ":", "if", "self", "is", "None", ":", "return", "if", "error", "not", "in", "PROCESS_ERROR_STRING", ":", "error", "=", "-", "1", "if", "not", "self", ".", "_prevent_logs", ":", "_logger", "(", ...
Logs process error
[ "Logs", "process", "error" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L370-L377
train
46,583
pyQode/pyqode.core
pyqode/core/api/client.py
BackendProcess._on_process_stdout_ready
def _on_process_stdout_ready(self): """ Logs process output """ if not self: return o = self.readAllStandardOutput() try: output = bytes(o).decode(self._encoding) except TypeError: output = bytes(o.data()).decode(self._encoding) for line in output.splitlines(): self._srv_logger.log(1, line)
python
def _on_process_stdout_ready(self): """ Logs process output """ if not self: return o = self.readAllStandardOutput() try: output = bytes(o).decode(self._encoding) except TypeError: output = bytes(o.data()).decode(self._encoding) for line in output.splitlines(): self._srv_logger.log(1, line)
[ "def", "_on_process_stdout_ready", "(", "self", ")", ":", "if", "not", "self", ":", "return", "o", "=", "self", ".", "readAllStandardOutput", "(", ")", "try", ":", "output", "=", "bytes", "(", "o", ")", ".", "decode", "(", "self", ".", "_encoding", ")"...
Logs process output
[ "Logs", "process", "output" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L387-L397
train
46,584
pyQode/pyqode.core
pyqode/core/modes/pygments_sh.py
replace_pattern
def replace_pattern(tokens, new_pattern): """ Given a RegexLexer token dictionary 'tokens', replace all patterns that match the token specified in 'new_pattern' with 'new_pattern'. """ for state in tokens.values(): for index, pattern in enumerate(state): if isinstance(pattern, tuple) and pattern[1] == new_pattern[1]: state[index] = new_pattern
python
def replace_pattern(tokens, new_pattern): """ Given a RegexLexer token dictionary 'tokens', replace all patterns that match the token specified in 'new_pattern' with 'new_pattern'. """ for state in tokens.values(): for index, pattern in enumerate(state): if isinstance(pattern, tuple) and pattern[1] == new_pattern[1]: state[index] = new_pattern
[ "def", "replace_pattern", "(", "tokens", ",", "new_pattern", ")", ":", "for", "state", "in", "tokens", ".", "values", "(", ")", ":", "for", "index", ",", "pattern", "in", "enumerate", "(", "state", ")", ":", "if", "isinstance", "(", "pattern", ",", "tu...
Given a RegexLexer token dictionary 'tokens', replace all patterns that match the token specified in 'new_pattern' with 'new_pattern'.
[ "Given", "a", "RegexLexer", "token", "dictionary", "tokens", "replace", "all", "patterns", "that", "match", "the", "token", "specified", "in", "new_pattern", "with", "new_pattern", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L108-L115
train
46,585
pyQode/pyqode.core
pyqode/core/modes/pygments_sh.py
PygmentsSH.set_mime_type
def set_mime_type(self, mime_type): """ Update the highlighter lexer based on a mime type. :param mime_type: mime type of the new lexer to setup. """ try: self.set_lexer_from_mime_type(mime_type) except ClassNotFound: _logger().exception('failed to get lexer from mimetype') self._lexer = TextLexer() return False except ImportError: # import error while loading some pygments plugins, the editor # should not crash _logger().warning('failed to get lexer from mimetype (%s)' % mime_type) self._lexer = TextLexer() return False else: return True
python
def set_mime_type(self, mime_type): """ Update the highlighter lexer based on a mime type. :param mime_type: mime type of the new lexer to setup. """ try: self.set_lexer_from_mime_type(mime_type) except ClassNotFound: _logger().exception('failed to get lexer from mimetype') self._lexer = TextLexer() return False except ImportError: # import error while loading some pygments plugins, the editor # should not crash _logger().warning('failed to get lexer from mimetype (%s)' % mime_type) self._lexer = TextLexer() return False else: return True
[ "def", "set_mime_type", "(", "self", ",", "mime_type", ")", ":", "try", ":", "self", ".", "set_lexer_from_mime_type", "(", "mime_type", ")", "except", "ClassNotFound", ":", "_logger", "(", ")", ".", "exception", "(", "'failed to get lexer from mimetype'", ")", "...
Update the highlighter lexer based on a mime type. :param mime_type: mime type of the new lexer to setup.
[ "Update", "the", "highlighter", "lexer", "based", "on", "a", "mime", "type", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L185-L205
train
46,586
pyQode/pyqode.core
pyqode/core/modes/pygments_sh.py
PygmentsSH.set_lexer_from_mime_type
def set_lexer_from_mime_type(self, mime, **options): """ Sets the pygments lexer from mime type. :param mime: mime type :param options: optional addtional options. """ self._lexer = get_lexer_for_mimetype(mime, **options) _logger().debug('lexer for mimetype (%s): %r', mime, self._lexer)
python
def set_lexer_from_mime_type(self, mime, **options): """ Sets the pygments lexer from mime type. :param mime: mime type :param options: optional addtional options. """ self._lexer = get_lexer_for_mimetype(mime, **options) _logger().debug('lexer for mimetype (%s): %r', mime, self._lexer)
[ "def", "set_lexer_from_mime_type", "(", "self", ",", "mime", ",", "*", "*", "options", ")", ":", "self", ".", "_lexer", "=", "get_lexer_for_mimetype", "(", "mime", ",", "*", "*", "options", ")", "_logger", "(", ")", ".", "debug", "(", "'lexer for mimetype ...
Sets the pygments lexer from mime type. :param mime: mime type :param options: optional addtional options.
[ "Sets", "the", "pygments", "lexer", "from", "mime", "type", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L232-L240
train
46,587
pyQode/pyqode.core
pyqode/core/modes/pygments_sh.py
PygmentsSH.highlight_block
def highlight_block(self, text, block): """ Highlights the block using a pygments lexer. :param text: text of the block to highlith :param block: block to highlight """ if self.color_scheme.name != self._pygments_style: self._pygments_style = self.color_scheme.name self._update_style() original_text = text if self.editor and self._lexer and self.enabled: if block.blockNumber(): prev_data = self._prev_block.userData() if prev_data: if hasattr(prev_data, "syntax_stack"): self._lexer._saved_state_stack = prev_data.syntax_stack elif hasattr(self._lexer, '_saved_state_stack'): del self._lexer._saved_state_stack # Lex the text using Pygments index = 0 usd = block.userData() if usd is None: usd = TextBlockUserData() block.setUserData(usd) tokens = list(self._lexer.get_tokens(text)) for token, text in tokens: length = len(text) fmt = self._get_format(token) if token in [Token.Literal.String, Token.Literal.String.Doc, Token.Comment]: fmt.setObjectType(fmt.UserObject) self.setFormat(index, length, fmt) index += length if hasattr(self._lexer, '_saved_state_stack'): setattr(usd, "syntax_stack", self._lexer._saved_state_stack) # Clean up for the next go-round. del self._lexer._saved_state_stack # spaces text = original_text expression = QRegExp(r'\s+') index = expression.indexIn(text, 0) while index >= 0: index = expression.pos(0) length = len(expression.cap(0)) self.setFormat(index, length, self._get_format(Whitespace)) index = expression.indexIn(text, index + length) self._prev_block = block
python
def highlight_block(self, text, block): """ Highlights the block using a pygments lexer. :param text: text of the block to highlith :param block: block to highlight """ if self.color_scheme.name != self._pygments_style: self._pygments_style = self.color_scheme.name self._update_style() original_text = text if self.editor and self._lexer and self.enabled: if block.blockNumber(): prev_data = self._prev_block.userData() if prev_data: if hasattr(prev_data, "syntax_stack"): self._lexer._saved_state_stack = prev_data.syntax_stack elif hasattr(self._lexer, '_saved_state_stack'): del self._lexer._saved_state_stack # Lex the text using Pygments index = 0 usd = block.userData() if usd is None: usd = TextBlockUserData() block.setUserData(usd) tokens = list(self._lexer.get_tokens(text)) for token, text in tokens: length = len(text) fmt = self._get_format(token) if token in [Token.Literal.String, Token.Literal.String.Doc, Token.Comment]: fmt.setObjectType(fmt.UserObject) self.setFormat(index, length, fmt) index += length if hasattr(self._lexer, '_saved_state_stack'): setattr(usd, "syntax_stack", self._lexer._saved_state_stack) # Clean up for the next go-round. del self._lexer._saved_state_stack # spaces text = original_text expression = QRegExp(r'\s+') index = expression.indexIn(text, 0) while index >= 0: index = expression.pos(0) length = len(expression.cap(0)) self.setFormat(index, length, self._get_format(Whitespace)) index = expression.indexIn(text, index + length) self._prev_block = block
[ "def", "highlight_block", "(", "self", ",", "text", ",", "block", ")", ":", "if", "self", ".", "color_scheme", ".", "name", "!=", "self", ".", "_pygments_style", ":", "self", ".", "_pygments_style", "=", "self", ".", "color_scheme", ".", "name", "self", ...
Highlights the block using a pygments lexer. :param text: text of the block to highlith :param block: block to highlight
[ "Highlights", "the", "block", "using", "a", "pygments", "lexer", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L242-L293
train
46,588
pyQode/pyqode.core
pyqode/core/api/utils.py
TextHelper.goto_line
def goto_line(self, line, column=0, move=True): """ Moves the text cursor to the specified position.. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. :return: The new text cursor :rtype: QtGui.QTextCursor """ text_cursor = self.move_cursor_to(line) if column: text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, column) if move: block = text_cursor.block() # unfold parent fold trigger if the block is collapsed try: folding_panel = self._editor.panels.get('FoldingPanel') except KeyError: pass else: from pyqode.core.api.folding import FoldScope if not block.isVisible(): block = FoldScope.find_parent_scope(block) if TextBlockHelper.is_collapsed(block): folding_panel.toggle_fold_trigger(block) self._editor.setTextCursor(text_cursor) return text_cursor
python
def goto_line(self, line, column=0, move=True): """ Moves the text cursor to the specified position.. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. :return: The new text cursor :rtype: QtGui.QTextCursor """ text_cursor = self.move_cursor_to(line) if column: text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, column) if move: block = text_cursor.block() # unfold parent fold trigger if the block is collapsed try: folding_panel = self._editor.panels.get('FoldingPanel') except KeyError: pass else: from pyqode.core.api.folding import FoldScope if not block.isVisible(): block = FoldScope.find_parent_scope(block) if TextBlockHelper.is_collapsed(block): folding_panel.toggle_fold_trigger(block) self._editor.setTextCursor(text_cursor) return text_cursor
[ "def", "goto_line", "(", "self", ",", "line", ",", "column", "=", "0", ",", "move", "=", "True", ")", ":", "text_cursor", "=", "self", ".", "move_cursor_to", "(", "line", ")", "if", "column", ":", "text_cursor", ".", "movePosition", "(", "text_cursor", ...
Moves the text cursor to the specified position.. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. :return: The new text cursor :rtype: QtGui.QTextCursor
[ "Moves", "the", "text", "cursor", "to", "the", "specified", "position", ".." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L149-L178
train
46,589
pyQode/pyqode.core
pyqode/core/api/utils.py
TextHelper.select_lines
def select_lines(self, start=0, end=-1, apply_selection=True): """ Selects entire lines between start and end line numbers. This functions apply the selection and returns the text cursor that contains the selection. Optionally it is possible to prevent the selection from being applied on the code editor widget by setting ``apply_selection`` to False. :param start: Start line number (0 based) :param end: End line number (0 based). Use -1 to select up to the end of the document :param apply_selection: True to apply the selection before returning the QTextCursor. :returns: A QTextCursor that holds the requested selection """ editor = self._editor if end == -1: end = self.line_count() - 1 if start < 0: start = 0 text_cursor = self.move_cursor_to(start) if end > start: # Going down text_cursor.movePosition(text_cursor.Down, text_cursor.KeepAnchor, end - start) text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.KeepAnchor) elif end < start: # going up # don't miss end of line ! text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.MoveAnchor) text_cursor.movePosition(text_cursor.Up, text_cursor.KeepAnchor, start - end) text_cursor.movePosition(text_cursor.StartOfLine, text_cursor.KeepAnchor) else: text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.KeepAnchor) if apply_selection: editor.setTextCursor(text_cursor) return text_cursor
python
def select_lines(self, start=0, end=-1, apply_selection=True): """ Selects entire lines between start and end line numbers. This functions apply the selection and returns the text cursor that contains the selection. Optionally it is possible to prevent the selection from being applied on the code editor widget by setting ``apply_selection`` to False. :param start: Start line number (0 based) :param end: End line number (0 based). Use -1 to select up to the end of the document :param apply_selection: True to apply the selection before returning the QTextCursor. :returns: A QTextCursor that holds the requested selection """ editor = self._editor if end == -1: end = self.line_count() - 1 if start < 0: start = 0 text_cursor = self.move_cursor_to(start) if end > start: # Going down text_cursor.movePosition(text_cursor.Down, text_cursor.KeepAnchor, end - start) text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.KeepAnchor) elif end < start: # going up # don't miss end of line ! text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.MoveAnchor) text_cursor.movePosition(text_cursor.Up, text_cursor.KeepAnchor, start - end) text_cursor.movePosition(text_cursor.StartOfLine, text_cursor.KeepAnchor) else: text_cursor.movePosition(text_cursor.EndOfLine, text_cursor.KeepAnchor) if apply_selection: editor.setTextCursor(text_cursor) return text_cursor
[ "def", "select_lines", "(", "self", ",", "start", "=", "0", ",", "end", "=", "-", "1", ",", "apply_selection", "=", "True", ")", ":", "editor", "=", "self", ".", "_editor", "if", "end", "==", "-", "1", ":", "end", "=", "self", ".", "line_count", ...
Selects entire lines between start and end line numbers. This functions apply the selection and returns the text cursor that contains the selection. Optionally it is possible to prevent the selection from being applied on the code editor widget by setting ``apply_selection`` to False. :param start: Start line number (0 based) :param end: End line number (0 based). Use -1 to select up to the end of the document :param apply_selection: True to apply the selection before returning the QTextCursor. :returns: A QTextCursor that holds the requested selection
[ "Selects", "entire", "lines", "between", "start", "and", "end", "line", "numbers", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L435-L476
train
46,590
pyQode/pyqode.core
pyqode/core/api/utils.py
TextHelper.line_indent
def line_indent(self, line_nbr=None): """ Returns the indent level of the specified line :param line_nbr: Number of the line to get indentation (1 base). Pass None to use the current line number. Note that you can also pass a QTextBlock instance instead of an int. :return: Number of spaces that makes the indentation level of the current line """ if line_nbr is None: line_nbr = self.current_line_nbr() elif isinstance(line_nbr, QtGui.QTextBlock): line_nbr = line_nbr.blockNumber() line = self.line_text(line_nbr) indentation = len(line) - len(line.lstrip()) return indentation
python
def line_indent(self, line_nbr=None): """ Returns the indent level of the specified line :param line_nbr: Number of the line to get indentation (1 base). Pass None to use the current line number. Note that you can also pass a QTextBlock instance instead of an int. :return: Number of spaces that makes the indentation level of the current line """ if line_nbr is None: line_nbr = self.current_line_nbr() elif isinstance(line_nbr, QtGui.QTextBlock): line_nbr = line_nbr.blockNumber() line = self.line_text(line_nbr) indentation = len(line) - len(line.lstrip()) return indentation
[ "def", "line_indent", "(", "self", ",", "line_nbr", "=", "None", ")", ":", "if", "line_nbr", "is", "None", ":", "line_nbr", "=", "self", ".", "current_line_nbr", "(", ")", "elif", "isinstance", "(", "line_nbr", ",", "QtGui", ".", "QTextBlock", ")", ":", ...
Returns the indent level of the specified line :param line_nbr: Number of the line to get indentation (1 base). Pass None to use the current line number. Note that you can also pass a QTextBlock instance instead of an int. :return: Number of spaces that makes the indentation level of the current line
[ "Returns", "the", "indent", "level", "of", "the", "specified", "line" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L539-L555
train
46,591
pyQode/pyqode.core
pyqode/core/api/utils.py
TextHelper.get_right_word
def get_right_word(self, cursor=None): """ Gets the character on the right of the text cursor. :param cursor: QTextCursor where the search will start. :return: The word that is on the right of the text cursor. """ if cursor is None: cursor = self._editor.textCursor() cursor.movePosition(QtGui.QTextCursor.WordRight, QtGui.QTextCursor.KeepAnchor) return cursor.selectedText().strip()
python
def get_right_word(self, cursor=None): """ Gets the character on the right of the text cursor. :param cursor: QTextCursor where the search will start. :return: The word that is on the right of the text cursor. """ if cursor is None: cursor = self._editor.textCursor() cursor.movePosition(QtGui.QTextCursor.WordRight, QtGui.QTextCursor.KeepAnchor) return cursor.selectedText().strip()
[ "def", "get_right_word", "(", "self", ",", "cursor", "=", "None", ")", ":", "if", "cursor", "is", "None", ":", "cursor", "=", "self", ".", "_editor", ".", "textCursor", "(", ")", "cursor", ".", "movePosition", "(", "QtGui", ".", "QTextCursor", ".", "Wo...
Gets the character on the right of the text cursor. :param cursor: QTextCursor where the search will start. :return: The word that is on the right of the text cursor.
[ "Gets", "the", "character", "on", "the", "right", "of", "the", "text", "cursor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L557-L569
train
46,592
pyQode/pyqode.core
pyqode/core/api/utils.py
TextHelper.search_text
def search_text(self, text_cursor, search_txt, search_flags): """ Searches a text in a text document. :param text_cursor: Current text cursor :param search_txt: Text to search :param search_flags: QTextDocument.FindFlags :returns: the list of occurrences, the current occurrence index :rtype: tuple([], int) """ def compare_cursors(cursor_a, cursor_b): """ Compares two QTextCursor :param cursor_a: cursor a :param cursor_b: cursor b :returns; True if both cursor are identical (same position, same selection) """ return (cursor_b.selectionStart() >= cursor_a.selectionStart() and cursor_b.selectionEnd() <= cursor_a.selectionEnd()) text_document = self._editor.document() occurrences = [] index = -1 cursor = text_document.find(search_txt, 0, search_flags) original_cursor = text_cursor while not cursor.isNull(): if compare_cursors(cursor, original_cursor): index = len(occurrences) occurrences.append((cursor.selectionStart(), cursor.selectionEnd())) cursor.setPosition(cursor.position() + 1) cursor = text_document.find(search_txt, cursor, search_flags) return occurrences, index
python
def search_text(self, text_cursor, search_txt, search_flags): """ Searches a text in a text document. :param text_cursor: Current text cursor :param search_txt: Text to search :param search_flags: QTextDocument.FindFlags :returns: the list of occurrences, the current occurrence index :rtype: tuple([], int) """ def compare_cursors(cursor_a, cursor_b): """ Compares two QTextCursor :param cursor_a: cursor a :param cursor_b: cursor b :returns; True if both cursor are identical (same position, same selection) """ return (cursor_b.selectionStart() >= cursor_a.selectionStart() and cursor_b.selectionEnd() <= cursor_a.selectionEnd()) text_document = self._editor.document() occurrences = [] index = -1 cursor = text_document.find(search_txt, 0, search_flags) original_cursor = text_cursor while not cursor.isNull(): if compare_cursors(cursor, original_cursor): index = len(occurrences) occurrences.append((cursor.selectionStart(), cursor.selectionEnd())) cursor.setPosition(cursor.position() + 1) cursor = text_document.find(search_txt, cursor, search_flags) return occurrences, index
[ "def", "search_text", "(", "self", ",", "text_cursor", ",", "search_txt", ",", "search_flags", ")", ":", "def", "compare_cursors", "(", "cursor_a", ",", "cursor_b", ")", ":", "\"\"\"\n Compares two QTextCursor\n\n :param cursor_a: cursor a\n :...
Searches a text in a text document. :param text_cursor: Current text cursor :param search_txt: Text to search :param search_flags: QTextDocument.FindFlags :returns: the list of occurrences, the current occurrence index :rtype: tuple([], int)
[ "Searches", "a", "text", "in", "a", "text", "document", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L640-L676
train
46,593
pyQode/pyqode.core
pyqode/core/api/utils.py
TextHelper.match_select
def match_select(self, ignored_symbols=None): """ Performs matched selection, selects text between matching quotes or parentheses. :param ignored_symbols; matching symbols to ignore. """ def filter_matching(ignored_symbols, matching): """ Removes any ignored symbol from the match dict. """ if ignored_symbols is not None: for symbol in matching.keys(): if symbol in ignored_symbols: matching.pop(symbol) return matching def find_opening_symbol(cursor, matching): """ Find the position ot the opening symbol :param cursor: Current text cursor :param matching: symbol matches map """ start_pos = None opening_char = None closed = {k: 0 for k in matching.values() if k not in ['"', "'"]} # go left stop = False while not stop and not cursor.atStart(): cursor.clearSelection() cursor.movePosition(cursor.Left, cursor.KeepAnchor) char = cursor.selectedText() if char in closed.keys(): closed[char] += 1 elif char in matching.keys(): opposite = matching[char] if opposite in closed.keys() and closed[opposite]: closed[opposite] -= 1 continue else: # found opening quote or parenthesis start_pos = cursor.position() + 1 stop = True opening_char = char return opening_char, start_pos def find_closing_symbol(cursor, matching, opening_char, original_pos): """ Finds the position of the closing symbol :param cursor: current text cursor :param matching: symbold matching dict :param opening_char: the opening character :param original_pos: position of the opening character. """ end_pos = None cursor.setPosition(original_pos) rev_matching = {v: k for k, v in matching.items()} opened = {k: 0 for k in rev_matching.values() if k not in ['"', "'"]} stop = False while not stop and not cursor.atEnd(): cursor.clearSelection() cursor.movePosition(cursor.Right, cursor.KeepAnchor) char = cursor.selectedText() if char in opened.keys(): opened[char] += 1 elif char in rev_matching.keys(): opposite = rev_matching[char] if opposite in opened.keys() and opened[opposite]: opened[opposite] -= 1 continue elif matching[opening_char] == char: # found opening quote or parenthesis end_pos = cursor.position() - 1 stop = True return end_pos matching = {'(': ')', '{': '}', '[': ']', '"': '"', "'": "'"} filter_matching(ignored_symbols, matching) cursor = self._editor.textCursor() original_pos = cursor.position() end_pos = None opening_char, start_pos = find_opening_symbol(cursor, matching) if opening_char: end_pos = find_closing_symbol( cursor, matching, opening_char, original_pos) if start_pos and end_pos: cursor.setPosition(start_pos) cursor.movePosition(cursor.Right, cursor.KeepAnchor, end_pos - start_pos) self._editor.setTextCursor(cursor) return True else: return False
python
def match_select(self, ignored_symbols=None): """ Performs matched selection, selects text between matching quotes or parentheses. :param ignored_symbols; matching symbols to ignore. """ def filter_matching(ignored_symbols, matching): """ Removes any ignored symbol from the match dict. """ if ignored_symbols is not None: for symbol in matching.keys(): if symbol in ignored_symbols: matching.pop(symbol) return matching def find_opening_symbol(cursor, matching): """ Find the position ot the opening symbol :param cursor: Current text cursor :param matching: symbol matches map """ start_pos = None opening_char = None closed = {k: 0 for k in matching.values() if k not in ['"', "'"]} # go left stop = False while not stop and not cursor.atStart(): cursor.clearSelection() cursor.movePosition(cursor.Left, cursor.KeepAnchor) char = cursor.selectedText() if char in closed.keys(): closed[char] += 1 elif char in matching.keys(): opposite = matching[char] if opposite in closed.keys() and closed[opposite]: closed[opposite] -= 1 continue else: # found opening quote or parenthesis start_pos = cursor.position() + 1 stop = True opening_char = char return opening_char, start_pos def find_closing_symbol(cursor, matching, opening_char, original_pos): """ Finds the position of the closing symbol :param cursor: current text cursor :param matching: symbold matching dict :param opening_char: the opening character :param original_pos: position of the opening character. """ end_pos = None cursor.setPosition(original_pos) rev_matching = {v: k for k, v in matching.items()} opened = {k: 0 for k in rev_matching.values() if k not in ['"', "'"]} stop = False while not stop and not cursor.atEnd(): cursor.clearSelection() cursor.movePosition(cursor.Right, cursor.KeepAnchor) char = cursor.selectedText() if char in opened.keys(): opened[char] += 1 elif char in rev_matching.keys(): opposite = rev_matching[char] if opposite in opened.keys() and opened[opposite]: opened[opposite] -= 1 continue elif matching[opening_char] == char: # found opening quote or parenthesis end_pos = cursor.position() - 1 stop = True return end_pos matching = {'(': ')', '{': '}', '[': ']', '"': '"', "'": "'"} filter_matching(ignored_symbols, matching) cursor = self._editor.textCursor() original_pos = cursor.position() end_pos = None opening_char, start_pos = find_opening_symbol(cursor, matching) if opening_char: end_pos = find_closing_symbol( cursor, matching, opening_char, original_pos) if start_pos and end_pos: cursor.setPosition(start_pos) cursor.movePosition(cursor.Right, cursor.KeepAnchor, end_pos - start_pos) self._editor.setTextCursor(cursor) return True else: return False
[ "def", "match_select", "(", "self", ",", "ignored_symbols", "=", "None", ")", ":", "def", "filter_matching", "(", "ignored_symbols", ",", "matching", ")", ":", "\"\"\"\n Removes any ignored symbol from the match dict.\n \"\"\"", "if", "ignored_symbols", ...
Performs matched selection, selects text between matching quotes or parentheses. :param ignored_symbols; matching symbols to ignore.
[ "Performs", "matched", "selection", "selects", "text", "between", "matching", "quotes", "or", "parentheses", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L759-L854
train
46,594
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/__init__.py
main
def main(): """Entrypoint for the console script gcp-devrel-py-tools.""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() appengine.register_commands(subparsers) requirements.register_commands(subparsers) pylint.register_commands(subparsers) args = parser.parse_args() args.func(args)
python
def main(): """Entrypoint for the console script gcp-devrel-py-tools.""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() appengine.register_commands(subparsers) requirements.register_commands(subparsers) pylint.register_commands(subparsers) args = parser.parse_args() args.func(args)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", ")", "appengine", ".", "register_commands", "(", "subparsers", ")", "requirements", ".", "register_commands", "("...
Entrypoint for the console script gcp-devrel-py-tools.
[ "Entrypoint", "for", "the", "console", "script", "gcp", "-", "devrel", "-", "py", "-", "tools", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/__init__.py#L22-L32
train
46,595
bachya/pypollencom
pypollencom/allergens.py
Allergens.outlook
async def outlook(self) -> dict: """Get allergen outlook.""" try: return await self._request( 'get', 'https://www.pollen.com/api/forecast/outlook') except RequestError as err: if '404' in str(err): raise InvalidZipError('No data returned for ZIP code') else: raise RequestError(err)
python
async def outlook(self) -> dict: """Get allergen outlook.""" try: return await self._request( 'get', 'https://www.pollen.com/api/forecast/outlook') except RequestError as err: if '404' in str(err): raise InvalidZipError('No data returned for ZIP code') else: raise RequestError(err)
[ "async", "def", "outlook", "(", "self", ")", "->", "dict", ":", "try", ":", "return", "await", "self", ".", "_request", "(", "'get'", ",", "'https://www.pollen.com/api/forecast/outlook'", ")", "except", "RequestError", "as", "err", ":", "if", "'404'", "in", ...
Get allergen outlook.
[ "Get", "allergen", "outlook", "." ]
d1616a8471b350953d4f99f5a1dddca035977366
https://github.com/bachya/pypollencom/blob/d1616a8471b350953d4f99f5a1dddca035977366/pypollencom/allergens.py#L33-L42
train
46,596
SchroterQuentin/django-search-listview
fabfile.py
dev
def dev(): """Define dev stage""" env.roledefs = { 'web': ['192.168.1.2'], 'lb': ['192.168.1.2'], } env.user = 'vagrant' env.backends = env.roledefs['web'] env.server_name = 'django_search_model-dev.net' env.short_server_name = 'django_search_model-dev' env.static_folder = '/site_media/' env.server_ip = '192.168.1.2' env.no_shared_sessions = False env.server_ssl_on = False env.goal = 'dev' env.socket_port = '8001' env.map_settings = {} execute(build_env)
python
def dev(): """Define dev stage""" env.roledefs = { 'web': ['192.168.1.2'], 'lb': ['192.168.1.2'], } env.user = 'vagrant' env.backends = env.roledefs['web'] env.server_name = 'django_search_model-dev.net' env.short_server_name = 'django_search_model-dev' env.static_folder = '/site_media/' env.server_ip = '192.168.1.2' env.no_shared_sessions = False env.server_ssl_on = False env.goal = 'dev' env.socket_port = '8001' env.map_settings = {} execute(build_env)
[ "def", "dev", "(", ")", ":", "env", ".", "roledefs", "=", "{", "'web'", ":", "[", "'192.168.1.2'", "]", ",", "'lb'", ":", "[", "'192.168.1.2'", "]", ",", "}", "env", ".", "user", "=", "'vagrant'", "env", ".", "backends", "=", "env", ".", "roledefs"...
Define dev stage
[ "Define", "dev", "stage" ]
8b027a6908dc30c6ebc613bb4fde6b1ba40124a3
https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/fabfile.py#L68-L85
train
46,597
SchroterQuentin/django-search-listview
fabfile.py
install_postgres
def install_postgres(user=None, dbname=None, password=None): """Install Postgres on remote""" execute(pydiploy.django.install_postgres_server, user=user, dbname=dbname, password=password)
python
def install_postgres(user=None, dbname=None, password=None): """Install Postgres on remote""" execute(pydiploy.django.install_postgres_server, user=user, dbname=dbname, password=password)
[ "def", "install_postgres", "(", "user", "=", "None", ",", "dbname", "=", "None", ",", "password", "=", "None", ")", ":", "execute", "(", "pydiploy", ".", "django", ".", "install_postgres_server", ",", "user", "=", "user", ",", "dbname", "=", "dbname", ",...
Install Postgres on remote
[ "Install", "Postgres", "on", "remote" ]
8b027a6908dc30c6ebc613bb4fde6b1ba40124a3
https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/fabfile.py#L256-L259
train
46,598
SchroterQuentin/django-search-listview
search_listview/list.py
field_to_dict
def field_to_dict(fields): """ Build dictionnary which dependancy for each field related to "root" fields = ["toto", "toto__tata", "titi__tutu"] dico = { "toto": { EMPTY_DICT, "tata": EMPTY_DICT }, "titi" : { "tutu": EMPTY_DICT } } EMPTY_DICT is useful because we don't lose field without it dico["toto"] would only contains "tata" inspired from django.db.models.sql.add_select_related """ field_dict = {} for field in fields: d_tmp = field_dict for part in field.split(LOOKUP_SEP)[:-1]: d_tmp = d_tmp.setdefault(part, {}) d_tmp = d_tmp.setdefault( field.split(LOOKUP_SEP)[-1], deepcopy(EMPTY_DICT) ).update(deepcopy(EMPTY_DICT)) return field_dict
python
def field_to_dict(fields): """ Build dictionnary which dependancy for each field related to "root" fields = ["toto", "toto__tata", "titi__tutu"] dico = { "toto": { EMPTY_DICT, "tata": EMPTY_DICT }, "titi" : { "tutu": EMPTY_DICT } } EMPTY_DICT is useful because we don't lose field without it dico["toto"] would only contains "tata" inspired from django.db.models.sql.add_select_related """ field_dict = {} for field in fields: d_tmp = field_dict for part in field.split(LOOKUP_SEP)[:-1]: d_tmp = d_tmp.setdefault(part, {}) d_tmp = d_tmp.setdefault( field.split(LOOKUP_SEP)[-1], deepcopy(EMPTY_DICT) ).update(deepcopy(EMPTY_DICT)) return field_dict
[ "def", "field_to_dict", "(", "fields", ")", ":", "field_dict", "=", "{", "}", "for", "field", "in", "fields", ":", "d_tmp", "=", "field_dict", "for", "part", "in", "field", ".", "split", "(", "LOOKUP_SEP", ")", "[", ":", "-", "1", "]", ":", "d_tmp", ...
Build dictionnary which dependancy for each field related to "root" fields = ["toto", "toto__tata", "titi__tutu"] dico = { "toto": { EMPTY_DICT, "tata": EMPTY_DICT }, "titi" : { "tutu": EMPTY_DICT } } EMPTY_DICT is useful because we don't lose field without it dico["toto"] would only contains "tata" inspired from django.db.models.sql.add_select_related
[ "Build", "dictionnary", "which", "dependancy", "for", "each", "field", "related", "to", "root" ]
8b027a6908dc30c6ebc613bb4fde6b1ba40124a3
https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L153-L182
train
46,599