repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
pyQode/pyqode.core | pyqode/core/modes/caret_line_highlight.py | CaretLineHighlighterMode.refresh | def refresh(self):
"""
Updates the current line decoration
"""
if self.enabled:
self._clear_deco()
if self._color:
color = self._color
else:
color = drift_color(self.editor.background, 110)
brush = QtGui.QBrush(color)
self._decoration = TextDecoration(self.editor.textCursor())
self._decoration.set_background(brush)
self._decoration.set_full_width()
self.editor.decorations.append(self._decoration) | python | def refresh(self):
"""
Updates the current line decoration
"""
if self.enabled:
self._clear_deco()
if self._color:
color = self._color
else:
color = drift_color(self.editor.background, 110)
brush = QtGui.QBrush(color)
self._decoration = TextDecoration(self.editor.textCursor())
self._decoration.set_background(brush)
self._decoration.set_full_width()
self.editor.decorations.append(self._decoration) | [
"def",
"refresh",
"(",
"self",
")",
":",
"if",
"self",
".",
"enabled",
":",
"self",
".",
"_clear_deco",
"(",
")",
"if",
"self",
".",
"_color",
":",
"color",
"=",
"self",
".",
"_color",
"else",
":",
"color",
"=",
"drift_color",
"(",
"self",
".",
"ed... | Updates the current line decoration | [
"Updates",
"the",
"current",
"line",
"decoration"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/caret_line_highlight.py#L65-L79 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/extended_selection.py#L72-L91 |
pyQode/pyqode.core | pyqode/core/modes/extended_selection.py | ExtendedSelectionMode.perform_word_selection | def perform_word_selection(self, event=None):
"""
Performs word selection
:param event: QMouseEvent
"""
self.editor.setTextCursor(
TextHelper(self.editor).word_under_cursor(True))
if event:
event.accept() | python | def perform_word_selection(self, event=None):
"""
Performs word selection
:param event: QMouseEvent
"""
self.editor.setTextCursor(
TextHelper(self.editor).word_under_cursor(True))
if event:
event.accept() | [
"def",
"perform_word_selection",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"self",
".",
"editor",
".",
"setTextCursor",
"(",
"TextHelper",
"(",
"self",
".",
"editor",
")",
".",
"word_under_cursor",
"(",
"True",
")",
")",
"if",
"event",
":",
"even... | Performs word selection
:param event: QMouseEvent | [
"Performs",
"word",
"selection",
":",
"param",
"event",
":",
"QMouseEvent"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/extended_selection.py#L121-L129 |
pyQode/pyqode.core | pyqode/core/modes/extended_selection.py | ExtendedSelectionMode.perform_extended_selection | def perform_extended_selection(self, event=None):
"""
Performs extended word selection.
:param event: QMouseEvent
"""
TextHelper(self.editor).select_extended_word(
continuation_chars=self.continuation_characters)
if event:
event.accept() | python | def perform_extended_selection(self, event=None):
"""
Performs extended word selection.
:param event: QMouseEvent
"""
TextHelper(self.editor).select_extended_word(
continuation_chars=self.continuation_characters)
if event:
event.accept() | [
"def",
"perform_extended_selection",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"TextHelper",
"(",
"self",
".",
"editor",
")",
".",
"select_extended_word",
"(",
"continuation_chars",
"=",
"self",
".",
"continuation_characters",
")",
"if",
"event",
":",
... | Performs extended word selection.
:param event: QMouseEvent | [
"Performs",
"extended",
"word",
"selection",
".",
":",
"param",
"event",
":",
"QMouseEvent"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/extended_selection.py#L131-L139 |
pyQode/pyqode.core | pyqode/core/modes/extended_selection.py | ExtendedSelectionMode.perform_matched_selection | def perform_matched_selection(self, event):
"""
Performs matched selection.
:param event: QMouseEvent
"""
selected = TextHelper(self.editor).match_select()
if selected and event:
event.accept() | python | def perform_matched_selection(self, event):
"""
Performs matched selection.
:param event: QMouseEvent
"""
selected = TextHelper(self.editor).match_select()
if selected and event:
event.accept() | [
"def",
"perform_matched_selection",
"(",
"self",
",",
"event",
")",
":",
"selected",
"=",
"TextHelper",
"(",
"self",
".",
"editor",
")",
".",
"match_select",
"(",
")",
"if",
"selected",
"and",
"event",
":",
"event",
".",
"accept",
"(",
")"
] | Performs matched selection.
:param event: QMouseEvent | [
"Performs",
"matched",
"selection",
".",
":",
"param",
"event",
":",
"QMouseEvent"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/extended_selection.py#L141-L148 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/share.py#L43-L55 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/share.py#L58-L67 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/indenter.py#L41-L68 |
pyQode/pyqode.core | pyqode/core/modes/indenter.py | IndenterMode.unindent_selection | def unindent_selection(self, cursor):
"""
Un-indents selected text
:param cursor: QTextCursor
"""
doc = self.editor.document()
tab_len = self.editor.tab_length
nb_lines = len(cursor.selection().toPlainText().splitlines())
if nb_lines == 0:
nb_lines = 1
block = doc.findBlock(cursor.selectionStart())
assert isinstance(block, QtGui.QTextBlock)
i = 0
debug('unindent selection: %d lines', nb_lines)
while i < nb_lines:
txt = block.text()
debug('line to unindent: %s', txt)
debug('self.editor.use_spaces_instead_of_tabs: %r',
self.editor.use_spaces_instead_of_tabs)
if self.editor.use_spaces_instead_of_tabs:
indentation = (len(txt) - len(txt.lstrip()))
else:
indentation = len(txt) - len(txt.replace('\t', ''))
debug('unindent line %d: %d spaces', i, indentation)
if indentation > 0:
c = QtGui.QTextCursor(block)
c.movePosition(c.StartOfLine, cursor.MoveAnchor)
for _ in range(tab_len):
txt = block.text()
if len(txt) and txt[0] == ' ':
c.deleteChar()
block = block.next()
i += 1
return cursor | python | def unindent_selection(self, cursor):
"""
Un-indents selected text
:param cursor: QTextCursor
"""
doc = self.editor.document()
tab_len = self.editor.tab_length
nb_lines = len(cursor.selection().toPlainText().splitlines())
if nb_lines == 0:
nb_lines = 1
block = doc.findBlock(cursor.selectionStart())
assert isinstance(block, QtGui.QTextBlock)
i = 0
debug('unindent selection: %d lines', nb_lines)
while i < nb_lines:
txt = block.text()
debug('line to unindent: %s', txt)
debug('self.editor.use_spaces_instead_of_tabs: %r',
self.editor.use_spaces_instead_of_tabs)
if self.editor.use_spaces_instead_of_tabs:
indentation = (len(txt) - len(txt.lstrip()))
else:
indentation = len(txt) - len(txt.replace('\t', ''))
debug('unindent line %d: %d spaces', i, indentation)
if indentation > 0:
c = QtGui.QTextCursor(block)
c.movePosition(c.StartOfLine, cursor.MoveAnchor)
for _ in range(tab_len):
txt = block.text()
if len(txt) and txt[0] == ' ':
c.deleteChar()
block = block.next()
i += 1
return cursor | [
"def",
"unindent_selection",
"(",
"self",
",",
"cursor",
")",
":",
"doc",
"=",
"self",
".",
"editor",
".",
"document",
"(",
")",
"tab_len",
"=",
"self",
".",
"editor",
".",
"tab_length",
"nb_lines",
"=",
"len",
"(",
"cursor",
".",
"selection",
"(",
")"... | Un-indents selected text
:param cursor: QTextCursor | [
"Un",
"-",
"indents",
"selected",
"text"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/indenter.py#L70-L104 |
pyQode/pyqode.core | pyqode/core/modes/indenter.py | IndenterMode.indent | def indent(self):
"""
Indents text at cursor position.
"""
cursor = self.editor.textCursor()
assert isinstance(cursor, QtGui.QTextCursor)
if cursor.hasSelection():
self.indent_selection(cursor)
else:
# simply insert indentation at the cursor position
tab_len = self.editor.tab_length
cursor.beginEditBlock()
if self.editor.use_spaces_instead_of_tabs:
nb_space_to_add = tab_len - cursor.positionInBlock() % tab_len
cursor.insertText(nb_space_to_add * " ")
else:
cursor.insertText('\t')
cursor.endEditBlock() | python | def indent(self):
"""
Indents text at cursor position.
"""
cursor = self.editor.textCursor()
assert isinstance(cursor, QtGui.QTextCursor)
if cursor.hasSelection():
self.indent_selection(cursor)
else:
# simply insert indentation at the cursor position
tab_len = self.editor.tab_length
cursor.beginEditBlock()
if self.editor.use_spaces_instead_of_tabs:
nb_space_to_add = tab_len - cursor.positionInBlock() % tab_len
cursor.insertText(nb_space_to_add * " ")
else:
cursor.insertText('\t')
cursor.endEditBlock() | [
"def",
"indent",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"editor",
".",
"textCursor",
"(",
")",
"assert",
"isinstance",
"(",
"cursor",
",",
"QtGui",
".",
"QTextCursor",
")",
"if",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"self",
".",
... | Indents text at cursor position. | [
"Indents",
"text",
"at",
"cursor",
"position",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/indenter.py#L106-L123 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.split | def split(self):
"""
Split the code editor widget, return a clone of the widget ready to
be used (and synchronised with its original).
Splitting the widget is done in 2 steps:
- first we clone the widget, you can override ``clone`` if your
widget needs additional arguments.
- then we link the two text document and disable some modes on the
cloned instance (such as the watcher mode).
"""
# cache cursor position so that the clone open at the current cursor
# pos
l, c = TextHelper(self).cursor_position()
clone = self.clone()
self.link(clone)
TextHelper(clone).goto_line(l, c)
self.clones.append(clone)
return clone | python | def split(self):
"""
Split the code editor widget, return a clone of the widget ready to
be used (and synchronised with its original).
Splitting the widget is done in 2 steps:
- first we clone the widget, you can override ``clone`` if your
widget needs additional arguments.
- then we link the two text document and disable some modes on the
cloned instance (such as the watcher mode).
"""
# cache cursor position so that the clone open at the current cursor
# pos
l, c = TextHelper(self).cursor_position()
clone = self.clone()
self.link(clone)
TextHelper(clone).goto_line(l, c)
self.clones.append(clone)
return clone | [
"def",
"split",
"(",
"self",
")",
":",
"# cache cursor position so that the clone open at the current cursor",
"# pos",
"l",
",",
"c",
"=",
"TextHelper",
"(",
"self",
")",
".",
"cursor_position",
"(",
")",
"clone",
"=",
"self",
".",
"clone",
"(",
")",
"self",
... | Split the code editor widget, return a clone of the widget ready to
be used (and synchronised with its original).
Splitting the widget is done in 2 steps:
- first we clone the widget, you can override ``clone`` if your
widget needs additional arguments.
- then we link the two text document and disable some modes on the
cloned instance (such as the watcher mode). | [
"Split",
"the",
"code",
"editor",
"widget",
"return",
"a",
"clone",
"of",
"the",
"widget",
"ready",
"to",
"be",
"used",
"(",
"and",
"synchronised",
"with",
"its",
"original",
")",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L509-L528 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.link | def link(self, clone):
"""
Links the clone with its original. We copy the file manager infos
(path, mimetype, ...) and setup the clone text document as reference
to our text document.
:param clone: clone to link.
"""
clone.file._path = self.file.path
clone.file._encoding = self.file.encoding
clone.file._mimetype = self.file.mimetype
clone.setDocument(self.document())
for original_mode, mode in zip(list(self.modes), list(clone.modes)):
mode.enabled = original_mode.enabled
mode.clone_settings(original_mode)
for original_panel, panel in zip(
list(self.panels), list(clone.panels)):
panel.enabled = original_panel.isEnabled()
panel.clone_settings(original_panel)
if not original_panel.isVisible():
panel.setVisible(False)
clone.use_spaces_instead_of_tabs = self.use_spaces_instead_of_tabs
clone.tab_length = self.tab_length
clone._save_on_focus_out = self._save_on_focus_out
clone.show_whitespaces = self.show_whitespaces
clone.font_name = self.font_name
clone.font_size = self.font_size
clone.zoom_level = self.zoom_level
clone.background = self.background
clone.foreground = self.foreground
clone.whitespaces_foreground = self.whitespaces_foreground
clone.selection_background = self.selection_background
clone.selection_foreground = self.selection_foreground
clone.word_separators = self.word_separators
clone.file.clone_settings(self.file) | python | def link(self, clone):
"""
Links the clone with its original. We copy the file manager infos
(path, mimetype, ...) and setup the clone text document as reference
to our text document.
:param clone: clone to link.
"""
clone.file._path = self.file.path
clone.file._encoding = self.file.encoding
clone.file._mimetype = self.file.mimetype
clone.setDocument(self.document())
for original_mode, mode in zip(list(self.modes), list(clone.modes)):
mode.enabled = original_mode.enabled
mode.clone_settings(original_mode)
for original_panel, panel in zip(
list(self.panels), list(clone.panels)):
panel.enabled = original_panel.isEnabled()
panel.clone_settings(original_panel)
if not original_panel.isVisible():
panel.setVisible(False)
clone.use_spaces_instead_of_tabs = self.use_spaces_instead_of_tabs
clone.tab_length = self.tab_length
clone._save_on_focus_out = self._save_on_focus_out
clone.show_whitespaces = self.show_whitespaces
clone.font_name = self.font_name
clone.font_size = self.font_size
clone.zoom_level = self.zoom_level
clone.background = self.background
clone.foreground = self.foreground
clone.whitespaces_foreground = self.whitespaces_foreground
clone.selection_background = self.selection_background
clone.selection_foreground = self.selection_foreground
clone.word_separators = self.word_separators
clone.file.clone_settings(self.file) | [
"def",
"link",
"(",
"self",
",",
"clone",
")",
":",
"clone",
".",
"file",
".",
"_path",
"=",
"self",
".",
"file",
".",
"path",
"clone",
".",
"file",
".",
"_encoding",
"=",
"self",
".",
"file",
".",
"encoding",
"clone",
".",
"file",
".",
"_mimetype"... | Links the clone with its original. We copy the file manager infos
(path, mimetype, ...) and setup the clone text document as reference
to our text document.
:param clone: clone to link. | [
"Links",
"the",
"clone",
"with",
"its",
"original",
".",
"We",
"copy",
"the",
"file",
"manager",
"infos",
"(",
"path",
"mimetype",
"...",
")",
"and",
"setup",
"the",
"clone",
"text",
"document",
"as",
"reference",
"to",
"our",
"text",
"document",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L538-L572 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.close | def close(self, clear=True):
"""
Closes the editor, stops the backend and removes any installed
mode/panel.
This is also where we cache the cursor position.
:param clear: True to clear the editor content before closing.
"""
if self._tooltips_runner:
self._tooltips_runner.cancel_requests()
self._tooltips_runner = None
self.decorations.clear()
self.modes.clear()
self.panels.clear()
self.backend.stop()
Cache().set_cursor_position(
self.file.path, self.textCursor().position())
super(CodeEdit, self).close() | python | def close(self, clear=True):
"""
Closes the editor, stops the backend and removes any installed
mode/panel.
This is also where we cache the cursor position.
:param clear: True to clear the editor content before closing.
"""
if self._tooltips_runner:
self._tooltips_runner.cancel_requests()
self._tooltips_runner = None
self.decorations.clear()
self.modes.clear()
self.panels.clear()
self.backend.stop()
Cache().set_cursor_position(
self.file.path, self.textCursor().position())
super(CodeEdit, self).close() | [
"def",
"close",
"(",
"self",
",",
"clear",
"=",
"True",
")",
":",
"if",
"self",
".",
"_tooltips_runner",
":",
"self",
".",
"_tooltips_runner",
".",
"cancel_requests",
"(",
")",
"self",
".",
"_tooltips_runner",
"=",
"None",
"self",
".",
"decorations",
".",
... | Closes the editor, stops the backend and removes any installed
mode/panel.
This is also where we cache the cursor position.
:param clear: True to clear the editor content before closing. | [
"Closes",
"the",
"editor",
"stops",
"the",
"backend",
"and",
"removes",
"any",
"installed",
"mode",
"/",
"panel",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L574-L592 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L603-L615 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L617-L639 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L641-L662 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L664-L677 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L686-L704 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.remove_action | def remove_action(self, action, sub_menu='Advanced'):
"""
Removes an action/separator from the editor's context menu.
:param action: Action/seprator to remove.
:param advanced: True to remove the action from the advanced submenu.
"""
if sub_menu:
try:
mnu = self._sub_menus[sub_menu]
except KeyError:
pass
else:
mnu.removeAction(action)
else:
try:
self._actions.remove(action)
except ValueError:
pass
self.removeAction(action) | python | def remove_action(self, action, sub_menu='Advanced'):
"""
Removes an action/separator from the editor's context menu.
:param action: Action/seprator to remove.
:param advanced: True to remove the action from the advanced submenu.
"""
if sub_menu:
try:
mnu = self._sub_menus[sub_menu]
except KeyError:
pass
else:
mnu.removeAction(action)
else:
try:
self._actions.remove(action)
except ValueError:
pass
self.removeAction(action) | [
"def",
"remove_action",
"(",
"self",
",",
"action",
",",
"sub_menu",
"=",
"'Advanced'",
")",
":",
"if",
"sub_menu",
":",
"try",
":",
"mnu",
"=",
"self",
".",
"_sub_menus",
"[",
"sub_menu",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"mnu",
"."... | Removes an action/separator from the editor's context menu.
:param action: Action/seprator to remove.
:param advanced: True to remove the action from the advanced submenu. | [
"Removes",
"an",
"action",
"/",
"separator",
"from",
"the",
"editor",
"s",
"context",
"menu",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L706-L725 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L727-L742 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.remove_menu | def remove_menu(self, menu):
"""
Removes a sub-menu from the context menu.
:param menu: Sub-menu to remove.
"""
self._menus.remove(menu)
for action in menu.actions():
self.removeAction(action) | python | def remove_menu(self, menu):
"""
Removes a sub-menu from the context menu.
:param menu: Sub-menu to remove.
"""
self._menus.remove(menu)
for action in menu.actions():
self.removeAction(action) | [
"def",
"remove_menu",
"(",
"self",
",",
"menu",
")",
":",
"self",
".",
"_menus",
".",
"remove",
"(",
"menu",
")",
"for",
"action",
"in",
"menu",
".",
"actions",
"(",
")",
":",
"self",
".",
"removeAction",
"(",
"action",
")"
] | Removes a sub-menu from the context menu.
:param menu: Sub-menu to remove. | [
"Removes",
"a",
"sub",
"-",
"menu",
"from",
"the",
"context",
"menu",
".",
":",
"param",
"menu",
":",
"Sub",
"-",
"menu",
"to",
"remove",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L744-L751 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.goto_line | def goto_line(self):
"""
Shows the *go to line dialog* and go to the selected line.
"""
helper = TextHelper(self)
line, result = DlgGotoLine.get_line(
self, helper.current_line_nbr(), helper.line_count())
if not result:
return
return helper.goto_line(line, move=True) | python | def goto_line(self):
"""
Shows the *go to line dialog* and go to the selected line.
"""
helper = TextHelper(self)
line, result = DlgGotoLine.get_line(
self, helper.current_line_nbr(), helper.line_count())
if not result:
return
return helper.goto_line(line, move=True) | [
"def",
"goto_line",
"(",
"self",
")",
":",
"helper",
"=",
"TextHelper",
"(",
"self",
")",
"line",
",",
"result",
"=",
"DlgGotoLine",
".",
"get_line",
"(",
"self",
",",
"helper",
".",
"current_line_nbr",
"(",
")",
",",
"helper",
".",
"line_count",
"(",
... | Shows the *go to line dialog* and go to the selected line. | [
"Shows",
"the",
"*",
"go",
"to",
"line",
"dialog",
"*",
"and",
"go",
"to",
"the",
"selected",
"line",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L763-L772 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.zoom_in | def zoom_in(self, increment=1):
"""
Zooms in the editor (makes the font bigger).
:param increment: zoom level increment. Default is 1.
"""
self.zoom_level += increment
TextHelper(self).mark_whole_doc_dirty()
self._reset_stylesheet() | python | def zoom_in(self, increment=1):
"""
Zooms in the editor (makes the font bigger).
:param increment: zoom level increment. Default is 1.
"""
self.zoom_level += increment
TextHelper(self).mark_whole_doc_dirty()
self._reset_stylesheet() | [
"def",
"zoom_in",
"(",
"self",
",",
"increment",
"=",
"1",
")",
":",
"self",
".",
"zoom_level",
"+=",
"increment",
"TextHelper",
"(",
"self",
")",
".",
"mark_whole_doc_dirty",
"(",
")",
"self",
".",
"_reset_stylesheet",
"(",
")"
] | Zooms in the editor (makes the font bigger).
:param increment: zoom level increment. Default is 1. | [
"Zooms",
"in",
"the",
"editor",
"(",
"makes",
"the",
"font",
"bigger",
")",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L788-L796 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.zoom_out | def zoom_out(self, decrement=1):
"""
Zooms out the editor (makes the font smaller).
:param decrement: zoom level decrement. Default is 1. The value is
given as an absolute value.
"""
self.zoom_level -= decrement
# make sure font size remains > 0
if self.font_size + self.zoom_level <= 0:
self.zoom_level = -self._font_size + 1
TextHelper(self).mark_whole_doc_dirty()
self._reset_stylesheet() | python | def zoom_out(self, decrement=1):
"""
Zooms out the editor (makes the font smaller).
:param decrement: zoom level decrement. Default is 1. The value is
given as an absolute value.
"""
self.zoom_level -= decrement
# make sure font size remains > 0
if self.font_size + self.zoom_level <= 0:
self.zoom_level = -self._font_size + 1
TextHelper(self).mark_whole_doc_dirty()
self._reset_stylesheet() | [
"def",
"zoom_out",
"(",
"self",
",",
"decrement",
"=",
"1",
")",
":",
"self",
".",
"zoom_level",
"-=",
"decrement",
"# make sure font size remains > 0",
"if",
"self",
".",
"font_size",
"+",
"self",
".",
"zoom_level",
"<=",
"0",
":",
"self",
".",
"zoom_level"... | Zooms out the editor (makes the font smaller).
:param decrement: zoom level decrement. Default is 1. The value is
given as an absolute value. | [
"Zooms",
"out",
"the",
"editor",
"(",
"makes",
"the",
"font",
"smaller",
")",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L798-L810 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L812-L835 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L869-L888 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit.copy | def copy(self):
"""
Copy the selected text to the clipboard. If no text was selected, the
entire line is copied (this feature can be turned off by
setting :attr:`select_line_on_copy_empty` to False.
"""
if self.select_line_on_copy_empty and not self.textCursor().hasSelection():
TextHelper(self).select_whole_line()
super(CodeEdit, self).copy() | python | def copy(self):
"""
Copy the selected text to the clipboard. If no text was selected, the
entire line is copied (this feature can be turned off by
setting :attr:`select_line_on_copy_empty` to False.
"""
if self.select_line_on_copy_empty and not self.textCursor().hasSelection():
TextHelper(self).select_whole_line()
super(CodeEdit, self).copy() | [
"def",
"copy",
"(",
"self",
")",
":",
"if",
"self",
".",
"select_line_on_copy_empty",
"and",
"not",
"self",
".",
"textCursor",
"(",
")",
".",
"hasSelection",
"(",
")",
":",
"TextHelper",
"(",
"self",
")",
".",
"select_whole_line",
"(",
")",
"super",
"(",... | Copy the selected text to the clipboard. If no text was selected, the
entire line is copied (this feature can be turned off by
setting :attr:`select_line_on_copy_empty` to False. | [
"Copy",
"the",
"selected",
"text",
"to",
"the",
"clipboard",
".",
"If",
"no",
"text",
"was",
"selected",
"the",
"entire",
"line",
"is",
"copied",
"(",
"this",
"feature",
"can",
"be",
"turned",
"off",
"by",
"setting",
":",
"attr",
":",
"select_line_on_copy_... | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L890-L898 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L921-L928 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L934-L943 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L945-L978 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L980-L993 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1003-L1010 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1018-L1035 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1037-L1048 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1050-L1061 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1063-L1093 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1095-L1098 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1112-L1123 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1125-L1133 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1135-L1145 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit._init_actions | def _init_actions(self, create_standard_actions):
""" Init context menu action """
menu_advanced = QtWidgets.QMenu(_('Advanced'))
self.add_menu(menu_advanced)
self._sub_menus = {
'Advanced': menu_advanced
}
if create_standard_actions:
# Undo
action = QtWidgets.QAction(_('Undo'), self)
action.setShortcut('Ctrl+Z')
action.setIcon(icons.icon(
'edit-undo', ':/pyqode-icons/rc/edit-undo.png', 'fa.undo'))
action.triggered.connect(self.undo)
self.undoAvailable.connect(action.setVisible)
action.setVisible(False)
self.add_action(action, sub_menu=None)
self.action_undo = action
# Redo
action = QtWidgets.QAction(_('Redo'), self)
action.setShortcut('Ctrl+Y')
action.setIcon(icons.icon(
'edit-redo', ':/pyqode-icons/rc/edit-redo.png', 'fa.repeat'))
action.triggered.connect(self.redo)
self.redoAvailable.connect(action.setVisible)
action.setVisible(False)
self.add_action(action, sub_menu=None)
self.action_redo = action
# Copy
action = QtWidgets.QAction(_('Copy'), self)
action.setShortcut(QtGui.QKeySequence.Copy)
action.setIcon(icons.icon(
'edit-copy', ':/pyqode-icons/rc/edit-copy.png', 'fa.copy'))
action.triggered.connect(self.copy)
self.add_action(action, sub_menu=None)
self.action_copy = action
# cut
action = QtWidgets.QAction(_('Cut'), self)
action.setShortcut(QtGui.QKeySequence.Cut)
action.setIcon(icons.icon(
'edit-cut', ':/pyqode-icons/rc/edit-cut.png', 'fa.cut'))
action.triggered.connect(self.cut)
self.add_action(action, sub_menu=None)
self.action_cut = action
# paste
action = QtWidgets.QAction(_('Paste'), self)
action.setShortcut(QtGui.QKeySequence.Paste)
action.setIcon(icons.icon(
'edit-paste', ':/pyqode-icons/rc/edit-paste.png',
'fa.paste'))
action.triggered.connect(self.paste)
self.add_action(action, sub_menu=None)
self.action_paste = action
# duplicate line
action = QtWidgets.QAction(_('Duplicate line'), self)
action.setShortcut('Ctrl+D')
action.triggered.connect(self.duplicate_line)
self.add_action(action, sub_menu=None)
self.action_duplicate_line = action
# swap line up
action = QtWidgets.QAction(_('Swap line up'), self)
action.setShortcut("Alt++")
action.triggered.connect(self.swapLineUp)
self.add_action(action, sub_menu=None)
self.action_swap_line_up = action
# swap line down
action = QtWidgets.QAction(_('Swap line down'), self)
action.setShortcut("Alt+-")
action.triggered.connect(self.swapLineDown)
self.add_action(action, sub_menu=None)
self.action_swap_line_down = action
# select all
action = QtWidgets.QAction(_('Select all'), self)
action.setShortcut(QtGui.QKeySequence.SelectAll)
action.triggered.connect(self.selectAll)
self.action_select_all = action
self.add_action(self.action_select_all, sub_menu=None)
self.add_separator(sub_menu=None)
if create_standard_actions:
# indent
action = QtWidgets.QAction(_('Indent'), self)
action.setShortcut('Tab')
action.setIcon(icons.icon(
'format-indent-more',
':/pyqode-icons/rc/format-indent-more.png', 'fa.indent'))
action.triggered.connect(self.indent)
self.add_action(action)
self.action_indent = action
# unindent
action = QtWidgets.QAction(_('Un-indent'), self)
action.setShortcut('Shift+Tab')
action.setIcon(icons.icon(
'format-indent-less',
':/pyqode-icons/rc/format-indent-less.png', 'fa.dedent'))
action.triggered.connect(self.un_indent)
self.add_action(action)
self.action_un_indent = action
self.add_separator()
# goto
action = QtWidgets.QAction(_('Go to line'), self)
action.setShortcut('Ctrl+G')
action.setIcon(icons.icon(
'go-jump', ':/pyqode-icons/rc/goto-line.png', 'fa.share'))
action.triggered.connect(self.goto_line)
self.add_action(action)
self.action_goto_line = action | python | def _init_actions(self, create_standard_actions):
""" Init context menu action """
menu_advanced = QtWidgets.QMenu(_('Advanced'))
self.add_menu(menu_advanced)
self._sub_menus = {
'Advanced': menu_advanced
}
if create_standard_actions:
# Undo
action = QtWidgets.QAction(_('Undo'), self)
action.setShortcut('Ctrl+Z')
action.setIcon(icons.icon(
'edit-undo', ':/pyqode-icons/rc/edit-undo.png', 'fa.undo'))
action.triggered.connect(self.undo)
self.undoAvailable.connect(action.setVisible)
action.setVisible(False)
self.add_action(action, sub_menu=None)
self.action_undo = action
# Redo
action = QtWidgets.QAction(_('Redo'), self)
action.setShortcut('Ctrl+Y')
action.setIcon(icons.icon(
'edit-redo', ':/pyqode-icons/rc/edit-redo.png', 'fa.repeat'))
action.triggered.connect(self.redo)
self.redoAvailable.connect(action.setVisible)
action.setVisible(False)
self.add_action(action, sub_menu=None)
self.action_redo = action
# Copy
action = QtWidgets.QAction(_('Copy'), self)
action.setShortcut(QtGui.QKeySequence.Copy)
action.setIcon(icons.icon(
'edit-copy', ':/pyqode-icons/rc/edit-copy.png', 'fa.copy'))
action.triggered.connect(self.copy)
self.add_action(action, sub_menu=None)
self.action_copy = action
# cut
action = QtWidgets.QAction(_('Cut'), self)
action.setShortcut(QtGui.QKeySequence.Cut)
action.setIcon(icons.icon(
'edit-cut', ':/pyqode-icons/rc/edit-cut.png', 'fa.cut'))
action.triggered.connect(self.cut)
self.add_action(action, sub_menu=None)
self.action_cut = action
# paste
action = QtWidgets.QAction(_('Paste'), self)
action.setShortcut(QtGui.QKeySequence.Paste)
action.setIcon(icons.icon(
'edit-paste', ':/pyqode-icons/rc/edit-paste.png',
'fa.paste'))
action.triggered.connect(self.paste)
self.add_action(action, sub_menu=None)
self.action_paste = action
# duplicate line
action = QtWidgets.QAction(_('Duplicate line'), self)
action.setShortcut('Ctrl+D')
action.triggered.connect(self.duplicate_line)
self.add_action(action, sub_menu=None)
self.action_duplicate_line = action
# swap line up
action = QtWidgets.QAction(_('Swap line up'), self)
action.setShortcut("Alt++")
action.triggered.connect(self.swapLineUp)
self.add_action(action, sub_menu=None)
self.action_swap_line_up = action
# swap line down
action = QtWidgets.QAction(_('Swap line down'), self)
action.setShortcut("Alt+-")
action.triggered.connect(self.swapLineDown)
self.add_action(action, sub_menu=None)
self.action_swap_line_down = action
# select all
action = QtWidgets.QAction(_('Select all'), self)
action.setShortcut(QtGui.QKeySequence.SelectAll)
action.triggered.connect(self.selectAll)
self.action_select_all = action
self.add_action(self.action_select_all, sub_menu=None)
self.add_separator(sub_menu=None)
if create_standard_actions:
# indent
action = QtWidgets.QAction(_('Indent'), self)
action.setShortcut('Tab')
action.setIcon(icons.icon(
'format-indent-more',
':/pyqode-icons/rc/format-indent-more.png', 'fa.indent'))
action.triggered.connect(self.indent)
self.add_action(action)
self.action_indent = action
# unindent
action = QtWidgets.QAction(_('Un-indent'), self)
action.setShortcut('Shift+Tab')
action.setIcon(icons.icon(
'format-indent-less',
':/pyqode-icons/rc/format-indent-less.png', 'fa.dedent'))
action.triggered.connect(self.un_indent)
self.add_action(action)
self.action_un_indent = action
self.add_separator()
# goto
action = QtWidgets.QAction(_('Go to line'), self)
action.setShortcut('Ctrl+G')
action.setIcon(icons.icon(
'go-jump', ':/pyqode-icons/rc/goto-line.png', 'fa.share'))
action.triggered.connect(self.goto_line)
self.add_action(action)
self.action_goto_line = action | [
"def",
"_init_actions",
"(",
"self",
",",
"create_standard_actions",
")",
":",
"menu_advanced",
"=",
"QtWidgets",
".",
"QMenu",
"(",
"_",
"(",
"'Advanced'",
")",
")",
"self",
".",
"add_menu",
"(",
"menu_advanced",
")",
"self",
".",
"_sub_menus",
"=",
"{",
... | Init context menu action | [
"Init",
"context",
"menu",
"action"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1147-L1252 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit._init_settings | def _init_settings(self):
""" Init setting """
self._show_whitespaces = False
self._tab_length = 4
self._use_spaces_instead_of_tabs = True
self.setTabStopWidth(self._tab_length *
self.fontMetrics().width(" "))
self._set_whitespaces_flags(self._show_whitespaces) | python | def _init_settings(self):
""" Init setting """
self._show_whitespaces = False
self._tab_length = 4
self._use_spaces_instead_of_tabs = True
self.setTabStopWidth(self._tab_length *
self.fontMetrics().width(" "))
self._set_whitespaces_flags(self._show_whitespaces) | [
"def",
"_init_settings",
"(",
"self",
")",
":",
"self",
".",
"_show_whitespaces",
"=",
"False",
"self",
".",
"_tab_length",
"=",
"4",
"self",
".",
"_use_spaces_instead_of_tabs",
"=",
"True",
"self",
".",
"setTabStopWidth",
"(",
"self",
".",
"_tab_length",
"*",... | Init setting | [
"Init",
"setting"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1254-L1261 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1263-L1272 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1274-L1293 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1295-L1299 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit._reset_stylesheet | def _reset_stylesheet(self):
""" Resets stylesheet"""
self.setFont(QtGui.QFont(self._font_family,
self._font_size + self._zoom_level))
flg_stylesheet = hasattr(self, '_flg_stylesheet')
if QtWidgets.QApplication.instance().styleSheet() or flg_stylesheet:
self._flg_stylesheet = True
# On Window, if the application once had a stylesheet, we must
# keep on using a stylesheet otherwise strange colors appear
# see https://github.com/OpenCobolIDE/OpenCobolIDE/issues/65
# Also happen on plasma 5
try:
plasma = os.environ['DESKTOP_SESSION'] == 'plasma'
except KeyError:
plasma = False
if sys.platform == 'win32' or plasma:
self.setStyleSheet('''QPlainTextEdit
{
background-color: %s;
color: %s;
}
''' % (self.background.name(), self.foreground.name()))
else:
# on linux/osx we just have to set an empty stylesheet to
# cancel any previous stylesheet and still keep a correct
# style for scrollbars
self.setStyleSheet('')
else:
p = self.palette()
p.setColor(QtGui.QPalette.Base, self.background)
p.setColor(QtGui.QPalette.Text, self.foreground)
p.setColor(QtGui.QPalette.Highlight,
self.selection_background)
p.setColor(QtGui.QPalette.HighlightedText,
self.selection_foreground)
self.setPalette(p)
self.repaint() | python | def _reset_stylesheet(self):
""" Resets stylesheet"""
self.setFont(QtGui.QFont(self._font_family,
self._font_size + self._zoom_level))
flg_stylesheet = hasattr(self, '_flg_stylesheet')
if QtWidgets.QApplication.instance().styleSheet() or flg_stylesheet:
self._flg_stylesheet = True
# On Window, if the application once had a stylesheet, we must
# keep on using a stylesheet otherwise strange colors appear
# see https://github.com/OpenCobolIDE/OpenCobolIDE/issues/65
# Also happen on plasma 5
try:
plasma = os.environ['DESKTOP_SESSION'] == 'plasma'
except KeyError:
plasma = False
if sys.platform == 'win32' or plasma:
self.setStyleSheet('''QPlainTextEdit
{
background-color: %s;
color: %s;
}
''' % (self.background.name(), self.foreground.name()))
else:
# on linux/osx we just have to set an empty stylesheet to
# cancel any previous stylesheet and still keep a correct
# style for scrollbars
self.setStyleSheet('')
else:
p = self.palette()
p.setColor(QtGui.QPalette.Base, self.background)
p.setColor(QtGui.QPalette.Text, self.foreground)
p.setColor(QtGui.QPalette.Highlight,
self.selection_background)
p.setColor(QtGui.QPalette.HighlightedText,
self.selection_foreground)
self.setPalette(p)
self.repaint() | [
"def",
"_reset_stylesheet",
"(",
"self",
")",
":",
"self",
".",
"setFont",
"(",
"QtGui",
".",
"QFont",
"(",
"self",
".",
"_font_family",
",",
"self",
".",
"_font_size",
"+",
"self",
".",
"_zoom_level",
")",
")",
"flg_stylesheet",
"=",
"hasattr",
"(",
"se... | Resets stylesheet | [
"Resets",
"stylesheet"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1301-L1337 |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | CodeEdit._do_home_key | def _do_home_key(self, event=None, select=False):
""" Performs home key action """
# get nb char to first significative char
delta = (self.textCursor().positionInBlock() -
TextHelper(self).line_indent())
cursor = self.textCursor()
move = QtGui.QTextCursor.MoveAnchor
if select:
move = QtGui.QTextCursor.KeepAnchor
if delta > 0:
cursor.movePosition(QtGui.QTextCursor.Left, move, delta)
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock, move)
self.setTextCursor(cursor)
if event:
event.accept() | python | def _do_home_key(self, event=None, select=False):
""" Performs home key action """
# get nb char to first significative char
delta = (self.textCursor().positionInBlock() -
TextHelper(self).line_indent())
cursor = self.textCursor()
move = QtGui.QTextCursor.MoveAnchor
if select:
move = QtGui.QTextCursor.KeepAnchor
if delta > 0:
cursor.movePosition(QtGui.QTextCursor.Left, move, delta)
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock, move)
self.setTextCursor(cursor)
if event:
event.accept() | [
"def",
"_do_home_key",
"(",
"self",
",",
"event",
"=",
"None",
",",
"select",
"=",
"False",
")",
":",
"# get nb char to first significative char",
"delta",
"=",
"(",
"self",
".",
"textCursor",
"(",
")",
".",
"positionInBlock",
"(",
")",
"-",
"TextHelper",
"(... | Performs home key action | [
"Performs",
"home",
"key",
"action"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L1339-L1354 |
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",
"."
] | train | https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/extensions.py#L23-L50 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L68-L73 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L79-L87 |
pyQode/pyqode.core | pyqode/core/widgets/errors_table.py | ErrorsTable._make_icon | def _make_icon(cls, status):
"""
Make icon from icon filename/tuple (if you want to use a theme)
"""
icon = cls.ICONS[status]
if isinstance(icon, tuple):
return QtGui.QIcon.fromTheme(
icon[0], QtGui.QIcon(icon[1]))
elif isinstance(icon, str):
return QtGui.QIcon(icon)
elif isinstance(icon, QtGui.QIcon):
return icon
else:
return None | python | def _make_icon(cls, status):
"""
Make icon from icon filename/tuple (if you want to use a theme)
"""
icon = cls.ICONS[status]
if isinstance(icon, tuple):
return QtGui.QIcon.fromTheme(
icon[0], QtGui.QIcon(icon[1]))
elif isinstance(icon, str):
return QtGui.QIcon(icon)
elif isinstance(icon, QtGui.QIcon):
return icon
else:
return None | [
"def",
"_make_icon",
"(",
"cls",
",",
"status",
")",
":",
"icon",
"=",
"cls",
".",
"ICONS",
"[",
"status",
"]",
"if",
"isinstance",
"(",
"icon",
",",
"tuple",
")",
":",
"return",
"QtGui",
".",
"QIcon",
".",
"fromTheme",
"(",
"icon",
"[",
"0",
"]",
... | Make icon from icon filename/tuple (if you want to use a theme) | [
"Make",
"icon",
"from",
"icon",
"filename",
"/",
"tuple",
"(",
"if",
"you",
"want",
"to",
"use",
"a",
"theme",
")"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L91-L104 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L106-L143 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L145-L150 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/errors_table.py#L152-L165 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/dialogs/goto.py#L28-L42 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L267-L273 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L309-L333 |
pyQode/pyqode.core | pyqode/core/panels/search_and_replace.py | SearchAndReplacePanel._set_widget_background_color | def _set_widget_background_color(widget, color):
"""
Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply
"""
pal = widget.palette()
pal.setColor(pal.Base, color)
widget.setPalette(pal) | python | def _set_widget_background_color(widget, color):
"""
Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply
"""
pal = widget.palette()
pal.setColor(pal.Base, color)
widget.setPalette(pal) | [
"def",
"_set_widget_background_color",
"(",
"widget",
",",
"color",
")",
":",
"pal",
"=",
"widget",
".",
"palette",
"(",
")",
"pal",
".",
"setColor",
"(",
"pal",
".",
"Base",
",",
"color",
")",
"widget",
".",
"setPalette",
"(",
"pal",
")"
] | Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply | [
"Changes",
"the",
"base",
"color",
"of",
"a",
"widget",
"(",
"background",
")",
".",
":",
"param",
"widget",
":",
"widget",
"to",
"modify",
":",
"param",
"color",
":",
"the",
"color",
"to",
"apply"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L336-L344 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L367-L403 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L443-L487 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L489-L501 |
pyQode/pyqode.core | pyqode/core/panels/search_and_replace.py | SearchAndReplacePanel._search_flags | def _search_flags(self):
"""
Returns the user search flag: (regex, case_sensitive, whole_words).
"""
return (self.checkBoxRegex.isChecked(),
self.checkBoxCase.isChecked(),
self.checkBoxWholeWords.isChecked(),
self.checkBoxInSelection.isChecked()) | python | def _search_flags(self):
"""
Returns the user search flag: (regex, case_sensitive, whole_words).
"""
return (self.checkBoxRegex.isChecked(),
self.checkBoxCase.isChecked(),
self.checkBoxWholeWords.isChecked(),
self.checkBoxInSelection.isChecked()) | [
"def",
"_search_flags",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"checkBoxRegex",
".",
"isChecked",
"(",
")",
",",
"self",
".",
"checkBoxCase",
".",
"isChecked",
"(",
")",
",",
"self",
".",
"checkBoxWholeWords",
".",
"isChecked",
"(",
")",
",",... | Returns the user search flag: (regex, case_sensitive, whole_words). | [
"Returns",
"the",
"user",
"search",
"flag",
":",
"(",
"regex",
"case_sensitive",
"whole_words",
")",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L525-L532 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L599-L607 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L210-L221 |
pyQode/pyqode.core | pyqode/core/api/client.py | JsonTcpClient.send | def send(self, obj, encoding='utf-8'):
"""
Sends a python object to the backend. The object **must be JSON
serialisable**.
:param obj: object to send
:param encoding: encoding used to encode the json message into a
bytes array, this should match CodeEdit.file.encoding.
"""
comm('sending request: %r', obj)
msg = json.dumps(obj)
msg = msg.encode(encoding)
header = struct.pack('=I', len(msg))
self.write(header)
self.write(msg) | python | def send(self, obj, encoding='utf-8'):
"""
Sends a python object to the backend. The object **must be JSON
serialisable**.
:param obj: object to send
:param encoding: encoding used to encode the json message into a
bytes array, this should match CodeEdit.file.encoding.
"""
comm('sending request: %r', obj)
msg = json.dumps(obj)
msg = msg.encode(encoding)
header = struct.pack('=I', len(msg))
self.write(header)
self.write(msg) | [
"def",
"send",
"(",
"self",
",",
"obj",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"comm",
"(",
"'sending request: %r'",
",",
"obj",
")",
"msg",
"=",
"json",
".",
"dumps",
"(",
"obj",
")",
"msg",
"=",
"msg",
".",
"encode",
"(",
"encoding",
")",
"he... | Sends a python object to the backend. The object **must be JSON
serialisable**.
:param obj: object to send
:param encoding: encoding used to encode the json message into a
bytes array, this should match CodeEdit.file.encoding. | [
"Sends",
"a",
"python",
"object",
"to",
"the",
"backend",
".",
"The",
"object",
"**",
"must",
"be",
"JSON",
"serialisable",
"**",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L223-L237 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L248-L256 |
pyQode/pyqode.core | pyqode/core/api/client.py | JsonTcpClient._read_payload | def _read_payload(self):
""" Reads the payload (=data) """
comm('reading payload data')
comm('remaining bytes to read: %d', self._to_read)
data_read = self.read(self._to_read)
nb_bytes_read = len(data_read)
comm('%d bytes read', nb_bytes_read)
self._data_buf += data_read
self._to_read -= nb_bytes_read
if self._to_read <= 0:
try:
data = self._data_buf.decode('utf-8')
except AttributeError:
data = bytes(self._data_buf.data()).decode('utf-8')
comm('payload read: %r', data)
comm('payload length: %r', len(self._data_buf))
comm('decoding payload as json object')
obj = json.loads(data)
comm('response received: %r', obj)
try:
results = obj['results']
except (KeyError, TypeError):
results = None
# possible callback
if self._callback and self._callback():
self._callback()(results)
self._header_complete = False
self._data_buf = bytes()
self.finished.emit(self) | python | def _read_payload(self):
""" Reads the payload (=data) """
comm('reading payload data')
comm('remaining bytes to read: %d', self._to_read)
data_read = self.read(self._to_read)
nb_bytes_read = len(data_read)
comm('%d bytes read', nb_bytes_read)
self._data_buf += data_read
self._to_read -= nb_bytes_read
if self._to_read <= 0:
try:
data = self._data_buf.decode('utf-8')
except AttributeError:
data = bytes(self._data_buf.data()).decode('utf-8')
comm('payload read: %r', data)
comm('payload length: %r', len(self._data_buf))
comm('decoding payload as json object')
obj = json.loads(data)
comm('response received: %r', obj)
try:
results = obj['results']
except (KeyError, TypeError):
results = None
# possible callback
if self._callback and self._callback():
self._callback()(results)
self._header_complete = False
self._data_buf = bytes()
self.finished.emit(self) | [
"def",
"_read_payload",
"(",
"self",
")",
":",
"comm",
"(",
"'reading payload data'",
")",
"comm",
"(",
"'remaining bytes to read: %d'",
",",
"self",
".",
"_to_read",
")",
"data_read",
"=",
"self",
".",
"read",
"(",
"self",
".",
"_to_read",
")",
"nb_bytes_read... | Reads the payload (=data) | [
"Reads",
"the",
"payload",
"(",
"=",
"data",
")"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L304-L332 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L334-L340 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L362-L368 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L370-L377 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L387-L397 |
pyQode/pyqode.core | pyqode/core/api/client.py | BackendProcess._on_process_stderr_ready | def _on_process_stderr_ready(self):
""" Logs process output (stderr) """
try:
o = self.readAllStandardError()
except (TypeError, RuntimeError):
# widget already deleted
return
try:
output = bytes(o).decode(self._encoding)
except TypeError:
output = bytes(o.data()).decode(self._encoding)
for line in output.splitlines():
self._srv_logger.error(line) | python | def _on_process_stderr_ready(self):
""" Logs process output (stderr) """
try:
o = self.readAllStandardError()
except (TypeError, RuntimeError):
# widget already deleted
return
try:
output = bytes(o).decode(self._encoding)
except TypeError:
output = bytes(o.data()).decode(self._encoding)
for line in output.splitlines():
self._srv_logger.error(line) | [
"def",
"_on_process_stderr_ready",
"(",
"self",
")",
":",
"try",
":",
"o",
"=",
"self",
".",
"readAllStandardError",
"(",
")",
"except",
"(",
"TypeError",
",",
"RuntimeError",
")",
":",
"# widget already deleted",
"return",
"try",
":",
"output",
"=",
"bytes",
... | Logs process output (stderr) | [
"Logs",
"process",
"output",
"(",
"stderr",
")"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/client.py#L399-L411 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L108-L115 |
pyQode/pyqode.core | pyqode/core/modes/pygments_sh.py | PygmentsSH.on_install | def on_install(self, editor):
"""
:type editor: pyqode.code.api.CodeEdit
"""
self._clear_caches()
self._update_style()
super(PygmentsSH, self).on_install(editor) | python | def on_install(self, editor):
"""
:type editor: pyqode.code.api.CodeEdit
"""
self._clear_caches()
self._update_style()
super(PygmentsSH, self).on_install(editor) | [
"def",
"on_install",
"(",
"self",
",",
"editor",
")",
":",
"self",
".",
"_clear_caches",
"(",
")",
"self",
".",
"_update_style",
"(",
")",
"super",
"(",
"PygmentsSH",
",",
"self",
")",
".",
"on_install",
"(",
"editor",
")"
] | :type editor: pyqode.code.api.CodeEdit | [
":",
"type",
"editor",
":",
"pyqode",
".",
"code",
".",
"api",
".",
"CodeEdit"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L177-L183 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L185-L205 |
pyQode/pyqode.core | pyqode/core/modes/pygments_sh.py | PygmentsSH.set_lexer_from_filename | def set_lexer_from_filename(self, filename):
"""
Change the lexer based on the filename (actually only the extension is
needed)
:param filename: Filename or extension
"""
self._lexer = None
if filename.endswith("~"):
filename = filename[0:len(filename) - 1]
try:
self._lexer = get_lexer_for_filename(filename)
except (ClassNotFound, ImportError):
print('class not found for url', filename)
try:
m = mimetypes.guess_type(filename)
print(m)
self._lexer = get_lexer_for_mimetype(m[0])
except (ClassNotFound, IndexError, ImportError):
self._lexer = get_lexer_for_mimetype('text/plain')
if self._lexer is None:
_logger().warning('failed to get lexer from filename: %s, using '
'plain text instead...', filename)
self._lexer = TextLexer() | python | def set_lexer_from_filename(self, filename):
"""
Change the lexer based on the filename (actually only the extension is
needed)
:param filename: Filename or extension
"""
self._lexer = None
if filename.endswith("~"):
filename = filename[0:len(filename) - 1]
try:
self._lexer = get_lexer_for_filename(filename)
except (ClassNotFound, ImportError):
print('class not found for url', filename)
try:
m = mimetypes.guess_type(filename)
print(m)
self._lexer = get_lexer_for_mimetype(m[0])
except (ClassNotFound, IndexError, ImportError):
self._lexer = get_lexer_for_mimetype('text/plain')
if self._lexer is None:
_logger().warning('failed to get lexer from filename: %s, using '
'plain text instead...', filename)
self._lexer = TextLexer() | [
"def",
"set_lexer_from_filename",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_lexer",
"=",
"None",
"if",
"filename",
".",
"endswith",
"(",
"\"~\"",
")",
":",
"filename",
"=",
"filename",
"[",
"0",
":",
"len",
"(",
"filename",
")",
"-",
"1",
... | Change the lexer based on the filename (actually only the extension is
needed)
:param filename: Filename or extension | [
"Change",
"the",
"lexer",
"based",
"on",
"the",
"filename",
"(",
"actually",
"only",
"the",
"extension",
"is",
"needed",
")"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L207-L230 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L232-L240 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L242-L293 |
pyQode/pyqode.core | pyqode/core/modes/pygments_sh.py | PygmentsSH._update_style | def _update_style(self):
""" Sets the style to the specified Pygments style.
"""
try:
self._style = get_style_by_name(self._pygments_style)
except ClassNotFound:
# unknown style, also happen with plugins style when used from a
# frozen app.
if self._pygments_style == 'qt':
from pyqode.core.styles import QtStyle
self._style = QtStyle
elif self._pygments_style == 'darcula':
from pyqode.core.styles import DarculaStyle
self._style = DarculaStyle
else:
self._style = get_style_by_name('default')
self._pygments_style = 'default'
self._clear_caches() | python | def _update_style(self):
""" Sets the style to the specified Pygments style.
"""
try:
self._style = get_style_by_name(self._pygments_style)
except ClassNotFound:
# unknown style, also happen with plugins style when used from a
# frozen app.
if self._pygments_style == 'qt':
from pyqode.core.styles import QtStyle
self._style = QtStyle
elif self._pygments_style == 'darcula':
from pyqode.core.styles import DarculaStyle
self._style = DarculaStyle
else:
self._style = get_style_by_name('default')
self._pygments_style = 'default'
self._clear_caches() | [
"def",
"_update_style",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_style",
"=",
"get_style_by_name",
"(",
"self",
".",
"_pygments_style",
")",
"except",
"ClassNotFound",
":",
"# unknown style, also happen with plugins style when used from a",
"# frozen app.",
"if... | Sets the style to the specified Pygments style. | [
"Sets",
"the",
"style",
"to",
"the",
"specified",
"Pygments",
"style",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L295-L312 |
pyQode/pyqode.core | pyqode/core/modes/pygments_sh.py | PygmentsSH._get_format | def _get_format(self, token):
""" Returns a QTextCharFormat for token or None.
"""
if token == Whitespace:
return self.editor.whitespaces_foreground
if token in self._formats:
return self._formats[token]
result = self._get_format_from_style(token, self._style)
self._formats[token] = result
return result | python | def _get_format(self, token):
""" Returns a QTextCharFormat for token or None.
"""
if token == Whitespace:
return self.editor.whitespaces_foreground
if token in self._formats:
return self._formats[token]
result = self._get_format_from_style(token, self._style)
self._formats[token] = result
return result | [
"def",
"_get_format",
"(",
"self",
",",
"token",
")",
":",
"if",
"token",
"==",
"Whitespace",
":",
"return",
"self",
".",
"editor",
".",
"whitespaces_foreground",
"if",
"token",
"in",
"self",
".",
"_formats",
":",
"return",
"self",
".",
"_formats",
"[",
... | Returns a QTextCharFormat for token or None. | [
"Returns",
"a",
"QTextCharFormat",
"for",
"token",
"or",
"None",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L320-L332 |
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",
".."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L149-L178 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L435-L476 |
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"
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L539-L555 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L557-L569 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L640-L676 |
pyQode/pyqode.core | pyqode/core/api/utils.py | TextHelper.is_comment_or_string | def is_comment_or_string(self, cursor_or_block, formats=None):
"""
Checks if a block/cursor is a string or a comment.
:param cursor_or_block: QTextCursor or QTextBlock
:param formats: the list of color scheme formats to consider. By
default, it will consider the following keys: 'comment', 'string',
'docstring'.
"""
if formats is None:
formats = ["comment", "string", "docstring"]
layout = None
pos = 0
if isinstance(cursor_or_block, QtGui.QTextBlock):
pos = len(cursor_or_block.text()) - 1
layout = cursor_or_block.layout()
elif isinstance(cursor_or_block, QtGui.QTextCursor):
b = cursor_or_block.block()
pos = cursor_or_block.position() - b.position()
layout = b.layout()
if layout is not None:
additional_formats = layout.additionalFormats()
sh = self._editor.syntax_highlighter
if sh:
ref_formats = sh.color_scheme.formats
for r in additional_formats:
if r.start <= pos < (r.start + r.length):
for fmt_type in formats:
is_user_obj = (r.format.objectType() ==
r.format.UserObject)
if (ref_formats[fmt_type] == r.format and
is_user_obj):
return True
return False | python | def is_comment_or_string(self, cursor_or_block, formats=None):
"""
Checks if a block/cursor is a string or a comment.
:param cursor_or_block: QTextCursor or QTextBlock
:param formats: the list of color scheme formats to consider. By
default, it will consider the following keys: 'comment', 'string',
'docstring'.
"""
if formats is None:
formats = ["comment", "string", "docstring"]
layout = None
pos = 0
if isinstance(cursor_or_block, QtGui.QTextBlock):
pos = len(cursor_or_block.text()) - 1
layout = cursor_or_block.layout()
elif isinstance(cursor_or_block, QtGui.QTextCursor):
b = cursor_or_block.block()
pos = cursor_or_block.position() - b.position()
layout = b.layout()
if layout is not None:
additional_formats = layout.additionalFormats()
sh = self._editor.syntax_highlighter
if sh:
ref_formats = sh.color_scheme.formats
for r in additional_formats:
if r.start <= pos < (r.start + r.length):
for fmt_type in formats:
is_user_obj = (r.format.objectType() ==
r.format.UserObject)
if (ref_formats[fmt_type] == r.format and
is_user_obj):
return True
return False | [
"def",
"is_comment_or_string",
"(",
"self",
",",
"cursor_or_block",
",",
"formats",
"=",
"None",
")",
":",
"if",
"formats",
"is",
"None",
":",
"formats",
"=",
"[",
"\"comment\"",
",",
"\"string\"",
",",
"\"docstring\"",
"]",
"layout",
"=",
"None",
"pos",
"... | Checks if a block/cursor is a string or a comment.
:param cursor_or_block: QTextCursor or QTextBlock
:param formats: the list of color scheme formats to consider. By
default, it will consider the following keys: 'comment', 'string',
'docstring'. | [
"Checks",
"if",
"a",
"block",
"/",
"cursor",
"is",
"a",
"string",
"or",
"a",
"comment",
".",
":",
"param",
"cursor_or_block",
":",
"QTextCursor",
"or",
"QTextBlock",
":",
"param",
"formats",
":",
"the",
"list",
"of",
"color",
"scheme",
"formats",
"to",
"... | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L678-L710 |
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",
"."
] | train | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/utils.py#L759-L854 |
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",
"."
] | train | https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/__init__.py#L22-L32 |
bachya/pypollencom | example.py | run | async def run(websession):
"""Run."""
try:
client = Client('17015', websession)
print('Client instantiated for ZIP "{0}"'.format(client.zip_code))
print()
print('CURRENT ALLERGENS')
print(await client.allergens.current())
print()
print('EXTENDED ALLERGENS')
print(await client.allergens.extended())
print()
print('HISTORIC ALLERGENS')
print(await client.allergens.historic())
print()
print('ALLERGY OUTLOOK')
print(await client.allergens.outlook())
print()
print('EXTENDED DISEASE INFO')
print(await client.disease.extended())
print()
print('CURRENT ASTHMA INFO')
print(await client.asthma.current())
print()
print('EXTENDED ASTHMA INFO')
print(await client.asthma.extended())
print()
print('HISTORIC ASTHMA INFO')
print(await client.asthma.historic())
except PollenComError as err:
print(err) | python | async def run(websession):
"""Run."""
try:
client = Client('17015', websession)
print('Client instantiated for ZIP "{0}"'.format(client.zip_code))
print()
print('CURRENT ALLERGENS')
print(await client.allergens.current())
print()
print('EXTENDED ALLERGENS')
print(await client.allergens.extended())
print()
print('HISTORIC ALLERGENS')
print(await client.allergens.historic())
print()
print('ALLERGY OUTLOOK')
print(await client.allergens.outlook())
print()
print('EXTENDED DISEASE INFO')
print(await client.disease.extended())
print()
print('CURRENT ASTHMA INFO')
print(await client.asthma.current())
print()
print('EXTENDED ASTHMA INFO')
print(await client.asthma.extended())
print()
print('HISTORIC ASTHMA INFO')
print(await client.asthma.historic())
except PollenComError as err:
print(err) | [
"async",
"def",
"run",
"(",
"websession",
")",
":",
"try",
":",
"client",
"=",
"Client",
"(",
"'17015'",
",",
"websession",
")",
"print",
"(",
"'Client instantiated for ZIP \"{0}\"'",
".",
"format",
"(",
"client",
".",
"zip_code",
")",
")",
"print",
"(",
"... | Run. | [
"Run",
"."
] | train | https://github.com/bachya/pypollencom/blob/d1616a8471b350953d4f99f5a1dddca035977366/example.py#L16-L54 |
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",
"."
] | train | https://github.com/bachya/pypollencom/blob/d1616a8471b350953d4f99f5a1dddca035977366/pypollencom/allergens.py#L33-L42 |
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"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/fabfile.py#L68-L85 |
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"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/fabfile.py#L256-L259 |
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"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L153-L182 |
SchroterQuentin/django-search-listview | search_listview/list.py | alias_field | def alias_field(model, field):
"""
Return the prefix name of a field
"""
for part in field.split(LOOKUP_SEP)[:-1]:
model = associate_model(model,part)
return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1] | python | def alias_field(model, field):
"""
Return the prefix name of a field
"""
for part in field.split(LOOKUP_SEP)[:-1]:
model = associate_model(model,part)
return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1] | [
"def",
"alias_field",
"(",
"model",
",",
"field",
")",
":",
"for",
"part",
"in",
"field",
".",
"split",
"(",
"LOOKUP_SEP",
")",
"[",
":",
"-",
"1",
"]",
":",
"model",
"=",
"associate_model",
"(",
"model",
",",
"part",
")",
"return",
"model",
".",
"... | Return the prefix name of a field | [
"Return",
"the",
"prefix",
"name",
"of",
"a",
"field"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L184-L190 |
SchroterQuentin/django-search-listview | search_listview/list.py | associate_model | def associate_model(model, field):
"""
Return the model associate to the ForeignKey or ManyToMany
relation
"""
class_field = model._meta.get_field(field)
if hasattr(class_field, "field"):
return class_field.field.related.related_model
else:
return class_field.related_model | python | def associate_model(model, field):
"""
Return the model associate to the ForeignKey or ManyToMany
relation
"""
class_field = model._meta.get_field(field)
if hasattr(class_field, "field"):
return class_field.field.related.related_model
else:
return class_field.related_model | [
"def",
"associate_model",
"(",
"model",
",",
"field",
")",
":",
"class_field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"field",
")",
"if",
"hasattr",
"(",
"class_field",
",",
"\"field\"",
")",
":",
"return",
"class_field",
".",
"field",
".",
"... | Return the model associate to the ForeignKey or ManyToMany
relation | [
"Return",
"the",
"model",
"associate",
"to",
"the",
"ForeignKey",
"or",
"ManyToMany",
"relation"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L192-L201 |
SchroterQuentin/django-search-listview | search_listview/list.py | get_formfield | def get_formfield(model, field):
"""
Return the formfied associate to the field of the model
"""
class_field = model._meta.get_field(field)
if hasattr(class_field, "field"):
formfield = class_field.field.formfield()
else:
formfield = class_field.formfield()
# Otherwise the formfield contain the reverse relation
if isinstance(formfield, ChoiceField):
formfield.choices = class_field.get_choices()
return formfield | python | def get_formfield(model, field):
"""
Return the formfied associate to the field of the model
"""
class_field = model._meta.get_field(field)
if hasattr(class_field, "field"):
formfield = class_field.field.formfield()
else:
formfield = class_field.formfield()
# Otherwise the formfield contain the reverse relation
if isinstance(formfield, ChoiceField):
formfield.choices = class_field.get_choices()
return formfield | [
"def",
"get_formfield",
"(",
"model",
",",
"field",
")",
":",
"class_field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"field",
")",
"if",
"hasattr",
"(",
"class_field",
",",
"\"field\"",
")",
":",
"formfield",
"=",
"class_field",
".",
"field",
... | Return the formfied associate to the field of the model | [
"Return",
"the",
"formfied",
"associate",
"to",
"the",
"field",
"of",
"the",
"model"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L203-L218 |
SchroterQuentin/django-search-listview | search_listview/list.py | SearchableListView.get_q_object | def get_q_object(self):
"""
Build Q object to filter the queryset
"""
q_object = Q()
for field in self.searchable_fields:
value = self.request.GET.getlist(alias_field(self.model, field), None)
mini_q = Q()
for val in value:
attr = "{0}{1}".format(field, self.specifications.get(field, ''))
if val:
dic_tmp = {
attr: val
}
mini_q |= Q(**dic_tmp)
q_object &= mini_q
return q_object | python | def get_q_object(self):
"""
Build Q object to filter the queryset
"""
q_object = Q()
for field in self.searchable_fields:
value = self.request.GET.getlist(alias_field(self.model, field), None)
mini_q = Q()
for val in value:
attr = "{0}{1}".format(field, self.specifications.get(field, ''))
if val:
dic_tmp = {
attr: val
}
mini_q |= Q(**dic_tmp)
q_object &= mini_q
return q_object | [
"def",
"get_q_object",
"(",
"self",
")",
":",
"q_object",
"=",
"Q",
"(",
")",
"for",
"field",
"in",
"self",
".",
"searchable_fields",
":",
"value",
"=",
"self",
".",
"request",
".",
"GET",
".",
"getlist",
"(",
"alias_field",
"(",
"self",
".",
"model",
... | Build Q object to filter the queryset | [
"Build",
"Q",
"object",
"to",
"filter",
"the",
"queryset"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L26-L42 |
SchroterQuentin/django-search-listview | search_listview/list.py | SearchableListView.get_search_form | def get_search_form(self):
"""
Return list of form based on model
"""
magic_dico_form = self.get_dict_for_forms()
forms = []
initial = list(self.request.GET.lists())
for key, value in magic_dico_form.items():
form = Form()
model = value["model"]
if not value["fields"]:
continue
for field in value["fields"]:
formfield = get_formfield(model, field)
formfield.widget.attrs.update({'class': self.css_class})
form.fields.update({
field : formfield
})
initial_tmp = {}
for k, vals in initial:
tmp_list = k.split(model.__name__ + "-")
if len(tmp_list) == 2:
list_val_tmp = vals[0] if len(vals) == 1 else [val for val in vals if val != '']
initial_tmp[tmp_list[-1]] = list_val_tmp
form.initial = initial_tmp
form.prefix = model.__name__
forms.append(form)
return sorted(forms, key=lambda form: form.prefix) | python | def get_search_form(self):
"""
Return list of form based on model
"""
magic_dico_form = self.get_dict_for_forms()
forms = []
initial = list(self.request.GET.lists())
for key, value in magic_dico_form.items():
form = Form()
model = value["model"]
if not value["fields"]:
continue
for field in value["fields"]:
formfield = get_formfield(model, field)
formfield.widget.attrs.update({'class': self.css_class})
form.fields.update({
field : formfield
})
initial_tmp = {}
for k, vals in initial:
tmp_list = k.split(model.__name__ + "-")
if len(tmp_list) == 2:
list_val_tmp = vals[0] if len(vals) == 1 else [val for val in vals if val != '']
initial_tmp[tmp_list[-1]] = list_val_tmp
form.initial = initial_tmp
form.prefix = model.__name__
forms.append(form)
return sorted(forms, key=lambda form: form.prefix) | [
"def",
"get_search_form",
"(",
"self",
")",
":",
"magic_dico_form",
"=",
"self",
".",
"get_dict_for_forms",
"(",
")",
"forms",
"=",
"[",
"]",
"initial",
"=",
"list",
"(",
"self",
".",
"request",
".",
"GET",
".",
"lists",
"(",
")",
")",
"for",
"key",
... | Return list of form based on model | [
"Return",
"list",
"of",
"form",
"based",
"on",
"model"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L44-L74 |
SchroterQuentin/django-search-listview | search_listview/list.py | SearchableListView.get_dict_for_forms | def get_dict_for_forms(self):
"""
Build a dictionnary where searchable_fields are
next to their model to be use in modelform_factory
dico = {
"str(model)" : {
"model" : Model,
"fields" = [] #searchable_fields which are attribute of Model
}
}
"""
magic_dico = field_to_dict(self.searchable_fields)
dico = {}
def dict_from_fields_r(mini_dict, dico, model):
"""
Create the dico recursively from the magic_dico
"""
dico[str(model)] = {}
dico[str(model)]["model"] = model
dico[str(model)]["fields"] = []
for key, value in mini_dict.items():
if isinstance(value, bool):
continue
if value == EMPTY_DICT:
dico[str(model)]["fields"].append(key)
elif EMPTY_DICT.items() <= value.items():
dico[str(model)]["fields"].append(key)
model_tmp = associate_model(model, key)
dict_from_fields_r(value, dico, model_tmp)
else:
model_tmp = associate_model(model, key)
dict_from_fields_r(value, dico, model_tmp)
if magic_dico:
dict_from_fields_r(magic_dico, dico, self.model)
return dico | python | def get_dict_for_forms(self):
"""
Build a dictionnary where searchable_fields are
next to their model to be use in modelform_factory
dico = {
"str(model)" : {
"model" : Model,
"fields" = [] #searchable_fields which are attribute of Model
}
}
"""
magic_dico = field_to_dict(self.searchable_fields)
dico = {}
def dict_from_fields_r(mini_dict, dico, model):
"""
Create the dico recursively from the magic_dico
"""
dico[str(model)] = {}
dico[str(model)]["model"] = model
dico[str(model)]["fields"] = []
for key, value in mini_dict.items():
if isinstance(value, bool):
continue
if value == EMPTY_DICT:
dico[str(model)]["fields"].append(key)
elif EMPTY_DICT.items() <= value.items():
dico[str(model)]["fields"].append(key)
model_tmp = associate_model(model, key)
dict_from_fields_r(value, dico, model_tmp)
else:
model_tmp = associate_model(model, key)
dict_from_fields_r(value, dico, model_tmp)
if magic_dico:
dict_from_fields_r(magic_dico, dico, self.model)
return dico | [
"def",
"get_dict_for_forms",
"(",
"self",
")",
":",
"magic_dico",
"=",
"field_to_dict",
"(",
"self",
".",
"searchable_fields",
")",
"dico",
"=",
"{",
"}",
"def",
"dict_from_fields_r",
"(",
"mini_dict",
",",
"dico",
",",
"model",
")",
":",
"\"\"\"\n ... | Build a dictionnary where searchable_fields are
next to their model to be use in modelform_factory
dico = {
"str(model)" : {
"model" : Model,
"fields" = [] #searchable_fields which are attribute of Model
}
} | [
"Build",
"a",
"dictionnary",
"where",
"searchable_fields",
"are",
"next",
"to",
"their",
"model",
"to",
"be",
"use",
"in",
"modelform_factory"
] | train | https://github.com/SchroterQuentin/django-search-listview/blob/8b027a6908dc30c6ebc613bb4fde6b1ba40124a3/search_listview/list.py#L111-L150 |
bachya/pypollencom | pypollencom/decorators.py | raise_on_invalid_zip | def raise_on_invalid_zip(func: Callable) -> Callable:
"""Raise an exception when there's no data (via a bad ZIP code)."""
async def decorator(*args: list, **kwargs: dict) -> dict:
"""Decorate."""
data = await func(*args, **kwargs)
if not data['Location']['periods']:
raise InvalidZipError('No data returned for ZIP code')
return data
return decorator | python | def raise_on_invalid_zip(func: Callable) -> Callable:
"""Raise an exception when there's no data (via a bad ZIP code)."""
async def decorator(*args: list, **kwargs: dict) -> dict:
"""Decorate."""
data = await func(*args, **kwargs)
if not data['Location']['periods']:
raise InvalidZipError('No data returned for ZIP code')
return data
return decorator | [
"def",
"raise_on_invalid_zip",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"async",
"def",
"decorator",
"(",
"*",
"args",
":",
"list",
",",
"*",
"*",
"kwargs",
":",
"dict",
")",
"->",
"dict",
":",
"\"\"\"Decorate.\"\"\"",
"data",
"=",
"awai... | Raise an exception when there's no data (via a bad ZIP code). | [
"Raise",
"an",
"exception",
"when",
"there",
"s",
"no",
"data",
"(",
"via",
"a",
"bad",
"ZIP",
"code",
")",
"."
] | train | https://github.com/bachya/pypollencom/blob/d1616a8471b350953d4f99f5a1dddca035977366/pypollencom/decorators.py#L7-L16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.