id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
31,000 | spyder-ide/spyder | spyder/plugins/editor/utils/autosave.py | AutosaveForStack.remove_autosave_file | def remove_autosave_file(self, fileinfo):
"""
Remove autosave file for specified file.
This function also updates `self.autosave_mapping` and clears the
`changed_since_autosave` flag.
"""
filename = fileinfo.filename
if filename not in self.name_mapping:
return
autosave_filename = self.name_mapping[filename]
try:
os.remove(autosave_filename)
except EnvironmentError as error:
action = (_('Error while removing autosave file {}')
.format(autosave_filename))
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled()
del self.name_mapping[filename]
self.stack.sig_option_changed.emit(
'autosave_mapping', self.name_mapping)
logger.debug('Removing autosave file %s', autosave_filename) | python | def remove_autosave_file(self, fileinfo):
"""
Remove autosave file for specified file.
This function also updates `self.autosave_mapping` and clears the
`changed_since_autosave` flag.
"""
filename = fileinfo.filename
if filename not in self.name_mapping:
return
autosave_filename = self.name_mapping[filename]
try:
os.remove(autosave_filename)
except EnvironmentError as error:
action = (_('Error while removing autosave file {}')
.format(autosave_filename))
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled()
del self.name_mapping[filename]
self.stack.sig_option_changed.emit(
'autosave_mapping', self.name_mapping)
logger.debug('Removing autosave file %s', autosave_filename) | [
"def",
"remove_autosave_file",
"(",
"self",
",",
"fileinfo",
")",
":",
"filename",
"=",
"fileinfo",
".",
"filename",
"if",
"filename",
"not",
"in",
"self",
".",
"name_mapping",
":",
"return",
"autosave_filename",
"=",
"self",
".",
"name_mapping",
"[",
"filenam... | Remove autosave file for specified file.
This function also updates `self.autosave_mapping` and clears the
`changed_since_autosave` flag. | [
"Remove",
"autosave",
"file",
"for",
"specified",
"file",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L154-L175 |
31,001 | spyder-ide/spyder | spyder/plugins/editor/utils/autosave.py | AutosaveForStack.get_autosave_filename | def get_autosave_filename(self, filename):
"""
Get name of autosave file for specified file name.
This function uses the dict in `self.name_mapping`. If `filename` is
in the mapping, then return the corresponding autosave file name.
Otherwise, construct a unique file name and update the mapping.
Args:
filename (str): original file name
"""
try:
autosave_filename = self.name_mapping[filename]
except KeyError:
autosave_dir = get_conf_path('autosave')
if not osp.isdir(autosave_dir):
try:
os.mkdir(autosave_dir)
except EnvironmentError as error:
action = _('Error while creating autosave directory')
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled()
autosave_filename = self.create_unique_autosave_filename(
filename, autosave_dir)
self.name_mapping[filename] = autosave_filename
self.stack.sig_option_changed.emit(
'autosave_mapping', self.name_mapping)
logger.debug('New autosave file name')
return autosave_filename | python | def get_autosave_filename(self, filename):
"""
Get name of autosave file for specified file name.
This function uses the dict in `self.name_mapping`. If `filename` is
in the mapping, then return the corresponding autosave file name.
Otherwise, construct a unique file name and update the mapping.
Args:
filename (str): original file name
"""
try:
autosave_filename = self.name_mapping[filename]
except KeyError:
autosave_dir = get_conf_path('autosave')
if not osp.isdir(autosave_dir):
try:
os.mkdir(autosave_dir)
except EnvironmentError as error:
action = _('Error while creating autosave directory')
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled()
autosave_filename = self.create_unique_autosave_filename(
filename, autosave_dir)
self.name_mapping[filename] = autosave_filename
self.stack.sig_option_changed.emit(
'autosave_mapping', self.name_mapping)
logger.debug('New autosave file name')
return autosave_filename | [
"def",
"get_autosave_filename",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"autosave_filename",
"=",
"self",
".",
"name_mapping",
"[",
"filename",
"]",
"except",
"KeyError",
":",
"autosave_dir",
"=",
"get_conf_path",
"(",
"'autosave'",
")",
"if",
"not... | Get name of autosave file for specified file name.
This function uses the dict in `self.name_mapping`. If `filename` is
in the mapping, then return the corresponding autosave file name.
Otherwise, construct a unique file name and update the mapping.
Args:
filename (str): original file name | [
"Get",
"name",
"of",
"autosave",
"file",
"for",
"specified",
"file",
"name",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L177-L205 |
31,002 | spyder-ide/spyder | spyder/plugins/editor/utils/autosave.py | AutosaveForStack.autosave | def autosave(self, index):
"""
Autosave a file.
Do nothing if the `changed_since_autosave` flag is not set or the file
is newly created (and thus not named by the user). Otherwise, save a
copy of the file with the name given by `self.get_autosave_filename()`
and clear the `changed_since_autosave` flag. Errors raised when saving
are silently ignored.
Args:
index (int): index into self.stack.data
"""
finfo = self.stack.data[index]
document = finfo.editor.document()
if not document.changed_since_autosave or finfo.newly_created:
return
autosave_filename = self.get_autosave_filename(finfo.filename)
logger.debug('Autosaving %s to %s', finfo.filename, autosave_filename)
try:
self.stack._write_to_file(finfo, autosave_filename)
document.changed_since_autosave = False
except EnvironmentError as error:
action = (_('Error while autosaving {} to {}')
.format(finfo.filename, autosave_filename))
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled() | python | def autosave(self, index):
"""
Autosave a file.
Do nothing if the `changed_since_autosave` flag is not set or the file
is newly created (and thus not named by the user). Otherwise, save a
copy of the file with the name given by `self.get_autosave_filename()`
and clear the `changed_since_autosave` flag. Errors raised when saving
are silently ignored.
Args:
index (int): index into self.stack.data
"""
finfo = self.stack.data[index]
document = finfo.editor.document()
if not document.changed_since_autosave or finfo.newly_created:
return
autosave_filename = self.get_autosave_filename(finfo.filename)
logger.debug('Autosaving %s to %s', finfo.filename, autosave_filename)
try:
self.stack._write_to_file(finfo, autosave_filename)
document.changed_since_autosave = False
except EnvironmentError as error:
action = (_('Error while autosaving {} to {}')
.format(finfo.filename, autosave_filename))
msgbox = AutosaveErrorDialog(action, error)
msgbox.exec_if_enabled() | [
"def",
"autosave",
"(",
"self",
",",
"index",
")",
":",
"finfo",
"=",
"self",
".",
"stack",
".",
"data",
"[",
"index",
"]",
"document",
"=",
"finfo",
".",
"editor",
".",
"document",
"(",
")",
"if",
"not",
"document",
".",
"changed_since_autosave",
"or"... | Autosave a file.
Do nothing if the `changed_since_autosave` flag is not set or the file
is newly created (and thus not named by the user). Otherwise, save a
copy of the file with the name given by `self.get_autosave_filename()`
and clear the `changed_since_autosave` flag. Errors raised when saving
are silently ignored.
Args:
index (int): index into self.stack.data | [
"Autosave",
"a",
"file",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L207-L233 |
31,003 | spyder-ide/spyder | spyder/plugins/editor/utils/autosave.py | AutosaveForStack.autosave_all | def autosave_all(self):
"""Autosave all opened files."""
for index in range(self.stack.get_stack_count()):
self.autosave(index) | python | def autosave_all(self):
"""Autosave all opened files."""
for index in range(self.stack.get_stack_count()):
self.autosave(index) | [
"def",
"autosave_all",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"stack",
".",
"get_stack_count",
"(",
")",
")",
":",
"self",
".",
"autosave",
"(",
"index",
")"
] | Autosave all opened files. | [
"Autosave",
"all",
"opened",
"files",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L235-L238 |
31,004 | spyder-ide/spyder | spyder/utils/fixtures.py | tmpconfig | def tmpconfig(request):
"""
Fixtures that returns a temporary CONF element.
"""
SUBFOLDER = tempfile.mkdtemp()
CONF = UserConfig('spyder-test',
defaults=DEFAULTS,
version=CONF_VERSION,
subfolder=SUBFOLDER,
raw_mode=True,
)
def fin():
"""
Fixture finalizer to delete the temporary CONF element.
"""
shutil.rmtree(SUBFOLDER)
request.addfinalizer(fin)
return CONF | python | def tmpconfig(request):
"""
Fixtures that returns a temporary CONF element.
"""
SUBFOLDER = tempfile.mkdtemp()
CONF = UserConfig('spyder-test',
defaults=DEFAULTS,
version=CONF_VERSION,
subfolder=SUBFOLDER,
raw_mode=True,
)
def fin():
"""
Fixture finalizer to delete the temporary CONF element.
"""
shutil.rmtree(SUBFOLDER)
request.addfinalizer(fin)
return CONF | [
"def",
"tmpconfig",
"(",
"request",
")",
":",
"SUBFOLDER",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"CONF",
"=",
"UserConfig",
"(",
"'spyder-test'",
",",
"defaults",
"=",
"DEFAULTS",
",",
"version",
"=",
"CONF_VERSION",
",",
"subfolder",
"=",
"SUBFOLDER",
... | Fixtures that returns a temporary CONF element. | [
"Fixtures",
"that",
"returns",
"a",
"temporary",
"CONF",
"element",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/fixtures.py#L27-L46 |
31,005 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.offset | def offset(self):
"""This property holds the vertical offset of the scroll flag area
relative to the top of the text editor."""
vsb = self.editor.verticalScrollBar()
style = vsb.style()
opt = QStyleOptionSlider()
vsb.initStyleOption(opt)
# Get the area in which the slider handle may move.
groove_rect = style.subControlRect(
QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self)
return groove_rect.y() | python | def offset(self):
"""This property holds the vertical offset of the scroll flag area
relative to the top of the text editor."""
vsb = self.editor.verticalScrollBar()
style = vsb.style()
opt = QStyleOptionSlider()
vsb.initStyleOption(opt)
# Get the area in which the slider handle may move.
groove_rect = style.subControlRect(
QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self)
return groove_rect.y() | [
"def",
"offset",
"(",
"self",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"style",
"=",
"vsb",
".",
"style",
"(",
")",
"opt",
"=",
"QStyleOptionSlider",
"(",
")",
"vsb",
".",
"initStyleOption",
"(",
"opt",
")",
"#... | This property holds the vertical offset of the scroll flag area
relative to the top of the text editor. | [
"This",
"property",
"holds",
"the",
"vertical",
"offset",
"of",
"the",
"scroll",
"flag",
"area",
"relative",
"to",
"the",
"top",
"of",
"the",
"text",
"editor",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L49-L61 |
31,006 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.paintEvent | def paintEvent(self, event):
"""
Override Qt method.
Painting the scroll flag area
"""
make_flag = self.make_flag_qrect
# Fill the whole painting area
painter = QPainter(self)
painter.fillRect(event.rect(), self.editor.sideareas_color)
# Paint warnings and todos
block = self.editor.document().firstBlock()
for line_number in range(self.editor.document().blockCount()+1):
data = block.userData()
if data:
if data.code_analysis:
# Paint the warnings
color = self.editor.warning_color
for source, code, severity, message in data.code_analysis:
error = severity == DiagnosticSeverity.ERROR
if error:
color = self.editor.error_color
break
self.set_painter(painter, color)
painter.drawRect(make_flag(line_number))
if data.todo:
# Paint the todos
self.set_painter(painter, self.editor.todo_color)
painter.drawRect(make_flag(line_number))
if data.breakpoint:
# Paint the breakpoints
self.set_painter(painter, self.editor.breakpoint_color)
painter.drawRect(make_flag(line_number))
block = block.next()
# Paint the occurrences
if self.editor.occurrences:
self.set_painter(painter, self.editor.occurrence_color)
for line_number in self.editor.occurrences:
painter.drawRect(make_flag(line_number))
# Paint the found results
if self.editor.found_results:
self.set_painter(painter, self.editor.found_results_color)
for line_number in self.editor.found_results:
painter.drawRect(make_flag(line_number))
# Paint the slider range
if not self._unit_testing:
alt = QApplication.queryKeyboardModifiers() & Qt.AltModifier
else:
alt = self._alt_key_is_down
cursor_pos = self.mapFromGlobal(QCursor().pos())
is_over_self = self.rect().contains(cursor_pos)
is_over_editor = self.editor.rect().contains(
self.editor.mapFromGlobal(QCursor().pos()))
# We use QRect.contains instead of QWidget.underMouse method to
# determined if the cursor is over the editor or the flag scrollbar
# because the later gives a wrong result when a mouse button
# is pressed.
if ((is_over_self or (alt and is_over_editor)) and self.slider):
pen_color = QColor(Qt.gray)
pen_color.setAlphaF(.85)
painter.setPen(pen_color)
brush_color = QColor(Qt.gray)
brush_color.setAlphaF(.5)
painter.setBrush(QBrush(brush_color))
painter.drawRect(self.make_slider_range(cursor_pos))
self._range_indicator_is_visible = True
else:
self._range_indicator_is_visible = False | python | def paintEvent(self, event):
"""
Override Qt method.
Painting the scroll flag area
"""
make_flag = self.make_flag_qrect
# Fill the whole painting area
painter = QPainter(self)
painter.fillRect(event.rect(), self.editor.sideareas_color)
# Paint warnings and todos
block = self.editor.document().firstBlock()
for line_number in range(self.editor.document().blockCount()+1):
data = block.userData()
if data:
if data.code_analysis:
# Paint the warnings
color = self.editor.warning_color
for source, code, severity, message in data.code_analysis:
error = severity == DiagnosticSeverity.ERROR
if error:
color = self.editor.error_color
break
self.set_painter(painter, color)
painter.drawRect(make_flag(line_number))
if data.todo:
# Paint the todos
self.set_painter(painter, self.editor.todo_color)
painter.drawRect(make_flag(line_number))
if data.breakpoint:
# Paint the breakpoints
self.set_painter(painter, self.editor.breakpoint_color)
painter.drawRect(make_flag(line_number))
block = block.next()
# Paint the occurrences
if self.editor.occurrences:
self.set_painter(painter, self.editor.occurrence_color)
for line_number in self.editor.occurrences:
painter.drawRect(make_flag(line_number))
# Paint the found results
if self.editor.found_results:
self.set_painter(painter, self.editor.found_results_color)
for line_number in self.editor.found_results:
painter.drawRect(make_flag(line_number))
# Paint the slider range
if not self._unit_testing:
alt = QApplication.queryKeyboardModifiers() & Qt.AltModifier
else:
alt = self._alt_key_is_down
cursor_pos = self.mapFromGlobal(QCursor().pos())
is_over_self = self.rect().contains(cursor_pos)
is_over_editor = self.editor.rect().contains(
self.editor.mapFromGlobal(QCursor().pos()))
# We use QRect.contains instead of QWidget.underMouse method to
# determined if the cursor is over the editor or the flag scrollbar
# because the later gives a wrong result when a mouse button
# is pressed.
if ((is_over_self or (alt and is_over_editor)) and self.slider):
pen_color = QColor(Qt.gray)
pen_color.setAlphaF(.85)
painter.setPen(pen_color)
brush_color = QColor(Qt.gray)
brush_color.setAlphaF(.5)
painter.setBrush(QBrush(brush_color))
painter.drawRect(self.make_slider_range(cursor_pos))
self._range_indicator_is_visible = True
else:
self._range_indicator_is_visible = False | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"make_flag",
"=",
"self",
".",
"make_flag_qrect",
"# Fill the whole painting area",
"painter",
"=",
"QPainter",
"(",
"self",
")",
"painter",
".",
"fillRect",
"(",
"event",
".",
"rect",
"(",
")",
",",
... | Override Qt method.
Painting the scroll flag area | [
"Override",
"Qt",
"method",
".",
"Painting",
"the",
"scroll",
"flag",
"area"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L67-L138 |
31,007 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.get_scrollbar_position_height | def get_scrollbar_position_height(self):
"""Return the pixel span height of the scrollbar area in which
the slider handle may move"""
vsb = self.editor.verticalScrollBar()
style = vsb.style()
opt = QStyleOptionSlider()
vsb.initStyleOption(opt)
# Get the area in which the slider handle may move.
groove_rect = style.subControlRect(
QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self)
return float(groove_rect.height()) | python | def get_scrollbar_position_height(self):
"""Return the pixel span height of the scrollbar area in which
the slider handle may move"""
vsb = self.editor.verticalScrollBar()
style = vsb.style()
opt = QStyleOptionSlider()
vsb.initStyleOption(opt)
# Get the area in which the slider handle may move.
groove_rect = style.subControlRect(
QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self)
return float(groove_rect.height()) | [
"def",
"get_scrollbar_position_height",
"(",
"self",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"style",
"=",
"vsb",
".",
"style",
"(",
")",
"opt",
"=",
"QStyleOptionSlider",
"(",
")",
"vsb",
".",
"initStyleOption",
"(... | Return the pixel span height of the scrollbar area in which
the slider handle may move | [
"Return",
"the",
"pixel",
"span",
"height",
"of",
"the",
"scrollbar",
"area",
"in",
"which",
"the",
"slider",
"handle",
"may",
"move"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L171-L183 |
31,008 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.get_scrollbar_value_height | def get_scrollbar_value_height(self):
"""Return the value span height of the scrollbar"""
vsb = self.editor.verticalScrollBar()
return vsb.maximum()-vsb.minimum()+vsb.pageStep() | python | def get_scrollbar_value_height(self):
"""Return the value span height of the scrollbar"""
vsb = self.editor.verticalScrollBar()
return vsb.maximum()-vsb.minimum()+vsb.pageStep() | [
"def",
"get_scrollbar_value_height",
"(",
"self",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"return",
"vsb",
".",
"maximum",
"(",
")",
"-",
"vsb",
".",
"minimum",
"(",
")",
"+",
"vsb",
".",
"pageStep",
"(",
")"
] | Return the value span height of the scrollbar | [
"Return",
"the",
"value",
"span",
"height",
"of",
"the",
"scrollbar"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L185-L188 |
31,009 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.value_to_position | def value_to_position(self, y):
"""Convert value to position in pixels"""
vsb = self.editor.verticalScrollBar()
return (y-vsb.minimum())*self.get_scale_factor()+self.offset | python | def value_to_position(self, y):
"""Convert value to position in pixels"""
vsb = self.editor.verticalScrollBar()
return (y-vsb.minimum())*self.get_scale_factor()+self.offset | [
"def",
"value_to_position",
"(",
"self",
",",
"y",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"return",
"(",
"y",
"-",
"vsb",
".",
"minimum",
"(",
")",
")",
"*",
"self",
".",
"get_scale_factor",
"(",
")",
"+",
... | Convert value to position in pixels | [
"Convert",
"value",
"to",
"position",
"in",
"pixels"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L196-L199 |
31,010 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.position_to_value | def position_to_value(self, y):
"""Convert position in pixels to value"""
vsb = self.editor.verticalScrollBar()
return vsb.minimum()+max([0, (y-self.offset)/self.get_scale_factor()]) | python | def position_to_value(self, y):
"""Convert position in pixels to value"""
vsb = self.editor.verticalScrollBar()
return vsb.minimum()+max([0, (y-self.offset)/self.get_scale_factor()]) | [
"def",
"position_to_value",
"(",
"self",
",",
"y",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"return",
"vsb",
".",
"minimum",
"(",
")",
"+",
"max",
"(",
"[",
"0",
",",
"(",
"y",
"-",
"self",
".",
"offset",
"... | Convert position in pixels to value | [
"Convert",
"position",
"in",
"pixels",
"to",
"value"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L201-L204 |
31,011 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.make_flag_qrect | def make_flag_qrect(self, value):
"""Make flag QRect"""
if self.slider:
position = self.value_to_position(value+0.5)
# The 0.5 offset is used to align the flags with the center of
# their corresponding text edit block before scaling.
return QRect(self.FLAGS_DX/2, position-self.FLAGS_DY/2,
self.WIDTH-self.FLAGS_DX, self.FLAGS_DY)
else:
# When the vertical scrollbar is not visible, the flags are
# vertically aligned with the center of their corresponding
# text block with no scaling.
block = self.editor.document().findBlockByLineNumber(value)
top = self.editor.blockBoundingGeometry(block).translated(
self.editor.contentOffset()).top()
bottom = top + self.editor.blockBoundingRect(block).height()
middle = (top + bottom)/2
return QRect(self.FLAGS_DX/2, middle-self.FLAGS_DY/2,
self.WIDTH-self.FLAGS_DX, self.FLAGS_DY) | python | def make_flag_qrect(self, value):
"""Make flag QRect"""
if self.slider:
position = self.value_to_position(value+0.5)
# The 0.5 offset is used to align the flags with the center of
# their corresponding text edit block before scaling.
return QRect(self.FLAGS_DX/2, position-self.FLAGS_DY/2,
self.WIDTH-self.FLAGS_DX, self.FLAGS_DY)
else:
# When the vertical scrollbar is not visible, the flags are
# vertically aligned with the center of their corresponding
# text block with no scaling.
block = self.editor.document().findBlockByLineNumber(value)
top = self.editor.blockBoundingGeometry(block).translated(
self.editor.contentOffset()).top()
bottom = top + self.editor.blockBoundingRect(block).height()
middle = (top + bottom)/2
return QRect(self.FLAGS_DX/2, middle-self.FLAGS_DY/2,
self.WIDTH-self.FLAGS_DX, self.FLAGS_DY) | [
"def",
"make_flag_qrect",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"slider",
":",
"position",
"=",
"self",
".",
"value_to_position",
"(",
"value",
"+",
"0.5",
")",
"# The 0.5 offset is used to align the flags with the center of",
"# their corresponding ... | Make flag QRect | [
"Make",
"flag",
"QRect"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L206-L226 |
31,012 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.make_slider_range | def make_slider_range(self, cursor_pos):
"""Make slider range QRect"""
# The slider range indicator position follows the mouse vertical
# position while its height corresponds to the part of the file that
# is currently visible on screen.
vsb = self.editor.verticalScrollBar()
groove_height = self.get_scrollbar_position_height()
slider_height = self.value_to_position(vsb.pageStep())-self.offset
# Calcul the minimum and maximum y-value to constraint the slider
# range indicator position to the height span of the scrollbar area
# where the slider may move.
min_ypos = self.offset
max_ypos = groove_height + self.offset - slider_height
# Determine the bounded y-position of the slider rect.
slider_y = max(min_ypos, min(max_ypos, cursor_pos.y()-slider_height/2))
return QRect(1, slider_y, self.WIDTH-2, slider_height) | python | def make_slider_range(self, cursor_pos):
"""Make slider range QRect"""
# The slider range indicator position follows the mouse vertical
# position while its height corresponds to the part of the file that
# is currently visible on screen.
vsb = self.editor.verticalScrollBar()
groove_height = self.get_scrollbar_position_height()
slider_height = self.value_to_position(vsb.pageStep())-self.offset
# Calcul the minimum and maximum y-value to constraint the slider
# range indicator position to the height span of the scrollbar area
# where the slider may move.
min_ypos = self.offset
max_ypos = groove_height + self.offset - slider_height
# Determine the bounded y-position of the slider rect.
slider_y = max(min_ypos, min(max_ypos, cursor_pos.y()-slider_height/2))
return QRect(1, slider_y, self.WIDTH-2, slider_height) | [
"def",
"make_slider_range",
"(",
"self",
",",
"cursor_pos",
")",
":",
"# The slider range indicator position follows the mouse vertical",
"# position while its height corresponds to the part of the file that",
"# is currently visible on screen.",
"vsb",
"=",
"self",
".",
"editor",
".... | Make slider range QRect | [
"Make",
"slider",
"range",
"QRect"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L228-L247 |
31,013 | spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | ScrollFlagArea.set_painter | def set_painter(self, painter, light_color):
"""Set scroll flag area painter pen and brush colors"""
painter.setPen(QColor(light_color).darker(120))
painter.setBrush(QBrush(QColor(light_color))) | python | def set_painter(self, painter, light_color):
"""Set scroll flag area painter pen and brush colors"""
painter.setPen(QColor(light_color).darker(120))
painter.setBrush(QBrush(QColor(light_color))) | [
"def",
"set_painter",
"(",
"self",
",",
"painter",
",",
"light_color",
")",
":",
"painter",
".",
"setPen",
"(",
"QColor",
"(",
"light_color",
")",
".",
"darker",
"(",
"120",
")",
")",
"painter",
".",
"setBrush",
"(",
"QBrush",
"(",
"QColor",
"(",
"ligh... | Set scroll flag area painter pen and brush colors | [
"Set",
"scroll",
"flag",
"area",
"painter",
"pen",
"and",
"brush",
"colors"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L253-L256 |
31,014 | spyder-ide/spyder | spyder/plugins/profiler/plugin.py | Profiler.on_first_registration | def on_first_registration(self):
"""Action to be performed on first plugin registration"""
self.main.tabify_plugins(self.main.help, self)
self.dockwidget.hide() | python | def on_first_registration(self):
"""Action to be performed on first plugin registration"""
self.main.tabify_plugins(self.main.help, self)
self.dockwidget.hide() | [
"def",
"on_first_registration",
"(",
"self",
")",
":",
"self",
".",
"main",
".",
"tabify_plugins",
"(",
"self",
".",
"main",
".",
"help",
",",
"self",
")",
"self",
".",
"dockwidget",
".",
"hide",
"(",
")"
] | Action to be performed on first plugin registration | [
"Action",
"to",
"be",
"performed",
"on",
"first",
"plugin",
"registration"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/plugin.py#L75-L78 |
31,015 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | drift_color | def drift_color(base_color, factor=110):
"""
Return color that is lighter or darker than the base color.
If base_color.lightness is higher than 128, the returned color is darker
otherwise is is lighter.
:param base_color: The base color to drift from
;:param factor: drift factor (%)
:return A lighter or darker color.
"""
base_color = QColor(base_color)
if base_color.lightness() > 128:
return base_color.darker(factor)
else:
if base_color == QColor('#000000'):
return drift_color(QColor('#101010'), factor + 20)
else:
return base_color.lighter(factor + 10) | python | def drift_color(base_color, factor=110):
"""
Return color that is lighter or darker than the base color.
If base_color.lightness is higher than 128, the returned color is darker
otherwise is is lighter.
:param base_color: The base color to drift from
;:param factor: drift factor (%)
:return A lighter or darker color.
"""
base_color = QColor(base_color)
if base_color.lightness() > 128:
return base_color.darker(factor)
else:
if base_color == QColor('#000000'):
return drift_color(QColor('#101010'), factor + 20)
else:
return base_color.lighter(factor + 10) | [
"def",
"drift_color",
"(",
"base_color",
",",
"factor",
"=",
"110",
")",
":",
"base_color",
"=",
"QColor",
"(",
"base_color",
")",
"if",
"base_color",
".",
"lightness",
"(",
")",
">",
"128",
":",
"return",
"base_color",
".",
"darker",
"(",
"factor",
")",... | Return color that is lighter or darker than the base color.
If base_color.lightness is higher than 128, the returned color is darker
otherwise is is lighter.
:param base_color: The base color to drift from
;:param factor: drift factor (%)
:return A lighter or darker color. | [
"Return",
"color",
"that",
"is",
"lighter",
"or",
"darker",
"than",
"the",
"base",
"color",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L33-L51 |
31,016 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | get_block_symbol_data | def get_block_symbol_data(editor, block):
"""
Gets the list of ParenthesisInfo for specific text block.
:param editor: Code editor instance
:param block: block to parse
"""
def list_symbols(editor, block, character):
"""
Retuns a list of symbols found in the block text
:param editor: code editor instance
:param block: block to parse
:param character: character to look for.
"""
text = block.text()
symbols = []
cursor = QTextCursor(block)
cursor.movePosition(cursor.StartOfBlock)
pos = text.find(character, 0)
cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)
while pos != -1:
if not TextHelper(editor).is_comment_or_string(cursor):
# skips symbols in string literal or comment
info = ParenthesisInfo(pos, character)
symbols.append(info)
pos = text.find(character, pos + 1)
cursor.movePosition(cursor.StartOfBlock)
cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)
return symbols
parentheses = sorted(
list_symbols(editor, block, '(') + list_symbols(editor, block, ')'),
key=lambda x: x.position)
square_brackets = sorted(
list_symbols(editor, block, '[') + list_symbols(editor, block, ']'),
key=lambda x: x.position)
braces = sorted(
list_symbols(editor, block, '{') + list_symbols(editor, block, '}'),
key=lambda x: x.position)
return parentheses, square_brackets, braces | python | def get_block_symbol_data(editor, block):
"""
Gets the list of ParenthesisInfo for specific text block.
:param editor: Code editor instance
:param block: block to parse
"""
def list_symbols(editor, block, character):
"""
Retuns a list of symbols found in the block text
:param editor: code editor instance
:param block: block to parse
:param character: character to look for.
"""
text = block.text()
symbols = []
cursor = QTextCursor(block)
cursor.movePosition(cursor.StartOfBlock)
pos = text.find(character, 0)
cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)
while pos != -1:
if not TextHelper(editor).is_comment_or_string(cursor):
# skips symbols in string literal or comment
info = ParenthesisInfo(pos, character)
symbols.append(info)
pos = text.find(character, pos + 1)
cursor.movePosition(cursor.StartOfBlock)
cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)
return symbols
parentheses = sorted(
list_symbols(editor, block, '(') + list_symbols(editor, block, ')'),
key=lambda x: x.position)
square_brackets = sorted(
list_symbols(editor, block, '[') + list_symbols(editor, block, ']'),
key=lambda x: x.position)
braces = sorted(
list_symbols(editor, block, '{') + list_symbols(editor, block, '}'),
key=lambda x: x.position)
return parentheses, square_brackets, braces | [
"def",
"get_block_symbol_data",
"(",
"editor",
",",
"block",
")",
":",
"def",
"list_symbols",
"(",
"editor",
",",
"block",
",",
"character",
")",
":",
"\"\"\"\n Retuns a list of symbols found in the block text\n\n :param editor: code editor instance\n :param... | Gets the list of ParenthesisInfo for specific text block.
:param editor: Code editor instance
:param block: block to parse | [
"Gets",
"the",
"list",
"of",
"ParenthesisInfo",
"for",
"specific",
"text",
"block",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L1035-L1076 |
31,017 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | keep_tc_pos | def keep_tc_pos(func):
"""
Cache text cursor position and restore it when the wrapped
function exits.
This decorator can only be used on modes or panels.
:param func: wrapped function
"""
@functools.wraps(func)
def wrapper(editor, *args, **kwds):
""" Decorator """
sb = editor.verticalScrollBar()
spos = sb.sliderPosition()
pos = editor.textCursor().position()
retval = func(editor, *args, **kwds)
text_cursor = editor.textCursor()
text_cursor.setPosition(pos)
editor.setTextCursor(text_cursor)
sb.setSliderPosition(spos)
return retval
return wrapper | python | def keep_tc_pos(func):
"""
Cache text cursor position and restore it when the wrapped
function exits.
This decorator can only be used on modes or panels.
:param func: wrapped function
"""
@functools.wraps(func)
def wrapper(editor, *args, **kwds):
""" Decorator """
sb = editor.verticalScrollBar()
spos = sb.sliderPosition()
pos = editor.textCursor().position()
retval = func(editor, *args, **kwds)
text_cursor = editor.textCursor()
text_cursor.setPosition(pos)
editor.setTextCursor(text_cursor)
sb.setSliderPosition(spos)
return retval
return wrapper | [
"def",
"keep_tc_pos",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"editor",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"\"\"\" Decorator \"\"\"",
"sb",
"=",
"editor",
".",
"verticalScrollBar",
... | Cache text cursor position and restore it when the wrapped
function exits.
This decorator can only be used on modes or panels.
:param func: wrapped function | [
"Cache",
"text",
"cursor",
"position",
"and",
"restore",
"it",
"when",
"the",
"wrapped",
"function",
"exits",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L1079-L1100 |
31,018 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | with_wait_cursor | def with_wait_cursor(func):
"""
Show a wait cursor while the wrapped function is running. The cursor is
restored as soon as the function exits.
:param func: wrapped function
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
QApplication.setOverrideCursor(
QCursor(Qt.WaitCursor))
try:
ret_val = func(*args, **kwargs)
finally:
QApplication.restoreOverrideCursor()
return ret_val
return wrapper | python | def with_wait_cursor(func):
"""
Show a wait cursor while the wrapped function is running. The cursor is
restored as soon as the function exits.
:param func: wrapped function
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
QApplication.setOverrideCursor(
QCursor(Qt.WaitCursor))
try:
ret_val = func(*args, **kwargs)
finally:
QApplication.restoreOverrideCursor()
return ret_val
return wrapper | [
"def",
"with_wait_cursor",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"QApplication",
".",
"setOverrideCursor",
"(",
"QCursor",
"(",
"Qt",
".",
"WaitCu... | Show a wait cursor while the wrapped function is running. The cursor is
restored as soon as the function exits.
:param func: wrapped function | [
"Show",
"a",
"wait",
"cursor",
"while",
"the",
"wrapped",
"function",
"is",
"running",
".",
"The",
"cursor",
"is",
"restored",
"as",
"soon",
"as",
"the",
"function",
"exits",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L1103-L1119 |
31,019 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | BlockUserData.is_empty | def is_empty(self):
"""Return whether the block of user data is empty."""
return (not self.breakpoint and not self.code_analysis
and not self.todo and not self.bookmarks) | python | def is_empty(self):
"""Return whether the block of user data is empty."""
return (not self.breakpoint and not self.code_analysis
and not self.todo and not self.bookmarks) | [
"def",
"is_empty",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"breakpoint",
"and",
"not",
"self",
".",
"code_analysis",
"and",
"not",
"self",
".",
"todo",
"and",
"not",
"self",
".",
"bookmarks",
")"
] | Return whether the block of user data is empty. | [
"Return",
"whether",
"the",
"block",
"of",
"user",
"data",
"is",
"empty",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L67-L70 |
31,020 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | DelayJobRunner.request_job | def request_job(self, job, *args, **kwargs):
"""
Request a job execution.
The job will be executed after the delay specified in the
DelayJobRunner contructor elapsed if no other job is requested until
then.
:param job: job.
:type job: callable
:param args: job's position arguments
:param kwargs: job's keyworded arguments
"""
self.cancel_requests()
self._job = job
self._args = args
self._kwargs = kwargs
self._timer.start(self.delay) | python | def request_job(self, job, *args, **kwargs):
"""
Request a job execution.
The job will be executed after the delay specified in the
DelayJobRunner contructor elapsed if no other job is requested until
then.
:param job: job.
:type job: callable
:param args: job's position arguments
:param kwargs: job's keyworded arguments
"""
self.cancel_requests()
self._job = job
self._args = args
self._kwargs = kwargs
self._timer.start(self.delay) | [
"def",
"request_job",
"(",
"self",
",",
"job",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"cancel_requests",
"(",
")",
"self",
".",
"_job",
"=",
"job",
"self",
".",
"_args",
"=",
"args",
"self",
".",
"_kwargs",
"=",
"kwargs",... | Request a job execution.
The job will be executed after the delay specified in the
DelayJobRunner contructor elapsed if no other job is requested until
then.
:param job: job.
:type job: callable
:param args: job's position arguments
:param kwargs: job's keyworded arguments | [
"Request",
"a",
"job",
"execution",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L100-L117 |
31,021 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | DelayJobRunner.cancel_requests | def cancel_requests(self):
"""Cancels pending requests."""
self._timer.stop()
self._job = None
self._args = None
self._kwargs = None | python | def cancel_requests(self):
"""Cancels pending requests."""
self._timer.stop()
self._job = None
self._args = None
self._kwargs = None | [
"def",
"cancel_requests",
"(",
"self",
")",
":",
"self",
".",
"_timer",
".",
"stop",
"(",
")",
"self",
".",
"_job",
"=",
"None",
"self",
".",
"_args",
"=",
"None",
"self",
".",
"_kwargs",
"=",
"None"
] | Cancels pending requests. | [
"Cancels",
"pending",
"requests",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L119-L124 |
31,022 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | DelayJobRunner._exec_requested_job | def _exec_requested_job(self):
"""Execute the requested job after the timer has timeout."""
self._timer.stop()
self._job(*self._args, **self._kwargs) | python | def _exec_requested_job(self):
"""Execute the requested job after the timer has timeout."""
self._timer.stop()
self._job(*self._args, **self._kwargs) | [
"def",
"_exec_requested_job",
"(",
"self",
")",
":",
"self",
".",
"_timer",
".",
"stop",
"(",
")",
"self",
".",
"_job",
"(",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwargs",
")"
] | Execute the requested job after the timer has timeout. | [
"Execute",
"the",
"requested",
"job",
"after",
"the",
"timer",
"has",
"timeout",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L126-L129 |
31,023 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.goto_line | def goto_line(self, line, column=0, end_column=0, move=True, word=''):
"""
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.
:param word: Highlight the word, when moving to the line.
:return: The new text cursor
:rtype: QtGui.QTextCursor
"""
line = min(line, self.line_count())
text_cursor = self._move_cursor_to(line)
if column:
text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor,
column)
if end_column:
text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor,
end_column)
if move:
block = text_cursor.block()
self.unfold_if_colapsed(block)
self._editor.setTextCursor(text_cursor)
if self._editor.isVisible():
self._editor.centerCursor()
else:
self._editor.focus_in.connect(
self._editor.center_cursor_on_next_focus)
if word and to_text_string(word) in to_text_string(block.text()):
self._editor.find(word, QTextDocument.FindCaseSensitively)
return text_cursor | python | def goto_line(self, line, column=0, end_column=0, move=True, word=''):
"""
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.
:param word: Highlight the word, when moving to the line.
:return: The new text cursor
:rtype: QtGui.QTextCursor
"""
line = min(line, self.line_count())
text_cursor = self._move_cursor_to(line)
if column:
text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor,
column)
if end_column:
text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor,
end_column)
if move:
block = text_cursor.block()
self.unfold_if_colapsed(block)
self._editor.setTextCursor(text_cursor)
if self._editor.isVisible():
self._editor.centerCursor()
else:
self._editor.focus_in.connect(
self._editor.center_cursor_on_next_focus)
if word and to_text_string(word) in to_text_string(block.text()):
self._editor.find(word, QTextDocument.FindCaseSensitively)
return text_cursor | [
"def",
"goto_line",
"(",
"self",
",",
"line",
",",
"column",
"=",
"0",
",",
"end_column",
"=",
"0",
",",
"move",
"=",
"True",
",",
"word",
"=",
"''",
")",
":",
"line",
"=",
"min",
"(",
"line",
",",
"self",
".",
"line_count",
"(",
")",
")",
"tex... | 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.
:param word: Highlight the word, when moving to the line.
:return: The new text cursor
:rtype: QtGui.QTextCursor | [
"Moves",
"the",
"text",
"cursor",
"to",
"the",
"specified",
"position",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L154-L186 |
31,024 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.unfold_if_colapsed | def unfold_if_colapsed(self, block):
"""Unfold parent fold trigger if the block is collapsed.
:param block: Block to unfold.
"""
try:
folding_panel = self._editor.panels.get('FoldingPanel')
except KeyError:
pass
else:
from spyder.plugins.editor.utils.folding import FoldScope
if not block.isVisible():
block = FoldScope.find_parent_scope(block)
if TextBlockHelper.is_collapsed(block):
folding_panel.toggle_fold_trigger(block) | python | def unfold_if_colapsed(self, block):
"""Unfold parent fold trigger if the block is collapsed.
:param block: Block to unfold.
"""
try:
folding_panel = self._editor.panels.get('FoldingPanel')
except KeyError:
pass
else:
from spyder.plugins.editor.utils.folding import FoldScope
if not block.isVisible():
block = FoldScope.find_parent_scope(block)
if TextBlockHelper.is_collapsed(block):
folding_panel.toggle_fold_trigger(block) | [
"def",
"unfold_if_colapsed",
"(",
"self",
",",
"block",
")",
":",
"try",
":",
"folding_panel",
"=",
"self",
".",
"_editor",
".",
"panels",
".",
"get",
"(",
"'FoldingPanel'",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"from",
"spyder",
".",
"plu... | Unfold parent fold trigger if the block is collapsed.
:param block: Block to unfold. | [
"Unfold",
"parent",
"fold",
"trigger",
"if",
"the",
"block",
"is",
"collapsed",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L188-L202 |
31,025 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.line_text | def line_text(self, line_nbr):
"""
Gets the text of the specified line.
:param line_nbr: The line number of the text to get
:return: Entire line's text
:rtype: str
"""
doc = self._editor.document()
block = doc.findBlockByNumber(line_nbr)
return block.text() | python | def line_text(self, line_nbr):
"""
Gets the text of the specified line.
:param line_nbr: The line number of the text to get
:return: Entire line's text
:rtype: str
"""
doc = self._editor.document()
block = doc.findBlockByNumber(line_nbr)
return block.text() | [
"def",
"line_text",
"(",
"self",
",",
"line_nbr",
")",
":",
"doc",
"=",
"self",
".",
"_editor",
".",
"document",
"(",
")",
"block",
"=",
"doc",
".",
"findBlockByNumber",
"(",
"line_nbr",
")",
"return",
"block",
".",
"text",
"(",
")"
] | Gets the text of the specified line.
:param line_nbr: The line number of the text to get
:return: Entire line's text
:rtype: str | [
"Gets",
"the",
"text",
"of",
"the",
"specified",
"line",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L312-L323 |
31,026 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.set_line_text | def set_line_text(self, line_nbr, new_text):
"""
Replace an entire line with ``new_text``.
:param line_nbr: line number of the line to change.
:param new_text: The replacement text.
"""
editor = self._editor
text_cursor = self._move_cursor_to(line_nbr)
text_cursor.select(text_cursor.LineUnderCursor)
text_cursor.insertText(new_text)
editor.setTextCursor(text_cursor) | python | def set_line_text(self, line_nbr, new_text):
"""
Replace an entire line with ``new_text``.
:param line_nbr: line number of the line to change.
:param new_text: The replacement text.
"""
editor = self._editor
text_cursor = self._move_cursor_to(line_nbr)
text_cursor.select(text_cursor.LineUnderCursor)
text_cursor.insertText(new_text)
editor.setTextCursor(text_cursor) | [
"def",
"set_line_text",
"(",
"self",
",",
"line_nbr",
",",
"new_text",
")",
":",
"editor",
"=",
"self",
".",
"_editor",
"text_cursor",
"=",
"self",
".",
"_move_cursor_to",
"(",
"line_nbr",
")",
"text_cursor",
".",
"select",
"(",
"text_cursor",
".",
"LineUnde... | Replace an entire line with ``new_text``.
:param line_nbr: line number of the line to change.
:param new_text: The replacement text. | [
"Replace",
"an",
"entire",
"line",
"with",
"new_text",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L342-L354 |
31,027 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.remove_last_line | def remove_last_line(self):
"""Removes the last line of the document."""
editor = self._editor
text_cursor = editor.textCursor()
text_cursor.movePosition(text_cursor.End, text_cursor.MoveAnchor)
text_cursor.select(text_cursor.LineUnderCursor)
text_cursor.removeSelectedText()
text_cursor.deletePreviousChar()
editor.setTextCursor(text_cursor) | python | def remove_last_line(self):
"""Removes the last line of the document."""
editor = self._editor
text_cursor = editor.textCursor()
text_cursor.movePosition(text_cursor.End, text_cursor.MoveAnchor)
text_cursor.select(text_cursor.LineUnderCursor)
text_cursor.removeSelectedText()
text_cursor.deletePreviousChar()
editor.setTextCursor(text_cursor) | [
"def",
"remove_last_line",
"(",
"self",
")",
":",
"editor",
"=",
"self",
".",
"_editor",
"text_cursor",
"=",
"editor",
".",
"textCursor",
"(",
")",
"text_cursor",
".",
"movePosition",
"(",
"text_cursor",
".",
"End",
",",
"text_cursor",
".",
"MoveAnchor",
")"... | Removes the last line of the document. | [
"Removes",
"the",
"last",
"line",
"of",
"the",
"document",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L356-L364 |
31,028 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.clean_document | def clean_document(self):
"""
Removes trailing whitespaces and ensure one single blank line at the
end of the QTextDocument.
FIXME: It was deprecated in pyqode, maybe It should be deleted
"""
editor = self._editor
value = editor.verticalScrollBar().value()
pos = self.cursor_position()
editor.textCursor().beginEditBlock()
# cleanup whitespaces
editor._cleaning = True
eaten = 0
removed = set()
for line in editor._modified_lines:
# parse line before and line after modified line (for cases where
# key_delete or key_return has been pressed)
for j in range(-1, 2):
# skip current line
if line + j != pos[0]:
if line + j >= 0:
txt = self.line_text(line + j)
stxt = txt.rstrip()
if txt != stxt:
self.set_line_text(line + j, stxt)
removed.add(line + j)
editor._modified_lines -= removed
# ensure there is only one blank line left at the end of the file
i = self.line_count()
while i:
line = self.line_text(i - 1)
if line.strip():
break
self.remove_last_line()
i -= 1
if self.line_text(self.line_count() - 1):
editor.appendPlainText('')
# restore cursor and scrollbars
text_cursor = editor.textCursor()
doc = editor.document()
assert isinstance(doc, QTextDocument)
text_cursor = self._move_cursor_to(pos[0])
text_cursor.movePosition(text_cursor.StartOfLine,
text_cursor.MoveAnchor)
cpos = text_cursor.position()
text_cursor.select(text_cursor.LineUnderCursor)
if text_cursor.selectedText():
text_cursor.setPosition(cpos)
offset = pos[1] - eaten
text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor,
offset)
else:
text_cursor.setPosition(cpos)
editor.setTextCursor(text_cursor)
editor.verticalScrollBar().setValue(value)
text_cursor.endEditBlock()
editor._cleaning = False | python | def clean_document(self):
"""
Removes trailing whitespaces and ensure one single blank line at the
end of the QTextDocument.
FIXME: It was deprecated in pyqode, maybe It should be deleted
"""
editor = self._editor
value = editor.verticalScrollBar().value()
pos = self.cursor_position()
editor.textCursor().beginEditBlock()
# cleanup whitespaces
editor._cleaning = True
eaten = 0
removed = set()
for line in editor._modified_lines:
# parse line before and line after modified line (for cases where
# key_delete or key_return has been pressed)
for j in range(-1, 2):
# skip current line
if line + j != pos[0]:
if line + j >= 0:
txt = self.line_text(line + j)
stxt = txt.rstrip()
if txt != stxt:
self.set_line_text(line + j, stxt)
removed.add(line + j)
editor._modified_lines -= removed
# ensure there is only one blank line left at the end of the file
i = self.line_count()
while i:
line = self.line_text(i - 1)
if line.strip():
break
self.remove_last_line()
i -= 1
if self.line_text(self.line_count() - 1):
editor.appendPlainText('')
# restore cursor and scrollbars
text_cursor = editor.textCursor()
doc = editor.document()
assert isinstance(doc, QTextDocument)
text_cursor = self._move_cursor_to(pos[0])
text_cursor.movePosition(text_cursor.StartOfLine,
text_cursor.MoveAnchor)
cpos = text_cursor.position()
text_cursor.select(text_cursor.LineUnderCursor)
if text_cursor.selectedText():
text_cursor.setPosition(cpos)
offset = pos[1] - eaten
text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor,
offset)
else:
text_cursor.setPosition(cpos)
editor.setTextCursor(text_cursor)
editor.verticalScrollBar().setValue(value)
text_cursor.endEditBlock()
editor._cleaning = False | [
"def",
"clean_document",
"(",
"self",
")",
":",
"editor",
"=",
"self",
".",
"_editor",
"value",
"=",
"editor",
".",
"verticalScrollBar",
"(",
")",
".",
"value",
"(",
")",
"pos",
"=",
"self",
".",
"cursor_position",
"(",
")",
"editor",
".",
"textCursor",
... | Removes trailing whitespaces and ensure one single blank line at the
end of the QTextDocument.
FIXME: It was deprecated in pyqode, maybe It should be deleted | [
"Removes",
"trailing",
"whitespaces",
"and",
"ensure",
"one",
"single",
"blank",
"line",
"at",
"the",
"end",
"of",
"the",
"QTextDocument",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L366-L427 |
31,029 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.select_whole_line | def select_whole_line(self, line=None, apply_selection=True):
"""
Selects an entire line.
:param line: Line to select. If None, the current line will be selected
:param apply_selection: True to apply selection on the text editor
widget, False to just return the text cursor without setting it
on the editor.
:return: QTextCursor
"""
if line is None:
line = self.current_line_nbr()
return self.select_lines(line, line, apply_selection=apply_selection) | python | def select_whole_line(self, line=None, apply_selection=True):
"""
Selects an entire line.
:param line: Line to select. If None, the current line will be selected
:param apply_selection: True to apply selection on the text editor
widget, False to just return the text cursor without setting it
on the editor.
:return: QTextCursor
"""
if line is None:
line = self.current_line_nbr()
return self.select_lines(line, line, apply_selection=apply_selection) | [
"def",
"select_whole_line",
"(",
"self",
",",
"line",
"=",
"None",
",",
"apply_selection",
"=",
"True",
")",
":",
"if",
"line",
"is",
"None",
":",
"line",
"=",
"self",
".",
"current_line_nbr",
"(",
")",
"return",
"self",
".",
"select_lines",
"(",
"line",... | Selects an entire line.
:param line: Line to select. If None, the current line will be selected
:param apply_selection: True to apply selection on the text editor
widget, False to just return the text cursor without setting it
on the editor.
:return: QTextCursor | [
"Selects",
"an",
"entire",
"line",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L429-L441 |
31,030 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.line_nbr_from_position | def line_nbr_from_position(self, y_pos):
"""
Returns the line number from the y_pos.
:param y_pos: Y pos in the editor
:return: Line number (0 based), -1 if out of range
"""
editor = self._editor
height = editor.fontMetrics().height()
for top, line, block in editor.visible_blocks:
if top <= y_pos <= top + height:
return line
return -1 | python | def line_nbr_from_position(self, y_pos):
"""
Returns the line number from the y_pos.
:param y_pos: Y pos in the editor
:return: Line number (0 based), -1 if out of range
"""
editor = self._editor
height = editor.fontMetrics().height()
for top, line, block in editor.visible_blocks:
if top <= y_pos <= top + height:
return line
return -1 | [
"def",
"line_nbr_from_position",
"(",
"self",
",",
"y_pos",
")",
":",
"editor",
"=",
"self",
".",
"_editor",
"height",
"=",
"editor",
".",
"fontMetrics",
"(",
")",
".",
"height",
"(",
")",
"for",
"top",
",",
"line",
",",
"block",
"in",
"editor",
".",
... | Returns the line number from the y_pos.
:param y_pos: Y pos in the editor
:return: Line number (0 based), -1 if out of range | [
"Returns",
"the",
"line",
"number",
"from",
"the",
"y_pos",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L530-L542 |
31,031 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.get_right_character | def get_right_character(self, cursor=None):
"""
Gets the character that is on the right of the text cursor.
:param cursor: QTextCursor that defines the position where the search
will start.
"""
next_char = self.get_right_word(cursor=cursor)
if len(next_char):
next_char = next_char[0]
else:
next_char = None
return next_char | python | def get_right_character(self, cursor=None):
"""
Gets the character that is on the right of the text cursor.
:param cursor: QTextCursor that defines the position where the search
will start.
"""
next_char = self.get_right_word(cursor=cursor)
if len(next_char):
next_char = next_char[0]
else:
next_char = None
return next_char | [
"def",
"get_right_character",
"(",
"self",
",",
"cursor",
"=",
"None",
")",
":",
"next_char",
"=",
"self",
".",
"get_right_word",
"(",
"cursor",
"=",
"cursor",
")",
"if",
"len",
"(",
"next_char",
")",
":",
"next_char",
"=",
"next_char",
"[",
"0",
"]",
... | Gets the character that is on the right of the text cursor.
:param cursor: QTextCursor that defines the position where the search
will start. | [
"Gets",
"the",
"character",
"that",
"is",
"on",
"the",
"right",
"of",
"the",
"text",
"cursor",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L585-L597 |
31,032 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.insert_text | def insert_text(self, text, keep_position=True):
"""
Inserts text at the cursor position.
:param text: text to insert
:param keep_position: Flag that specifies if the cursor position must
be kept. Pass False for a regular insert (the cursor will be at
the end of the inserted text).
"""
text_cursor = self._editor.textCursor()
if keep_position:
s = text_cursor.selectionStart()
e = text_cursor.selectionEnd()
text_cursor.insertText(text)
if keep_position:
text_cursor.setPosition(s)
text_cursor.setPosition(e, text_cursor.KeepAnchor)
self._editor.setTextCursor(text_cursor) | python | def insert_text(self, text, keep_position=True):
"""
Inserts text at the cursor position.
:param text: text to insert
:param keep_position: Flag that specifies if the cursor position must
be kept. Pass False for a regular insert (the cursor will be at
the end of the inserted text).
"""
text_cursor = self._editor.textCursor()
if keep_position:
s = text_cursor.selectionStart()
e = text_cursor.selectionEnd()
text_cursor.insertText(text)
if keep_position:
text_cursor.setPosition(s)
text_cursor.setPosition(e, text_cursor.KeepAnchor)
self._editor.setTextCursor(text_cursor) | [
"def",
"insert_text",
"(",
"self",
",",
"text",
",",
"keep_position",
"=",
"True",
")",
":",
"text_cursor",
"=",
"self",
".",
"_editor",
".",
"textCursor",
"(",
")",
"if",
"keep_position",
":",
"s",
"=",
"text_cursor",
".",
"selectionStart",
"(",
")",
"e... | Inserts text at the cursor position.
:param text: text to insert
:param keep_position: Flag that specifies if the cursor position must
be kept. Pass False for a regular insert (the cursor will be at
the end of the inserted text). | [
"Inserts",
"text",
"at",
"the",
"cursor",
"position",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L599-L616 |
31,033 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.clear_selection | def clear_selection(self):
"""Clears text cursor selection."""
text_cursor = self._editor.textCursor()
text_cursor.clearSelection()
self._editor.setTextCursor(text_cursor) | python | def clear_selection(self):
"""Clears text cursor selection."""
text_cursor = self._editor.textCursor()
text_cursor.clearSelection()
self._editor.setTextCursor(text_cursor) | [
"def",
"clear_selection",
"(",
"self",
")",
":",
"text_cursor",
"=",
"self",
".",
"_editor",
".",
"textCursor",
"(",
")",
"text_cursor",
".",
"clearSelection",
"(",
")",
"self",
".",
"_editor",
".",
"setTextCursor",
"(",
"text_cursor",
")"
] | Clears text cursor selection. | [
"Clears",
"text",
"cursor",
"selection",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L618-L622 |
31,034 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.move_right | def move_right(self, keep_anchor=False, nb_chars=1):
"""
Moves the cursor on the right.
:param keep_anchor: True to keep anchor (to select text) or False to
move the anchor (no selection)
:param nb_chars: Number of characters to move.
"""
text_cursor = self._editor.textCursor()
text_cursor.movePosition(
text_cursor.Right, text_cursor.KeepAnchor if keep_anchor else
text_cursor.MoveAnchor, nb_chars)
self._editor.setTextCursor(text_cursor) | python | def move_right(self, keep_anchor=False, nb_chars=1):
"""
Moves the cursor on the right.
:param keep_anchor: True to keep anchor (to select text) or False to
move the anchor (no selection)
:param nb_chars: Number of characters to move.
"""
text_cursor = self._editor.textCursor()
text_cursor.movePosition(
text_cursor.Right, text_cursor.KeepAnchor if keep_anchor else
text_cursor.MoveAnchor, nb_chars)
self._editor.setTextCursor(text_cursor) | [
"def",
"move_right",
"(",
"self",
",",
"keep_anchor",
"=",
"False",
",",
"nb_chars",
"=",
"1",
")",
":",
"text_cursor",
"=",
"self",
".",
"_editor",
".",
"textCursor",
"(",
")",
"text_cursor",
".",
"movePosition",
"(",
"text_cursor",
".",
"Right",
",",
"... | Moves the cursor on the right.
:param keep_anchor: True to keep anchor (to select text) or False to
move the anchor (no selection)
:param nb_chars: Number of characters to move. | [
"Moves",
"the",
"cursor",
"on",
"the",
"right",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L624-L636 |
31,035 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextHelper.select_extended_word | def select_extended_word(self, continuation_chars=('.',)):
"""
Performs extended word selection. Extended selection consists in
selecting the word under cursor and any other words that are linked
by a ``continuation_chars``.
:param continuation_chars: the list of characters that may extend a
word.
"""
cursor = self._editor.textCursor()
original_pos = cursor.position()
start_pos = None
end_pos = None
# go left
stop = False
seps = self._editor.word_separators + [' ']
while not stop:
cursor.clearSelection()
cursor.movePosition(cursor.Left, cursor.KeepAnchor)
char = cursor.selectedText()
if cursor.atBlockStart():
stop = True
start_pos = cursor.position()
elif char in seps and char not in continuation_chars:
stop = True
start_pos = cursor.position() + 1
# go right
cursor.setPosition(original_pos)
stop = False
while not stop:
cursor.clearSelection()
cursor.movePosition(cursor.Right, cursor.KeepAnchor)
char = cursor.selectedText()
if cursor.atBlockEnd():
stop = True
end_pos = cursor.position()
if char in seps:
end_pos -= 1
elif char in seps and char not in continuation_chars:
stop = True
end_pos = cursor.position() - 1
if start_pos and end_pos:
cursor.setPosition(start_pos)
cursor.movePosition(cursor.Right, cursor.KeepAnchor,
end_pos - start_pos)
self._editor.setTextCursor(cursor) | python | def select_extended_word(self, continuation_chars=('.',)):
"""
Performs extended word selection. Extended selection consists in
selecting the word under cursor and any other words that are linked
by a ``continuation_chars``.
:param continuation_chars: the list of characters that may extend a
word.
"""
cursor = self._editor.textCursor()
original_pos = cursor.position()
start_pos = None
end_pos = None
# go left
stop = False
seps = self._editor.word_separators + [' ']
while not stop:
cursor.clearSelection()
cursor.movePosition(cursor.Left, cursor.KeepAnchor)
char = cursor.selectedText()
if cursor.atBlockStart():
stop = True
start_pos = cursor.position()
elif char in seps and char not in continuation_chars:
stop = True
start_pos = cursor.position() + 1
# go right
cursor.setPosition(original_pos)
stop = False
while not stop:
cursor.clearSelection()
cursor.movePosition(cursor.Right, cursor.KeepAnchor)
char = cursor.selectedText()
if cursor.atBlockEnd():
stop = True
end_pos = cursor.position()
if char in seps:
end_pos -= 1
elif char in seps and char not in continuation_chars:
stop = True
end_pos = cursor.position() - 1
if start_pos and end_pos:
cursor.setPosition(start_pos)
cursor.movePosition(cursor.Right, cursor.KeepAnchor,
end_pos - start_pos)
self._editor.setTextCursor(cursor) | [
"def",
"select_extended_word",
"(",
"self",
",",
"continuation_chars",
"=",
"(",
"'.'",
",",
")",
")",
":",
"cursor",
"=",
"self",
".",
"_editor",
".",
"textCursor",
"(",
")",
"original_pos",
"=",
"cursor",
".",
"position",
"(",
")",
"start_pos",
"=",
"N... | Performs extended word selection. Extended selection consists in
selecting the word under cursor and any other words that are linked
by a ``continuation_chars``.
:param continuation_chars: the list of characters that may extend a
word. | [
"Performs",
"extended",
"word",
"selection",
".",
"Extended",
"selection",
"consists",
"in",
"selecting",
"the",
"word",
"under",
"cursor",
"and",
"any",
"other",
"words",
"that",
"are",
"linked",
"by",
"a",
"continuation_chars",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L720-L765 |
31,036 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextBlockHelper.set_state | def set_state(block, state):
"""
Sets the user state, generally used for syntax highlighting.
:param block: block to modify
:param state: new state value.
:return:
"""
if block is None:
return
user_state = block.userState()
if user_state == -1:
user_state = 0
higher_part = user_state & 0x7FFF0000
state &= 0x0000FFFF
state |= higher_part
block.setUserState(state) | python | def set_state(block, state):
"""
Sets the user state, generally used for syntax highlighting.
:param block: block to modify
:param state: new state value.
:return:
"""
if block is None:
return
user_state = block.userState()
if user_state == -1:
user_state = 0
higher_part = user_state & 0x7FFF0000
state &= 0x0000FFFF
state |= higher_part
block.setUserState(state) | [
"def",
"set_state",
"(",
"block",
",",
"state",
")",
":",
"if",
"block",
"is",
"None",
":",
"return",
"user_state",
"=",
"block",
".",
"userState",
"(",
")",
"if",
"user_state",
"==",
"-",
"1",
":",
"user_state",
"=",
"0",
"higher_part",
"=",
"user_sta... | Sets the user state, generally used for syntax highlighting.
:param block: block to modify
:param state: new state value.
:return: | [
"Sets",
"the",
"user",
"state",
"generally",
"used",
"for",
"syntax",
"highlighting",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L905-L921 |
31,037 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextBlockHelper.set_fold_lvl | def set_fold_lvl(block, val):
"""
Sets the block fold level.
:param block: block to modify
:param val: The new fold level [0-7]
"""
if block is None:
return
state = block.userState()
if state == -1:
state = 0
if val >= 0x3FF:
val = 0x3FF
state &= 0x7C00FFFF
state |= val << 16
block.setUserState(state) | python | def set_fold_lvl(block, val):
"""
Sets the block fold level.
:param block: block to modify
:param val: The new fold level [0-7]
"""
if block is None:
return
state = block.userState()
if state == -1:
state = 0
if val >= 0x3FF:
val = 0x3FF
state &= 0x7C00FFFF
state |= val << 16
block.setUserState(state) | [
"def",
"set_fold_lvl",
"(",
"block",
",",
"val",
")",
":",
"if",
"block",
"is",
"None",
":",
"return",
"state",
"=",
"block",
".",
"userState",
"(",
")",
"if",
"state",
"==",
"-",
"1",
":",
"state",
"=",
"0",
"if",
"val",
">=",
"0x3FF",
":",
"val... | Sets the block fold level.
:param block: block to modify
:param val: The new fold level [0-7] | [
"Sets",
"the",
"block",
"fold",
"level",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L939-L955 |
31,038 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextBlockHelper.is_fold_trigger | def is_fold_trigger(block):
"""
Checks if the block is a fold trigger.
:param block: block to check
:return: True if the block is a fold trigger (represented as a node in
the fold panel)
"""
if block is None:
return False
state = block.userState()
if state == -1:
state = 0
return bool(state & 0x04000000) | python | def is_fold_trigger(block):
"""
Checks if the block is a fold trigger.
:param block: block to check
:return: True if the block is a fold trigger (represented as a node in
the fold panel)
"""
if block is None:
return False
state = block.userState()
if state == -1:
state = 0
return bool(state & 0x04000000) | [
"def",
"is_fold_trigger",
"(",
"block",
")",
":",
"if",
"block",
"is",
"None",
":",
"return",
"False",
"state",
"=",
"block",
".",
"userState",
"(",
")",
"if",
"state",
"==",
"-",
"1",
":",
"state",
"=",
"0",
"return",
"bool",
"(",
"state",
"&",
"0... | Checks if the block is a fold trigger.
:param block: block to check
:return: True if the block is a fold trigger (represented as a node in
the fold panel) | [
"Checks",
"if",
"the",
"block",
"is",
"a",
"fold",
"trigger",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L958-L971 |
31,039 | spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | TextBlockHelper.is_collapsed | def is_collapsed(block):
"""
Checks if the block is expanded or collased.
:param block: QTextBlock
:return: False for an open trigger, True for for closed trigger
"""
if block is None:
return False
state = block.userState()
if state == -1:
state = 0
return bool(state & 0x08000000) | python | def is_collapsed(block):
"""
Checks if the block is expanded or collased.
:param block: QTextBlock
:return: False for an open trigger, True for for closed trigger
"""
if block is None:
return False
state = block.userState()
if state == -1:
state = 0
return bool(state & 0x08000000) | [
"def",
"is_collapsed",
"(",
"block",
")",
":",
"if",
"block",
"is",
"None",
":",
"return",
"False",
"state",
"=",
"block",
".",
"userState",
"(",
")",
"if",
"state",
"==",
"-",
"1",
":",
"state",
"=",
"0",
"return",
"bool",
"(",
"state",
"&",
"0x08... | Checks if the block is expanded or collased.
:param block: QTextBlock
:return: False for an open trigger, True for for closed trigger | [
"Checks",
"if",
"the",
"block",
"is",
"expanded",
"or",
"collased",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L992-L1004 |
31,040 | spyder-ide/spyder | spyder/widgets/status.py | StatusBarWidget.set_value | def set_value(self, value):
"""Set formatted text value."""
self.value = value
if self.isVisible():
self.label_value.setText(value) | python | def set_value(self, value):
"""Set formatted text value."""
self.value = value
if self.isVisible():
self.label_value.setText(value) | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"value",
"=",
"value",
"if",
"self",
".",
"isVisible",
"(",
")",
":",
"self",
".",
"label_value",
".",
"setText",
"(",
"value",
")"
] | Set formatted text value. | [
"Set",
"formatted",
"text",
"value",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/status.py#L74-L78 |
31,041 | spyder-ide/spyder | spyder/widgets/status.py | BaseTimerStatus.setVisible | def setVisible(self, value):
"""Override Qt method to stops timers if widget is not visible."""
if self.timer is not None:
if value:
self.timer.start(self._interval)
else:
self.timer.stop()
super(BaseTimerStatus, self).setVisible(value) | python | def setVisible(self, value):
"""Override Qt method to stops timers if widget is not visible."""
if self.timer is not None:
if value:
self.timer.start(self._interval)
else:
self.timer.stop()
super(BaseTimerStatus, self).setVisible(value) | [
"def",
"setVisible",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"timer",
"is",
"not",
"None",
":",
"if",
"value",
":",
"self",
".",
"timer",
".",
"start",
"(",
"self",
".",
"_interval",
")",
"else",
":",
"self",
".",
"timer",
".",
"s... | Override Qt method to stops timers if widget is not visible. | [
"Override",
"Qt",
"method",
"to",
"stops",
"timers",
"if",
"widget",
"is",
"not",
"visible",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/status.py#L102-L109 |
31,042 | spyder-ide/spyder | spyder/widgets/status.py | MemoryStatus.get_value | def get_value(self):
"""Return memory usage."""
from spyder.utils.system import memory_usage
text = '%d%%' % memory_usage()
return 'Mem ' + text.rjust(3) | python | def get_value(self):
"""Return memory usage."""
from spyder.utils.system import memory_usage
text = '%d%%' % memory_usage()
return 'Mem ' + text.rjust(3) | [
"def",
"get_value",
"(",
"self",
")",
":",
"from",
"spyder",
".",
"utils",
".",
"system",
"import",
"memory_usage",
"text",
"=",
"'%d%%'",
"%",
"memory_usage",
"(",
")",
"return",
"'Mem '",
"+",
"text",
".",
"rjust",
"(",
"3",
")"
] | Return memory usage. | [
"Return",
"memory",
"usage",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/status.py#L150-L154 |
31,043 | spyder-ide/spyder | spyder/plugins/help/utils/sphinxify.py | warning | def warning(message, css_path=CSS_PATH):
"""Print a warning message on the rich text view"""
env = Environment()
env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates'))
warning = env.get_template("warning.html")
return warning.render(css_path=css_path, text=message) | python | def warning(message, css_path=CSS_PATH):
"""Print a warning message on the rich text view"""
env = Environment()
env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates'))
warning = env.get_template("warning.html")
return warning.render(css_path=css_path, text=message) | [
"def",
"warning",
"(",
"message",
",",
"css_path",
"=",
"CSS_PATH",
")",
":",
"env",
"=",
"Environment",
"(",
")",
"env",
".",
"loader",
"=",
"FileSystemLoader",
"(",
"osp",
".",
"join",
"(",
"CONFDIR_PATH",
",",
"'templates'",
")",
")",
"warning",
"=",
... | Print a warning message on the rich text view | [
"Print",
"a",
"warning",
"message",
"on",
"the",
"rich",
"text",
"view"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L77-L82 |
31,044 | spyder-ide/spyder | spyder/plugins/help/utils/sphinxify.py | usage | def usage(title, message, tutorial_message, tutorial, css_path=CSS_PATH):
"""Print a usage message on the rich text view"""
env = Environment()
env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates'))
usage = env.get_template("usage.html")
return usage.render(css_path=css_path, title=title, intro_message=message,
tutorial_message=tutorial_message, tutorial=tutorial) | python | def usage(title, message, tutorial_message, tutorial, css_path=CSS_PATH):
"""Print a usage message on the rich text view"""
env = Environment()
env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates'))
usage = env.get_template("usage.html")
return usage.render(css_path=css_path, title=title, intro_message=message,
tutorial_message=tutorial_message, tutorial=tutorial) | [
"def",
"usage",
"(",
"title",
",",
"message",
",",
"tutorial_message",
",",
"tutorial",
",",
"css_path",
"=",
"CSS_PATH",
")",
":",
"env",
"=",
"Environment",
"(",
")",
"env",
".",
"loader",
"=",
"FileSystemLoader",
"(",
"osp",
".",
"join",
"(",
"CONFDIR... | Print a usage message on the rich text view | [
"Print",
"a",
"usage",
"message",
"on",
"the",
"rich",
"text",
"view"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L85-L91 |
31,045 | spyder-ide/spyder | spyder/plugins/help/utils/sphinxify.py | generate_context | def generate_context(name='', argspec='', note='', math=False, collapse=False,
img_path='', css_path=CSS_PATH):
"""
Generate the html_context dictionary for our Sphinx conf file.
This is a set of variables to be passed to the Jinja template engine and
that are used to control how the webpage is rendered in connection with
Sphinx
Parameters
----------
name : str
Object's name.
note : str
A note describing what type has the function or method being
introspected
argspec : str
Argspec of the the function or method being introspected
math : bool
Turn on/off Latex rendering on the OI. If False, Latex will be shown in
plain text.
collapse : bool
Collapse sections
img_path : str
Path for images relative to the file containing the docstring
Returns
-------
A dict of strings to be used by Jinja to generate the webpage
"""
if img_path and os.name == 'nt':
img_path = img_path.replace('\\', '/')
context = \
{
# Arg dependent variables
'math_on': 'true' if math else '',
'name': name,
'argspec': argspec,
'note': note,
'collapse': collapse,
'img_path': img_path,
# Static variables
'css_path': css_path,
'js_path': JS_PATH,
'jquery_path': JQUERY_PATH,
'mathjax_path': MATHJAX_PATH,
'right_sphinx_version': '' if sphinx.__version__ < "1.1" else 'true',
'platform': sys.platform
}
return context | python | def generate_context(name='', argspec='', note='', math=False, collapse=False,
img_path='', css_path=CSS_PATH):
"""
Generate the html_context dictionary for our Sphinx conf file.
This is a set of variables to be passed to the Jinja template engine and
that are used to control how the webpage is rendered in connection with
Sphinx
Parameters
----------
name : str
Object's name.
note : str
A note describing what type has the function or method being
introspected
argspec : str
Argspec of the the function or method being introspected
math : bool
Turn on/off Latex rendering on the OI. If False, Latex will be shown in
plain text.
collapse : bool
Collapse sections
img_path : str
Path for images relative to the file containing the docstring
Returns
-------
A dict of strings to be used by Jinja to generate the webpage
"""
if img_path and os.name == 'nt':
img_path = img_path.replace('\\', '/')
context = \
{
# Arg dependent variables
'math_on': 'true' if math else '',
'name': name,
'argspec': argspec,
'note': note,
'collapse': collapse,
'img_path': img_path,
# Static variables
'css_path': css_path,
'js_path': JS_PATH,
'jquery_path': JQUERY_PATH,
'mathjax_path': MATHJAX_PATH,
'right_sphinx_version': '' if sphinx.__version__ < "1.1" else 'true',
'platform': sys.platform
}
return context | [
"def",
"generate_context",
"(",
"name",
"=",
"''",
",",
"argspec",
"=",
"''",
",",
"note",
"=",
"''",
",",
"math",
"=",
"False",
",",
"collapse",
"=",
"False",
",",
"img_path",
"=",
"''",
",",
"css_path",
"=",
"CSS_PATH",
")",
":",
"if",
"img_path",
... | Generate the html_context dictionary for our Sphinx conf file.
This is a set of variables to be passed to the Jinja template engine and
that are used to control how the webpage is rendered in connection with
Sphinx
Parameters
----------
name : str
Object's name.
note : str
A note describing what type has the function or method being
introspected
argspec : str
Argspec of the the function or method being introspected
math : bool
Turn on/off Latex rendering on the OI. If False, Latex will be shown in
plain text.
collapse : bool
Collapse sections
img_path : str
Path for images relative to the file containing the docstring
Returns
-------
A dict of strings to be used by Jinja to generate the webpage | [
"Generate",
"the",
"html_context",
"dictionary",
"for",
"our",
"Sphinx",
"conf",
"file",
".",
"This",
"is",
"a",
"set",
"of",
"variables",
"to",
"be",
"passed",
"to",
"the",
"Jinja",
"template",
"engine",
"and",
"that",
"are",
"used",
"to",
"control",
"how... | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L94-L146 |
31,046 | spyder-ide/spyder | spyder/plugins/help/utils/sphinxify.py | sphinxify | def sphinxify(docstring, context, buildername='html'):
"""
Runs Sphinx on a docstring and outputs the processed documentation.
Parameters
----------
docstring : str
a ReST-formatted docstring
context : dict
Variables to be passed to the layout template to control how its
rendered (through the Sphinx variable *html_context*).
buildername: str
It can be either `html` or `text`.
Returns
-------
An Sphinx-processed string, in either HTML or plain text format, depending
on the value of `buildername`
"""
srcdir = mkdtemp()
srcdir = encoding.to_unicode_from_fs(srcdir)
destdir = osp.join(srcdir, '_build')
rst_name = osp.join(srcdir, 'docstring.rst')
if buildername == 'html':
suffix = '.html'
else:
suffix = '.txt'
output_name = osp.join(destdir, 'docstring' + suffix)
# This is needed so users can type \\ on latex eqnarray envs inside raw
# docstrings
if context['right_sphinx_version'] and context['math_on']:
docstring = docstring.replace('\\\\', '\\\\\\\\')
# Add a class to several characters on the argspec. This way we can
# highlight them using css, in a similar way to what IPython does.
# NOTE: Before doing this, we escape common html chars so that they
# don't interfere with the rest of html present in the page
argspec = escape(context['argspec'])
for char in ['=', ',', '(', ')', '*', '**']:
argspec = argspec.replace(char,
'<span class="argspec-highlight">' + char + '</span>')
context['argspec'] = argspec
doc_file = codecs.open(rst_name, 'w', encoding='utf-8')
doc_file.write(docstring)
doc_file.close()
temp_confdir = False
if temp_confdir:
# TODO: This may be inefficient. Find a faster way to do it.
confdir = mkdtemp()
confdir = encoding.to_unicode_from_fs(confdir)
generate_configuration(confdir)
else:
confdir = osp.join(get_module_source_path('spyder.plugins.help.utils'))
confoverrides = {'html_context': context}
doctreedir = osp.join(srcdir, 'doctrees')
sphinx_app = Sphinx(srcdir, confdir, destdir, doctreedir, buildername,
confoverrides, status=None, warning=None,
freshenv=True, warningiserror=False, tags=None)
try:
sphinx_app.build(None, [rst_name])
except SystemMessage:
output = _("It was not possible to generate rich text help for this "
"object.</br>"
"Please see it in plain text.")
return warning(output)
# TODO: Investigate if this is necessary/important for us
if osp.exists(output_name):
output = codecs.open(output_name, 'r', encoding='utf-8').read()
output = output.replace('<pre>', '<pre class="literal-block">')
else:
output = _("It was not possible to generate rich text help for this "
"object.</br>"
"Please see it in plain text.")
return warning(output)
if temp_confdir:
shutil.rmtree(confdir, ignore_errors=True)
shutil.rmtree(srcdir, ignore_errors=True)
return output | python | def sphinxify(docstring, context, buildername='html'):
"""
Runs Sphinx on a docstring and outputs the processed documentation.
Parameters
----------
docstring : str
a ReST-formatted docstring
context : dict
Variables to be passed to the layout template to control how its
rendered (through the Sphinx variable *html_context*).
buildername: str
It can be either `html` or `text`.
Returns
-------
An Sphinx-processed string, in either HTML or plain text format, depending
on the value of `buildername`
"""
srcdir = mkdtemp()
srcdir = encoding.to_unicode_from_fs(srcdir)
destdir = osp.join(srcdir, '_build')
rst_name = osp.join(srcdir, 'docstring.rst')
if buildername == 'html':
suffix = '.html'
else:
suffix = '.txt'
output_name = osp.join(destdir, 'docstring' + suffix)
# This is needed so users can type \\ on latex eqnarray envs inside raw
# docstrings
if context['right_sphinx_version'] and context['math_on']:
docstring = docstring.replace('\\\\', '\\\\\\\\')
# Add a class to several characters on the argspec. This way we can
# highlight them using css, in a similar way to what IPython does.
# NOTE: Before doing this, we escape common html chars so that they
# don't interfere with the rest of html present in the page
argspec = escape(context['argspec'])
for char in ['=', ',', '(', ')', '*', '**']:
argspec = argspec.replace(char,
'<span class="argspec-highlight">' + char + '</span>')
context['argspec'] = argspec
doc_file = codecs.open(rst_name, 'w', encoding='utf-8')
doc_file.write(docstring)
doc_file.close()
temp_confdir = False
if temp_confdir:
# TODO: This may be inefficient. Find a faster way to do it.
confdir = mkdtemp()
confdir = encoding.to_unicode_from_fs(confdir)
generate_configuration(confdir)
else:
confdir = osp.join(get_module_source_path('spyder.plugins.help.utils'))
confoverrides = {'html_context': context}
doctreedir = osp.join(srcdir, 'doctrees')
sphinx_app = Sphinx(srcdir, confdir, destdir, doctreedir, buildername,
confoverrides, status=None, warning=None,
freshenv=True, warningiserror=False, tags=None)
try:
sphinx_app.build(None, [rst_name])
except SystemMessage:
output = _("It was not possible to generate rich text help for this "
"object.</br>"
"Please see it in plain text.")
return warning(output)
# TODO: Investigate if this is necessary/important for us
if osp.exists(output_name):
output = codecs.open(output_name, 'r', encoding='utf-8').read()
output = output.replace('<pre>', '<pre class="literal-block">')
else:
output = _("It was not possible to generate rich text help for this "
"object.</br>"
"Please see it in plain text.")
return warning(output)
if temp_confdir:
shutil.rmtree(confdir, ignore_errors=True)
shutil.rmtree(srcdir, ignore_errors=True)
return output | [
"def",
"sphinxify",
"(",
"docstring",
",",
"context",
",",
"buildername",
"=",
"'html'",
")",
":",
"srcdir",
"=",
"mkdtemp",
"(",
")",
"srcdir",
"=",
"encoding",
".",
"to_unicode_from_fs",
"(",
"srcdir",
")",
"destdir",
"=",
"osp",
".",
"join",
"(",
"src... | Runs Sphinx on a docstring and outputs the processed documentation.
Parameters
----------
docstring : str
a ReST-formatted docstring
context : dict
Variables to be passed to the layout template to control how its
rendered (through the Sphinx variable *html_context*).
buildername: str
It can be either `html` or `text`.
Returns
-------
An Sphinx-processed string, in either HTML or plain text format, depending
on the value of `buildername` | [
"Runs",
"Sphinx",
"on",
"a",
"docstring",
"and",
"outputs",
"the",
"processed",
"documentation",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L149-L239 |
31,047 | spyder-ide/spyder | spyder/plugins/help/utils/sphinxify.py | generate_configuration | def generate_configuration(directory):
"""
Generates a Sphinx configuration in `directory`.
Parameters
----------
directory : str
Base directory to use
"""
# conf.py file for Sphinx
conf = osp.join(get_module_source_path('spyder.plugins.help.utils'),
'conf.py')
# Docstring layout page (in Jinja):
layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html')
os.makedirs(osp.join(directory, 'templates'))
os.makedirs(osp.join(directory, 'static'))
shutil.copy(conf, directory)
shutil.copy(layout, osp.join(directory, 'templates'))
open(osp.join(directory, '__init__.py'), 'w').write('')
open(osp.join(directory, 'static', 'empty'), 'w').write('') | python | def generate_configuration(directory):
"""
Generates a Sphinx configuration in `directory`.
Parameters
----------
directory : str
Base directory to use
"""
# conf.py file for Sphinx
conf = osp.join(get_module_source_path('spyder.plugins.help.utils'),
'conf.py')
# Docstring layout page (in Jinja):
layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html')
os.makedirs(osp.join(directory, 'templates'))
os.makedirs(osp.join(directory, 'static'))
shutil.copy(conf, directory)
shutil.copy(layout, osp.join(directory, 'templates'))
open(osp.join(directory, '__init__.py'), 'w').write('')
open(osp.join(directory, 'static', 'empty'), 'w').write('') | [
"def",
"generate_configuration",
"(",
"directory",
")",
":",
"# conf.py file for Sphinx",
"conf",
"=",
"osp",
".",
"join",
"(",
"get_module_source_path",
"(",
"'spyder.plugins.help.utils'",
")",
",",
"'conf.py'",
")",
"# Docstring layout page (in Jinja):",
"layout",
"=",
... | Generates a Sphinx configuration in `directory`.
Parameters
----------
directory : str
Base directory to use | [
"Generates",
"a",
"Sphinx",
"configuration",
"in",
"directory",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L242-L264 |
31,048 | spyder-ide/spyder | spyder/plugins/editor/widgets/status.py | EOLStatus.update_eol | def update_eol(self, os_name):
"""Update end of line status."""
os_name = to_text_string(os_name)
value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR")
self.set_value(value) | python | def update_eol(self, os_name):
"""Update end of line status."""
os_name = to_text_string(os_name)
value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR")
self.set_value(value) | [
"def",
"update_eol",
"(",
"self",
",",
"os_name",
")",
":",
"os_name",
"=",
"to_text_string",
"(",
"os_name",
")",
"value",
"=",
"{",
"\"nt\"",
":",
"\"CRLF\"",
",",
"\"posix\"",
":",
"\"LF\"",
"}",
".",
"get",
"(",
"os_name",
",",
"\"CR\"",
")",
"self... | Update end of line status. | [
"Update",
"end",
"of",
"line",
"status",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L34-L38 |
31,049 | spyder-ide/spyder | spyder/plugins/editor/widgets/status.py | EncodingStatus.update_encoding | def update_encoding(self, encoding):
"""Update encoding of current file."""
value = str(encoding).upper()
self.set_value(value) | python | def update_encoding(self, encoding):
"""Update encoding of current file."""
value = str(encoding).upper()
self.set_value(value) | [
"def",
"update_encoding",
"(",
"self",
",",
"encoding",
")",
":",
"value",
"=",
"str",
"(",
"encoding",
")",
".",
"upper",
"(",
")",
"self",
".",
"set_value",
"(",
"value",
")"
] | Update encoding of current file. | [
"Update",
"encoding",
"of",
"current",
"file",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L45-L48 |
31,050 | spyder-ide/spyder | spyder/plugins/editor/widgets/status.py | CursorPositionStatus.update_cursor_position | def update_cursor_position(self, line, index):
"""Update cursor position."""
value = 'Line {}, Col {}'.format(line + 1, index + 1)
self.set_value(value) | python | def update_cursor_position(self, line, index):
"""Update cursor position."""
value = 'Line {}, Col {}'.format(line + 1, index + 1)
self.set_value(value) | [
"def",
"update_cursor_position",
"(",
"self",
",",
"line",
",",
"index",
")",
":",
"value",
"=",
"'Line {}, Col {}'",
".",
"format",
"(",
"line",
"+",
"1",
",",
"index",
"+",
"1",
")",
"self",
".",
"set_value",
"(",
"value",
")"
] | Update cursor position. | [
"Update",
"cursor",
"position",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L55-L58 |
31,051 | spyder-ide/spyder | spyder/plugins/editor/widgets/status.py | VCSStatus.update_vcs | def update_vcs(self, fname, index):
"""Update vcs status."""
fpath = os.path.dirname(fname)
branches, branch, files_modified = get_git_refs(fpath)
text = branch if branch else ''
if len(files_modified):
text = text + ' [{}]'.format(len(files_modified))
self.setVisible(bool(branch))
self.set_value(text) | python | def update_vcs(self, fname, index):
"""Update vcs status."""
fpath = os.path.dirname(fname)
branches, branch, files_modified = get_git_refs(fpath)
text = branch if branch else ''
if len(files_modified):
text = text + ' [{}]'.format(len(files_modified))
self.setVisible(bool(branch))
self.set_value(text) | [
"def",
"update_vcs",
"(",
"self",
",",
"fname",
",",
"index",
")",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"fname",
")",
"branches",
",",
"branch",
",",
"files_modified",
"=",
"get_git_refs",
"(",
"fpath",
")",
"text",
"=",
"branch",... | Update vcs status. | [
"Update",
"vcs",
"status",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L73-L83 |
31,052 | spyder-ide/spyder | spyder/plugins/variableexplorer/plugin.py | VariableExplorer.free_memory | def free_memory(self):
"""Free memory signal."""
self.main.free_memory()
QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER,
lambda: self.main.free_memory())
QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER,
lambda: self.main.free_memory()) | python | def free_memory(self):
"""Free memory signal."""
self.main.free_memory()
QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER,
lambda: self.main.free_memory())
QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER,
lambda: self.main.free_memory()) | [
"def",
"free_memory",
"(",
"self",
")",
":",
"self",
".",
"main",
".",
"free_memory",
"(",
")",
"QTimer",
".",
"singleShot",
"(",
"self",
".",
"INITIAL_FREE_MEMORY_TIME_TRIGGER",
",",
"lambda",
":",
"self",
".",
"main",
".",
"free_memory",
"(",
")",
")",
... | Free memory signal. | [
"Free",
"memory",
"signal",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/plugin.py#L96-L102 |
31,053 | spyder-ide/spyder | spyder/plugins/variableexplorer/plugin.py | VariableExplorer.add_shellwidget | def add_shellwidget(self, shellwidget):
"""
Register shell with variable explorer.
This function opens a new NamespaceBrowser for browsing the variables
in the shell.
"""
shellwidget_id = id(shellwidget)
if shellwidget_id not in self.shellwidgets:
self.options_button.setVisible(True)
nsb = NamespaceBrowser(self, options_button=self.options_button)
nsb.set_shellwidget(shellwidget)
nsb.setup(**self.get_settings())
nsb.sig_option_changed.connect(self.change_option)
nsb.sig_free_memory.connect(self.free_memory)
self.add_widget(nsb)
self.shellwidgets[shellwidget_id] = nsb
self.set_shellwidget_from_id(shellwidget_id)
return nsb | python | def add_shellwidget(self, shellwidget):
"""
Register shell with variable explorer.
This function opens a new NamespaceBrowser for browsing the variables
in the shell.
"""
shellwidget_id = id(shellwidget)
if shellwidget_id not in self.shellwidgets:
self.options_button.setVisible(True)
nsb = NamespaceBrowser(self, options_button=self.options_button)
nsb.set_shellwidget(shellwidget)
nsb.setup(**self.get_settings())
nsb.sig_option_changed.connect(self.change_option)
nsb.sig_free_memory.connect(self.free_memory)
self.add_widget(nsb)
self.shellwidgets[shellwidget_id] = nsb
self.set_shellwidget_from_id(shellwidget_id)
return nsb | [
"def",
"add_shellwidget",
"(",
"self",
",",
"shellwidget",
")",
":",
"shellwidget_id",
"=",
"id",
"(",
"shellwidget",
")",
"if",
"shellwidget_id",
"not",
"in",
"self",
".",
"shellwidgets",
":",
"self",
".",
"options_button",
".",
"setVisible",
"(",
"True",
"... | Register shell with variable explorer.
This function opens a new NamespaceBrowser for browsing the variables
in the shell. | [
"Register",
"shell",
"with",
"variable",
"explorer",
".",
"This",
"function",
"opens",
"a",
"new",
"NamespaceBrowser",
"for",
"browsing",
"the",
"variables",
"in",
"the",
"shell",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/plugin.py#L125-L143 |
31,054 | spyder-ide/spyder | spyder/plugins/variableexplorer/plugin.py | VariableExplorer.import_data | def import_data(self, fname):
"""Import data in current namespace"""
if self.count():
nsb = self.current_widget()
nsb.refresh_table()
nsb.import_data(filenames=fname)
if self.dockwidget and not self.ismaximized:
self.dockwidget.setVisible(True)
self.dockwidget.raise_() | python | def import_data(self, fname):
"""Import data in current namespace"""
if self.count():
nsb = self.current_widget()
nsb.refresh_table()
nsb.import_data(filenames=fname)
if self.dockwidget and not self.ismaximized:
self.dockwidget.setVisible(True)
self.dockwidget.raise_() | [
"def",
"import_data",
"(",
"self",
",",
"fname",
")",
":",
"if",
"self",
".",
"count",
"(",
")",
":",
"nsb",
"=",
"self",
".",
"current_widget",
"(",
")",
"nsb",
".",
"refresh_table",
"(",
")",
"nsb",
".",
"import_data",
"(",
"filenames",
"=",
"fname... | Import data in current namespace | [
"Import",
"data",
"in",
"current",
"namespace"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/plugin.py#L158-L166 |
31,055 | spyder-ide/spyder | spyder/plugins/help/widgets.py | ObjectComboBox.validate | def validate(self, qstr, editing=True):
"""Reimplemented to avoid formatting actions"""
valid = self.is_valid(qstr)
if self.hasFocus() and valid is not None:
if editing and not valid:
# Combo box text is being modified: invalidate the entry
self.show_tip(self.tips[valid])
self.valid.emit(False, False)
else:
# A new item has just been selected
if valid:
self.selected()
else:
self.valid.emit(False, False) | python | def validate(self, qstr, editing=True):
"""Reimplemented to avoid formatting actions"""
valid = self.is_valid(qstr)
if self.hasFocus() and valid is not None:
if editing and not valid:
# Combo box text is being modified: invalidate the entry
self.show_tip(self.tips[valid])
self.valid.emit(False, False)
else:
# A new item has just been selected
if valid:
self.selected()
else:
self.valid.emit(False, False) | [
"def",
"validate",
"(",
"self",
",",
"qstr",
",",
"editing",
"=",
"True",
")",
":",
"valid",
"=",
"self",
".",
"is_valid",
"(",
"qstr",
")",
"if",
"self",
".",
"hasFocus",
"(",
")",
"and",
"valid",
"is",
"not",
"None",
":",
"if",
"editing",
"and",
... | Reimplemented to avoid formatting actions | [
"Reimplemented",
"to",
"avoid",
"formatting",
"actions"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/widgets.py#L78-L91 |
31,056 | spyder-ide/spyder | spyder/utils/codeanalysis.py | check_with_pyflakes | def check_with_pyflakes(source_code, filename=None):
"""Check source code with pyflakes
Returns an empty list if pyflakes is not installed"""
try:
if filename is None:
filename = '<string>'
try:
source_code += '\n'
except TypeError:
# Python 3
source_code += to_binary_string('\n')
import _ast
from pyflakes.checker import Checker
# First, compile into an AST and handle syntax errors.
try:
tree = compile(source_code, filename, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError as value:
# If there's an encoding problem with the file, the text is None.
if value.text is None:
results = []
else:
results = [(value.args[0], value.lineno)]
except (ValueError, TypeError):
# Example of ValueError: file contains invalid \x escape character
# (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674797)
# Example of TypeError: file contains null character
# (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674796)
results = []
else:
# Okay, it's syntactically valid. Now check it.
w = Checker(tree, filename)
w.messages.sort(key=lambda x: x.lineno)
results = []
coding = encoding.get_coding(source_code)
lines = source_code.splitlines()
for warning in w.messages:
if 'analysis:ignore' not in \
to_text_string(lines[warning.lineno-1], coding):
results.append((warning.message % warning.message_args,
warning.lineno))
except Exception:
# Never return None to avoid lock in spyder/widgets/editor.py
# See Issue 1547
results = []
if DEBUG_EDITOR:
traceback.print_exc() # Print exception in internal console
return results | python | def check_with_pyflakes(source_code, filename=None):
"""Check source code with pyflakes
Returns an empty list if pyflakes is not installed"""
try:
if filename is None:
filename = '<string>'
try:
source_code += '\n'
except TypeError:
# Python 3
source_code += to_binary_string('\n')
import _ast
from pyflakes.checker import Checker
# First, compile into an AST and handle syntax errors.
try:
tree = compile(source_code, filename, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError as value:
# If there's an encoding problem with the file, the text is None.
if value.text is None:
results = []
else:
results = [(value.args[0], value.lineno)]
except (ValueError, TypeError):
# Example of ValueError: file contains invalid \x escape character
# (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674797)
# Example of TypeError: file contains null character
# (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674796)
results = []
else:
# Okay, it's syntactically valid. Now check it.
w = Checker(tree, filename)
w.messages.sort(key=lambda x: x.lineno)
results = []
coding = encoding.get_coding(source_code)
lines = source_code.splitlines()
for warning in w.messages:
if 'analysis:ignore' not in \
to_text_string(lines[warning.lineno-1], coding):
results.append((warning.message % warning.message_args,
warning.lineno))
except Exception:
# Never return None to avoid lock in spyder/widgets/editor.py
# See Issue 1547
results = []
if DEBUG_EDITOR:
traceback.print_exc() # Print exception in internal console
return results | [
"def",
"check_with_pyflakes",
"(",
"source_code",
",",
"filename",
"=",
"None",
")",
":",
"try",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"'<string>'",
"try",
":",
"source_code",
"+=",
"'\\n'",
"except",
"TypeError",
":",
"# Python 3\r",
"s... | Check source code with pyflakes
Returns an empty list if pyflakes is not installed | [
"Check",
"source",
"code",
"with",
"pyflakes",
"Returns",
"an",
"empty",
"list",
"if",
"pyflakes",
"is",
"not",
"installed"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L41-L88 |
31,057 | spyder-ide/spyder | spyder/utils/codeanalysis.py | get_checker_executable | def get_checker_executable(name):
"""Return checker executable in the form of a list of arguments
for subprocess.Popen"""
if programs.is_program_installed(name):
# Checker is properly installed
return [name]
else:
path1 = programs.python_script_exists(package=None,
module=name+'_script')
path2 = programs.python_script_exists(package=None, module=name)
if path1 is not None: # checker_script.py is available
# Checker script is available but has not been installed
# (this may work with pyflakes)
return [sys.executable, path1]
elif path2 is not None: # checker.py is available
# Checker package is available but its script has not been
# installed (this works with pycodestyle but not with pyflakes)
return [sys.executable, path2] | python | def get_checker_executable(name):
"""Return checker executable in the form of a list of arguments
for subprocess.Popen"""
if programs.is_program_installed(name):
# Checker is properly installed
return [name]
else:
path1 = programs.python_script_exists(package=None,
module=name+'_script')
path2 = programs.python_script_exists(package=None, module=name)
if path1 is not None: # checker_script.py is available
# Checker script is available but has not been installed
# (this may work with pyflakes)
return [sys.executable, path1]
elif path2 is not None: # checker.py is available
# Checker package is available but its script has not been
# installed (this works with pycodestyle but not with pyflakes)
return [sys.executable, path2] | [
"def",
"get_checker_executable",
"(",
"name",
")",
":",
"if",
"programs",
".",
"is_program_installed",
"(",
"name",
")",
":",
"# Checker is properly installed\r",
"return",
"[",
"name",
"]",
"else",
":",
"path1",
"=",
"programs",
".",
"python_script_exists",
"(",
... | Return checker executable in the form of a list of arguments
for subprocess.Popen | [
"Return",
"checker",
"executable",
"in",
"the",
"form",
"of",
"a",
"list",
"of",
"arguments",
"for",
"subprocess",
".",
"Popen"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L96-L113 |
31,058 | spyder-ide/spyder | spyder/utils/codeanalysis.py | check_with_pep8 | def check_with_pep8(source_code, filename=None):
"""Check source code with pycodestyle"""
try:
args = get_checker_executable('pycodestyle')
results = check(args, source_code, filename=filename, options=['-r'])
except Exception:
# Never return None to avoid lock in spyder/widgets/editor.py
# See Issue 1547
results = []
if DEBUG_EDITOR:
traceback.print_exc() # Print exception in internal console
return results | python | def check_with_pep8(source_code, filename=None):
"""Check source code with pycodestyle"""
try:
args = get_checker_executable('pycodestyle')
results = check(args, source_code, filename=filename, options=['-r'])
except Exception:
# Never return None to avoid lock in spyder/widgets/editor.py
# See Issue 1547
results = []
if DEBUG_EDITOR:
traceback.print_exc() # Print exception in internal console
return results | [
"def",
"check_with_pep8",
"(",
"source_code",
",",
"filename",
"=",
"None",
")",
":",
"try",
":",
"args",
"=",
"get_checker_executable",
"(",
"'pycodestyle'",
")",
"results",
"=",
"check",
"(",
"args",
",",
"source_code",
",",
"filename",
"=",
"filename",
",... | Check source code with pycodestyle | [
"Check",
"source",
"code",
"with",
"pycodestyle"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L164-L175 |
31,059 | spyder-ide/spyder | spyder/utils/qthelpers.py | get_image_label | def get_image_label(name, default="not_found.png"):
"""Return image inside a QLabel object"""
label = QLabel()
label.setPixmap(QPixmap(get_image_path(name, default)))
return label | python | def get_image_label(name, default="not_found.png"):
"""Return image inside a QLabel object"""
label = QLabel()
label.setPixmap(QPixmap(get_image_path(name, default)))
return label | [
"def",
"get_image_label",
"(",
"name",
",",
"default",
"=",
"\"not_found.png\"",
")",
":",
"label",
"=",
"QLabel",
"(",
")",
"label",
".",
"setPixmap",
"(",
"QPixmap",
"(",
"get_image_path",
"(",
"name",
",",
"default",
")",
")",
")",
"return",
"label"
] | Return image inside a QLabel object | [
"Return",
"image",
"inside",
"a",
"QLabel",
"object"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L44-L48 |
31,060 | spyder-ide/spyder | spyder/utils/qthelpers.py | file_uri | def file_uri(fname):
"""Select the right file uri scheme according to the operating system"""
if os.name == 'nt':
# Local file
if re.search(r'^[a-zA-Z]:', fname):
return 'file:///' + fname
# UNC based path
else:
return 'file://' + fname
else:
return 'file://' + fname | python | def file_uri(fname):
"""Select the right file uri scheme according to the operating system"""
if os.name == 'nt':
# Local file
if re.search(r'^[a-zA-Z]:', fname):
return 'file:///' + fname
# UNC based path
else:
return 'file://' + fname
else:
return 'file://' + fname | [
"def",
"file_uri",
"(",
"fname",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# Local file\r",
"if",
"re",
".",
"search",
"(",
"r'^[a-zA-Z]:'",
",",
"fname",
")",
":",
"return",
"'file:///'",
"+",
"fname",
"# UNC based path\r",
"else",
":",
"re... | Select the right file uri scheme according to the operating system | [
"Select",
"the",
"right",
"file",
"uri",
"scheme",
"according",
"to",
"the",
"operating",
"system"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L97-L107 |
31,061 | spyder-ide/spyder | spyder/utils/qthelpers.py | install_translator | def install_translator(qapp):
"""Install Qt translator to the QApplication instance"""
global QT_TRANSLATOR
if QT_TRANSLATOR is None:
qt_translator = QTranslator()
if qt_translator.load("qt_"+QLocale.system().name(),
QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
QT_TRANSLATOR = qt_translator # Keep reference alive
if QT_TRANSLATOR is not None:
qapp.installTranslator(QT_TRANSLATOR) | python | def install_translator(qapp):
"""Install Qt translator to the QApplication instance"""
global QT_TRANSLATOR
if QT_TRANSLATOR is None:
qt_translator = QTranslator()
if qt_translator.load("qt_"+QLocale.system().name(),
QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
QT_TRANSLATOR = qt_translator # Keep reference alive
if QT_TRANSLATOR is not None:
qapp.installTranslator(QT_TRANSLATOR) | [
"def",
"install_translator",
"(",
"qapp",
")",
":",
"global",
"QT_TRANSLATOR",
"if",
"QT_TRANSLATOR",
"is",
"None",
":",
"qt_translator",
"=",
"QTranslator",
"(",
")",
"if",
"qt_translator",
".",
"load",
"(",
"\"qt_\"",
"+",
"QLocale",
".",
"system",
"(",
")... | Install Qt translator to the QApplication instance | [
"Install",
"Qt",
"translator",
"to",
"the",
"QApplication",
"instance"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L111-L120 |
31,062 | spyder-ide/spyder | spyder/utils/qthelpers.py | keyevent2tuple | def keyevent2tuple(event):
"""Convert QKeyEvent instance into a tuple"""
return (event.type(), event.key(), event.modifiers(), event.text(),
event.isAutoRepeat(), event.count()) | python | def keyevent2tuple(event):
"""Convert QKeyEvent instance into a tuple"""
return (event.type(), event.key(), event.modifiers(), event.text(),
event.isAutoRepeat(), event.count()) | [
"def",
"keyevent2tuple",
"(",
"event",
")",
":",
"return",
"(",
"event",
".",
"type",
"(",
")",
",",
"event",
".",
"key",
"(",
")",
",",
"event",
".",
"modifiers",
"(",
")",
",",
"event",
".",
"text",
"(",
")",
",",
"event",
".",
"isAutoRepeat",
... | Convert QKeyEvent instance into a tuple | [
"Convert",
"QKeyEvent",
"instance",
"into",
"a",
"tuple"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L166-L169 |
31,063 | spyder-ide/spyder | spyder/utils/qthelpers.py | create_toolbutton | def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None,
toggled=None, triggered=None,
autoraise=True, text_beside_icon=False):
"""Create a QToolButton"""
button = QToolButton(parent)
if text is not None:
button.setText(text)
if icon is not None:
if is_text_string(icon):
icon = get_icon(icon)
button.setIcon(icon)
if text is not None or tip is not None:
button.setToolTip(text if tip is None else tip)
if text_beside_icon:
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
button.setAutoRaise(autoraise)
if triggered is not None:
button.clicked.connect(triggered)
if toggled is not None:
button.toggled.connect(toggled)
button.setCheckable(True)
if shortcut is not None:
button.setShortcut(shortcut)
return button | python | def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None,
toggled=None, triggered=None,
autoraise=True, text_beside_icon=False):
"""Create a QToolButton"""
button = QToolButton(parent)
if text is not None:
button.setText(text)
if icon is not None:
if is_text_string(icon):
icon = get_icon(icon)
button.setIcon(icon)
if text is not None or tip is not None:
button.setToolTip(text if tip is None else tip)
if text_beside_icon:
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
button.setAutoRaise(autoraise)
if triggered is not None:
button.clicked.connect(triggered)
if toggled is not None:
button.toggled.connect(toggled)
button.setCheckable(True)
if shortcut is not None:
button.setShortcut(shortcut)
return button | [
"def",
"create_toolbutton",
"(",
"parent",
",",
"text",
"=",
"None",
",",
"shortcut",
"=",
"None",
",",
"icon",
"=",
"None",
",",
"tip",
"=",
"None",
",",
"toggled",
"=",
"None",
",",
"triggered",
"=",
"None",
",",
"autoraise",
"=",
"True",
",",
"tex... | Create a QToolButton | [
"Create",
"a",
"QToolButton"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L190-L213 |
31,064 | spyder-ide/spyder | spyder/utils/qthelpers.py | action2button | def action2button(action, autoraise=True, text_beside_icon=False, parent=None):
"""Create a QToolButton directly from a QAction object"""
if parent is None:
parent = action.parent()
button = QToolButton(parent)
button.setDefaultAction(action)
button.setAutoRaise(autoraise)
if text_beside_icon:
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
return button | python | def action2button(action, autoraise=True, text_beside_icon=False, parent=None):
"""Create a QToolButton directly from a QAction object"""
if parent is None:
parent = action.parent()
button = QToolButton(parent)
button.setDefaultAction(action)
button.setAutoRaise(autoraise)
if text_beside_icon:
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
return button | [
"def",
"action2button",
"(",
"action",
",",
"autoraise",
"=",
"True",
",",
"text_beside_icon",
"=",
"False",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"action",
".",
"parent",
"(",
")",
"button",
"=",
"QToo... | Create a QToolButton directly from a QAction object | [
"Create",
"a",
"QToolButton",
"directly",
"from",
"a",
"QAction",
"object"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L216-L225 |
31,065 | spyder-ide/spyder | spyder/utils/qthelpers.py | add_shortcut_to_tooltip | def add_shortcut_to_tooltip(action, context, name):
"""Add the shortcut associated with a given action to its tooltip"""
action.setToolTip(action.toolTip() + ' (%s)' %
get_shortcut(context=context, name=name)) | python | def add_shortcut_to_tooltip(action, context, name):
"""Add the shortcut associated with a given action to its tooltip"""
action.setToolTip(action.toolTip() + ' (%s)' %
get_shortcut(context=context, name=name)) | [
"def",
"add_shortcut_to_tooltip",
"(",
"action",
",",
"context",
",",
"name",
")",
":",
"action",
".",
"setToolTip",
"(",
"action",
".",
"toolTip",
"(",
")",
"+",
"' (%s)'",
"%",
"get_shortcut",
"(",
"context",
"=",
"context",
",",
"name",
"=",
"name",
"... | Add the shortcut associated with a given action to its tooltip | [
"Add",
"the",
"shortcut",
"associated",
"with",
"a",
"given",
"action",
"to",
"its",
"tooltip"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L281-L284 |
31,066 | spyder-ide/spyder | spyder/utils/qthelpers.py | add_actions | def add_actions(target, actions, insert_before=None):
"""Add actions to a QMenu or a QToolBar."""
previous_action = None
target_actions = list(target.actions())
if target_actions:
previous_action = target_actions[-1]
if previous_action.isSeparator():
previous_action = None
for action in actions:
if (action is None) and (previous_action is not None):
if insert_before is None:
target.addSeparator()
else:
target.insertSeparator(insert_before)
elif isinstance(action, QMenu):
if insert_before is None:
target.addMenu(action)
else:
target.insertMenu(insert_before, action)
elif isinstance(action, QAction):
if isinstance(action, SpyderAction):
if isinstance(target, QMenu) or not isinstance(target, QToolBar):
try:
action = action.no_icon_action
except RuntimeError:
continue
if insert_before is None:
# This is needed in order to ignore adding an action whose
# wrapped C/C++ object has been deleted. See issue 5074
try:
target.addAction(action)
except RuntimeError:
continue
else:
target.insertAction(insert_before, action)
previous_action = action | python | def add_actions(target, actions, insert_before=None):
"""Add actions to a QMenu or a QToolBar."""
previous_action = None
target_actions = list(target.actions())
if target_actions:
previous_action = target_actions[-1]
if previous_action.isSeparator():
previous_action = None
for action in actions:
if (action is None) and (previous_action is not None):
if insert_before is None:
target.addSeparator()
else:
target.insertSeparator(insert_before)
elif isinstance(action, QMenu):
if insert_before is None:
target.addMenu(action)
else:
target.insertMenu(insert_before, action)
elif isinstance(action, QAction):
if isinstance(action, SpyderAction):
if isinstance(target, QMenu) or not isinstance(target, QToolBar):
try:
action = action.no_icon_action
except RuntimeError:
continue
if insert_before is None:
# This is needed in order to ignore adding an action whose
# wrapped C/C++ object has been deleted. See issue 5074
try:
target.addAction(action)
except RuntimeError:
continue
else:
target.insertAction(insert_before, action)
previous_action = action | [
"def",
"add_actions",
"(",
"target",
",",
"actions",
",",
"insert_before",
"=",
"None",
")",
":",
"previous_action",
"=",
"None",
"target_actions",
"=",
"list",
"(",
"target",
".",
"actions",
"(",
")",
")",
"if",
"target_actions",
":",
"previous_action",
"="... | Add actions to a QMenu or a QToolBar. | [
"Add",
"actions",
"to",
"a",
"QMenu",
"or",
"a",
"QToolBar",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L287-L322 |
31,067 | spyder-ide/spyder | spyder/utils/qthelpers.py | create_bookmark_action | def create_bookmark_action(parent, url, title, icon=None, shortcut=None):
"""Create bookmark action"""
@Slot()
def open_url():
return programs.start_file(url)
return create_action( parent, title, shortcut=shortcut, icon=icon,
triggered=open_url) | python | def create_bookmark_action(parent, url, title, icon=None, shortcut=None):
"""Create bookmark action"""
@Slot()
def open_url():
return programs.start_file(url)
return create_action( parent, title, shortcut=shortcut, icon=icon,
triggered=open_url) | [
"def",
"create_bookmark_action",
"(",
"parent",
",",
"url",
",",
"title",
",",
"icon",
"=",
"None",
",",
"shortcut",
"=",
"None",
")",
":",
"@",
"Slot",
"(",
")",
"def",
"open_url",
"(",
")",
":",
"return",
"programs",
".",
"start_file",
"(",
"url",
... | Create bookmark action | [
"Create",
"bookmark",
"action"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L335-L343 |
31,068 | spyder-ide/spyder | spyder/utils/qthelpers.py | create_program_action | def create_program_action(parent, text, name, icon=None, nt_name=None):
"""Create action to run a program"""
if is_text_string(icon):
icon = get_icon(icon)
if os.name == 'nt' and nt_name is not None:
name = nt_name
path = programs.find_program(name)
if path is not None:
return create_action(parent, text, icon=icon,
triggered=lambda: programs.run_program(name)) | python | def create_program_action(parent, text, name, icon=None, nt_name=None):
"""Create action to run a program"""
if is_text_string(icon):
icon = get_icon(icon)
if os.name == 'nt' and nt_name is not None:
name = nt_name
path = programs.find_program(name)
if path is not None:
return create_action(parent, text, icon=icon,
triggered=lambda: programs.run_program(name)) | [
"def",
"create_program_action",
"(",
"parent",
",",
"text",
",",
"name",
",",
"icon",
"=",
"None",
",",
"nt_name",
"=",
"None",
")",
":",
"if",
"is_text_string",
"(",
"icon",
")",
":",
"icon",
"=",
"get_icon",
"(",
"icon",
")",
"if",
"os",
".",
"name... | Create action to run a program | [
"Create",
"action",
"to",
"run",
"a",
"program"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L365-L374 |
31,069 | spyder-ide/spyder | spyder/utils/qthelpers.py | create_python_script_action | def create_python_script_action(parent, text, icon, package, module, args=[]):
"""Create action to run a GUI based Python script"""
if is_text_string(icon):
icon = get_icon(icon)
if programs.python_script_exists(package, module):
return create_action(parent, text, icon=icon,
triggered=lambda:
programs.run_python_script(package, module, args)) | python | def create_python_script_action(parent, text, icon, package, module, args=[]):
"""Create action to run a GUI based Python script"""
if is_text_string(icon):
icon = get_icon(icon)
if programs.python_script_exists(package, module):
return create_action(parent, text, icon=icon,
triggered=lambda:
programs.run_python_script(package, module, args)) | [
"def",
"create_python_script_action",
"(",
"parent",
",",
"text",
",",
"icon",
",",
"package",
",",
"module",
",",
"args",
"=",
"[",
"]",
")",
":",
"if",
"is_text_string",
"(",
"icon",
")",
":",
"icon",
"=",
"get_icon",
"(",
"icon",
")",
"if",
"program... | Create action to run a GUI based Python script | [
"Create",
"action",
"to",
"run",
"a",
"GUI",
"based",
"Python",
"script"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L377-L384 |
31,070 | spyder-ide/spyder | spyder/utils/qthelpers.py | get_filetype_icon | def get_filetype_icon(fname):
"""Return file type icon"""
ext = osp.splitext(fname)[1]
if ext.startswith('.'):
ext = ext[1:]
return get_icon( "%s.png" % ext, ima.icon('FileIcon') ) | python | def get_filetype_icon(fname):
"""Return file type icon"""
ext = osp.splitext(fname)[1]
if ext.startswith('.'):
ext = ext[1:]
return get_icon( "%s.png" % ext, ima.icon('FileIcon') ) | [
"def",
"get_filetype_icon",
"(",
"fname",
")",
":",
"ext",
"=",
"osp",
".",
"splitext",
"(",
"fname",
")",
"[",
"1",
"]",
"if",
"ext",
".",
"startswith",
"(",
"'.'",
")",
":",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"return",
"get_icon",
"(",
"\"%... | Return file type icon | [
"Return",
"file",
"type",
"icon"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L423-L428 |
31,071 | spyder-ide/spyder | spyder/utils/qthelpers.py | show_std_icons | def show_std_icons():
"""
Show all standard Icons
"""
app = qapplication()
dialog = ShowStdIcons(None)
dialog.show()
sys.exit(app.exec_()) | python | def show_std_icons():
"""
Show all standard Icons
"""
app = qapplication()
dialog = ShowStdIcons(None)
dialog.show()
sys.exit(app.exec_()) | [
"def",
"show_std_icons",
"(",
")",
":",
"app",
"=",
"qapplication",
"(",
")",
"dialog",
"=",
"ShowStdIcons",
"(",
"None",
")",
"dialog",
".",
"show",
"(",
")",
"sys",
".",
"exit",
"(",
"app",
".",
"exec_",
"(",
")",
")"
] | Show all standard Icons | [
"Show",
"all",
"standard",
"Icons"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L501-L508 |
31,072 | spyder-ide/spyder | spyder/utils/qthelpers.py | DialogManager.show | def show(self, dialog):
"""Generic method to show a non-modal dialog and keep reference
to the Qt C++ object"""
for dlg in list(self.dialogs.values()):
if to_text_string(dlg.windowTitle()) \
== to_text_string(dialog.windowTitle()):
dlg.show()
dlg.raise_()
break
else:
dialog.show()
self.dialogs[id(dialog)] = dialog
dialog.accepted.connect(
lambda eid=id(dialog): self.dialog_finished(eid))
dialog.rejected.connect(
lambda eid=id(dialog): self.dialog_finished(eid)) | python | def show(self, dialog):
"""Generic method to show a non-modal dialog and keep reference
to the Qt C++ object"""
for dlg in list(self.dialogs.values()):
if to_text_string(dlg.windowTitle()) \
== to_text_string(dialog.windowTitle()):
dlg.show()
dlg.raise_()
break
else:
dialog.show()
self.dialogs[id(dialog)] = dialog
dialog.accepted.connect(
lambda eid=id(dialog): self.dialog_finished(eid))
dialog.rejected.connect(
lambda eid=id(dialog): self.dialog_finished(eid)) | [
"def",
"show",
"(",
"self",
",",
"dialog",
")",
":",
"for",
"dlg",
"in",
"list",
"(",
"self",
".",
"dialogs",
".",
"values",
"(",
")",
")",
":",
"if",
"to_text_string",
"(",
"dlg",
".",
"windowTitle",
"(",
")",
")",
"==",
"to_text_string",
"(",
"di... | Generic method to show a non-modal dialog and keep reference
to the Qt C++ object | [
"Generic",
"method",
"to",
"show",
"a",
"non",
"-",
"modal",
"dialog",
"and",
"keep",
"reference",
"to",
"the",
"Qt",
"C",
"++",
"object"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L396-L411 |
31,073 | spyder-ide/spyder | spyder/dependencies.py | add | def add(modname, features, required_version, installed_version=None,
optional=False):
"""Add Spyder dependency"""
global DEPENDENCIES
for dependency in DEPENDENCIES:
if dependency.modname == modname:
raise ValueError("Dependency has already been registered: %s"\
% modname)
DEPENDENCIES += [Dependency(modname, features, required_version,
installed_version, optional)] | python | def add(modname, features, required_version, installed_version=None,
optional=False):
"""Add Spyder dependency"""
global DEPENDENCIES
for dependency in DEPENDENCIES:
if dependency.modname == modname:
raise ValueError("Dependency has already been registered: %s"\
% modname)
DEPENDENCIES += [Dependency(modname, features, required_version,
installed_version, optional)] | [
"def",
"add",
"(",
"modname",
",",
"features",
",",
"required_version",
",",
"installed_version",
"=",
"None",
",",
"optional",
"=",
"False",
")",
":",
"global",
"DEPENDENCIES",
"for",
"dependency",
"in",
"DEPENDENCIES",
":",
"if",
"dependency",
".",
"modname"... | Add Spyder dependency | [
"Add",
"Spyder",
"dependency"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/dependencies.py#L66-L75 |
31,074 | spyder-ide/spyder | spyder/dependencies.py | check | def check(modname):
"""Check if required dependency is installed"""
for dependency in DEPENDENCIES:
if dependency.modname == modname:
return dependency.check()
else:
raise RuntimeError("Unkwown dependency %s" % modname) | python | def check(modname):
"""Check if required dependency is installed"""
for dependency in DEPENDENCIES:
if dependency.modname == modname:
return dependency.check()
else:
raise RuntimeError("Unkwown dependency %s" % modname) | [
"def",
"check",
"(",
"modname",
")",
":",
"for",
"dependency",
"in",
"DEPENDENCIES",
":",
"if",
"dependency",
".",
"modname",
"==",
"modname",
":",
"return",
"dependency",
".",
"check",
"(",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Unkwown dependen... | Check if required dependency is installed | [
"Check",
"if",
"required",
"dependency",
"is",
"installed"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/dependencies.py#L78-L84 |
31,075 | spyder-ide/spyder | spyder/dependencies.py | status | def status(deps=DEPENDENCIES, linesep=os.linesep):
"""Return a status of dependencies"""
maxwidth = 0
col1 = []
col2 = []
for dependency in deps:
title1 = dependency.modname
title1 += ' ' + dependency.required_version
col1.append(title1)
maxwidth = max([maxwidth, len(title1)])
col2.append(dependency.get_installed_version())
text = ""
for index in range(len(deps)):
text += col1[index].ljust(maxwidth) + ': ' + col2[index] + linesep
return text[:-1] | python | def status(deps=DEPENDENCIES, linesep=os.linesep):
"""Return a status of dependencies"""
maxwidth = 0
col1 = []
col2 = []
for dependency in deps:
title1 = dependency.modname
title1 += ' ' + dependency.required_version
col1.append(title1)
maxwidth = max([maxwidth, len(title1)])
col2.append(dependency.get_installed_version())
text = ""
for index in range(len(deps)):
text += col1[index].ljust(maxwidth) + ': ' + col2[index] + linesep
return text[:-1] | [
"def",
"status",
"(",
"deps",
"=",
"DEPENDENCIES",
",",
"linesep",
"=",
"os",
".",
"linesep",
")",
":",
"maxwidth",
"=",
"0",
"col1",
"=",
"[",
"]",
"col2",
"=",
"[",
"]",
"for",
"dependency",
"in",
"deps",
":",
"title1",
"=",
"dependency",
".",
"m... | Return a status of dependencies | [
"Return",
"a",
"status",
"of",
"dependencies"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/dependencies.py#L87-L101 |
31,076 | spyder-ide/spyder | spyder/dependencies.py | Dependency.check | def check(self):
"""Check if dependency is installed"""
return programs.is_module_installed(self.modname,
self.required_version,
self.installed_version) | python | def check(self):
"""Check if dependency is installed"""
return programs.is_module_installed(self.modname,
self.required_version,
self.installed_version) | [
"def",
"check",
"(",
"self",
")",
":",
"return",
"programs",
".",
"is_module_installed",
"(",
"self",
".",
"modname",
",",
"self",
".",
"required_version",
",",
"self",
".",
"installed_version",
")"
] | Check if dependency is installed | [
"Check",
"if",
"dependency",
"is",
"installed"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/dependencies.py#L42-L46 |
31,077 | spyder-ide/spyder | spyder/otherplugins.py | get_spyderplugins_mods | def get_spyderplugins_mods(io=False):
"""Import modules from plugins package and return the list"""
# Create user directory
user_plugin_path = osp.join(get_conf_path(), USER_PLUGIN_DIR)
if not osp.isdir(user_plugin_path):
os.makedirs(user_plugin_path)
modlist, modnames = [], []
# The user plugins directory is given the priority when looking for modules
for plugin_path in [user_plugin_path] + sys.path:
_get_spyderplugins(plugin_path, io, modnames, modlist)
return modlist | python | def get_spyderplugins_mods(io=False):
"""Import modules from plugins package and return the list"""
# Create user directory
user_plugin_path = osp.join(get_conf_path(), USER_PLUGIN_DIR)
if not osp.isdir(user_plugin_path):
os.makedirs(user_plugin_path)
modlist, modnames = [], []
# The user plugins directory is given the priority when looking for modules
for plugin_path in [user_plugin_path] + sys.path:
_get_spyderplugins(plugin_path, io, modnames, modlist)
return modlist | [
"def",
"get_spyderplugins_mods",
"(",
"io",
"=",
"False",
")",
":",
"# Create user directory\r",
"user_plugin_path",
"=",
"osp",
".",
"join",
"(",
"get_conf_path",
"(",
")",
",",
"USER_PLUGIN_DIR",
")",
"if",
"not",
"osp",
".",
"isdir",
"(",
"user_plugin_path",
... | Import modules from plugins package and return the list | [
"Import",
"modules",
"from",
"plugins",
"package",
"and",
"return",
"the",
"list"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/otherplugins.py#L31-L43 |
31,078 | spyder-ide/spyder | spyder/otherplugins.py | _get_spyderplugins | def _get_spyderplugins(plugin_path, is_io, modnames, modlist):
"""Scan the directory `plugin_path` for plugin packages and loads them."""
if not osp.isdir(plugin_path):
return
for name in os.listdir(plugin_path):
# This is needed in order to register the spyder_io_hdf5 plugin.
# See issue 4487
# Is this a Spyder plugin?
if not name.startswith(PLUGIN_PREFIX):
continue
# Ensure right type of plugin
if is_io != name.startswith(IO_PREFIX):
continue
# Skip names that end in certain suffixes
forbidden_suffixes = ['dist-info', 'egg.info', 'egg-info', 'egg-link',
'kernels']
if any([name.endswith(s) for s in forbidden_suffixes]):
continue
# Import the plugin
_import_plugin(name, plugin_path, modnames, modlist) | python | def _get_spyderplugins(plugin_path, is_io, modnames, modlist):
"""Scan the directory `plugin_path` for plugin packages and loads them."""
if not osp.isdir(plugin_path):
return
for name in os.listdir(plugin_path):
# This is needed in order to register the spyder_io_hdf5 plugin.
# See issue 4487
# Is this a Spyder plugin?
if not name.startswith(PLUGIN_PREFIX):
continue
# Ensure right type of plugin
if is_io != name.startswith(IO_PREFIX):
continue
# Skip names that end in certain suffixes
forbidden_suffixes = ['dist-info', 'egg.info', 'egg-info', 'egg-link',
'kernels']
if any([name.endswith(s) for s in forbidden_suffixes]):
continue
# Import the plugin
_import_plugin(name, plugin_path, modnames, modlist) | [
"def",
"_get_spyderplugins",
"(",
"plugin_path",
",",
"is_io",
",",
"modnames",
",",
"modlist",
")",
":",
"if",
"not",
"osp",
".",
"isdir",
"(",
"plugin_path",
")",
":",
"return",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"plugin_path",
")",
":",
... | Scan the directory `plugin_path` for plugin packages and loads them. | [
"Scan",
"the",
"directory",
"plugin_path",
"for",
"plugin",
"packages",
"and",
"loads",
"them",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/otherplugins.py#L46-L69 |
31,079 | spyder-ide/spyder | spyder/otherplugins.py | _import_plugin | def _import_plugin(module_name, plugin_path, modnames, modlist):
"""Import the plugin `module_name` from `plugin_path`, add it to `modlist`
and adds its name to `modnames`.
"""
if module_name in modnames:
return
try:
# First add a mock module with the LOCALEPATH attribute so that the
# helper method can find the locale on import
mock = _ModuleMock()
mock.LOCALEPATH = osp.join(plugin_path, module_name, 'locale')
sys.modules[module_name] = mock
if osp.isdir(osp.join(plugin_path, module_name)):
module = _import_module_from_path(module_name, plugin_path)
else:
module = None
# Then restore the actual loaded module instead of the mock
if module and getattr(module, 'PLUGIN_CLASS', False):
sys.modules[module_name] = module
modlist.append(module)
modnames.append(module_name)
except Exception:
sys.stderr.write("ERROR: 3rd party plugin import failed for "
"`{0}`\n".format(module_name))
traceback.print_exc(file=sys.stderr) | python | def _import_plugin(module_name, plugin_path, modnames, modlist):
"""Import the plugin `module_name` from `plugin_path`, add it to `modlist`
and adds its name to `modnames`.
"""
if module_name in modnames:
return
try:
# First add a mock module with the LOCALEPATH attribute so that the
# helper method can find the locale on import
mock = _ModuleMock()
mock.LOCALEPATH = osp.join(plugin_path, module_name, 'locale')
sys.modules[module_name] = mock
if osp.isdir(osp.join(plugin_path, module_name)):
module = _import_module_from_path(module_name, plugin_path)
else:
module = None
# Then restore the actual loaded module instead of the mock
if module and getattr(module, 'PLUGIN_CLASS', False):
sys.modules[module_name] = module
modlist.append(module)
modnames.append(module_name)
except Exception:
sys.stderr.write("ERROR: 3rd party plugin import failed for "
"`{0}`\n".format(module_name))
traceback.print_exc(file=sys.stderr) | [
"def",
"_import_plugin",
"(",
"module_name",
",",
"plugin_path",
",",
"modnames",
",",
"modlist",
")",
":",
"if",
"module_name",
"in",
"modnames",
":",
"return",
"try",
":",
"# First add a mock module with the LOCALEPATH attribute so that the\r",
"# helper method can find t... | Import the plugin `module_name` from `plugin_path`, add it to `modlist`
and adds its name to `modnames`. | [
"Import",
"the",
"plugin",
"module_name",
"from",
"plugin_path",
"add",
"it",
"to",
"modlist",
"and",
"adds",
"its",
"name",
"to",
"modnames",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/otherplugins.py#L72-L98 |
31,080 | spyder-ide/spyder | spyder/otherplugins.py | _import_module_from_path | def _import_module_from_path(module_name, plugin_path):
"""Imports `module_name` from `plugin_path`.
Return None if no module is found.
"""
module = None
try:
if PY2:
info = imp.find_module(module_name, [plugin_path])
if info:
module = imp.load_module(module_name, *info)
else: # Python 3.4+
spec = importlib.machinery.PathFinder.find_spec(
module_name,
[plugin_path])
if spec:
module = spec.loader.load_module(module_name)
except Exception:
pass
return module | python | def _import_module_from_path(module_name, plugin_path):
"""Imports `module_name` from `plugin_path`.
Return None if no module is found.
"""
module = None
try:
if PY2:
info = imp.find_module(module_name, [plugin_path])
if info:
module = imp.load_module(module_name, *info)
else: # Python 3.4+
spec = importlib.machinery.PathFinder.find_spec(
module_name,
[plugin_path])
if spec:
module = spec.loader.load_module(module_name)
except Exception:
pass
return module | [
"def",
"_import_module_from_path",
"(",
"module_name",
",",
"plugin_path",
")",
":",
"module",
"=",
"None",
"try",
":",
"if",
"PY2",
":",
"info",
"=",
"imp",
".",
"find_module",
"(",
"module_name",
",",
"[",
"plugin_path",
"]",
")",
"if",
"info",
":",
"m... | Imports `module_name` from `plugin_path`.
Return None if no module is found. | [
"Imports",
"module_name",
"from",
"plugin_path",
".",
"Return",
"None",
"if",
"no",
"module",
"is",
"found",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/otherplugins.py#L101-L121 |
31,081 | spyder-ide/spyder | spyder/utils/icon_manager.py | get_icon | def get_icon(name, default=None, resample=False):
"""Return image inside a QIcon object.
default: default image name or icon
resample: if True, manually resample icon pixmaps for usual sizes
(16, 24, 32, 48, 96, 128, 256). This is recommended for QMainWindow icons
created from SVG images on non-Windows platforms due to a Qt bug (see
Issue 1314).
"""
icon_path = get_image_path(name, default=None)
if icon_path is not None:
icon = QIcon(icon_path)
elif isinstance(default, QIcon):
icon = default
elif default is None:
try:
icon = get_std_icon(name[:-4])
except AttributeError:
icon = QIcon(get_image_path(name, default))
else:
icon = QIcon(get_image_path(name, default))
if resample:
icon0 = QIcon()
for size in (16, 24, 32, 48, 96, 128, 256, 512):
icon0.addPixmap(icon.pixmap(size, size))
return icon0
else:
return icon | python | def get_icon(name, default=None, resample=False):
"""Return image inside a QIcon object.
default: default image name or icon
resample: if True, manually resample icon pixmaps for usual sizes
(16, 24, 32, 48, 96, 128, 256). This is recommended for QMainWindow icons
created from SVG images on non-Windows platforms due to a Qt bug (see
Issue 1314).
"""
icon_path = get_image_path(name, default=None)
if icon_path is not None:
icon = QIcon(icon_path)
elif isinstance(default, QIcon):
icon = default
elif default is None:
try:
icon = get_std_icon(name[:-4])
except AttributeError:
icon = QIcon(get_image_path(name, default))
else:
icon = QIcon(get_image_path(name, default))
if resample:
icon0 = QIcon()
for size in (16, 24, 32, 48, 96, 128, 256, 512):
icon0.addPixmap(icon.pixmap(size, size))
return icon0
else:
return icon | [
"def",
"get_icon",
"(",
"name",
",",
"default",
"=",
"None",
",",
"resample",
"=",
"False",
")",
":",
"icon_path",
"=",
"get_image_path",
"(",
"name",
",",
"default",
"=",
"None",
")",
"if",
"icon_path",
"is",
"not",
"None",
":",
"icon",
"=",
"QIcon",
... | Return image inside a QIcon object.
default: default image name or icon
resample: if True, manually resample icon pixmaps for usual sizes
(16, 24, 32, 48, 96, 128, 256). This is recommended for QMainWindow icons
created from SVG images on non-Windows platforms due to a Qt bug (see
Issue 1314). | [
"Return",
"image",
"inside",
"a",
"QIcon",
"object",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/icon_manager.py#L358-L386 |
31,082 | spyder-ide/spyder | spyder/utils/icon_manager.py | get_icon_by_extension | def get_icon_by_extension(fname, scale_factor):
"""Return the icon depending on the file extension"""
application_icons = {}
application_icons.update(BIN_FILES)
application_icons.update(DOCUMENT_FILES)
if osp.isdir(fname):
return icon('DirOpenIcon', scale_factor)
else:
basename = osp.basename(fname)
__, extension = osp.splitext(basename.lower())
mime_type, __ = mime.guess_type(basename)
icon_by_extension = icon('FileIcon', scale_factor)
if extension in OFFICE_FILES:
icon_by_extension = icon(OFFICE_FILES[extension], scale_factor)
if extension in LANGUAGE_ICONS:
icon_by_extension = icon(LANGUAGE_ICONS[extension], scale_factor)
else:
if extension == '.ipynb':
if is_dark_interface():
icon_by_extension = QIcon(
get_image_path('notebook_dark.svg'))
else:
icon_by_extension = QIcon(
get_image_path('notebook_light.svg'))
elif mime_type is not None:
try:
# Fix for issue 5080. Even though
# mimetypes.guess_type documentation states that
# the return value will be None or a tuple of
# the form type/subtype, in the Windows registry,
# .sql has a mimetype of text\plain
# instead of text/plain therefore mimetypes is
# returning it incorrectly.
file_type, bin_name = mime_type.split('/')
except ValueError:
file_type = 'text'
if file_type == 'text':
icon_by_extension = icon('TextFileIcon', scale_factor)
elif file_type == 'audio':
icon_by_extension = icon('AudioFileIcon', scale_factor)
elif file_type == 'video':
icon_by_extension = icon('VideoFileIcon', scale_factor)
elif file_type == 'image':
icon_by_extension = icon('ImageFileIcon', scale_factor)
elif file_type == 'application':
if bin_name in application_icons:
icon_by_extension = icon(
application_icons[bin_name], scale_factor)
return icon_by_extension | python | def get_icon_by_extension(fname, scale_factor):
"""Return the icon depending on the file extension"""
application_icons = {}
application_icons.update(BIN_FILES)
application_icons.update(DOCUMENT_FILES)
if osp.isdir(fname):
return icon('DirOpenIcon', scale_factor)
else:
basename = osp.basename(fname)
__, extension = osp.splitext(basename.lower())
mime_type, __ = mime.guess_type(basename)
icon_by_extension = icon('FileIcon', scale_factor)
if extension in OFFICE_FILES:
icon_by_extension = icon(OFFICE_FILES[extension], scale_factor)
if extension in LANGUAGE_ICONS:
icon_by_extension = icon(LANGUAGE_ICONS[extension], scale_factor)
else:
if extension == '.ipynb':
if is_dark_interface():
icon_by_extension = QIcon(
get_image_path('notebook_dark.svg'))
else:
icon_by_extension = QIcon(
get_image_path('notebook_light.svg'))
elif mime_type is not None:
try:
# Fix for issue 5080. Even though
# mimetypes.guess_type documentation states that
# the return value will be None or a tuple of
# the form type/subtype, in the Windows registry,
# .sql has a mimetype of text\plain
# instead of text/plain therefore mimetypes is
# returning it incorrectly.
file_type, bin_name = mime_type.split('/')
except ValueError:
file_type = 'text'
if file_type == 'text':
icon_by_extension = icon('TextFileIcon', scale_factor)
elif file_type == 'audio':
icon_by_extension = icon('AudioFileIcon', scale_factor)
elif file_type == 'video':
icon_by_extension = icon('VideoFileIcon', scale_factor)
elif file_type == 'image':
icon_by_extension = icon('ImageFileIcon', scale_factor)
elif file_type == 'application':
if bin_name in application_icons:
icon_by_extension = icon(
application_icons[bin_name], scale_factor)
return icon_by_extension | [
"def",
"get_icon_by_extension",
"(",
"fname",
",",
"scale_factor",
")",
":",
"application_icons",
"=",
"{",
"}",
"application_icons",
".",
"update",
"(",
"BIN_FILES",
")",
"application_icons",
".",
"update",
"(",
"DOCUMENT_FILES",
")",
"if",
"osp",
".",
"isdir",... | Return the icon depending on the file extension | [
"Return",
"the",
"icon",
"depending",
"on",
"the",
"file",
"extension"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/icon_manager.py#L409-L459 |
31,083 | spyder-ide/spyder | spyder/plugins/editor/widgets/autosaveerror.py | AutosaveErrorDialog.accept | def accept(self):
"""
Update `show_errors` and hide dialog box.
Overrides method of `QDialogBox`.
"""
AutosaveErrorDialog.show_errors = not self.dismiss_box.isChecked()
return QDialog.accept(self) | python | def accept(self):
"""
Update `show_errors` and hide dialog box.
Overrides method of `QDialogBox`.
"""
AutosaveErrorDialog.show_errors = not self.dismiss_box.isChecked()
return QDialog.accept(self) | [
"def",
"accept",
"(",
"self",
")",
":",
"AutosaveErrorDialog",
".",
"show_errors",
"=",
"not",
"self",
".",
"dismiss_box",
".",
"isChecked",
"(",
")",
"return",
"QDialog",
".",
"accept",
"(",
"self",
")"
] | Update `show_errors` and hide dialog box.
Overrides method of `QDialogBox`. | [
"Update",
"show_errors",
"and",
"hide",
"dialog",
"box",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/autosaveerror.py#L78-L85 |
31,084 | spyder-ide/spyder | spyder/widgets/onecolumntree.py | OneColumnTree.get_menu_actions | def get_menu_actions(self):
"""Returns a list of menu actions"""
items = self.selectedItems()
actions = self.get_actions_from_items(items)
if actions:
actions.append(None)
actions += self.common_actions
return actions | python | def get_menu_actions(self):
"""Returns a list of menu actions"""
items = self.selectedItems()
actions = self.get_actions_from_items(items)
if actions:
actions.append(None)
actions += self.common_actions
return actions | [
"def",
"get_menu_actions",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"selectedItems",
"(",
")",
"actions",
"=",
"self",
".",
"get_actions_from_items",
"(",
"items",
")",
"if",
"actions",
":",
"actions",
".",
"append",
"(",
"None",
")",
"actions",
... | Returns a list of menu actions | [
"Returns",
"a",
"list",
"of",
"menu",
"actions"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/onecolumntree.py#L76-L83 |
31,085 | spyder-ide/spyder | spyder/widgets/onecolumntree.py | OneColumnTree.item_selection_changed | def item_selection_changed(self):
"""Item selection has changed"""
is_selection = len(self.selectedItems()) > 0
self.expand_selection_action.setEnabled(is_selection)
self.collapse_selection_action.setEnabled(is_selection) | python | def item_selection_changed(self):
"""Item selection has changed"""
is_selection = len(self.selectedItems()) > 0
self.expand_selection_action.setEnabled(is_selection)
self.collapse_selection_action.setEnabled(is_selection) | [
"def",
"item_selection_changed",
"(",
"self",
")",
":",
"is_selection",
"=",
"len",
"(",
"self",
".",
"selectedItems",
"(",
")",
")",
">",
"0",
"self",
".",
"expand_selection_action",
".",
"setEnabled",
"(",
"is_selection",
")",
"self",
".",
"collapse_selectio... | Item selection has changed | [
"Item",
"selection",
"has",
"changed"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/onecolumntree.py#L139-L143 |
31,086 | spyder-ide/spyder | spyder/widgets/onecolumntree.py | OneColumnTree.sort_top_level_items | def sort_top_level_items(self, key):
"""Sorting tree wrt top level items"""
self.save_expanded_state()
items = sorted([self.takeTopLevelItem(0)
for index in range(self.topLevelItemCount())], key=key)
for index, item in enumerate(items):
self.insertTopLevelItem(index, item)
self.restore_expanded_state() | python | def sort_top_level_items(self, key):
"""Sorting tree wrt top level items"""
self.save_expanded_state()
items = sorted([self.takeTopLevelItem(0)
for index in range(self.topLevelItemCount())], key=key)
for index, item in enumerate(items):
self.insertTopLevelItem(index, item)
self.restore_expanded_state() | [
"def",
"sort_top_level_items",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"save_expanded_state",
"(",
")",
"items",
"=",
"sorted",
"(",
"[",
"self",
".",
"takeTopLevelItem",
"(",
"0",
")",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"topLevelIt... | Sorting tree wrt top level items | [
"Sorting",
"tree",
"wrt",
"top",
"level",
"items"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/onecolumntree.py#L204-L211 |
31,087 | spyder-ide/spyder | spyder/plugins/editor/api/folding.py | print_tree | def print_tree(editor, file=sys.stdout, print_blocks=False, return_list=False):
"""
Prints the editor fold tree to stdout, for debugging purpose.
:param editor: CodeEditor instance.
:param file: file handle where the tree will be printed. Default is stdout.
:param print_blocks: True to print all blocks, False to only print blocks
that are fold triggers
"""
output_list = []
block = editor.document().firstBlock()
while block.isValid():
trigger = TextBlockHelper().is_fold_trigger(block)
trigger_state = TextBlockHelper().is_collapsed(block)
lvl = TextBlockHelper().get_fold_lvl(block)
visible = 'V' if block.isVisible() else 'I'
if trigger:
trigger = '+' if trigger_state else '-'
if return_list:
output_list.append([block.blockNumber() + 1, lvl, visible])
else:
print('l%d:%s%s%s' %
(block.blockNumber() + 1, lvl, trigger, visible),
file=file)
elif print_blocks:
if return_list:
output_list.append([block.blockNumber() + 1, lvl, visible])
else:
print('l%d:%s%s' %
(block.blockNumber() + 1, lvl, visible), file=file)
block = block.next()
if return_list:
return output_list | python | def print_tree(editor, file=sys.stdout, print_blocks=False, return_list=False):
"""
Prints the editor fold tree to stdout, for debugging purpose.
:param editor: CodeEditor instance.
:param file: file handle where the tree will be printed. Default is stdout.
:param print_blocks: True to print all blocks, False to only print blocks
that are fold triggers
"""
output_list = []
block = editor.document().firstBlock()
while block.isValid():
trigger = TextBlockHelper().is_fold_trigger(block)
trigger_state = TextBlockHelper().is_collapsed(block)
lvl = TextBlockHelper().get_fold_lvl(block)
visible = 'V' if block.isVisible() else 'I'
if trigger:
trigger = '+' if trigger_state else '-'
if return_list:
output_list.append([block.blockNumber() + 1, lvl, visible])
else:
print('l%d:%s%s%s' %
(block.blockNumber() + 1, lvl, trigger, visible),
file=file)
elif print_blocks:
if return_list:
output_list.append([block.blockNumber() + 1, lvl, visible])
else:
print('l%d:%s%s' %
(block.blockNumber() + 1, lvl, visible), file=file)
block = block.next()
if return_list:
return output_list | [
"def",
"print_tree",
"(",
"editor",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"print_blocks",
"=",
"False",
",",
"return_list",
"=",
"False",
")",
":",
"output_list",
"=",
"[",
"]",
"block",
"=",
"editor",
".",
"document",
"(",
")",
".",
"firstBlock... | Prints the editor fold tree to stdout, for debugging purpose.
:param editor: CodeEditor instance.
:param file: file handle where the tree will be printed. Default is stdout.
:param print_blocks: True to print all blocks, False to only print blocks
that are fold triggers | [
"Prints",
"the",
"editor",
"fold",
"tree",
"to",
"stdout",
"for",
"debugging",
"purpose",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/api/folding.py#L29-L63 |
31,088 | spyder-ide/spyder | spyder/utils/environ.py | main | def main():
"""Run Windows environment variable editor"""
from spyder.utils.qthelpers import qapplication
app = qapplication()
if os.name == 'nt':
dialog = WinUserEnvDialog()
else:
dialog = EnvDialog()
dialog.show()
app.exec_() | python | def main():
"""Run Windows environment variable editor"""
from spyder.utils.qthelpers import qapplication
app = qapplication()
if os.name == 'nt':
dialog = WinUserEnvDialog()
else:
dialog = EnvDialog()
dialog.show()
app.exec_() | [
"def",
"main",
"(",
")",
":",
"from",
"spyder",
".",
"utils",
".",
"qthelpers",
"import",
"qapplication",
"app",
"=",
"qapplication",
"(",
")",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"dialog",
"=",
"WinUserEnvDialog",
"(",
")",
"else",
":",
"dialo... | Run Windows environment variable editor | [
"Run",
"Windows",
"environment",
"variable",
"editor"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/environ.py#L141-L150 |
31,089 | spyder-ide/spyder | spyder/widgets/arraybuilder.py | NumpyArrayInline.event | def event(self, event):
"""
Qt override.
This is needed to be able to intercept the Tab key press event.
"""
if event.type() == QEvent.KeyPress:
if (event.key() == Qt.Key_Tab or event.key() == Qt.Key_Space):
text = self.text()
cursor = self.cursorPosition()
# fix to include in "undo/redo" history
if cursor != 0 and text[cursor-1] == ' ':
text = text[:cursor-1] + ROW_SEPARATOR + ' ' +\
text[cursor:]
else:
text = text[:cursor] + ' ' + text[cursor:]
self.setCursorPosition(cursor)
self.setText(text)
self.setCursorPosition(cursor + 1)
return False
return QWidget.event(self, event) | python | def event(self, event):
"""
Qt override.
This is needed to be able to intercept the Tab key press event.
"""
if event.type() == QEvent.KeyPress:
if (event.key() == Qt.Key_Tab or event.key() == Qt.Key_Space):
text = self.text()
cursor = self.cursorPosition()
# fix to include in "undo/redo" history
if cursor != 0 and text[cursor-1] == ' ':
text = text[:cursor-1] + ROW_SEPARATOR + ' ' +\
text[cursor:]
else:
text = text[:cursor] + ' ' + text[cursor:]
self.setCursorPosition(cursor)
self.setText(text)
self.setCursorPosition(cursor + 1)
return False
return QWidget.event(self, event) | [
"def",
"event",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"type",
"(",
")",
"==",
"QEvent",
".",
"KeyPress",
":",
"if",
"(",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Tab",
"or",
"event",
".",
"key",
"(",
")",
"==",
... | Qt override.
This is needed to be able to intercept the Tab key press event. | [
"Qt",
"override",
".",
"This",
"is",
"needed",
"to",
"be",
"able",
"to",
"intercept",
"the",
"Tab",
"key",
"press",
"event",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L59-L79 |
31,090 | spyder-ide/spyder | spyder/widgets/arraybuilder.py | NumpyArrayTable.reset_headers | def reset_headers(self):
"""
Update the column and row numbering in the headers.
"""
rows = self.rowCount()
cols = self.columnCount()
for r in range(rows):
self.setVerticalHeaderItem(r, QTableWidgetItem(str(r)))
for c in range(cols):
self.setHorizontalHeaderItem(c, QTableWidgetItem(str(c)))
self.setColumnWidth(c, 40) | python | def reset_headers(self):
"""
Update the column and row numbering in the headers.
"""
rows = self.rowCount()
cols = self.columnCount()
for r in range(rows):
self.setVerticalHeaderItem(r, QTableWidgetItem(str(r)))
for c in range(cols):
self.setHorizontalHeaderItem(c, QTableWidgetItem(str(c)))
self.setColumnWidth(c, 40) | [
"def",
"reset_headers",
"(",
"self",
")",
":",
"rows",
"=",
"self",
".",
"rowCount",
"(",
")",
"cols",
"=",
"self",
".",
"columnCount",
"(",
")",
"for",
"r",
"in",
"range",
"(",
"rows",
")",
":",
"self",
".",
"setVerticalHeaderItem",
"(",
"r",
",",
... | Update the column and row numbering in the headers. | [
"Update",
"the",
"column",
"and",
"row",
"numbering",
"in",
"the",
"headers",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L124-L135 |
31,091 | spyder-ide/spyder | spyder/widgets/arraybuilder.py | NumpyArrayTable.text | def text(self):
"""
Return the entered array in a parseable form.
"""
text = []
rows = self.rowCount()
cols = self.columnCount()
# handle empty table case
if rows == 2 and cols == 2:
item = self.item(0, 0)
if item is None:
return ''
for r in range(rows - 1):
for c in range(cols - 1):
item = self.item(r, c)
if item is not None:
value = item.text()
else:
value = '0'
if not value.strip():
value = '0'
text.append(' ')
text.append(value)
text.append(ROW_SEPARATOR)
return ''.join(text[:-1]) | python | def text(self):
"""
Return the entered array in a parseable form.
"""
text = []
rows = self.rowCount()
cols = self.columnCount()
# handle empty table case
if rows == 2 and cols == 2:
item = self.item(0, 0)
if item is None:
return ''
for r in range(rows - 1):
for c in range(cols - 1):
item = self.item(r, c)
if item is not None:
value = item.text()
else:
value = '0'
if not value.strip():
value = '0'
text.append(' ')
text.append(value)
text.append(ROW_SEPARATOR)
return ''.join(text[:-1]) | [
"def",
"text",
"(",
"self",
")",
":",
"text",
"=",
"[",
"]",
"rows",
"=",
"self",
".",
"rowCount",
"(",
")",
"cols",
"=",
"self",
".",
"columnCount",
"(",
")",
"# handle empty table case\r",
"if",
"rows",
"==",
"2",
"and",
"cols",
"==",
"2",
":",
"... | Return the entered array in a parseable form. | [
"Return",
"the",
"entered",
"array",
"in",
"a",
"parseable",
"form",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L137-L166 |
31,092 | spyder-ide/spyder | spyder/widgets/arraybuilder.py | NumpyArrayDialog.event | def event(self, event):
"""
Qt Override.
Usefull when in line edit mode.
"""
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
return False
return QWidget.event(self, event) | python | def event(self, event):
"""
Qt Override.
Usefull when in line edit mode.
"""
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
return False
return QWidget.event(self, event) | [
"def",
"event",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"type",
"(",
")",
"==",
"QEvent",
".",
"KeyPress",
"and",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Tab",
":",
"return",
"False",
"return",
"QWidget",
".",
"event",... | Qt Override.
Usefull when in line edit mode. | [
"Qt",
"Override",
".",
"Usefull",
"when",
"in",
"line",
"edit",
"mode",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L287-L295 |
31,093 | spyder-ide/spyder | spyder/widgets/arraybuilder.py | NumpyArrayDialog.process_text | def process_text(self, array=True):
"""
Construct the text based on the entered content in the widget.
"""
if array:
prefix = 'np.array([['
else:
prefix = 'np.matrix([['
suffix = ']])'
values = self._widget.text().strip()
if values != '':
# cleans repeated spaces
exp = r'(\s*)' + ROW_SEPARATOR + r'(\s*)'
values = re.sub(exp, ROW_SEPARATOR, values)
values = re.sub(r"\s+", " ", values)
values = re.sub(r"]$", "", values)
values = re.sub(r"^\[", "", values)
values = re.sub(ROW_SEPARATOR + r'*$', '', values)
# replaces spaces by commas
values = values.replace(' ', ELEMENT_SEPARATOR)
# iterate to find number of rows and columns
new_values = []
rows = values.split(ROW_SEPARATOR)
nrows = len(rows)
ncols = []
for row in rows:
new_row = []
elements = row.split(ELEMENT_SEPARATOR)
ncols.append(len(elements))
for e in elements:
num = e
# replaces not defined values
if num in NAN_VALUES:
num = 'np.nan'
# Convert numbers to floating point
if self._force_float:
try:
num = str(float(e))
except:
pass
new_row.append(num)
new_values.append(ELEMENT_SEPARATOR.join(new_row))
new_values = ROW_SEPARATOR.join(new_values)
values = new_values
# Check validity
if len(set(ncols)) == 1:
self._valid = True
else:
self._valid = False
# Single rows are parsed as 1D arrays/matrices
if nrows == 1:
prefix = prefix[:-1]
suffix = suffix.replace("]])", "])")
# Fix offset
offset = self._offset
braces = BRACES.replace(' ', '\n' + ' '*(offset + len(prefix) - 1))
values = values.replace(ROW_SEPARATOR, braces)
text = "{0}{1}{2}".format(prefix, values, suffix)
self._text = text
else:
self._text = ''
self.update_warning() | python | def process_text(self, array=True):
"""
Construct the text based on the entered content in the widget.
"""
if array:
prefix = 'np.array([['
else:
prefix = 'np.matrix([['
suffix = ']])'
values = self._widget.text().strip()
if values != '':
# cleans repeated spaces
exp = r'(\s*)' + ROW_SEPARATOR + r'(\s*)'
values = re.sub(exp, ROW_SEPARATOR, values)
values = re.sub(r"\s+", " ", values)
values = re.sub(r"]$", "", values)
values = re.sub(r"^\[", "", values)
values = re.sub(ROW_SEPARATOR + r'*$', '', values)
# replaces spaces by commas
values = values.replace(' ', ELEMENT_SEPARATOR)
# iterate to find number of rows and columns
new_values = []
rows = values.split(ROW_SEPARATOR)
nrows = len(rows)
ncols = []
for row in rows:
new_row = []
elements = row.split(ELEMENT_SEPARATOR)
ncols.append(len(elements))
for e in elements:
num = e
# replaces not defined values
if num in NAN_VALUES:
num = 'np.nan'
# Convert numbers to floating point
if self._force_float:
try:
num = str(float(e))
except:
pass
new_row.append(num)
new_values.append(ELEMENT_SEPARATOR.join(new_row))
new_values = ROW_SEPARATOR.join(new_values)
values = new_values
# Check validity
if len(set(ncols)) == 1:
self._valid = True
else:
self._valid = False
# Single rows are parsed as 1D arrays/matrices
if nrows == 1:
prefix = prefix[:-1]
suffix = suffix.replace("]])", "])")
# Fix offset
offset = self._offset
braces = BRACES.replace(' ', '\n' + ' '*(offset + len(prefix) - 1))
values = values.replace(ROW_SEPARATOR, braces)
text = "{0}{1}{2}".format(prefix, values, suffix)
self._text = text
else:
self._text = ''
self.update_warning() | [
"def",
"process_text",
"(",
"self",
",",
"array",
"=",
"True",
")",
":",
"if",
"array",
":",
"prefix",
"=",
"'np.array([['",
"else",
":",
"prefix",
"=",
"'np.matrix([['",
"suffix",
"=",
"']])'",
"values",
"=",
"self",
".",
"_widget",
".",
"text",
"(",
... | Construct the text based on the entered content in the widget. | [
"Construct",
"the",
"text",
"based",
"on",
"the",
"entered",
"content",
"in",
"the",
"widget",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L297-L369 |
31,094 | spyder-ide/spyder | spyder/widgets/arraybuilder.py | NumpyArrayDialog.update_warning | def update_warning(self):
"""
Updates the icon and tip based on the validity of the array content.
"""
widget = self._button_warning
if not self.is_valid():
tip = _('Array dimensions not valid')
widget.setIcon(ima.icon('MessageBoxWarning'))
widget.setToolTip(tip)
QToolTip.showText(self._widget.mapToGlobal(QPoint(0, 5)), tip)
else:
self._button_warning.setToolTip('') | python | def update_warning(self):
"""
Updates the icon and tip based on the validity of the array content.
"""
widget = self._button_warning
if not self.is_valid():
tip = _('Array dimensions not valid')
widget.setIcon(ima.icon('MessageBoxWarning'))
widget.setToolTip(tip)
QToolTip.showText(self._widget.mapToGlobal(QPoint(0, 5)), tip)
else:
self._button_warning.setToolTip('') | [
"def",
"update_warning",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"_button_warning",
"if",
"not",
"self",
".",
"is_valid",
"(",
")",
":",
"tip",
"=",
"_",
"(",
"'Array dimensions not valid'",
")",
"widget",
".",
"setIcon",
"(",
"ima",
".",
"ico... | Updates the icon and tip based on the validity of the array content. | [
"Updates",
"the",
"icon",
"and",
"tip",
"based",
"on",
"the",
"validity",
"of",
"the",
"array",
"content",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L371-L382 |
31,095 | spyder-ide/spyder | spyder/preferences/general.py | MainConfigPage._save_lang | def _save_lang(self):
"""
Get selected language setting and save to language configuration file.
"""
for combobox, (option, _default) in list(self.comboboxes.items()):
if option == 'interface_language':
data = combobox.itemData(combobox.currentIndex())
value = from_qvariant(data, to_text_string)
break
try:
save_lang_conf(value)
self.set_option('interface_language', value)
except Exception:
QMessageBox.critical(
self, _("Error"),
_("We're sorry but the following error occurred while trying "
"to set your selected language:<br><br>"
"<tt>{}</tt>").format(traceback.format_exc()),
QMessageBox.Ok)
return | python | def _save_lang(self):
"""
Get selected language setting and save to language configuration file.
"""
for combobox, (option, _default) in list(self.comboboxes.items()):
if option == 'interface_language':
data = combobox.itemData(combobox.currentIndex())
value = from_qvariant(data, to_text_string)
break
try:
save_lang_conf(value)
self.set_option('interface_language', value)
except Exception:
QMessageBox.critical(
self, _("Error"),
_("We're sorry but the following error occurred while trying "
"to set your selected language:<br><br>"
"<tt>{}</tt>").format(traceback.format_exc()),
QMessageBox.Ok)
return | [
"def",
"_save_lang",
"(",
"self",
")",
":",
"for",
"combobox",
",",
"(",
"option",
",",
"_default",
")",
"in",
"list",
"(",
"self",
".",
"comboboxes",
".",
"items",
"(",
")",
")",
":",
"if",
"option",
"==",
"'interface_language'",
":",
"data",
"=",
"... | Get selected language setting and save to language configuration file. | [
"Get",
"selected",
"language",
"setting",
"and",
"save",
"to",
"language",
"configuration",
"file",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/general.py#L262-L281 |
31,096 | spyder-ide/spyder | spyder/plugins/projects/widgets/projectdialog.py | is_writable | def is_writable(path):
"""Check if path has write access"""
try:
testfile = tempfile.TemporaryFile(dir=path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES: # 13
return False
return True | python | def is_writable(path):
"""Check if path has write access"""
try:
testfile = tempfile.TemporaryFile(dir=path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES: # 13
return False
return True | [
"def",
"is_writable",
"(",
"path",
")",
":",
"try",
":",
"testfile",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
"dir",
"=",
"path",
")",
"testfile",
".",
"close",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",... | Check if path has write access | [
"Check",
"if",
"path",
"has",
"write",
"access"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/widgets/projectdialog.py#L35-L43 |
31,097 | spyder-ide/spyder | spyder/plugins/projects/widgets/projectdialog.py | ProjectDialog._get_project_types | def _get_project_types(self):
"""Get all available project types."""
project_types = get_available_project_types()
projects = []
for project in project_types:
projects.append(project.PROJECT_TYPE_NAME)
return projects | python | def _get_project_types(self):
"""Get all available project types."""
project_types = get_available_project_types()
projects = []
for project in project_types:
projects.append(project.PROJECT_TYPE_NAME)
return projects | [
"def",
"_get_project_types",
"(",
"self",
")",
":",
"project_types",
"=",
"get_available_project_types",
"(",
")",
"projects",
"=",
"[",
"]",
"for",
"project",
"in",
"project_types",
":",
"projects",
".",
"append",
"(",
"project",
".",
"PROJECT_TYPE_NAME",
")",
... | Get all available project types. | [
"Get",
"all",
"available",
"project",
"types",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/widgets/projectdialog.py#L143-L151 |
31,098 | spyder-ide/spyder | spyder/plugins/projects/widgets/projectdialog.py | ProjectDialog.select_location | def select_location(self):
"""Select directory."""
location = osp.normpath(getexistingdirectory(self,
_("Select directory"),
self.location))
if location:
if is_writable(location):
self.location = location
self.update_location() | python | def select_location(self):
"""Select directory."""
location = osp.normpath(getexistingdirectory(self,
_("Select directory"),
self.location))
if location:
if is_writable(location):
self.location = location
self.update_location() | [
"def",
"select_location",
"(",
"self",
")",
":",
"location",
"=",
"osp",
".",
"normpath",
"(",
"getexistingdirectory",
"(",
"self",
",",
"_",
"(",
"\"Select directory\"",
")",
",",
"self",
".",
"location",
")",
")",
"if",
"location",
":",
"if",
"is_writabl... | Select directory. | [
"Select",
"directory",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/widgets/projectdialog.py#L153-L162 |
31,099 | spyder-ide/spyder | spyder/plugins/projects/widgets/projectdialog.py | ProjectDialog.update_location | def update_location(self, text=''):
"""Update text of location."""
self.text_project_name.setEnabled(self.radio_new_dir.isChecked())
name = self.text_project_name.text().strip()
if name and self.radio_new_dir.isChecked():
path = osp.join(self.location, name)
self.button_create.setDisabled(os.path.isdir(path))
elif self.radio_from_dir.isChecked():
self.button_create.setEnabled(True)
path = self.location
else:
self.button_create.setEnabled(False)
path = self.location
self.text_location.setText(path) | python | def update_location(self, text=''):
"""Update text of location."""
self.text_project_name.setEnabled(self.radio_new_dir.isChecked())
name = self.text_project_name.text().strip()
if name and self.radio_new_dir.isChecked():
path = osp.join(self.location, name)
self.button_create.setDisabled(os.path.isdir(path))
elif self.radio_from_dir.isChecked():
self.button_create.setEnabled(True)
path = self.location
else:
self.button_create.setEnabled(False)
path = self.location
self.text_location.setText(path) | [
"def",
"update_location",
"(",
"self",
",",
"text",
"=",
"''",
")",
":",
"self",
".",
"text_project_name",
".",
"setEnabled",
"(",
"self",
".",
"radio_new_dir",
".",
"isChecked",
"(",
")",
")",
"name",
"=",
"self",
".",
"text_project_name",
".",
"text",
... | Update text of location. | [
"Update",
"text",
"of",
"location",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/widgets/projectdialog.py#L164-L179 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.