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,500
spyder-ide/spyder
spyder/plugins/editor/widgets/codeeditor.py
get_file_language
def get_file_language(filename, text=None): """Get file language from filename""" ext = osp.splitext(filename)[1] if ext.startswith('.'): ext = ext[1:] # file extension with leading dot language = ext if not ext: if text is None: text, _enc = encoding.read(filename) for line in text.splitlines(): if not line.strip(): continue if line.startswith('#!'): shebang = line[2:] if 'python' in shebang: language = 'python' else: break return language
python
def get_file_language(filename, text=None): """Get file language from filename""" ext = osp.splitext(filename)[1] if ext.startswith('.'): ext = ext[1:] # file extension with leading dot language = ext if not ext: if text is None: text, _enc = encoding.read(filename) for line in text.splitlines(): if not line.strip(): continue if line.startswith('#!'): shebang = line[2:] if 'python' in shebang: language = 'python' else: break return language
[ "def", "get_file_language", "(", "filename", ",", "text", "=", "None", ")", ":", "ext", "=", "osp", ".", "splitext", "(", "filename", ")", "[", "1", "]", "if", "ext", ".", "startswith", "(", "'.'", ")", ":", "ext", "=", "ext", "[", "1", ":", "]",...
Get file language from filename
[ "Get", "file", "language", "from", "filename" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/codeeditor.py#L175-L193
31,501
spyder-ide/spyder
spyder/plugins/editor/widgets/codeeditor.py
GoToLineDialog.text_has_changed
def text_has_changed(self, text): """Line edit's text has changed""" text = to_text_string(text) if text: self.lineno = int(text) else: self.lineno = None
python
def text_has_changed(self, text): """Line edit's text has changed""" text = to_text_string(text) if text: self.lineno = int(text) else: self.lineno = None
[ "def", "text_has_changed", "(", "self", ",", "text", ")", ":", "text", "=", "to_text_string", "(", "text", ")", "if", "text", ":", "self", ".", "lineno", "=", "int", "(", "text", ")", "else", ":", "self", ".", "lineno", "=", "None" ]
Line edit's text has changed
[ "Line", "edit", "s", "text", "has", "changed" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/codeeditor.py#L157-L163
31,502
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
save_figure_tofile
def save_figure_tofile(fig, fmt, fname): """Save fig to fname in the format specified by fmt.""" root, ext = osp.splitext(fname) if ext == '.png' and fmt == 'image/svg+xml': qimg = svg_to_image(fig) qimg.save(fname) else: if fmt == 'image/svg+xml' and is_unicode(fig): fig = fig.encode('utf-8') with open(fname, 'wb') as f: f.write(fig)
python
def save_figure_tofile(fig, fmt, fname): """Save fig to fname in the format specified by fmt.""" root, ext = osp.splitext(fname) if ext == '.png' and fmt == 'image/svg+xml': qimg = svg_to_image(fig) qimg.save(fname) else: if fmt == 'image/svg+xml' and is_unicode(fig): fig = fig.encode('utf-8') with open(fname, 'wb') as f: f.write(fig)
[ "def", "save_figure_tofile", "(", "fig", ",", "fmt", ",", "fname", ")", ":", "root", ",", "ext", "=", "osp", ".", "splitext", "(", "fname", ")", "if", "ext", "==", "'.png'", "and", "fmt", "==", "'image/svg+xml'", ":", "qimg", "=", "svg_to_image", "(", ...
Save fig to fname in the format specified by fmt.
[ "Save", "fig", "to", "fname", "in", "the", "format", "specified", "by", "fmt", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L38-L49
31,503
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
get_unique_figname
def get_unique_figname(dirname, root, ext): """ Append a number to "root" to form a filename that does not already exist in "dirname". """ i = 1 figname = root + '_%d' % i + ext while True: if osp.exists(osp.join(dirname, figname)): i += 1 figname = root + '_%d' % i + ext else: return osp.join(dirname, figname)
python
def get_unique_figname(dirname, root, ext): """ Append a number to "root" to form a filename that does not already exist in "dirname". """ i = 1 figname = root + '_%d' % i + ext while True: if osp.exists(osp.join(dirname, figname)): i += 1 figname = root + '_%d' % i + ext else: return osp.join(dirname, figname)
[ "def", "get_unique_figname", "(", "dirname", ",", "root", ",", "ext", ")", ":", "i", "=", "1", "figname", "=", "root", "+", "'_%d'", "%", "i", "+", "ext", "while", "True", ":", "if", "osp", ".", "exists", "(", "osp", ".", "join", "(", "dirname", ...
Append a number to "root" to form a filename that does not already exist in "dirname".
[ "Append", "a", "number", "to", "root", "to", "form", "a", "filename", "that", "does", "not", "already", "exist", "in", "dirname", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L52-L64
31,504
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureBrowser.setup
def setup(self, mute_inline_plotting=None, show_plot_outline=None): """Setup the figure browser with provided settings.""" assert self.shellwidget is not None self.mute_inline_plotting = mute_inline_plotting self.show_plot_outline = show_plot_outline if self.figviewer is not None: self.mute_inline_action.setChecked(mute_inline_plotting) self.show_plot_outline_action.setChecked(show_plot_outline) return self.figviewer = FigureViewer(background_color=self.background_color) self.figviewer.setStyleSheet("FigureViewer{" "border: 1px solid lightgrey;" "border-top-width: 0px;" "border-bottom-width: 0px;" "border-left-width: 0px;" "}") self.thumbnails_sb = ThumbnailScrollBar( self.figviewer, background_color=self.background_color) # Option actions : self.setup_option_actions(mute_inline_plotting, show_plot_outline) # Create the layout : main_widget = QSplitter() main_widget.addWidget(self.figviewer) main_widget.addWidget(self.thumbnails_sb) main_widget.setFrameStyle(QScrollArea().frameStyle()) self.tools_layout = QHBoxLayout() toolbar = self.setup_toolbar() for widget in toolbar: self.tools_layout.addWidget(widget) self.tools_layout.addStretch() self.setup_options_button() layout = create_plugin_layout(self.tools_layout, main_widget) self.setLayout(layout)
python
def setup(self, mute_inline_plotting=None, show_plot_outline=None): """Setup the figure browser with provided settings.""" assert self.shellwidget is not None self.mute_inline_plotting = mute_inline_plotting self.show_plot_outline = show_plot_outline if self.figviewer is not None: self.mute_inline_action.setChecked(mute_inline_plotting) self.show_plot_outline_action.setChecked(show_plot_outline) return self.figviewer = FigureViewer(background_color=self.background_color) self.figviewer.setStyleSheet("FigureViewer{" "border: 1px solid lightgrey;" "border-top-width: 0px;" "border-bottom-width: 0px;" "border-left-width: 0px;" "}") self.thumbnails_sb = ThumbnailScrollBar( self.figviewer, background_color=self.background_color) # Option actions : self.setup_option_actions(mute_inline_plotting, show_plot_outline) # Create the layout : main_widget = QSplitter() main_widget.addWidget(self.figviewer) main_widget.addWidget(self.thumbnails_sb) main_widget.setFrameStyle(QScrollArea().frameStyle()) self.tools_layout = QHBoxLayout() toolbar = self.setup_toolbar() for widget in toolbar: self.tools_layout.addWidget(widget) self.tools_layout.addStretch() self.setup_options_button() layout = create_plugin_layout(self.tools_layout, main_widget) self.setLayout(layout)
[ "def", "setup", "(", "self", ",", "mute_inline_plotting", "=", "None", ",", "show_plot_outline", "=", "None", ")", ":", "assert", "self", ".", "shellwidget", "is", "not", "None", "self", ".", "mute_inline_plotting", "=", "mute_inline_plotting", "self", ".", "s...
Setup the figure browser with provided settings.
[ "Setup", "the", "figure", "browser", "with", "provided", "settings", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L97-L136
31,505
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureBrowser.setup_toolbar
def setup_toolbar(self): """Setup the toolbar""" savefig_btn = create_toolbutton( self, icon=ima.icon('filesave'), tip=_("Save Image As..."), triggered=self.save_figure) saveall_btn = create_toolbutton( self, icon=ima.icon('save_all'), tip=_("Save All Images..."), triggered=self.save_all_figures) copyfig_btn = create_toolbutton( self, icon=ima.icon('editcopy'), tip=_("Copy plot to clipboard as image (%s)" % get_shortcut('plots', 'copy')), triggered=self.copy_figure) closefig_btn = create_toolbutton( self, icon=ima.icon('editclear'), tip=_("Remove image"), triggered=self.close_figure) closeall_btn = create_toolbutton( self, icon=ima.icon('filecloseall'), tip=_("Remove all images from the explorer"), triggered=self.close_all_figures) vsep1 = QFrame() vsep1.setFrameStyle(53) goback_btn = create_toolbutton( self, icon=ima.icon('ArrowBack'), tip=_("Previous Figure ({})".format( get_shortcut('plots', 'previous figure'))), triggered=self.go_previous_thumbnail) gonext_btn = create_toolbutton( self, icon=ima.icon('ArrowForward'), tip=_("Next Figure ({})".format( get_shortcut('plots', 'next figure'))), triggered=self.go_next_thumbnail) vsep2 = QFrame() vsep2.setFrameStyle(53) zoom_out_btn = create_toolbutton( self, icon=ima.icon('zoom_out'), tip=_("Zoom out (Ctrl + mouse-wheel-down)"), triggered=self.zoom_out) zoom_in_btn = create_toolbutton( self, icon=ima.icon('zoom_in'), tip=_("Zoom in (Ctrl + mouse-wheel-up)"), triggered=self.zoom_in) self.zoom_disp = QSpinBox() self.zoom_disp.setAlignment(Qt.AlignCenter) self.zoom_disp.setButtonSymbols(QSpinBox.NoButtons) self.zoom_disp.setReadOnly(True) self.zoom_disp.setSuffix(' %') self.zoom_disp.setRange(0, 9999) self.zoom_disp.setValue(100) self.figviewer.sig_zoom_changed.connect(self.zoom_disp.setValue) zoom_pan = QWidget() layout = QHBoxLayout(zoom_pan) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(zoom_out_btn) layout.addWidget(zoom_in_btn) layout.addWidget(self.zoom_disp) return [savefig_btn, saveall_btn, copyfig_btn, closefig_btn, closeall_btn, vsep1, goback_btn, gonext_btn, vsep2, zoom_pan]
python
def setup_toolbar(self): """Setup the toolbar""" savefig_btn = create_toolbutton( self, icon=ima.icon('filesave'), tip=_("Save Image As..."), triggered=self.save_figure) saveall_btn = create_toolbutton( self, icon=ima.icon('save_all'), tip=_("Save All Images..."), triggered=self.save_all_figures) copyfig_btn = create_toolbutton( self, icon=ima.icon('editcopy'), tip=_("Copy plot to clipboard as image (%s)" % get_shortcut('plots', 'copy')), triggered=self.copy_figure) closefig_btn = create_toolbutton( self, icon=ima.icon('editclear'), tip=_("Remove image"), triggered=self.close_figure) closeall_btn = create_toolbutton( self, icon=ima.icon('filecloseall'), tip=_("Remove all images from the explorer"), triggered=self.close_all_figures) vsep1 = QFrame() vsep1.setFrameStyle(53) goback_btn = create_toolbutton( self, icon=ima.icon('ArrowBack'), tip=_("Previous Figure ({})".format( get_shortcut('plots', 'previous figure'))), triggered=self.go_previous_thumbnail) gonext_btn = create_toolbutton( self, icon=ima.icon('ArrowForward'), tip=_("Next Figure ({})".format( get_shortcut('plots', 'next figure'))), triggered=self.go_next_thumbnail) vsep2 = QFrame() vsep2.setFrameStyle(53) zoom_out_btn = create_toolbutton( self, icon=ima.icon('zoom_out'), tip=_("Zoom out (Ctrl + mouse-wheel-down)"), triggered=self.zoom_out) zoom_in_btn = create_toolbutton( self, icon=ima.icon('zoom_in'), tip=_("Zoom in (Ctrl + mouse-wheel-up)"), triggered=self.zoom_in) self.zoom_disp = QSpinBox() self.zoom_disp.setAlignment(Qt.AlignCenter) self.zoom_disp.setButtonSymbols(QSpinBox.NoButtons) self.zoom_disp.setReadOnly(True) self.zoom_disp.setSuffix(' %') self.zoom_disp.setRange(0, 9999) self.zoom_disp.setValue(100) self.figviewer.sig_zoom_changed.connect(self.zoom_disp.setValue) zoom_pan = QWidget() layout = QHBoxLayout(zoom_pan) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(zoom_out_btn) layout.addWidget(zoom_in_btn) layout.addWidget(self.zoom_disp) return [savefig_btn, saveall_btn, copyfig_btn, closefig_btn, closeall_btn, vsep1, goback_btn, gonext_btn, vsep2, zoom_pan]
[ "def", "setup_toolbar", "(", "self", ")", ":", "savefig_btn", "=", "create_toolbutton", "(", "self", ",", "icon", "=", "ima", ".", "icon", "(", "'filesave'", ")", ",", "tip", "=", "_", "(", "\"Save Image As...\"", ")", ",", "triggered", "=", "self", ".",...
Setup the toolbar
[ "Setup", "the", "toolbar" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L138-L212
31,506
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureBrowser.create_shortcuts
def create_shortcuts(self): """Create shortcuts for this widget.""" # Configurable copyfig = config_shortcut(self.copy_figure, context='plots', name='copy', parent=self) prevfig = config_shortcut(self.go_previous_thumbnail, context='plots', name='previous figure', parent=self) nextfig = config_shortcut(self.go_next_thumbnail, context='plots', name='next figure', parent=self) return [copyfig, prevfig, nextfig]
python
def create_shortcuts(self): """Create shortcuts for this widget.""" # Configurable copyfig = config_shortcut(self.copy_figure, context='plots', name='copy', parent=self) prevfig = config_shortcut(self.go_previous_thumbnail, context='plots', name='previous figure', parent=self) nextfig = config_shortcut(self.go_next_thumbnail, context='plots', name='next figure', parent=self) return [copyfig, prevfig, nextfig]
[ "def", "create_shortcuts", "(", "self", ")", ":", "# Configurable", "copyfig", "=", "config_shortcut", "(", "self", ".", "copy_figure", ",", "context", "=", "'plots'", ",", "name", "=", "'copy'", ",", "parent", "=", "self", ")", "prevfig", "=", "config_short...
Create shortcuts for this widget.
[ "Create", "shortcuts", "for", "this", "widget", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L255-L265
31,507
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureBrowser.option_changed
def option_changed(self, option, value): """Handle when the value of an option has changed""" setattr(self, to_text_string(option), value) self.shellwidget.set_namespace_view_settings() if self.setup_in_progress is False: self.sig_option_changed.emit(option, value)
python
def option_changed(self, option, value): """Handle when the value of an option has changed""" setattr(self, to_text_string(option), value) self.shellwidget.set_namespace_view_settings() if self.setup_in_progress is False: self.sig_option_changed.emit(option, value)
[ "def", "option_changed", "(", "self", ",", "option", ",", "value", ")", ":", "setattr", "(", "self", ",", "to_text_string", "(", "option", ")", ",", "value", ")", "self", ".", "shellwidget", ".", "set_namespace_view_settings", "(", ")", "if", "self", ".", ...
Handle when the value of an option has changed
[ "Handle", "when", "the", "value", "of", "an", "option", "has", "changed" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L277-L282
31,508
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureBrowser.show_fig_outline_in_viewer
def show_fig_outline_in_viewer(self, state): """Draw a frame around the figure viewer if state is True.""" if state is True: self.figviewer.figcanvas.setStyleSheet( "FigureCanvas{border: 1px solid lightgrey;}") else: self.figviewer.figcanvas.setStyleSheet("FigureCanvas{}") self.option_changed('show_plot_outline', state)
python
def show_fig_outline_in_viewer(self, state): """Draw a frame around the figure viewer if state is True.""" if state is True: self.figviewer.figcanvas.setStyleSheet( "FigureCanvas{border: 1px solid lightgrey;}") else: self.figviewer.figcanvas.setStyleSheet("FigureCanvas{}") self.option_changed('show_plot_outline', state)
[ "def", "show_fig_outline_in_viewer", "(", "self", ",", "state", ")", ":", "if", "state", "is", "True", ":", "self", ".", "figviewer", ".", "figcanvas", ".", "setStyleSheet", "(", "\"FigureCanvas{border: 1px solid lightgrey;}\"", ")", "else", ":", "self", ".", "f...
Draw a frame around the figure viewer if state is True.
[ "Draw", "a", "frame", "around", "the", "figure", "viewer", "if", "state", "is", "True", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L284-L291
31,509
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureBrowser.set_shellwidget
def set_shellwidget(self, shellwidget): """Bind the shellwidget instance to the figure browser""" self.shellwidget = shellwidget shellwidget.set_figurebrowser(self) shellwidget.sig_new_inline_figure.connect(self._handle_new_figure)
python
def set_shellwidget(self, shellwidget): """Bind the shellwidget instance to the figure browser""" self.shellwidget = shellwidget shellwidget.set_figurebrowser(self) shellwidget.sig_new_inline_figure.connect(self._handle_new_figure)
[ "def", "set_shellwidget", "(", "self", ",", "shellwidget", ")", ":", "self", ".", "shellwidget", "=", "shellwidget", "shellwidget", ".", "set_figurebrowser", "(", "self", ")", "shellwidget", ".", "sig_new_inline_figure", ".", "connect", "(", "self", ".", "_handl...
Bind the shellwidget instance to the figure browser
[ "Bind", "the", "shellwidget", "instance", "to", "the", "figure", "browser" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L293-L297
31,510
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureBrowser.copy_figure
def copy_figure(self): """Copy figure from figviewer to clipboard.""" if self.figviewer and self.figviewer.figcanvas.fig: self.figviewer.figcanvas.copy_figure()
python
def copy_figure(self): """Copy figure from figviewer to clipboard.""" if self.figviewer and self.figviewer.figcanvas.fig: self.figviewer.figcanvas.copy_figure()
[ "def", "copy_figure", "(", "self", ")", ":", "if", "self", ".", "figviewer", "and", "self", ".", "figviewer", ".", "figcanvas", ".", "fig", ":", "self", ".", "figviewer", ".", "figcanvas", ".", "copy_figure", "(", ")" ]
Copy figure from figviewer to clipboard.
[ "Copy", "figure", "from", "figviewer", "to", "clipboard", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L349-L352
31,511
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureViewer.setup_figcanvas
def setup_figcanvas(self): """Setup the FigureCanvas.""" self.figcanvas = FigureCanvas(background_color=self.background_color) self.figcanvas.installEventFilter(self) self.setWidget(self.figcanvas)
python
def setup_figcanvas(self): """Setup the FigureCanvas.""" self.figcanvas = FigureCanvas(background_color=self.background_color) self.figcanvas.installEventFilter(self) self.setWidget(self.figcanvas)
[ "def", "setup_figcanvas", "(", "self", ")", ":", "self", ".", "figcanvas", "=", "FigureCanvas", "(", "background_color", "=", "self", ".", "background_color", ")", "self", ".", "figcanvas", ".", "installEventFilter", "(", "self", ")", "self", ".", "setWidget",...
Setup the FigureCanvas.
[ "Setup", "the", "FigureCanvas", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L382-L386
31,512
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureViewer.load_figure
def load_figure(self, fig, fmt): """Set a new figure in the figure canvas.""" self.figcanvas.load_figure(fig, fmt) self.scale_image() self.figcanvas.repaint()
python
def load_figure(self, fig, fmt): """Set a new figure in the figure canvas.""" self.figcanvas.load_figure(fig, fmt) self.scale_image() self.figcanvas.repaint()
[ "def", "load_figure", "(", "self", ",", "fig", ",", "fmt", ")", ":", "self", ".", "figcanvas", ".", "load_figure", "(", "fig", ",", "fmt", ")", "self", ".", "scale_image", "(", ")", "self", ".", "figcanvas", ".", "repaint", "(", ")" ]
Set a new figure in the figure canvas.
[ "Set", "a", "new", "figure", "in", "the", "figure", "canvas", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L388-L392
31,513
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureViewer.eventFilter
def eventFilter(self, widget, event): """A filter to control the zooming and panning of the figure canvas.""" # ---- Zooming if event.type() == QEvent.Wheel: modifiers = QApplication.keyboardModifiers() if modifiers == Qt.ControlModifier: if event.angleDelta().y() > 0: self.zoom_in() else: self.zoom_out() return True else: return False # ---- Panning # Set ClosedHandCursor: elif event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: QApplication.setOverrideCursor(Qt.ClosedHandCursor) self._ispanning = True self.xclick = event.globalX() self.yclick = event.globalY() # Reset Cursor: elif event.type() == QEvent.MouseButtonRelease: QApplication.restoreOverrideCursor() self._ispanning = False # Move ScrollBar: elif event.type() == QEvent.MouseMove: if self._ispanning: dx = self.xclick - event.globalX() self.xclick = event.globalX() dy = self.yclick - event.globalY() self.yclick = event.globalY() scrollBarH = self.horizontalScrollBar() scrollBarH.setValue(scrollBarH.value() + dx) scrollBarV = self.verticalScrollBar() scrollBarV.setValue(scrollBarV.value() + dy) return QWidget.eventFilter(self, widget, event)
python
def eventFilter(self, widget, event): """A filter to control the zooming and panning of the figure canvas.""" # ---- Zooming if event.type() == QEvent.Wheel: modifiers = QApplication.keyboardModifiers() if modifiers == Qt.ControlModifier: if event.angleDelta().y() > 0: self.zoom_in() else: self.zoom_out() return True else: return False # ---- Panning # Set ClosedHandCursor: elif event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: QApplication.setOverrideCursor(Qt.ClosedHandCursor) self._ispanning = True self.xclick = event.globalX() self.yclick = event.globalY() # Reset Cursor: elif event.type() == QEvent.MouseButtonRelease: QApplication.restoreOverrideCursor() self._ispanning = False # Move ScrollBar: elif event.type() == QEvent.MouseMove: if self._ispanning: dx = self.xclick - event.globalX() self.xclick = event.globalX() dy = self.yclick - event.globalY() self.yclick = event.globalY() scrollBarH = self.horizontalScrollBar() scrollBarH.setValue(scrollBarH.value() + dx) scrollBarV = self.verticalScrollBar() scrollBarV.setValue(scrollBarV.value() + dy) return QWidget.eventFilter(self, widget, event)
[ "def", "eventFilter", "(", "self", ",", "widget", ",", "event", ")", ":", "# ---- Zooming", "if", "event", ".", "type", "(", ")", "==", "QEvent", ".", "Wheel", ":", "modifiers", "=", "QApplication", ".", "keyboardModifiers", "(", ")", "if", "modifiers", ...
A filter to control the zooming and panning of the figure canvas.
[ "A", "filter", "to", "control", "the", "zooming", "and", "panning", "of", "the", "figure", "canvas", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L394-L438
31,514
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureViewer.zoom_in
def zoom_in(self): """Scale the image up by one scale step.""" if self._scalefactor <= self._sfmax: self._scalefactor += 1 self.scale_image() self._adjust_scrollbar(self._scalestep) self.sig_zoom_changed.emit(self.get_scaling())
python
def zoom_in(self): """Scale the image up by one scale step.""" if self._scalefactor <= self._sfmax: self._scalefactor += 1 self.scale_image() self._adjust_scrollbar(self._scalestep) self.sig_zoom_changed.emit(self.get_scaling())
[ "def", "zoom_in", "(", "self", ")", ":", "if", "self", ".", "_scalefactor", "<=", "self", ".", "_sfmax", ":", "self", ".", "_scalefactor", "+=", "1", "self", ".", "scale_image", "(", ")", "self", ".", "_adjust_scrollbar", "(", "self", ".", "_scalestep", ...
Scale the image up by one scale step.
[ "Scale", "the", "image", "up", "by", "one", "scale", "step", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L441-L447
31,515
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureViewer.zoom_out
def zoom_out(self): """Scale the image down by one scale step.""" if self._scalefactor >= self._sfmin: self._scalefactor -= 1 self.scale_image() self._adjust_scrollbar(1/self._scalestep) self.sig_zoom_changed.emit(self.get_scaling())
python
def zoom_out(self): """Scale the image down by one scale step.""" if self._scalefactor >= self._sfmin: self._scalefactor -= 1 self.scale_image() self._adjust_scrollbar(1/self._scalestep) self.sig_zoom_changed.emit(self.get_scaling())
[ "def", "zoom_out", "(", "self", ")", ":", "if", "self", ".", "_scalefactor", ">=", "self", ".", "_sfmin", ":", "self", ".", "_scalefactor", "-=", "1", "self", ".", "scale_image", "(", ")", "self", ".", "_adjust_scrollbar", "(", "1", "/", "self", ".", ...
Scale the image down by one scale step.
[ "Scale", "the", "image", "down", "by", "one", "scale", "step", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L449-L455
31,516
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureViewer.scale_image
def scale_image(self): """Scale the image size.""" new_width = int(self.figcanvas.fwidth * self._scalestep ** self._scalefactor) new_height = int(self.figcanvas.fheight * self._scalestep ** self._scalefactor) self.figcanvas.setFixedSize(new_width, new_height)
python
def scale_image(self): """Scale the image size.""" new_width = int(self.figcanvas.fwidth * self._scalestep ** self._scalefactor) new_height = int(self.figcanvas.fheight * self._scalestep ** self._scalefactor) self.figcanvas.setFixedSize(new_width, new_height)
[ "def", "scale_image", "(", "self", ")", ":", "new_width", "=", "int", "(", "self", ".", "figcanvas", ".", "fwidth", "*", "self", ".", "_scalestep", "**", "self", ".", "_scalefactor", ")", "new_height", "=", "int", "(", "self", ".", "figcanvas", ".", "f...
Scale the image size.
[ "Scale", "the", "image", "size", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L457-L463
31,517
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureViewer._adjust_scrollbar
def _adjust_scrollbar(self, f): """ Adjust the scrollbar position to take into account the zooming of the figure. """ # Adjust horizontal scrollbar : hb = self.horizontalScrollBar() hb.setValue(int(f * hb.value() + ((f - 1) * hb.pageStep()/2))) # Adjust the vertical scrollbar : vb = self.verticalScrollBar() vb.setValue(int(f * vb.value() + ((f - 1) * vb.pageStep()/2)))
python
def _adjust_scrollbar(self, f): """ Adjust the scrollbar position to take into account the zooming of the figure. """ # Adjust horizontal scrollbar : hb = self.horizontalScrollBar() hb.setValue(int(f * hb.value() + ((f - 1) * hb.pageStep()/2))) # Adjust the vertical scrollbar : vb = self.verticalScrollBar() vb.setValue(int(f * vb.value() + ((f - 1) * vb.pageStep()/2)))
[ "def", "_adjust_scrollbar", "(", "self", ",", "f", ")", ":", "# Adjust horizontal scrollbar :", "hb", "=", "self", ".", "horizontalScrollBar", "(", ")", "hb", ".", "setValue", "(", "int", "(", "f", "*", "hb", ".", "value", "(", ")", "+", "(", "(", "f",...
Adjust the scrollbar position to take into account the zooming of the figure.
[ "Adjust", "the", "scrollbar", "position", "to", "take", "into", "account", "the", "zooming", "of", "the", "figure", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L474-L485
31,518
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.setup_scrollarea
def setup_scrollarea(self): """Setup the scrollarea that will contain the FigureThumbnails.""" self.view = QWidget() self.scene = QGridLayout(self.view) self.scene.setColumnStretch(0, 100) self.scene.setColumnStretch(2, 100) self.scrollarea = QScrollArea() self.scrollarea.setWidget(self.view) self.scrollarea.setWidgetResizable(True) self.scrollarea.setFrameStyle(0) self.scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollarea.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)) # Set the vertical scrollbar explicitely : # This is required to avoid a "RuntimeError: no access to protected # functions or signals for objects not created from Python" in Linux. self.scrollarea.setVerticalScrollBar(QScrollBar()) return self.scrollarea
python
def setup_scrollarea(self): """Setup the scrollarea that will contain the FigureThumbnails.""" self.view = QWidget() self.scene = QGridLayout(self.view) self.scene.setColumnStretch(0, 100) self.scene.setColumnStretch(2, 100) self.scrollarea = QScrollArea() self.scrollarea.setWidget(self.view) self.scrollarea.setWidgetResizable(True) self.scrollarea.setFrameStyle(0) self.scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollarea.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)) # Set the vertical scrollbar explicitely : # This is required to avoid a "RuntimeError: no access to protected # functions or signals for objects not created from Python" in Linux. self.scrollarea.setVerticalScrollBar(QScrollBar()) return self.scrollarea
[ "def", "setup_scrollarea", "(", "self", ")", ":", "self", ".", "view", "=", "QWidget", "(", ")", "self", ".", "scene", "=", "QGridLayout", "(", "self", ".", "view", ")", "self", ".", "scene", ".", "setColumnStretch", "(", "0", ",", "100", ")", "self"...
Setup the scrollarea that will contain the FigureThumbnails.
[ "Setup", "the", "scrollarea", "that", "will", "contain", "the", "FigureThumbnails", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L517-L539
31,519
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.setup_arrow_buttons
def setup_arrow_buttons(self): """ Setup the up and down arrow buttons that are placed at the top and bottom of the scrollarea. """ # Get the height of the up/down arrow of the default vertical # scrollbar : vsb = self.scrollarea.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) vsb_up_arrow = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarAddLine, self) # Setup the up and down arrow button : up_btn = up_btn = QPushButton(icon=ima.icon('last_edit_location')) up_btn.setFlat(True) up_btn.setFixedHeight(vsb_up_arrow.size().height()) up_btn.clicked.connect(self.go_up) down_btn = QPushButton(icon=ima.icon('folding.arrow_down_on')) down_btn.setFlat(True) down_btn.setFixedHeight(vsb_up_arrow.size().height()) down_btn.clicked.connect(self.go_down) return up_btn, down_btn
python
def setup_arrow_buttons(self): """ Setup the up and down arrow buttons that are placed at the top and bottom of the scrollarea. """ # Get the height of the up/down arrow of the default vertical # scrollbar : vsb = self.scrollarea.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) vsb_up_arrow = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarAddLine, self) # Setup the up and down arrow button : up_btn = up_btn = QPushButton(icon=ima.icon('last_edit_location')) up_btn.setFlat(True) up_btn.setFixedHeight(vsb_up_arrow.size().height()) up_btn.clicked.connect(self.go_up) down_btn = QPushButton(icon=ima.icon('folding.arrow_down_on')) down_btn.setFlat(True) down_btn.setFixedHeight(vsb_up_arrow.size().height()) down_btn.clicked.connect(self.go_down) return up_btn, down_btn
[ "def", "setup_arrow_buttons", "(", "self", ")", ":", "# Get the height of the up/down arrow of the default vertical", "# scrollbar :", "vsb", "=", "self", ".", "scrollarea", ".", "verticalScrollBar", "(", ")", "style", "=", "vsb", ".", "style", "(", ")", "opt", "=",...
Setup the up and down arrow buttons that are placed at the top and bottom of the scrollarea.
[ "Setup", "the", "up", "and", "down", "arrow", "buttons", "that", "are", "placed", "at", "the", "top", "and", "bottom", "of", "the", "scrollarea", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L541-L566
31,520
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.save_all_figures_as
def save_all_figures_as(self): """Save all the figures to a file.""" self.redirect_stdio.emit(False) dirname = getexistingdirectory(self, caption='Save all figures', basedir=getcwd_or_home()) self.redirect_stdio.emit(True) if dirname: return self.save_all_figures_todir(dirname)
python
def save_all_figures_as(self): """Save all the figures to a file.""" self.redirect_stdio.emit(False) dirname = getexistingdirectory(self, caption='Save all figures', basedir=getcwd_or_home()) self.redirect_stdio.emit(True) if dirname: return self.save_all_figures_todir(dirname)
[ "def", "save_all_figures_as", "(", "self", ")", ":", "self", ".", "redirect_stdio", ".", "emit", "(", "False", ")", "dirname", "=", "getexistingdirectory", "(", "self", ",", "caption", "=", "'Save all figures'", ",", "basedir", "=", "getcwd_or_home", "(", ")",...
Save all the figures to a file.
[ "Save", "all", "the", "figures", "to", "a", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L573-L580
31,521
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.save_all_figures_todir
def save_all_figures_todir(self, dirname): """Save all figure in dirname.""" fignames = [] for thumbnail in self._thumbnails: fig = thumbnail.canvas.fig fmt = thumbnail.canvas.fmt fext = {'image/png': '.png', 'image/jpeg': '.jpg', 'image/svg+xml': '.svg'}[fmt] figname = get_unique_figname(dirname, 'Figure', fext) save_figure_tofile(fig, fmt, figname) fignames.append(figname) return fignames
python
def save_all_figures_todir(self, dirname): """Save all figure in dirname.""" fignames = [] for thumbnail in self._thumbnails: fig = thumbnail.canvas.fig fmt = thumbnail.canvas.fmt fext = {'image/png': '.png', 'image/jpeg': '.jpg', 'image/svg+xml': '.svg'}[fmt] figname = get_unique_figname(dirname, 'Figure', fext) save_figure_tofile(fig, fmt, figname) fignames.append(figname) return fignames
[ "def", "save_all_figures_todir", "(", "self", ",", "dirname", ")", ":", "fignames", "=", "[", "]", "for", "thumbnail", "in", "self", ".", "_thumbnails", ":", "fig", "=", "thumbnail", ".", "canvas", ".", "fig", "fmt", "=", "thumbnail", ".", "canvas", ".",...
Save all figure in dirname.
[ "Save", "all", "figure", "in", "dirname", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L582-L595
31,522
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.save_current_figure_as
def save_current_figure_as(self): """Save the currently selected figure.""" if self.current_thumbnail is not None: self.save_figure_as(self.current_thumbnail.canvas.fig, self.current_thumbnail.canvas.fmt)
python
def save_current_figure_as(self): """Save the currently selected figure.""" if self.current_thumbnail is not None: self.save_figure_as(self.current_thumbnail.canvas.fig, self.current_thumbnail.canvas.fmt)
[ "def", "save_current_figure_as", "(", "self", ")", ":", "if", "self", ".", "current_thumbnail", "is", "not", "None", ":", "self", ".", "save_figure_as", "(", "self", ".", "current_thumbnail", ".", "canvas", ".", "fig", ",", "self", ".", "current_thumbnail", ...
Save the currently selected figure.
[ "Save", "the", "currently", "selected", "figure", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L597-L601
31,523
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.save_figure_as
def save_figure_as(self, fig, fmt): """Save the figure to a file.""" fext, ffilt = { 'image/png': ('.png', 'PNG (*.png)'), 'image/jpeg': ('.jpg', 'JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)'), 'image/svg+xml': ('.svg', 'SVG (*.svg);;PNG (*.png)')}[fmt] figname = get_unique_figname(getcwd_or_home(), 'Figure', fext) self.redirect_stdio.emit(False) fname, fext = getsavefilename( parent=self.parent(), caption='Save Figure', basedir=figname, filters=ffilt, selectedfilter='', options=None) self.redirect_stdio.emit(True) if fname: save_figure_tofile(fig, fmt, fname)
python
def save_figure_as(self, fig, fmt): """Save the figure to a file.""" fext, ffilt = { 'image/png': ('.png', 'PNG (*.png)'), 'image/jpeg': ('.jpg', 'JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)'), 'image/svg+xml': ('.svg', 'SVG (*.svg);;PNG (*.png)')}[fmt] figname = get_unique_figname(getcwd_or_home(), 'Figure', fext) self.redirect_stdio.emit(False) fname, fext = getsavefilename( parent=self.parent(), caption='Save Figure', basedir=figname, filters=ffilt, selectedfilter='', options=None) self.redirect_stdio.emit(True) if fname: save_figure_tofile(fig, fmt, fname)
[ "def", "save_figure_as", "(", "self", ",", "fig", ",", "fmt", ")", ":", "fext", ",", "ffilt", "=", "{", "'image/png'", ":", "(", "'.png'", ",", "'PNG (*.png)'", ")", ",", "'image/jpeg'", ":", "(", "'.jpg'", ",", "'JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)'", ")", "...
Save the figure to a file.
[ "Save", "the", "figure", "to", "a", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L603-L620
31,524
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.remove_all_thumbnails
def remove_all_thumbnails(self): """Remove all thumbnails.""" for thumbnail in self._thumbnails: self.layout().removeWidget(thumbnail) thumbnail.sig_canvas_clicked.disconnect() thumbnail.sig_remove_figure.disconnect() thumbnail.sig_save_figure.disconnect() thumbnail.deleteLater() self._thumbnails = [] self.current_thumbnail = None self.figure_viewer.figcanvas.clear_canvas()
python
def remove_all_thumbnails(self): """Remove all thumbnails.""" for thumbnail in self._thumbnails: self.layout().removeWidget(thumbnail) thumbnail.sig_canvas_clicked.disconnect() thumbnail.sig_remove_figure.disconnect() thumbnail.sig_save_figure.disconnect() thumbnail.deleteLater() self._thumbnails = [] self.current_thumbnail = None self.figure_viewer.figcanvas.clear_canvas()
[ "def", "remove_all_thumbnails", "(", "self", ")", ":", "for", "thumbnail", "in", "self", ".", "_thumbnails", ":", "self", ".", "layout", "(", ")", ".", "removeWidget", "(", "thumbnail", ")", "thumbnail", ".", "sig_canvas_clicked", ".", "disconnect", "(", ")"...
Remove all thumbnails.
[ "Remove", "all", "thumbnails", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L656-L666
31,525
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.remove_thumbnail
def remove_thumbnail(self, thumbnail): """Remove thumbnail.""" if thumbnail in self._thumbnails: index = self._thumbnails.index(thumbnail) self._thumbnails.remove(thumbnail) self.layout().removeWidget(thumbnail) thumbnail.deleteLater() thumbnail.sig_canvas_clicked.disconnect() thumbnail.sig_remove_figure.disconnect() thumbnail.sig_save_figure.disconnect() # Select a new thumbnail if any : if thumbnail == self.current_thumbnail: if len(self._thumbnails) > 0: self.set_current_index(min(index, len(self._thumbnails)-1)) else: self.current_thumbnail = None self.figure_viewer.figcanvas.clear_canvas()
python
def remove_thumbnail(self, thumbnail): """Remove thumbnail.""" if thumbnail in self._thumbnails: index = self._thumbnails.index(thumbnail) self._thumbnails.remove(thumbnail) self.layout().removeWidget(thumbnail) thumbnail.deleteLater() thumbnail.sig_canvas_clicked.disconnect() thumbnail.sig_remove_figure.disconnect() thumbnail.sig_save_figure.disconnect() # Select a new thumbnail if any : if thumbnail == self.current_thumbnail: if len(self._thumbnails) > 0: self.set_current_index(min(index, len(self._thumbnails)-1)) else: self.current_thumbnail = None self.figure_viewer.figcanvas.clear_canvas()
[ "def", "remove_thumbnail", "(", "self", ",", "thumbnail", ")", ":", "if", "thumbnail", "in", "self", ".", "_thumbnails", ":", "index", "=", "self", ".", "_thumbnails", ".", "index", "(", "thumbnail", ")", "self", ".", "_thumbnails", ".", "remove", "(", "...
Remove thumbnail.
[ "Remove", "thumbnail", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L668-L685
31,526
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.set_current_thumbnail
def set_current_thumbnail(self, thumbnail): """Set the currently selected thumbnail.""" self.current_thumbnail = thumbnail self.figure_viewer.load_figure( thumbnail.canvas.fig, thumbnail.canvas.fmt) for thumbnail in self._thumbnails: thumbnail.highlight_canvas(thumbnail == self.current_thumbnail)
python
def set_current_thumbnail(self, thumbnail): """Set the currently selected thumbnail.""" self.current_thumbnail = thumbnail self.figure_viewer.load_figure( thumbnail.canvas.fig, thumbnail.canvas.fmt) for thumbnail in self._thumbnails: thumbnail.highlight_canvas(thumbnail == self.current_thumbnail)
[ "def", "set_current_thumbnail", "(", "self", ",", "thumbnail", ")", ":", "self", ".", "current_thumbnail", "=", "thumbnail", "self", ".", "figure_viewer", ".", "load_figure", "(", "thumbnail", ".", "canvas", ".", "fig", ",", "thumbnail", ".", "canvas", ".", ...
Set the currently selected thumbnail.
[ "Set", "the", "currently", "selected", "thumbnail", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L698-L704
31,527
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.go_previous_thumbnail
def go_previous_thumbnail(self): """Select the thumbnail previous to the currently selected one.""" if self.current_thumbnail is not None: index = self._thumbnails.index(self.current_thumbnail) - 1 index = index if index >= 0 else len(self._thumbnails) - 1 self.set_current_index(index) self.scroll_to_item(index)
python
def go_previous_thumbnail(self): """Select the thumbnail previous to the currently selected one.""" if self.current_thumbnail is not None: index = self._thumbnails.index(self.current_thumbnail) - 1 index = index if index >= 0 else len(self._thumbnails) - 1 self.set_current_index(index) self.scroll_to_item(index)
[ "def", "go_previous_thumbnail", "(", "self", ")", ":", "if", "self", ".", "current_thumbnail", "is", "not", "None", ":", "index", "=", "self", ".", "_thumbnails", ".", "index", "(", "self", ".", "current_thumbnail", ")", "-", "1", "index", "=", "index", ...
Select the thumbnail previous to the currently selected one.
[ "Select", "the", "thumbnail", "previous", "to", "the", "currently", "selected", "one", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L706-L712
31,528
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.go_next_thumbnail
def go_next_thumbnail(self): """Select thumbnail next to the currently selected one.""" if self.current_thumbnail is not None: index = self._thumbnails.index(self.current_thumbnail) + 1 index = 0 if index >= len(self._thumbnails) else index self.set_current_index(index) self.scroll_to_item(index)
python
def go_next_thumbnail(self): """Select thumbnail next to the currently selected one.""" if self.current_thumbnail is not None: index = self._thumbnails.index(self.current_thumbnail) + 1 index = 0 if index >= len(self._thumbnails) else index self.set_current_index(index) self.scroll_to_item(index)
[ "def", "go_next_thumbnail", "(", "self", ")", ":", "if", "self", ".", "current_thumbnail", "is", "not", "None", ":", "index", "=", "self", ".", "_thumbnails", ".", "index", "(", "self", ".", "current_thumbnail", ")", "+", "1", "index", "=", "0", "if", ...
Select thumbnail next to the currently selected one.
[ "Select", "thumbnail", "next", "to", "the", "currently", "selected", "one", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L714-L720
31,529
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.scroll_to_item
def scroll_to_item(self, index): """Scroll to the selected item of ThumbnailScrollBar.""" spacing_between_items = self.scene.verticalSpacing() height_view = self.scrollarea.viewport().height() height_item = self.scene.itemAt(index).sizeHint().height() height_view_excluding_item = max(0, height_view - height_item) height_of_top_items = spacing_between_items for i in range(index): item = self.scene.itemAt(i) height_of_top_items += item.sizeHint().height() height_of_top_items += spacing_between_items pos_scroll = height_of_top_items - height_view_excluding_item // 2 vsb = self.scrollarea.verticalScrollBar() vsb.setValue(pos_scroll)
python
def scroll_to_item(self, index): """Scroll to the selected item of ThumbnailScrollBar.""" spacing_between_items = self.scene.verticalSpacing() height_view = self.scrollarea.viewport().height() height_item = self.scene.itemAt(index).sizeHint().height() height_view_excluding_item = max(0, height_view - height_item) height_of_top_items = spacing_between_items for i in range(index): item = self.scene.itemAt(i) height_of_top_items += item.sizeHint().height() height_of_top_items += spacing_between_items pos_scroll = height_of_top_items - height_view_excluding_item // 2 vsb = self.scrollarea.verticalScrollBar() vsb.setValue(pos_scroll)
[ "def", "scroll_to_item", "(", "self", ",", "index", ")", ":", "spacing_between_items", "=", "self", ".", "scene", ".", "verticalSpacing", "(", ")", "height_view", "=", "self", ".", "scrollarea", ".", "viewport", "(", ")", ".", "height", "(", ")", "height_i...
Scroll to the selected item of ThumbnailScrollBar.
[ "Scroll", "to", "the", "selected", "item", "of", "ThumbnailScrollBar", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L722-L738
31,530
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
ThumbnailScrollBar.go_up
def go_up(self): """Scroll the scrollbar of the scrollarea up by a single step.""" vsb = self.scrollarea.verticalScrollBar() vsb.setValue(int(vsb.value() - vsb.singleStep()))
python
def go_up(self): """Scroll the scrollbar of the scrollarea up by a single step.""" vsb = self.scrollarea.verticalScrollBar() vsb.setValue(int(vsb.value() - vsb.singleStep()))
[ "def", "go_up", "(", "self", ")", ":", "vsb", "=", "self", ".", "scrollarea", ".", "verticalScrollBar", "(", ")", "vsb", ".", "setValue", "(", "int", "(", "vsb", ".", "value", "(", ")", "-", "vsb", ".", "singleStep", "(", ")", ")", ")" ]
Scroll the scrollbar of the scrollarea up by a single step.
[ "Scroll", "the", "scrollbar", "of", "the", "scrollarea", "up", "by", "a", "single", "step", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L741-L744
31,531
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureThumbnail.setup_toolbar
def setup_toolbar(self): """Setup the toolbar.""" self.savefig_btn = create_toolbutton( self, icon=ima.icon('filesave'), tip=_("Save Image As..."), triggered=self.emit_save_figure) self.delfig_btn = create_toolbutton( self, icon=ima.icon('editclear'), tip=_("Delete image"), triggered=self.emit_remove_figure) toolbar = QVBoxLayout() toolbar.setContentsMargins(0, 0, 0, 0) toolbar.setSpacing(1) toolbar.addWidget(self.savefig_btn) toolbar.addWidget(self.delfig_btn) toolbar.addStretch(2) return toolbar
python
def setup_toolbar(self): """Setup the toolbar.""" self.savefig_btn = create_toolbutton( self, icon=ima.icon('filesave'), tip=_("Save Image As..."), triggered=self.emit_save_figure) self.delfig_btn = create_toolbutton( self, icon=ima.icon('editclear'), tip=_("Delete image"), triggered=self.emit_remove_figure) toolbar = QVBoxLayout() toolbar.setContentsMargins(0, 0, 0, 0) toolbar.setSpacing(1) toolbar.addWidget(self.savefig_btn) toolbar.addWidget(self.delfig_btn) toolbar.addStretch(2) return toolbar
[ "def", "setup_toolbar", "(", "self", ")", ":", "self", ".", "savefig_btn", "=", "create_toolbutton", "(", "self", ",", "icon", "=", "ima", ".", "icon", "(", "'filesave'", ")", ",", "tip", "=", "_", "(", "\"Save Image As...\"", ")", ",", "triggered", "=",...
Setup the toolbar.
[ "Setup", "the", "toolbar", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L778-L796
31,532
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureThumbnail.highlight_canvas
def highlight_canvas(self, highlight): """ Set a colored frame around the FigureCanvas if highlight is True. """ colorname = self.canvas.palette().highlight().color().name() if highlight: self.canvas.setStyleSheet( "FigureCanvas{border: 1px solid %s;}" % colorname) else: self.canvas.setStyleSheet("FigureCanvas{}")
python
def highlight_canvas(self, highlight): """ Set a colored frame around the FigureCanvas if highlight is True. """ colorname = self.canvas.palette().highlight().color().name() if highlight: self.canvas.setStyleSheet( "FigureCanvas{border: 1px solid %s;}" % colorname) else: self.canvas.setStyleSheet("FigureCanvas{}")
[ "def", "highlight_canvas", "(", "self", ",", "highlight", ")", ":", "colorname", "=", "self", ".", "canvas", ".", "palette", "(", ")", ".", "highlight", "(", ")", ".", "color", "(", ")", ".", "name", "(", ")", "if", "highlight", ":", "self", ".", "...
Set a colored frame around the FigureCanvas if highlight is True.
[ "Set", "a", "colored", "frame", "around", "the", "FigureCanvas", "if", "highlight", "is", "True", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L798-L807
31,533
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureThumbnail.eventFilter
def eventFilter(self, widget, event): """ A filter that is used to send a signal when the figure canvas is clicked. """ if event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: self.sig_canvas_clicked.emit(self) return super(FigureThumbnail, self).eventFilter(widget, event)
python
def eventFilter(self, widget, event): """ A filter that is used to send a signal when the figure canvas is clicked. """ if event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: self.sig_canvas_clicked.emit(self) return super(FigureThumbnail, self).eventFilter(widget, event)
[ "def", "eventFilter", "(", "self", ",", "widget", ",", "event", ")", ":", "if", "event", ".", "type", "(", ")", "==", "QEvent", ".", "MouseButtonPress", ":", "if", "event", ".", "button", "(", ")", "==", "Qt", ".", "LeftButton", ":", "self", ".", "...
A filter that is used to send a signal when the figure canvas is clicked.
[ "A", "filter", "that", "is", "used", "to", "send", "a", "signal", "when", "the", "figure", "canvas", "is", "clicked", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L809-L817
31,534
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureThumbnail.emit_save_figure
def emit_save_figure(self): """ Emit a signal when the toolbutton to save the figure is clicked. """ self.sig_save_figure.emit(self.canvas.fig, self.canvas.fmt)
python
def emit_save_figure(self): """ Emit a signal when the toolbutton to save the figure is clicked. """ self.sig_save_figure.emit(self.canvas.fig, self.canvas.fmt)
[ "def", "emit_save_figure", "(", "self", ")", ":", "self", ".", "sig_save_figure", ".", "emit", "(", "self", ".", "canvas", ".", "fig", ",", "self", ".", "canvas", ".", "fmt", ")" ]
Emit a signal when the toolbutton to save the figure is clicked.
[ "Emit", "a", "signal", "when", "the", "toolbutton", "to", "save", "the", "figure", "is", "clicked", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L819-L823
31,535
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureCanvas.context_menu_requested
def context_menu_requested(self, event): """Popup context menu.""" if self.fig: pos = QPoint(event.x(), event.y()) context_menu = QMenu(self) context_menu.addAction(ima.icon('editcopy'), "Copy Image", self.copy_figure, QKeySequence( get_shortcut('plots', 'copy'))) context_menu.popup(self.mapToGlobal(pos))
python
def context_menu_requested(self, event): """Popup context menu.""" if self.fig: pos = QPoint(event.x(), event.y()) context_menu = QMenu(self) context_menu.addAction(ima.icon('editcopy'), "Copy Image", self.copy_figure, QKeySequence( get_shortcut('plots', 'copy'))) context_menu.popup(self.mapToGlobal(pos))
[ "def", "context_menu_requested", "(", "self", ",", "event", ")", ":", "if", "self", ".", "fig", ":", "pos", "=", "QPoint", "(", "event", ".", "x", "(", ")", ",", "event", ".", "y", "(", ")", ")", "context_menu", "=", "QMenu", "(", "self", ")", "c...
Popup context menu.
[ "Popup", "context", "menu", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L853-L862
31,536
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureCanvas.copy_figure
def copy_figure(self): """Copy figure to clipboard.""" if self.fmt in ['image/png', 'image/jpeg']: qpixmap = QPixmap() qpixmap.loadFromData(self.fig, self.fmt.upper()) QApplication.clipboard().setImage(qpixmap.toImage()) elif self.fmt == 'image/svg+xml': svg_to_clipboard(self.fig) else: return self.blink_figure()
python
def copy_figure(self): """Copy figure to clipboard.""" if self.fmt in ['image/png', 'image/jpeg']: qpixmap = QPixmap() qpixmap.loadFromData(self.fig, self.fmt.upper()) QApplication.clipboard().setImage(qpixmap.toImage()) elif self.fmt == 'image/svg+xml': svg_to_clipboard(self.fig) else: return self.blink_figure()
[ "def", "copy_figure", "(", "self", ")", ":", "if", "self", ".", "fmt", "in", "[", "'image/png'", ",", "'image/jpeg'", "]", ":", "qpixmap", "=", "QPixmap", "(", ")", "qpixmap", ".", "loadFromData", "(", "self", ".", "fig", ",", "self", ".", "fmt", "."...
Copy figure to clipboard.
[ "Copy", "figure", "to", "clipboard", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L865-L876
31,537
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureCanvas.blink_figure
def blink_figure(self): """Blink figure once.""" if self.fig: self._blink_flag = not self._blink_flag self.repaint() if self._blink_flag: timer = QTimer() timer.singleShot(40, self.blink_figure)
python
def blink_figure(self): """Blink figure once.""" if self.fig: self._blink_flag = not self._blink_flag self.repaint() if self._blink_flag: timer = QTimer() timer.singleShot(40, self.blink_figure)
[ "def", "blink_figure", "(", "self", ")", ":", "if", "self", ".", "fig", ":", "self", ".", "_blink_flag", "=", "not", "self", ".", "_blink_flag", "self", ".", "repaint", "(", ")", "if", "self", ".", "_blink_flag", ":", "timer", "=", "QTimer", "(", ")"...
Blink figure once.
[ "Blink", "figure", "once", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L878-L885
31,538
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureCanvas.clear_canvas
def clear_canvas(self): """Clear the figure that was painted on the widget.""" self.fig = None self.fmt = None self._qpix_buffer = [] self.repaint()
python
def clear_canvas(self): """Clear the figure that was painted on the widget.""" self.fig = None self.fmt = None self._qpix_buffer = [] self.repaint()
[ "def", "clear_canvas", "(", "self", ")", ":", "self", ".", "fig", "=", "None", "self", ".", "fmt", "=", "None", "self", ".", "_qpix_buffer", "=", "[", "]", "self", ".", "repaint", "(", ")" ]
Clear the figure that was painted on the widget.
[ "Clear", "the", "figure", "that", "was", "painted", "on", "the", "widget", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L887-L892
31,539
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureCanvas.load_figure
def load_figure(self, fig, fmt): """ Load the figure from a png, jpg, or svg image, convert it in a QPixmap, and force a repaint of the widget. """ self.fig = fig self.fmt = fmt if fmt in ['image/png', 'image/jpeg']: self._qpix_orig = QPixmap() self._qpix_orig.loadFromData(fig, fmt.upper()) elif fmt == 'image/svg+xml': self._qpix_orig = QPixmap(svg_to_image(fig)) self._qpix_buffer = [self._qpix_orig] self.fwidth = self._qpix_orig.width() self.fheight = self._qpix_orig.height()
python
def load_figure(self, fig, fmt): """ Load the figure from a png, jpg, or svg image, convert it in a QPixmap, and force a repaint of the widget. """ self.fig = fig self.fmt = fmt if fmt in ['image/png', 'image/jpeg']: self._qpix_orig = QPixmap() self._qpix_orig.loadFromData(fig, fmt.upper()) elif fmt == 'image/svg+xml': self._qpix_orig = QPixmap(svg_to_image(fig)) self._qpix_buffer = [self._qpix_orig] self.fwidth = self._qpix_orig.width() self.fheight = self._qpix_orig.height()
[ "def", "load_figure", "(", "self", ",", "fig", ",", "fmt", ")", ":", "self", ".", "fig", "=", "fig", "self", ".", "fmt", "=", "fmt", "if", "fmt", "in", "[", "'image/png'", ",", "'image/jpeg'", "]", ":", "self", ".", "_qpix_orig", "=", "QPixmap", "(...
Load the figure from a png, jpg, or svg image, convert it in a QPixmap, and force a repaint of the widget.
[ "Load", "the", "figure", "from", "a", "png", "jpg", "or", "svg", "image", "convert", "it", "in", "a", "QPixmap", "and", "force", "a", "repaint", "of", "the", "widget", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L894-L910
31,540
spyder-ide/spyder
spyder/plugins/plots/widgets/figurebrowser.py
FigureCanvas.paintEvent
def paintEvent(self, event): """Qt method override to paint a custom image on the Widget.""" super(FigureCanvas, self).paintEvent(event) # Prepare the rect on which the image is going to be painted : fw = self.frameWidth() rect = QRect(0 + fw, 0 + fw, self.size().width() - 2 * fw, self.size().height() - 2 * fw) if self.fig is None or self._blink_flag: return # Check/update the qpixmap buffer : qpix2paint = None for qpix in self._qpix_buffer: if qpix.size().width() == rect.width(): qpix2paint = qpix break else: if self.fmt in ['image/png', 'image/jpeg']: qpix2paint = self._qpix_orig.scaledToWidth( rect.width(), mode=Qt.SmoothTransformation) elif self.fmt == 'image/svg+xml': qpix2paint = QPixmap(svg_to_image(self.fig, rect.size())) self._qpix_buffer.append(qpix2paint) if qpix2paint is not None: # Paint the image on the widget : qp = QPainter() qp.begin(self) qp.drawPixmap(rect, qpix2paint) qp.end()
python
def paintEvent(self, event): """Qt method override to paint a custom image on the Widget.""" super(FigureCanvas, self).paintEvent(event) # Prepare the rect on which the image is going to be painted : fw = self.frameWidth() rect = QRect(0 + fw, 0 + fw, self.size().width() - 2 * fw, self.size().height() - 2 * fw) if self.fig is None or self._blink_flag: return # Check/update the qpixmap buffer : qpix2paint = None for qpix in self._qpix_buffer: if qpix.size().width() == rect.width(): qpix2paint = qpix break else: if self.fmt in ['image/png', 'image/jpeg']: qpix2paint = self._qpix_orig.scaledToWidth( rect.width(), mode=Qt.SmoothTransformation) elif self.fmt == 'image/svg+xml': qpix2paint = QPixmap(svg_to_image(self.fig, rect.size())) self._qpix_buffer.append(qpix2paint) if qpix2paint is not None: # Paint the image on the widget : qp = QPainter() qp.begin(self) qp.drawPixmap(rect, qpix2paint) qp.end()
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "super", "(", "FigureCanvas", ",", "self", ")", ".", "paintEvent", "(", "event", ")", "# Prepare the rect on which the image is going to be painted :", "fw", "=", "self", ".", "frameWidth", "(", ")", "rec...
Qt method override to paint a custom image on the Widget.
[ "Qt", "method", "override", "to", "paint", "a", "custom", "image", "on", "the", "Widget", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L912-L943
31,541
spyder-ide/spyder
spyder/preferences/maininterpreter.py
MainInterpreterConfigPage.python_executable_changed
def python_executable_changed(self, pyexec): """Custom Python executable value has been changed""" if not self.cus_exec_radio.isChecked(): return False def_pyexec = get_python_executable() if not is_text_string(pyexec): pyexec = to_text_string(pyexec.toUtf8(), 'utf-8') if pyexec == def_pyexec: return False if (not programs.is_python_interpreter(pyexec) or not self.warn_python_compatibility(pyexec)): QMessageBox.warning(self, _('Warning'), _("You selected an invalid Python interpreter for the " "console so the previous interpreter will stay. Please " "make sure to select a valid one."), QMessageBox.Ok) self.def_exec_radio.setChecked(True) return False return True
python
def python_executable_changed(self, pyexec): """Custom Python executable value has been changed""" if not self.cus_exec_radio.isChecked(): return False def_pyexec = get_python_executable() if not is_text_string(pyexec): pyexec = to_text_string(pyexec.toUtf8(), 'utf-8') if pyexec == def_pyexec: return False if (not programs.is_python_interpreter(pyexec) or not self.warn_python_compatibility(pyexec)): QMessageBox.warning(self, _('Warning'), _("You selected an invalid Python interpreter for the " "console so the previous interpreter will stay. Please " "make sure to select a valid one."), QMessageBox.Ok) self.def_exec_radio.setChecked(True) return False return True
[ "def", "python_executable_changed", "(", "self", ",", "pyexec", ")", ":", "if", "not", "self", ".", "cus_exec_radio", ".", "isChecked", "(", ")", ":", "return", "False", "def_pyexec", "=", "get_python_executable", "(", ")", "if", "not", "is_text_string", "(", ...
Custom Python executable value has been changed
[ "Custom", "Python", "executable", "value", "has", "been", "changed" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/maininterpreter.py#L151-L168
31,542
spyder-ide/spyder
spyder/preferences/maininterpreter.py
MainInterpreterConfigPage.set_umr_namelist
def set_umr_namelist(self): """Set UMR excluded modules name list""" arguments, valid = QInputDialog.getText(self, _('UMR'), _("Set the list of excluded modules as " "this: <i>numpy, scipy</i>"), QLineEdit.Normal, ", ".join(self.get_option('umr/namelist'))) if valid: arguments = to_text_string(arguments) if arguments: namelist = arguments.replace(' ', '').split(',') fixed_namelist = [] non_ascii_namelist = [] for module_name in namelist: if PY2: if all(ord(c) < 128 for c in module_name): if programs.is_module_installed(module_name): fixed_namelist.append(module_name) else: QMessageBox.warning(self, _('Warning'), _("You are working with Python 2, this means that " "you can not import a module that contains non-" "ascii characters."), QMessageBox.Ok) non_ascii_namelist.append(module_name) elif programs.is_module_installed(module_name): fixed_namelist.append(module_name) invalid = ", ".join(set(namelist)-set(fixed_namelist)- set(non_ascii_namelist)) if invalid: QMessageBox.warning(self, _('UMR'), _("The following modules are not " "installed on your machine:\n%s" ) % invalid, QMessageBox.Ok) QMessageBox.information(self, _('UMR'), _("Please note that these changes will " "be applied only to new Python/IPython " "consoles"), QMessageBox.Ok) else: fixed_namelist = [] self.set_option('umr/namelist', fixed_namelist)
python
def set_umr_namelist(self): """Set UMR excluded modules name list""" arguments, valid = QInputDialog.getText(self, _('UMR'), _("Set the list of excluded modules as " "this: <i>numpy, scipy</i>"), QLineEdit.Normal, ", ".join(self.get_option('umr/namelist'))) if valid: arguments = to_text_string(arguments) if arguments: namelist = arguments.replace(' ', '').split(',') fixed_namelist = [] non_ascii_namelist = [] for module_name in namelist: if PY2: if all(ord(c) < 128 for c in module_name): if programs.is_module_installed(module_name): fixed_namelist.append(module_name) else: QMessageBox.warning(self, _('Warning'), _("You are working with Python 2, this means that " "you can not import a module that contains non-" "ascii characters."), QMessageBox.Ok) non_ascii_namelist.append(module_name) elif programs.is_module_installed(module_name): fixed_namelist.append(module_name) invalid = ", ".join(set(namelist)-set(fixed_namelist)- set(non_ascii_namelist)) if invalid: QMessageBox.warning(self, _('UMR'), _("The following modules are not " "installed on your machine:\n%s" ) % invalid, QMessageBox.Ok) QMessageBox.information(self, _('UMR'), _("Please note that these changes will " "be applied only to new Python/IPython " "consoles"), QMessageBox.Ok) else: fixed_namelist = [] self.set_option('umr/namelist', fixed_namelist)
[ "def", "set_umr_namelist", "(", "self", ")", ":", "arguments", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ",", "_", "(", "'UMR'", ")", ",", "_", "(", "\"Set the list of excluded modules as \"", "\"this: <i>numpy, scipy</i>\"", ")", ",", "QLi...
Set UMR excluded modules name list
[ "Set", "UMR", "excluded", "modules", "name", "list" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/maininterpreter.py#L193-L232
31,543
spyder-ide/spyder
spyder/preferences/maininterpreter.py
MainInterpreterConfigPage.set_custom_interpreters_list
def set_custom_interpreters_list(self, value): """Update the list of interpreters used and the current one.""" custom_list = self.get_option('custom_interpreters_list') if value not in custom_list and value != get_python_executable(): custom_list.append(value) self.set_option('custom_interpreters_list', custom_list)
python
def set_custom_interpreters_list(self, value): """Update the list of interpreters used and the current one.""" custom_list = self.get_option('custom_interpreters_list') if value not in custom_list and value != get_python_executable(): custom_list.append(value) self.set_option('custom_interpreters_list', custom_list)
[ "def", "set_custom_interpreters_list", "(", "self", ",", "value", ")", ":", "custom_list", "=", "self", ".", "get_option", "(", "'custom_interpreters_list'", ")", "if", "value", "not", "in", "custom_list", "and", "value", "!=", "get_python_executable", "(", ")", ...
Update the list of interpreters used and the current one.
[ "Update", "the", "list", "of", "interpreters", "used", "and", "the", "current", "one", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/maininterpreter.py#L234-L239
31,544
spyder-ide/spyder
spyder/preferences/maininterpreter.py
MainInterpreterConfigPage.validate_custom_interpreters_list
def validate_custom_interpreters_list(self): """Check that the used custom interpreters are still valid.""" custom_list = self.get_option('custom_interpreters_list') valid_custom_list = [] for value in custom_list: if (osp.isfile(value) and programs.is_python_interpreter(value) and value != get_python_executable()): valid_custom_list.append(value) self.set_option('custom_interpreters_list', valid_custom_list)
python
def validate_custom_interpreters_list(self): """Check that the used custom interpreters are still valid.""" custom_list = self.get_option('custom_interpreters_list') valid_custom_list = [] for value in custom_list: if (osp.isfile(value) and programs.is_python_interpreter(value) and value != get_python_executable()): valid_custom_list.append(value) self.set_option('custom_interpreters_list', valid_custom_list)
[ "def", "validate_custom_interpreters_list", "(", "self", ")", ":", "custom_list", "=", "self", ".", "get_option", "(", "'custom_interpreters_list'", ")", "valid_custom_list", "=", "[", "]", "for", "value", "in", "custom_list", ":", "if", "(", "osp", ".", "isfile...
Check that the used custom interpreters are still valid.
[ "Check", "that", "the", "used", "custom", "interpreters", "are", "still", "valid", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/maininterpreter.py#L241-L249
31,545
spyder-ide/spyder
spyder/api/panel.py
Panel.paintEvent
def paintEvent(self, event): """Fills the panel background using QPalette.""" if self.isVisible() and self.position != self.Position.FLOATING: # fill background self._background_brush = QBrush(QColor( self.editor.sideareas_color)) self._foreground_pen = QPen(QColor( self.palette().windowText().color())) painter = QPainter(self) painter.fillRect(event.rect(), self._background_brush)
python
def paintEvent(self, event): """Fills the panel background using QPalette.""" if self.isVisible() and self.position != self.Position.FLOATING: # fill background self._background_brush = QBrush(QColor( self.editor.sideareas_color)) self._foreground_pen = QPen(QColor( self.palette().windowText().color())) painter = QPainter(self) painter.fillRect(event.rect(), self._background_brush)
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "isVisible", "(", ")", "and", "self", ".", "position", "!=", "self", ".", "Position", ".", "FLOATING", ":", "# fill background", "self", ".", "_background_brush", "=", "QBrush", ...
Fills the panel background using QPalette.
[ "Fills", "the", "panel", "background", "using", "QPalette", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/panel.py#L116-L125
31,546
spyder-ide/spyder
spyder/api/panel.py
Panel.set_geometry
def set_geometry(self, crect): """Set geometry for floating panels. Normally you don't need to override this method, you should override `geometry` instead. """ x0, y0, width, height = self.geometry() if width is None: width = crect.width() if height is None: height = crect.height() # Calculate editor coordinates with their offsets offset = self.editor.contentOffset() x = self.editor.blockBoundingGeometry(self.editor.firstVisibleBlock())\ .translated(offset.x(), offset.y()).left() \ + self.editor.document().documentMargin() \ + self.editor.panels.margin_size(Panel.Position.LEFT) y = crect.top() + self.editor.panels.margin_size(Panel.Position.TOP) self.setGeometry(QRect(x+x0, y+y0, width, height))
python
def set_geometry(self, crect): """Set geometry for floating panels. Normally you don't need to override this method, you should override `geometry` instead. """ x0, y0, width, height = self.geometry() if width is None: width = crect.width() if height is None: height = crect.height() # Calculate editor coordinates with their offsets offset = self.editor.contentOffset() x = self.editor.blockBoundingGeometry(self.editor.firstVisibleBlock())\ .translated(offset.x(), offset.y()).left() \ + self.editor.document().documentMargin() \ + self.editor.panels.margin_size(Panel.Position.LEFT) y = crect.top() + self.editor.panels.margin_size(Panel.Position.TOP) self.setGeometry(QRect(x+x0, y+y0, width, height))
[ "def", "set_geometry", "(", "self", ",", "crect", ")", ":", "x0", ",", "y0", ",", "width", ",", "height", "=", "self", ".", "geometry", "(", ")", "if", "width", "is", "None", ":", "width", "=", "crect", ".", "width", "(", ")", "if", "height", "is...
Set geometry for floating panels. Normally you don't need to override this method, you should override `geometry` instead.
[ "Set", "geometry", "for", "floating", "panels", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/panel.py#L149-L170
31,547
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/namespacebrowser.py
NamepaceBrowserWidget.configure_namespacebrowser
def configure_namespacebrowser(self): """Configure associated namespace browser widget""" # Update namespace view self.sig_namespace_view.connect(lambda data: self.namespacebrowser.process_remote_view(data)) # Update properties of variables self.sig_var_properties.connect(lambda data: self.namespacebrowser.set_var_properties(data))
python
def configure_namespacebrowser(self): """Configure associated namespace browser widget""" # Update namespace view self.sig_namespace_view.connect(lambda data: self.namespacebrowser.process_remote_view(data)) # Update properties of variables self.sig_var_properties.connect(lambda data: self.namespacebrowser.set_var_properties(data))
[ "def", "configure_namespacebrowser", "(", "self", ")", ":", "# Update namespace view", "self", ".", "sig_namespace_view", ".", "connect", "(", "lambda", "data", ":", "self", ".", "namespacebrowser", ".", "process_remote_view", "(", "data", ")", ")", "# Update proper...
Configure associated namespace browser widget
[ "Configure", "associated", "namespace", "browser", "widget" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L55-L63
31,548
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/namespacebrowser.py
NamepaceBrowserWidget.set_namespace_view_settings
def set_namespace_view_settings(self): """Set the namespace view settings""" if self.namespacebrowser: settings = to_text_string( self.namespacebrowser.get_view_settings()) code =(u"get_ipython().kernel.namespace_view_settings = %s" % settings) self.silent_execute(code)
python
def set_namespace_view_settings(self): """Set the namespace view settings""" if self.namespacebrowser: settings = to_text_string( self.namespacebrowser.get_view_settings()) code =(u"get_ipython().kernel.namespace_view_settings = %s" % settings) self.silent_execute(code)
[ "def", "set_namespace_view_settings", "(", "self", ")", ":", "if", "self", ".", "namespacebrowser", ":", "settings", "=", "to_text_string", "(", "self", ".", "namespacebrowser", ".", "get_view_settings", "(", ")", ")", "code", "=", "(", "u\"get_ipython().kernel.na...
Set the namespace view settings
[ "Set", "the", "namespace", "view", "settings" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L73-L80
31,549
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/namespacebrowser.py
NamepaceBrowserWidget.get_value
def get_value(self, name): """Ask kernel for a value""" code = u"get_ipython().kernel.get_value('%s')" % name if self._reading: method = self.kernel_client.input code = u'!' + code else: method = self.silent_execute # Wait until the kernel returns the value wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) method(code) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None # Handle exceptions if self._kernel_value is None: if self._kernel_reply: msg = self._kernel_reply[:] self._kernel_reply = None raise ValueError(msg) return self._kernel_value
python
def get_value(self, name): """Ask kernel for a value""" code = u"get_ipython().kernel.get_value('%s')" % name if self._reading: method = self.kernel_client.input code = u'!' + code else: method = self.silent_execute # Wait until the kernel returns the value wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) method(code) wait_loop.exec_() # Remove loop connection and loop self.sig_got_reply.disconnect(wait_loop.quit) wait_loop = None # Handle exceptions if self._kernel_value is None: if self._kernel_reply: msg = self._kernel_reply[:] self._kernel_reply = None raise ValueError(msg) return self._kernel_value
[ "def", "get_value", "(", "self", ",", "name", ")", ":", "code", "=", "u\"get_ipython().kernel.get_value('%s')\"", "%", "name", "if", "self", ".", "_reading", ":", "method", "=", "self", ".", "kernel_client", ".", "input", "code", "=", "u'!'", "+", "code", ...
Ask kernel for a value
[ "Ask", "kernel", "for", "a", "value" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L82-L108
31,550
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/namespacebrowser.py
NamepaceBrowserWidget.set_value
def set_value(self, name, value): """Set value for a variable""" value = to_text_string(value) code = u"get_ipython().kernel.set_value('%s', %s, %s)" % (name, value, PY2) if self._reading: self.kernel_client.input(u'!' + code) else: self.silent_execute(code)
python
def set_value(self, name, value): """Set value for a variable""" value = to_text_string(value) code = u"get_ipython().kernel.set_value('%s', %s, %s)" % (name, value, PY2) if self._reading: self.kernel_client.input(u'!' + code) else: self.silent_execute(code)
[ "def", "set_value", "(", "self", ",", "name", ",", "value", ")", ":", "value", "=", "to_text_string", "(", "value", ")", "code", "=", "u\"get_ipython().kernel.set_value('%s', %s, %s)\"", "%", "(", "name", ",", "value", ",", "PY2", ")", "if", "self", ".", "...
Set value for a variable
[ "Set", "value", "for", "a", "variable" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L110-L119
31,551
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/namespacebrowser.py
NamepaceBrowserWidget._handle_spyder_msg
def _handle_spyder_msg(self, msg): """ Handle internal spyder messages """ spyder_msg_type = msg['content'].get('spyder_msg_type') if spyder_msg_type == 'data': # Deserialize data try: if PY2: value = cloudpickle.loads(msg['buffers'][0]) else: value = cloudpickle.loads(bytes(msg['buffers'][0])) except Exception as msg: self._kernel_value = None self._kernel_reply = repr(msg) else: self._kernel_value = value self.sig_got_reply.emit() return elif spyder_msg_type == 'pdb_state': pdb_state = msg['content']['pdb_state'] if pdb_state is not None and isinstance(pdb_state, dict): self.refresh_from_pdb(pdb_state) elif spyder_msg_type == 'pdb_continue': # Run Pdb continue to get to the first breakpoint # Fixes 2034 self.write_to_stdin('continue') elif spyder_msg_type == 'set_breakpoints': self.set_spyder_breakpoints(force=True) else: logger.debug("No such spyder message type: %s" % spyder_msg_type)
python
def _handle_spyder_msg(self, msg): """ Handle internal spyder messages """ spyder_msg_type = msg['content'].get('spyder_msg_type') if spyder_msg_type == 'data': # Deserialize data try: if PY2: value = cloudpickle.loads(msg['buffers'][0]) else: value = cloudpickle.loads(bytes(msg['buffers'][0])) except Exception as msg: self._kernel_value = None self._kernel_reply = repr(msg) else: self._kernel_value = value self.sig_got_reply.emit() return elif spyder_msg_type == 'pdb_state': pdb_state = msg['content']['pdb_state'] if pdb_state is not None and isinstance(pdb_state, dict): self.refresh_from_pdb(pdb_state) elif spyder_msg_type == 'pdb_continue': # Run Pdb continue to get to the first breakpoint # Fixes 2034 self.write_to_stdin('continue') elif spyder_msg_type == 'set_breakpoints': self.set_spyder_breakpoints(force=True) else: logger.debug("No such spyder message type: %s" % spyder_msg_type)
[ "def", "_handle_spyder_msg", "(", "self", ",", "msg", ")", ":", "spyder_msg_type", "=", "msg", "[", "'content'", "]", ".", "get", "(", "'spyder_msg_type'", ")", "if", "spyder_msg_type", "==", "'data'", ":", "# Deserialize data", "try", ":", "if", "PY2", ":",...
Handle internal spyder messages
[ "Handle", "internal", "spyder", "messages" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L176-L206
31,552
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/namespacebrowser.py
NamepaceBrowserWidget._handle_execute_reply
def _handle_execute_reply(self, msg): """ Reimplemented to handle communications between Spyder and the kernel """ msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) # unset reading flag, because if execute finished, raw_input can't # still be pending. self._reading = False # Refresh namespacebrowser after the kernel starts running exec_count = msg['content'].get('execution_count', '') if exec_count == 0 and self._kernel_is_starting: if self.namespacebrowser is not None: self.set_namespace_view_settings() self.refresh_namespacebrowser() self._kernel_is_starting = False self.ipyclient.t0 = time.monotonic() # Handle silent execution of kernel methods if info and info.kind == 'silent_exec_method' and not self._hidden: self.handle_exec_method(msg) self._request_info['execute'].pop(msg_id) else: super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
python
def _handle_execute_reply(self, msg): """ Reimplemented to handle communications between Spyder and the kernel """ msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) # unset reading flag, because if execute finished, raw_input can't # still be pending. self._reading = False # Refresh namespacebrowser after the kernel starts running exec_count = msg['content'].get('execution_count', '') if exec_count == 0 and self._kernel_is_starting: if self.namespacebrowser is not None: self.set_namespace_view_settings() self.refresh_namespacebrowser() self._kernel_is_starting = False self.ipyclient.t0 = time.monotonic() # Handle silent execution of kernel methods if info and info.kind == 'silent_exec_method' and not self._hidden: self.handle_exec_method(msg) self._request_info['execute'].pop(msg_id) else: super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
[ "def", "_handle_execute_reply", "(", "self", ",", "msg", ")", ":", "msg_id", "=", "msg", "[", "'parent_header'", "]", "[", "'msg_id'", "]", "info", "=", "self", ".", "_request_info", "[", "'execute'", "]", ".", "get", "(", "msg_id", ")", "# unset reading f...
Reimplemented to handle communications between Spyder and the kernel
[ "Reimplemented", "to", "handle", "communications", "between", "Spyder", "and", "the", "kernel" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L209-L234
31,553
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/namespacebrowser.py
NamepaceBrowserWidget._handle_status
def _handle_status(self, msg): """ Reimplemented to refresh the namespacebrowser after kernel restarts """ state = msg['content'].get('execution_state', '') msg_type = msg['parent_header'].get('msg_type', '') if state == 'starting': # This is needed to show the time a kernel # has been alive in each console. self.ipyclient.t0 = time.monotonic() self.ipyclient.timer.timeout.connect(self.ipyclient.show_time) self.ipyclient.timer.start(1000) # This handles restarts when the kernel dies # unexpectedly if not self._kernel_is_starting: self._kernel_is_starting = True elif state == 'idle' and msg_type == 'shutdown_request': # This handles restarts asked by the user if self.namespacebrowser is not None: self.set_namespace_view_settings() self.refresh_namespacebrowser() self.ipyclient.t0 = time.monotonic() else: super(NamepaceBrowserWidget, self)._handle_status(msg)
python
def _handle_status(self, msg): """ Reimplemented to refresh the namespacebrowser after kernel restarts """ state = msg['content'].get('execution_state', '') msg_type = msg['parent_header'].get('msg_type', '') if state == 'starting': # This is needed to show the time a kernel # has been alive in each console. self.ipyclient.t0 = time.monotonic() self.ipyclient.timer.timeout.connect(self.ipyclient.show_time) self.ipyclient.timer.start(1000) # This handles restarts when the kernel dies # unexpectedly if not self._kernel_is_starting: self._kernel_is_starting = True elif state == 'idle' and msg_type == 'shutdown_request': # This handles restarts asked by the user if self.namespacebrowser is not None: self.set_namespace_view_settings() self.refresh_namespacebrowser() self.ipyclient.t0 = time.monotonic() else: super(NamepaceBrowserWidget, self)._handle_status(msg)
[ "def", "_handle_status", "(", "self", ",", "msg", ")", ":", "state", "=", "msg", "[", "'content'", "]", ".", "get", "(", "'execution_state'", ",", "''", ")", "msg_type", "=", "msg", "[", "'parent_header'", "]", ".", "get", "(", "'msg_type'", ",", "''",...
Reimplemented to refresh the namespacebrowser after kernel restarts
[ "Reimplemented", "to", "refresh", "the", "namespacebrowser", "after", "kernel", "restarts" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L236-L261
31,554
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.initialize_plugin_in_mainwindow_layout
def initialize_plugin_in_mainwindow_layout(self): """ If this is the first time the plugin is shown, perform actions to initialize plugin position in Spyder's window layout. Use on_first_registration to define the actions to be run by your plugin """ if self.get_option('first_time', True): try: self.on_first_registration() except NotImplementedError: return self.set_option('first_time', False)
python
def initialize_plugin_in_mainwindow_layout(self): """ If this is the first time the plugin is shown, perform actions to initialize plugin position in Spyder's window layout. Use on_first_registration to define the actions to be run by your plugin """ if self.get_option('first_time', True): try: self.on_first_registration() except NotImplementedError: return self.set_option('first_time', False)
[ "def", "initialize_plugin_in_mainwindow_layout", "(", "self", ")", ":", "if", "self", ".", "get_option", "(", "'first_time'", ",", "True", ")", ":", "try", ":", "self", ".", "on_first_registration", "(", ")", "except", "NotImplementedError", ":", "return", "self...
If this is the first time the plugin is shown, perform actions to initialize plugin position in Spyder's window layout. Use on_first_registration to define the actions to be run by your plugin
[ "If", "this", "is", "the", "first", "time", "the", "plugin", "is", "shown", "perform", "actions", "to", "initialize", "plugin", "position", "in", "Spyder", "s", "window", "layout", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L76-L89
31,555
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.update_margins
def update_margins(self): """Update plugin margins""" layout = self.layout() if self.default_margins is None: self.default_margins = layout.getContentsMargins() if CONF.get('main', 'use_custom_margin'): margin = CONF.get('main', 'custom_margin') layout.setContentsMargins(*[margin]*4) else: layout.setContentsMargins(*self.default_margins)
python
def update_margins(self): """Update plugin margins""" layout = self.layout() if self.default_margins is None: self.default_margins = layout.getContentsMargins() if CONF.get('main', 'use_custom_margin'): margin = CONF.get('main', 'custom_margin') layout.setContentsMargins(*[margin]*4) else: layout.setContentsMargins(*self.default_margins)
[ "def", "update_margins", "(", "self", ")", ":", "layout", "=", "self", ".", "layout", "(", ")", "if", "self", ".", "default_margins", "is", "None", ":", "self", ".", "default_margins", "=", "layout", ".", "getContentsMargins", "(", ")", "if", "CONF", "."...
Update plugin margins
[ "Update", "plugin", "margins" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L91-L100
31,556
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.update_plugin_title
def update_plugin_title(self): """Update plugin title, i.e. dockwidget or window title""" if self.dockwidget is not None: win = self.dockwidget elif self.undocked_window is not None: win = self.undocked_window else: return win.setWindowTitle(self.get_plugin_title())
python
def update_plugin_title(self): """Update plugin title, i.e. dockwidget or window title""" if self.dockwidget is not None: win = self.dockwidget elif self.undocked_window is not None: win = self.undocked_window else: return win.setWindowTitle(self.get_plugin_title())
[ "def", "update_plugin_title", "(", "self", ")", ":", "if", "self", ".", "dockwidget", "is", "not", "None", ":", "win", "=", "self", ".", "dockwidget", "elif", "self", ".", "undocked_window", "is", "not", "None", ":", "win", "=", "self", ".", "undocked_wi...
Update plugin title, i.e. dockwidget or window title
[ "Update", "plugin", "title", "i", ".", "e", ".", "dockwidget", "or", "window", "title" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L102-L110
31,557
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.create_dockwidget
def create_dockwidget(self): """Add to parent QMainWindow as a dock widget""" # Creating dock widget dock = SpyderDockWidget(self.get_plugin_title(), self.main) # Set properties dock.setObjectName(self.__class__.__name__+"_dw") dock.setAllowedAreas(self.ALLOWED_AREAS) dock.setFeatures(self.FEATURES) dock.setWidget(self) self.update_margins() dock.visibilityChanged.connect(self.visibility_changed) dock.topLevelChanged.connect(self.on_top_level_changed) dock.sig_plugin_closed.connect(self.plugin_closed) self.dockwidget = dock if self.shortcut is not None: sc = QShortcut(QKeySequence(self.shortcut), self.main, self.switch_to_plugin) self.register_shortcut(sc, "_", "Switch to %s" % self.CONF_SECTION) return (dock, self.LOCATION)
python
def create_dockwidget(self): """Add to parent QMainWindow as a dock widget""" # Creating dock widget dock = SpyderDockWidget(self.get_plugin_title(), self.main) # Set properties dock.setObjectName(self.__class__.__name__+"_dw") dock.setAllowedAreas(self.ALLOWED_AREAS) dock.setFeatures(self.FEATURES) dock.setWidget(self) self.update_margins() dock.visibilityChanged.connect(self.visibility_changed) dock.topLevelChanged.connect(self.on_top_level_changed) dock.sig_plugin_closed.connect(self.plugin_closed) self.dockwidget = dock if self.shortcut is not None: sc = QShortcut(QKeySequence(self.shortcut), self.main, self.switch_to_plugin) self.register_shortcut(sc, "_", "Switch to %s" % self.CONF_SECTION) return (dock, self.LOCATION)
[ "def", "create_dockwidget", "(", "self", ")", ":", "# Creating dock widget", "dock", "=", "SpyderDockWidget", "(", "self", ".", "get_plugin_title", "(", ")", ",", "self", ".", "main", ")", "# Set properties", "dock", ".", "setObjectName", "(", "self", ".", "__...
Add to parent QMainWindow as a dock widget
[ "Add", "to", "parent", "QMainWindow", "as", "a", "dock", "widget" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L112-L131
31,558
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.create_configwidget
def create_configwidget(self, parent): """Create configuration dialog box page widget""" if self.CONFIGWIDGET_CLASS is not None: configwidget = self.CONFIGWIDGET_CLASS(self, parent) configwidget.initialize() return configwidget
python
def create_configwidget(self, parent): """Create configuration dialog box page widget""" if self.CONFIGWIDGET_CLASS is not None: configwidget = self.CONFIGWIDGET_CLASS(self, parent) configwidget.initialize() return configwidget
[ "def", "create_configwidget", "(", "self", ",", "parent", ")", ":", "if", "self", ".", "CONFIGWIDGET_CLASS", "is", "not", "None", ":", "configwidget", "=", "self", ".", "CONFIGWIDGET_CLASS", "(", "self", ",", "parent", ")", "configwidget", ".", "initialize", ...
Create configuration dialog box page widget
[ "Create", "configuration", "dialog", "box", "page", "widget" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L133-L138
31,559
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.get_plugin_font
def get_plugin_font(self, rich_text=False): """ Return plugin font option. All plugins in Spyder use a global font. This is a convenience method in case some plugins will have a delta size based on the default size. """ if rich_text: option = 'rich_font' font_size_delta = self.RICH_FONT_SIZE_DELTA else: option = 'font' font_size_delta = self.FONT_SIZE_DELTA return get_font(option=option, font_size_delta=font_size_delta)
python
def get_plugin_font(self, rich_text=False): """ Return plugin font option. All plugins in Spyder use a global font. This is a convenience method in case some plugins will have a delta size based on the default size. """ if rich_text: option = 'rich_font' font_size_delta = self.RICH_FONT_SIZE_DELTA else: option = 'font' font_size_delta = self.FONT_SIZE_DELTA return get_font(option=option, font_size_delta=font_size_delta)
[ "def", "get_plugin_font", "(", "self", ",", "rich_text", "=", "False", ")", ":", "if", "rich_text", ":", "option", "=", "'rich_font'", "font_size_delta", "=", "self", ".", "RICH_FONT_SIZE_DELTA", "else", ":", "option", "=", "'font'", "font_size_delta", "=", "s...
Return plugin font option. All plugins in Spyder use a global font. This is a convenience method in case some plugins will have a delta size based on the default size.
[ "Return", "plugin", "font", "option", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L155-L170
31,560
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.show_message
def show_message(self, message, timeout=0): """Show message in main window's status bar""" self.main.statusBar().showMessage(message, timeout)
python
def show_message(self, message, timeout=0): """Show message in main window's status bar""" self.main.statusBar().showMessage(message, timeout)
[ "def", "show_message", "(", "self", ",", "message", ",", "timeout", "=", "0", ")", ":", "self", ".", "main", ".", "statusBar", "(", ")", ".", "showMessage", "(", "message", ",", "timeout", ")" ]
Show message in main window's status bar
[ "Show", "message", "in", "main", "window", "s", "status", "bar" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L183-L185
31,561
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.create_toggle_view_action
def create_toggle_view_action(self): """Associate a toggle view action with each plugin""" title = self.get_plugin_title() if self.CONF_SECTION == 'editor': title = _('Editor') if self.shortcut is not None: action = create_action(self, title, toggled=lambda checked: self.toggle_view(checked), shortcut=QKeySequence(self.shortcut), context=Qt.WidgetShortcut) else: action = create_action(self, title, toggled=lambda checked: self.toggle_view(checked)) self.toggle_view_action = action
python
def create_toggle_view_action(self): """Associate a toggle view action with each plugin""" title = self.get_plugin_title() if self.CONF_SECTION == 'editor': title = _('Editor') if self.shortcut is not None: action = create_action(self, title, toggled=lambda checked: self.toggle_view(checked), shortcut=QKeySequence(self.shortcut), context=Qt.WidgetShortcut) else: action = create_action(self, title, toggled=lambda checked: self.toggle_view(checked)) self.toggle_view_action = action
[ "def", "create_toggle_view_action", "(", "self", ")", ":", "title", "=", "self", ".", "get_plugin_title", "(", ")", "if", "self", ".", "CONF_SECTION", "==", "'editor'", ":", "title", "=", "_", "(", "'Editor'", ")", "if", "self", ".", "shortcut", "is", "n...
Associate a toggle view action with each plugin
[ "Associate", "a", "toggle", "view", "action", "with", "each", "plugin" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L187-L200
31,562
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.close_window
def close_window(self): """Close QMainWindow instance that contains this plugin.""" if self.undocked_window is not None: self.undocked_window.close() self.undocked_window = None # Oddly, these actions can appear disabled after the Dock # action is pressed self.undock_action.setDisabled(False) self.close_plugin_action.setDisabled(False)
python
def close_window(self): """Close QMainWindow instance that contains this plugin.""" if self.undocked_window is not None: self.undocked_window.close() self.undocked_window = None # Oddly, these actions can appear disabled after the Dock # action is pressed self.undock_action.setDisabled(False) self.close_plugin_action.setDisabled(False)
[ "def", "close_window", "(", "self", ")", ":", "if", "self", ".", "undocked_window", "is", "not", "None", ":", "self", ".", "undocked_window", ".", "close", "(", ")", "self", ".", "undocked_window", "=", "None", "# Oddly, these actions can appear disabled after the...
Close QMainWindow instance that contains this plugin.
[ "Close", "QMainWindow", "instance", "that", "contains", "this", "plugin", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L213-L222
31,563
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.create_window
def create_window(self): """Create a QMainWindow instance containing this plugin.""" self.undocked_window = window = PluginWindow(self) window.setAttribute(Qt.WA_DeleteOnClose) icon = self.get_plugin_icon() if is_text_string(icon): icon = self.get_icon(icon) window.setWindowIcon(icon) window.setWindowTitle(self.get_plugin_title()) window.setCentralWidget(self) window.resize(self.size()) self.refresh_plugin() self.dockwidget.setFloating(False) self.dockwidget.setVisible(False) window.show()
python
def create_window(self): """Create a QMainWindow instance containing this plugin.""" self.undocked_window = window = PluginWindow(self) window.setAttribute(Qt.WA_DeleteOnClose) icon = self.get_plugin_icon() if is_text_string(icon): icon = self.get_icon(icon) window.setWindowIcon(icon) window.setWindowTitle(self.get_plugin_title()) window.setCentralWidget(self) window.resize(self.size()) self.refresh_plugin() self.dockwidget.setFloating(False) self.dockwidget.setVisible(False) window.show()
[ "def", "create_window", "(", "self", ")", ":", "self", ".", "undocked_window", "=", "window", "=", "PluginWindow", "(", "self", ")", "window", ".", "setAttribute", "(", "Qt", ".", "WA_DeleteOnClose", ")", "icon", "=", "self", ".", "get_plugin_icon", "(", "...
Create a QMainWindow instance containing this plugin.
[ "Create", "a", "QMainWindow", "instance", "containing", "this", "plugin", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L225-L241
31,564
spyder-ide/spyder
spyder/plugins/base.py
BasePluginMixin.on_top_level_changed
def on_top_level_changed(self, top_level): """Actions to perform when a plugin is undocked to be moved.""" if top_level: self.undock_action.setDisabled(True) else: self.undock_action.setDisabled(False)
python
def on_top_level_changed(self, top_level): """Actions to perform when a plugin is undocked to be moved.""" if top_level: self.undock_action.setDisabled(True) else: self.undock_action.setDisabled(False)
[ "def", "on_top_level_changed", "(", "self", ",", "top_level", ")", ":", "if", "top_level", ":", "self", ".", "undock_action", ".", "setDisabled", "(", "True", ")", "else", ":", "self", ".", "undock_action", ".", "setDisabled", "(", "False", ")" ]
Actions to perform when a plugin is undocked to be moved.
[ "Actions", "to", "perform", "when", "a", "plugin", "is", "undocked", "to", "be", "moved", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L244-L249
31,565
spyder-ide/spyder
spyder/widgets/reporterror.py
DescriptionWidget.keyPressEvent
def keyPressEvent(self, event): """Reimplemented Qt Method to avoid removing the header.""" event, text, key, ctrl, shift = restore_keyevent(event) cursor_position = self.get_position('cursor') if cursor_position < self.header_end_pos: self.restrict_cursor_position(self.header_end_pos, 'eof') elif key == Qt.Key_Delete: if self.has_selected_text(): self.remove_text() else: self.stdkey_clear() elif key == Qt.Key_Backspace: if self.has_selected_text(): self.remove_text() elif self.header_end_pos == cursor_position: return else: self.stdkey_backspace() elif key == Qt.Key_X and ctrl: self.cut() else: CodeEditor.keyPressEvent(self, event)
python
def keyPressEvent(self, event): """Reimplemented Qt Method to avoid removing the header.""" event, text, key, ctrl, shift = restore_keyevent(event) cursor_position = self.get_position('cursor') if cursor_position < self.header_end_pos: self.restrict_cursor_position(self.header_end_pos, 'eof') elif key == Qt.Key_Delete: if self.has_selected_text(): self.remove_text() else: self.stdkey_clear() elif key == Qt.Key_Backspace: if self.has_selected_text(): self.remove_text() elif self.header_end_pos == cursor_position: return else: self.stdkey_backspace() elif key == Qt.Key_X and ctrl: self.cut() else: CodeEditor.keyPressEvent(self, event)
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "event", ",", "text", ",", "key", ",", "ctrl", ",", "shift", "=", "restore_keyevent", "(", "event", ")", "cursor_position", "=", "self", ".", "get_position", "(", "'cursor'", ")", "if", "cursor...
Reimplemented Qt Method to avoid removing the header.
[ "Reimplemented", "Qt", "Method", "to", "avoid", "removing", "the", "header", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/reporterror.py#L82-L104
31,566
spyder-ide/spyder
spyder/widgets/reporterror.py
SpyderErrorDialog._submit_to_github
def _submit_to_github(self): """Action to take when pressing the submit button.""" # Get reference to the main window if self.parent() is not None: if getattr(self.parent(), 'main', False): # This covers the case when the dialog is attached # to the internal console main = self.parent().main else: # Else the dialog is attached to the main window # directly main = self.parent() else: main = None # Getting description and traceback title = self.title.text() description = self.input_description.toPlainText() traceback = self.error_traceback[:-1] # Remove last EOL # Render issue if main is not None: issue_text = main.render_issue(description=description, traceback=traceback) else: issue_text = description try: if main is None: org = 'ccordoba12' else: org = 'spyder-ide' github_backend = GithubBackend(org, 'spyder', parent_widget=main) github_report = github_backend.send_report(title, issue_text) if github_report: self.close() except Exception: ret = QMessageBox.question( self, _('Error'), _("An error occurred while trying to send the issue to " "Github automatically. Would you like to open it " "manually?<br><br>" "If so, please make sure to paste your clipboard " "into the issue report box that will appear in a new " "browser tab before clicking <i>Submit</i> on that " "page.")) if ret in [QMessageBox.Yes, QMessageBox.Ok]: QApplication.clipboard().setText(issue_text) issue_body = ( " \n<!--- *** BEFORE SUBMITTING: PASTE CLIPBOARD HERE " "TO COMPLETE YOUR REPORT *** ---!>\n") if main is not None: main.report_issue(body=issue_body, title=title, open_webpage=True) else: pass
python
def _submit_to_github(self): """Action to take when pressing the submit button.""" # Get reference to the main window if self.parent() is not None: if getattr(self.parent(), 'main', False): # This covers the case when the dialog is attached # to the internal console main = self.parent().main else: # Else the dialog is attached to the main window # directly main = self.parent() else: main = None # Getting description and traceback title = self.title.text() description = self.input_description.toPlainText() traceback = self.error_traceback[:-1] # Remove last EOL # Render issue if main is not None: issue_text = main.render_issue(description=description, traceback=traceback) else: issue_text = description try: if main is None: org = 'ccordoba12' else: org = 'spyder-ide' github_backend = GithubBackend(org, 'spyder', parent_widget=main) github_report = github_backend.send_report(title, issue_text) if github_report: self.close() except Exception: ret = QMessageBox.question( self, _('Error'), _("An error occurred while trying to send the issue to " "Github automatically. Would you like to open it " "manually?<br><br>" "If so, please make sure to paste your clipboard " "into the issue report box that will appear in a new " "browser tab before clicking <i>Submit</i> on that " "page.")) if ret in [QMessageBox.Yes, QMessageBox.Ok]: QApplication.clipboard().setText(issue_text) issue_body = ( " \n<!--- *** BEFORE SUBMITTING: PASTE CLIPBOARD HERE " "TO COMPLETE YOUR REPORT *** ---!>\n") if main is not None: main.report_issue(body=issue_body, title=title, open_webpage=True) else: pass
[ "def", "_submit_to_github", "(", "self", ")", ":", "# Get reference to the main window", "if", "self", ".", "parent", "(", ")", "is", "not", "None", ":", "if", "getattr", "(", "self", ".", "parent", "(", ")", ",", "'main'", ",", "False", ")", ":", "# Thi...
Action to take when pressing the submit button.
[ "Action", "to", "take", "when", "pressing", "the", "submit", "button", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/reporterror.py#L250-L305
31,567
spyder-ide/spyder
spyder/widgets/reporterror.py
SpyderErrorDialog._show_details
def _show_details(self): """Show traceback on its own dialog""" if self.details.isVisible(): self.details.hide() self.details_btn.setText(_('Show details')) else: self.resize(570, 700) self.details.document().setPlainText('') self.details.append_text_to_shell(self.error_traceback, error=True, prompt=False) self.details.show() self.details_btn.setText(_('Hide details'))
python
def _show_details(self): """Show traceback on its own dialog""" if self.details.isVisible(): self.details.hide() self.details_btn.setText(_('Show details')) else: self.resize(570, 700) self.details.document().setPlainText('') self.details.append_text_to_shell(self.error_traceback, error=True, prompt=False) self.details.show() self.details_btn.setText(_('Hide details'))
[ "def", "_show_details", "(", "self", ")", ":", "if", "self", ".", "details", ".", "isVisible", "(", ")", ":", "self", ".", "details", ".", "hide", "(", ")", "self", ".", "details_btn", ".", "setText", "(", "_", "(", "'Show details'", ")", ")", "else"...
Show traceback on its own dialog
[ "Show", "traceback", "on", "its", "own", "dialog" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/reporterror.py#L311-L323
31,568
spyder-ide/spyder
spyder/widgets/reporterror.py
SpyderErrorDialog._contents_changed
def _contents_changed(self): """Activate submit_btn.""" desc_chars = (len(self.input_description.toPlainText()) - self.initial_chars) if desc_chars < DESC_MIN_CHARS: self.desc_chars_label.setText( u"{} {}".format(DESC_MIN_CHARS - desc_chars, _("more characters to go..."))) else: self.desc_chars_label.setText(_("Description complete; thanks!")) title_chars = len(self.title.text()) if title_chars < TITLE_MIN_CHARS: self.title_chars_label.setText( u"{} {}".format(TITLE_MIN_CHARS - title_chars, _("more characters to go..."))) else: self.title_chars_label.setText(_("Title complete; thanks!")) submission_enabled = (desc_chars >= DESC_MIN_CHARS and title_chars >= TITLE_MIN_CHARS) self.submit_btn.setEnabled(submission_enabled)
python
def _contents_changed(self): """Activate submit_btn.""" desc_chars = (len(self.input_description.toPlainText()) - self.initial_chars) if desc_chars < DESC_MIN_CHARS: self.desc_chars_label.setText( u"{} {}".format(DESC_MIN_CHARS - desc_chars, _("more characters to go..."))) else: self.desc_chars_label.setText(_("Description complete; thanks!")) title_chars = len(self.title.text()) if title_chars < TITLE_MIN_CHARS: self.title_chars_label.setText( u"{} {}".format(TITLE_MIN_CHARS - title_chars, _("more characters to go..."))) else: self.title_chars_label.setText(_("Title complete; thanks!")) submission_enabled = (desc_chars >= DESC_MIN_CHARS and title_chars >= TITLE_MIN_CHARS) self.submit_btn.setEnabled(submission_enabled)
[ "def", "_contents_changed", "(", "self", ")", ":", "desc_chars", "=", "(", "len", "(", "self", ".", "input_description", ".", "toPlainText", "(", ")", ")", "-", "self", ".", "initial_chars", ")", "if", "desc_chars", "<", "DESC_MIN_CHARS", ":", "self", ".",...
Activate submit_btn.
[ "Activate", "submit_btn", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/reporterror.py#L325-L346
31,569
spyder-ide/spyder
spyder/plugins/editor/extensions/closebrackets.py
CloseBracketsExtension.unmatched_brackets_in_line
def unmatched_brackets_in_line(self, text, closing_brackets_type=None): """ Checks if there is an unmatched brackets in the 'text'. The brackets type can be general or specified by closing_brackets_type (')', ']' or '}') """ if closing_brackets_type is None: opening_brackets = self.BRACKETS_LEFT.values() closing_brackets = self.BRACKETS_RIGHT.values() else: closing_brackets = [closing_brackets_type] opening_brackets = [{')': '(', '}': '{', ']': '['}[closing_brackets_type]] block = self.editor.textCursor().block() line_pos = block.position() for pos, char in enumerate(text): if char in opening_brackets: match = self.editor.find_brace_match(line_pos+pos, char, forward=True) if (match is None) or (match > line_pos+len(text)): return True if char in closing_brackets: match = self.editor.find_brace_match(line_pos+pos, char, forward=False) if (match is None) or (match < line_pos): return True return False
python
def unmatched_brackets_in_line(self, text, closing_brackets_type=None): """ Checks if there is an unmatched brackets in the 'text'. The brackets type can be general or specified by closing_brackets_type (')', ']' or '}') """ if closing_brackets_type is None: opening_brackets = self.BRACKETS_LEFT.values() closing_brackets = self.BRACKETS_RIGHT.values() else: closing_brackets = [closing_brackets_type] opening_brackets = [{')': '(', '}': '{', ']': '['}[closing_brackets_type]] block = self.editor.textCursor().block() line_pos = block.position() for pos, char in enumerate(text): if char in opening_brackets: match = self.editor.find_brace_match(line_pos+pos, char, forward=True) if (match is None) or (match > line_pos+len(text)): return True if char in closing_brackets: match = self.editor.find_brace_match(line_pos+pos, char, forward=False) if (match is None) or (match < line_pos): return True return False
[ "def", "unmatched_brackets_in_line", "(", "self", ",", "text", ",", "closing_brackets_type", "=", "None", ")", ":", "if", "closing_brackets_type", "is", "None", ":", "opening_brackets", "=", "self", ".", "BRACKETS_LEFT", ".", "values", "(", ")", "closing_brackets"...
Checks if there is an unmatched brackets in the 'text'. The brackets type can be general or specified by closing_brackets_type (')', ']' or '}')
[ "Checks", "if", "there", "is", "an", "unmatched", "brackets", "in", "the", "text", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/closebrackets.py#L44-L71
31,570
spyder-ide/spyder
spyder/plugins/editor/extensions/closebrackets.py
CloseBracketsExtension._autoinsert_brackets
def _autoinsert_brackets(self, key): """Control automatic insertation of brackets in various situations.""" char = self.BRACKETS_CHAR[key] pair = self.BRACKETS_PAIR[key] line_text = self.editor.get_text('sol', 'eol') line_to_cursor = self.editor.get_text('sol', 'cursor') cursor = self.editor.textCursor() trailing_text = self.editor.get_text('cursor', 'eol').strip() if self.editor.has_selected_text(): text = self.editor.get_selected_text() self.editor.insert_text("{0}{1}{2}".format(pair[0], text, pair[1])) # Keep text selected, for inserting multiple brackets cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, 1) cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, len(text)) self.editor.setTextCursor(cursor) elif key in self.BRACKETS_LEFT: if (not trailing_text or trailing_text[0] in self.BRACKETS_RIGHT.values() or trailing_text[0] in [',', ':', ';']): # Automatic insertion of brackets self.editor.insert_text(pair) cursor.movePosition(QTextCursor.PreviousCharacter) self.editor.setTextCursor(cursor) else: self.editor.insert_text(char) if char in self.editor.signature_completion_characters: self.editor.request_signature() elif key in self.BRACKETS_RIGHT: if (self.editor.next_char() == char and not self.editor.textCursor().atBlockEnd() and not self.unmatched_brackets_in_line( cursor.block().text(), char)): # Overwrite an existing brackets if all in line are matched cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, 1) cursor.clearSelection() self.editor.setTextCursor(cursor) else: self.editor.insert_text(char)
python
def _autoinsert_brackets(self, key): """Control automatic insertation of brackets in various situations.""" char = self.BRACKETS_CHAR[key] pair = self.BRACKETS_PAIR[key] line_text = self.editor.get_text('sol', 'eol') line_to_cursor = self.editor.get_text('sol', 'cursor') cursor = self.editor.textCursor() trailing_text = self.editor.get_text('cursor', 'eol').strip() if self.editor.has_selected_text(): text = self.editor.get_selected_text() self.editor.insert_text("{0}{1}{2}".format(pair[0], text, pair[1])) # Keep text selected, for inserting multiple brackets cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, 1) cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, len(text)) self.editor.setTextCursor(cursor) elif key in self.BRACKETS_LEFT: if (not trailing_text or trailing_text[0] in self.BRACKETS_RIGHT.values() or trailing_text[0] in [',', ':', ';']): # Automatic insertion of brackets self.editor.insert_text(pair) cursor.movePosition(QTextCursor.PreviousCharacter) self.editor.setTextCursor(cursor) else: self.editor.insert_text(char) if char in self.editor.signature_completion_characters: self.editor.request_signature() elif key in self.BRACKETS_RIGHT: if (self.editor.next_char() == char and not self.editor.textCursor().atBlockEnd() and not self.unmatched_brackets_in_line( cursor.block().text(), char)): # Overwrite an existing brackets if all in line are matched cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, 1) cursor.clearSelection() self.editor.setTextCursor(cursor) else: self.editor.insert_text(char)
[ "def", "_autoinsert_brackets", "(", "self", ",", "key", ")", ":", "char", "=", "self", ".", "BRACKETS_CHAR", "[", "key", "]", "pair", "=", "self", ".", "BRACKETS_PAIR", "[", "key", "]", "line_text", "=", "self", ".", "editor", ".", "get_text", "(", "'s...
Control automatic insertation of brackets in various situations.
[ "Control", "automatic", "insertation", "of", "brackets", "in", "various", "situations", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/closebrackets.py#L73-L114
31,571
jrosebr1/imutils
imutils/text.py
put_text
def put_text(img, text, org, font_face, font_scale, color, thickness=1, line_type=8, bottom_left_origin=False): """Utility for drawing text with line breaks :param img: Image. :param text: Text string to be drawn. :param org: Bottom-left corner of the first line of the text string in the image. :param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s can be combined with FONT_ITALIC to get the slanted letters. :param font_scale: Font scale factor that is multiplied by the font-specific base size. :param color: Text color. :param thickness: Thickness of the lines used to draw a text. :param line_type: Line type. See the line for details. :param bottom_left_origin: When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner. :return: None; image is modified in place """ # Break out drawing coords x, y = org # Break text into list of text lines text_lines = text.split('\n') # Get height of text lines in pixels (height of all lines is the same) _, line_height = cv2.getTextSize('', font_face, font_scale, thickness)[0] # Set distance between lines in pixels line_gap = line_height // 3 for i, text_line in enumerate(text_lines): # Find total size of text block before this line line_y_adjustment = i * (line_gap + line_height) # Move text down from original line based on line number if not bottom_left_origin: line_y = y + line_y_adjustment else: line_y = y - line_y_adjustment # Draw text cv2.putText(img, text=text_lines[i], org=(x, line_y), fontFace=font_face, fontScale=font_scale, color=color, thickness=thickness, lineType=line_type, bottomLeftOrigin=bottom_left_origin)
python
def put_text(img, text, org, font_face, font_scale, color, thickness=1, line_type=8, bottom_left_origin=False): """Utility for drawing text with line breaks :param img: Image. :param text: Text string to be drawn. :param org: Bottom-left corner of the first line of the text string in the image. :param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s can be combined with FONT_ITALIC to get the slanted letters. :param font_scale: Font scale factor that is multiplied by the font-specific base size. :param color: Text color. :param thickness: Thickness of the lines used to draw a text. :param line_type: Line type. See the line for details. :param bottom_left_origin: When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner. :return: None; image is modified in place """ # Break out drawing coords x, y = org # Break text into list of text lines text_lines = text.split('\n') # Get height of text lines in pixels (height of all lines is the same) _, line_height = cv2.getTextSize('', font_face, font_scale, thickness)[0] # Set distance between lines in pixels line_gap = line_height // 3 for i, text_line in enumerate(text_lines): # Find total size of text block before this line line_y_adjustment = i * (line_gap + line_height) # Move text down from original line based on line number if not bottom_left_origin: line_y = y + line_y_adjustment else: line_y = y - line_y_adjustment # Draw text cv2.putText(img, text=text_lines[i], org=(x, line_y), fontFace=font_face, fontScale=font_scale, color=color, thickness=thickness, lineType=line_type, bottomLeftOrigin=bottom_left_origin)
[ "def", "put_text", "(", "img", ",", "text", ",", "org", ",", "font_face", ",", "font_scale", ",", "color", ",", "thickness", "=", "1", ",", "line_type", "=", "8", ",", "bottom_left_origin", "=", "False", ")", ":", "# Break out drawing coords", "x", ",", ...
Utility for drawing text with line breaks :param img: Image. :param text: Text string to be drawn. :param org: Bottom-left corner of the first line of the text string in the image. :param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s can be combined with FONT_ITALIC to get the slanted letters. :param font_scale: Font scale factor that is multiplied by the font-specific base size. :param color: Text color. :param thickness: Thickness of the lines used to draw a text. :param line_type: Line type. See the line for details. :param bottom_left_origin: When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner. :return: None; image is modified in place
[ "Utility", "for", "drawing", "text", "with", "line", "breaks" ]
4430083199793bd66db64e574379cbe18414d420
https://github.com/jrosebr1/imutils/blob/4430083199793bd66db64e574379cbe18414d420/imutils/text.py#L4-L52
31,572
jrosebr1/imutils
imutils/text.py
put_centered_text
def put_centered_text(img, text, font_face, font_scale, color, thickness=1, line_type=8): """Utility for drawing vertically & horizontally centered text with line breaks :param img: Image. :param text: Text string to be drawn. :param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s can be combined with FONT_ITALIC to get the slanted letters. :param font_scale: Font scale factor that is multiplied by the font-specific base size. :param color: Text color. :param thickness: Thickness of the lines used to draw a text. :param line_type: Line type. See the line for details. :return: None; image is modified in place """ # Save img dimensions img_h, img_w = img.shape[:2] # Break text into list of text lines text_lines = text.split('\n') # Get height of text lines in pixels (height of all lines is the same; width differs) _, line_height = cv2.getTextSize('', font_face, font_scale, thickness)[0] # Set distance between lines in pixels line_gap = line_height // 3 # Calculate total text block height for centering text_block_height = len(text_lines) * (line_height + line_gap) text_block_height -= line_gap # There's one less gap than lines for i, text_line in enumerate(text_lines): # Get width of text line in pixels (height of all lines is the same) line_width, _ = cv2.getTextSize(text_line, font_face, font_scale, thickness)[0] # Center line with image dimensions x = (img_w - line_width) // 2 y = (img_h + line_height) // 2 # Find total size of text block before this line line_adjustment = i * (line_gap + line_height) # Adjust line y and re-center relative to total text block height y += line_adjustment - text_block_height // 2 + line_gap # Draw text cv2.putText(img, text=text_lines[i], org=(x, y), fontFace=font_face, fontScale=font_scale, color=color, thickness=thickness, lineType=line_type)
python
def put_centered_text(img, text, font_face, font_scale, color, thickness=1, line_type=8): """Utility for drawing vertically & horizontally centered text with line breaks :param img: Image. :param text: Text string to be drawn. :param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s can be combined with FONT_ITALIC to get the slanted letters. :param font_scale: Font scale factor that is multiplied by the font-specific base size. :param color: Text color. :param thickness: Thickness of the lines used to draw a text. :param line_type: Line type. See the line for details. :return: None; image is modified in place """ # Save img dimensions img_h, img_w = img.shape[:2] # Break text into list of text lines text_lines = text.split('\n') # Get height of text lines in pixels (height of all lines is the same; width differs) _, line_height = cv2.getTextSize('', font_face, font_scale, thickness)[0] # Set distance between lines in pixels line_gap = line_height // 3 # Calculate total text block height for centering text_block_height = len(text_lines) * (line_height + line_gap) text_block_height -= line_gap # There's one less gap than lines for i, text_line in enumerate(text_lines): # Get width of text line in pixels (height of all lines is the same) line_width, _ = cv2.getTextSize(text_line, font_face, font_scale, thickness)[0] # Center line with image dimensions x = (img_w - line_width) // 2 y = (img_h + line_height) // 2 # Find total size of text block before this line line_adjustment = i * (line_gap + line_height) # Adjust line y and re-center relative to total text block height y += line_adjustment - text_block_height // 2 + line_gap # Draw text cv2.putText(img, text=text_lines[i], org=(x, y), fontFace=font_face, fontScale=font_scale, color=color, thickness=thickness, lineType=line_type)
[ "def", "put_centered_text", "(", "img", ",", "text", ",", "font_face", ",", "font_scale", ",", "color", ",", "thickness", "=", "1", ",", "line_type", "=", "8", ")", ":", "# Save img dimensions", "img_h", ",", "img_w", "=", "img", ".", "shape", "[", ":", ...
Utility for drawing vertically & horizontally centered text with line breaks :param img: Image. :param text: Text string to be drawn. :param font_face: Font type. One of FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, FONT_HERSHEY_DUPLEX, FONT_HERSHEY_COMPLEX, FONT_HERSHEY_TRIPLEX, FONT_HERSHEY_COMPLEX_SMALL, FONT_HERSHEY_SCRIPT_SIMPLEX, or FONT_HERSHEY_SCRIPT_COMPLEX, where each of the font ID’s can be combined with FONT_ITALIC to get the slanted letters. :param font_scale: Font scale factor that is multiplied by the font-specific base size. :param color: Text color. :param thickness: Thickness of the lines used to draw a text. :param line_type: Line type. See the line for details. :return: None; image is modified in place
[ "Utility", "for", "drawing", "vertically", "&", "horizontally", "centered", "text", "with", "line", "breaks" ]
4430083199793bd66db64e574379cbe18414d420
https://github.com/jrosebr1/imutils/blob/4430083199793bd66db64e574379cbe18414d420/imutils/text.py#L55-L107
31,573
jrosebr1/imutils
imutils/feature/helpers.py
corners_to_keypoints
def corners_to_keypoints(corners): """function to take the corners from cv2.GoodFeaturesToTrack and return cv2.KeyPoints""" if corners is None: keypoints = [] else: keypoints = [cv2.KeyPoint(kp[0][0], kp[0][1], 1) for kp in corners] return keypoints
python
def corners_to_keypoints(corners): """function to take the corners from cv2.GoodFeaturesToTrack and return cv2.KeyPoints""" if corners is None: keypoints = [] else: keypoints = [cv2.KeyPoint(kp[0][0], kp[0][1], 1) for kp in corners] return keypoints
[ "def", "corners_to_keypoints", "(", "corners", ")", ":", "if", "corners", "is", "None", ":", "keypoints", "=", "[", "]", "else", ":", "keypoints", "=", "[", "cv2", ".", "KeyPoint", "(", "kp", "[", "0", "]", "[", "0", "]", ",", "kp", "[", "0", "]"...
function to take the corners from cv2.GoodFeaturesToTrack and return cv2.KeyPoints
[ "function", "to", "take", "the", "corners", "from", "cv2", ".", "GoodFeaturesToTrack", "and", "return", "cv2", ".", "KeyPoints" ]
4430083199793bd66db64e574379cbe18414d420
https://github.com/jrosebr1/imutils/blob/4430083199793bd66db64e574379cbe18414d420/imutils/feature/helpers.py#L4-L11
31,574
sdispater/poetry
poetry/packages/utils/utils.py
is_installable_dir
def is_installable_dir(path): """Return True if `path` is a directory containing a setup.py file.""" if not os.path.isdir(path): return False setup_py = os.path.join(path, "setup.py") if os.path.isfile(setup_py): return True return False
python
def is_installable_dir(path): """Return True if `path` is a directory containing a setup.py file.""" if not os.path.isdir(path): return False setup_py = os.path.join(path, "setup.py") if os.path.isfile(setup_py): return True return False
[ "def", "is_installable_dir", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "False", "setup_py", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"setup.py\"", ")", "if", "os", ".", "pa...
Return True if `path` is a directory containing a setup.py file.
[ "Return", "True", "if", "path", "is", "a", "directory", "containing", "a", "setup", ".", "py", "file", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/utils/utils.py#L90-L97
31,575
sdispater/poetry
poetry/config.py
Config.setting
def setting(self, setting_name, default=None): # type: (str) -> Any """ Retrieve a setting value. """ keys = setting_name.split(".") config = self._content for key in keys: if key not in config: return default config = config[key] return config
python
def setting(self, setting_name, default=None): # type: (str) -> Any """ Retrieve a setting value. """ keys = setting_name.split(".") config = self._content for key in keys: if key not in config: return default config = config[key] return config
[ "def", "setting", "(", "self", ",", "setting_name", ",", "default", "=", "None", ")", ":", "# type: (str) -> Any", "keys", "=", "setting_name", ".", "split", "(", "\".\"", ")", "config", "=", "self", ".", "_content", "for", "key", "in", "keys", ":", "if"...
Retrieve a setting value.
[ "Retrieve", "a", "setting", "value", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/config.py#L36-L49
31,576
sdispater/poetry
poetry/masonry/api.py
get_requires_for_build_wheel
def get_requires_for_build_wheel(config_settings=None): """ Returns a list of requirements for building, as strings """ poetry = Poetry.create(".") main, _ = SdistBuilder.convert_dependencies(poetry.package, poetry.package.requires) return main
python
def get_requires_for_build_wheel(config_settings=None): """ Returns a list of requirements for building, as strings """ poetry = Poetry.create(".") main, _ = SdistBuilder.convert_dependencies(poetry.package, poetry.package.requires) return main
[ "def", "get_requires_for_build_wheel", "(", "config_settings", "=", "None", ")", ":", "poetry", "=", "Poetry", ".", "create", "(", "\".\"", ")", "main", ",", "_", "=", "SdistBuilder", ".", "convert_dependencies", "(", "poetry", ".", "package", ",", "poetry", ...
Returns a list of requirements for building, as strings
[ "Returns", "a", "list", "of", "requirements", "for", "building", "as", "strings" ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/api.py#L19-L27
31,577
sdispater/poetry
poetry/masonry/api.py
build_wheel
def build_wheel(wheel_directory, config_settings=None, metadata_directory=None): """Builds a wheel, places it in wheel_directory""" poetry = Poetry.create(".") return unicode( WheelBuilder.make_in( poetry, SystemEnv(Path(sys.prefix)), NullIO(), Path(wheel_directory) ) )
python
def build_wheel(wheel_directory, config_settings=None, metadata_directory=None): """Builds a wheel, places it in wheel_directory""" poetry = Poetry.create(".") return unicode( WheelBuilder.make_in( poetry, SystemEnv(Path(sys.prefix)), NullIO(), Path(wheel_directory) ) )
[ "def", "build_wheel", "(", "wheel_directory", ",", "config_settings", "=", "None", ",", "metadata_directory", "=", "None", ")", ":", "poetry", "=", "Poetry", ".", "create", "(", "\".\"", ")", "return", "unicode", "(", "WheelBuilder", ".", "make_in", "(", "po...
Builds a wheel, places it in wheel_directory
[ "Builds", "a", "wheel", "places", "it", "in", "wheel_directory" ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/api.py#L54-L62
31,578
sdispater/poetry
poetry/masonry/api.py
build_sdist
def build_sdist(sdist_directory, config_settings=None): """Builds an sdist, places it in sdist_directory""" poetry = Poetry.create(".") path = SdistBuilder(poetry, SystemEnv(Path(sys.prefix)), NullIO()).build( Path(sdist_directory) ) return unicode(path.name)
python
def build_sdist(sdist_directory, config_settings=None): """Builds an sdist, places it in sdist_directory""" poetry = Poetry.create(".") path = SdistBuilder(poetry, SystemEnv(Path(sys.prefix)), NullIO()).build( Path(sdist_directory) ) return unicode(path.name)
[ "def", "build_sdist", "(", "sdist_directory", ",", "config_settings", "=", "None", ")", ":", "poetry", "=", "Poetry", ".", "create", "(", "\".\"", ")", "path", "=", "SdistBuilder", "(", "poetry", ",", "SystemEnv", "(", "Path", "(", "sys", ".", "prefix", ...
Builds an sdist, places it in sdist_directory
[ "Builds", "an", "sdist", "places", "it", "in", "sdist_directory" ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/api.py#L65-L73
31,579
sdispater/poetry
poetry/mixology/incompatibility.py
Incompatibility.external_incompatibilities
def external_incompatibilities(self): # type: () -> Generator[Incompatibility] """ Returns all external incompatibilities in this incompatibility's derivation graph. """ if isinstance(self._cause, ConflictCause): cause = self._cause # type: ConflictCause for incompatibility in cause.conflict.external_incompatibilities: yield incompatibility for incompatibility in cause.other.external_incompatibilities: yield incompatibility else: yield self
python
def external_incompatibilities(self): # type: () -> Generator[Incompatibility] """ Returns all external incompatibilities in this incompatibility's derivation graph. """ if isinstance(self._cause, ConflictCause): cause = self._cause # type: ConflictCause for incompatibility in cause.conflict.external_incompatibilities: yield incompatibility for incompatibility in cause.other.external_incompatibilities: yield incompatibility else: yield self
[ "def", "external_incompatibilities", "(", "self", ")", ":", "# type: () -> Generator[Incompatibility]", "if", "isinstance", "(", "self", ".", "_cause", ",", "ConflictCause", ")", ":", "cause", "=", "self", ".", "_cause", "# type: ConflictCause", "for", "incompatibilit...
Returns all external incompatibilities in this incompatibility's derivation graph.
[ "Returns", "all", "external", "incompatibilities", "in", "this", "incompatibility", "s", "derivation", "graph", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/incompatibility.py#L88-L101
31,580
sdispater/poetry
poetry/mixology/partial_solution.py
PartialSolution.decide
def decide(self, package): # type: (Package) -> None """ Adds an assignment of package as a decision and increments the decision level. """ # When we make a new decision after backtracking, count an additional # attempted solution. If we backtrack multiple times in a row, though, we # only want to count one, since we haven't actually started attempting a # new solution. if self._backtracking: self._attempted_solutions += 1 self._backtracking = False self._decisions[package.name] = package self._assign( Assignment.decision(package, self.decision_level, len(self._assignments)) )
python
def decide(self, package): # type: (Package) -> None """ Adds an assignment of package as a decision and increments the decision level. """ # When we make a new decision after backtracking, count an additional # attempted solution. If we backtrack multiple times in a row, though, we # only want to count one, since we haven't actually started attempting a # new solution. if self._backtracking: self._attempted_solutions += 1 self._backtracking = False self._decisions[package.name] = package self._assign( Assignment.decision(package, self.decision_level, len(self._assignments)) )
[ "def", "decide", "(", "self", ",", "package", ")", ":", "# type: (Package) -> None", "# When we make a new decision after backtracking, count an additional", "# attempted solution. If we backtrack multiple times in a row, though, we", "# only want to count one, since we haven't actually starte...
Adds an assignment of package as a decision and increments the decision level.
[ "Adds", "an", "assignment", "of", "package", "as", "a", "decision", "and", "increments", "the", "decision", "level", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/partial_solution.py#L73-L90
31,581
sdispater/poetry
poetry/mixology/partial_solution.py
PartialSolution.derive
def derive( self, dependency, is_positive, cause ): # type: (Dependency, bool, Incompatibility) -> None """ Adds an assignment of package as a derivation. """ self._assign( Assignment.derivation( dependency, is_positive, cause, self.decision_level, len(self._assignments), ) )
python
def derive( self, dependency, is_positive, cause ): # type: (Dependency, bool, Incompatibility) -> None """ Adds an assignment of package as a derivation. """ self._assign( Assignment.derivation( dependency, is_positive, cause, self.decision_level, len(self._assignments), ) )
[ "def", "derive", "(", "self", ",", "dependency", ",", "is_positive", ",", "cause", ")", ":", "# type: (Dependency, bool, Incompatibility) -> None", "self", ".", "_assign", "(", "Assignment", ".", "derivation", "(", "dependency", ",", "is_positive", ",", "cause", "...
Adds an assignment of package as a derivation.
[ "Adds", "an", "assignment", "of", "package", "as", "a", "derivation", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/partial_solution.py#L92-L106
31,582
sdispater/poetry
poetry/mixology/partial_solution.py
PartialSolution._assign
def _assign(self, assignment): # type: (Assignment) -> None """ Adds an Assignment to _assignments and _positive or _negative. """ self._assignments.append(assignment) self._register(assignment)
python
def _assign(self, assignment): # type: (Assignment) -> None """ Adds an Assignment to _assignments and _positive or _negative. """ self._assignments.append(assignment) self._register(assignment)
[ "def", "_assign", "(", "self", ",", "assignment", ")", ":", "# type: (Assignment) -> None", "self", ".", "_assignments", ".", "append", "(", "assignment", ")", "self", ".", "_register", "(", "assignment", ")" ]
Adds an Assignment to _assignments and _positive or _negative.
[ "Adds", "an", "Assignment", "to", "_assignments", "and", "_positive", "or", "_negative", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/partial_solution.py#L108-L113
31,583
sdispater/poetry
poetry/mixology/partial_solution.py
PartialSolution.backtrack
def backtrack(self, decision_level): # type: (int) -> None """ Resets the current decision level to decision_level, and removes all assignments made after that level. """ self._backtracking = True packages = set() while self._assignments[-1].decision_level > decision_level: removed = self._assignments.pop(-1) packages.add(removed.dependency.name) if removed.is_decision(): del self._decisions[removed.dependency.name] # Re-compute _positive and _negative for the packages that were removed. for package in packages: if package in self._positive: del self._positive[package] if package in self._negative: del self._negative[package] for assignment in self._assignments: if assignment.dependency.name in packages: self._register(assignment)
python
def backtrack(self, decision_level): # type: (int) -> None """ Resets the current decision level to decision_level, and removes all assignments made after that level. """ self._backtracking = True packages = set() while self._assignments[-1].decision_level > decision_level: removed = self._assignments.pop(-1) packages.add(removed.dependency.name) if removed.is_decision(): del self._decisions[removed.dependency.name] # Re-compute _positive and _negative for the packages that were removed. for package in packages: if package in self._positive: del self._positive[package] if package in self._negative: del self._negative[package] for assignment in self._assignments: if assignment.dependency.name in packages: self._register(assignment)
[ "def", "backtrack", "(", "self", ",", "decision_level", ")", ":", "# type: (int) -> None", "self", ".", "_backtracking", "=", "True", "packages", "=", "set", "(", ")", "while", "self", ".", "_assignments", "[", "-", "1", "]", ".", "decision_level", ">", "d...
Resets the current decision level to decision_level, and removes all assignments made after that level.
[ "Resets", "the", "current", "decision", "level", "to", "decision_level", "and", "removes", "all", "assignments", "made", "after", "that", "level", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/partial_solution.py#L115-L139
31,584
sdispater/poetry
poetry/mixology/partial_solution.py
PartialSolution._register
def _register(self, assignment): # type: (Assignment) -> None """ Registers an Assignment in _positive or _negative. """ name = assignment.dependency.name old_positive = self._positive.get(name) if old_positive is not None: self._positive[name] = old_positive.intersect(assignment) return ref = assignment.dependency.name negative_by_ref = self._negative.get(name) old_negative = None if negative_by_ref is None else negative_by_ref.get(ref) if old_negative is None: term = assignment else: term = assignment.intersect(old_negative) if term.is_positive(): if name in self._negative: del self._negative[name] self._positive[name] = term else: if name not in self._negative: self._negative[name] = {} self._negative[name][ref] = term
python
def _register(self, assignment): # type: (Assignment) -> None """ Registers an Assignment in _positive or _negative. """ name = assignment.dependency.name old_positive = self._positive.get(name) if old_positive is not None: self._positive[name] = old_positive.intersect(assignment) return ref = assignment.dependency.name negative_by_ref = self._negative.get(name) old_negative = None if negative_by_ref is None else negative_by_ref.get(ref) if old_negative is None: term = assignment else: term = assignment.intersect(old_negative) if term.is_positive(): if name in self._negative: del self._negative[name] self._positive[name] = term else: if name not in self._negative: self._negative[name] = {} self._negative[name][ref] = term
[ "def", "_register", "(", "self", ",", "assignment", ")", ":", "# type: (Assignment) -> None", "name", "=", "assignment", ".", "dependency", ".", "name", "old_positive", "=", "self", ".", "_positive", ".", "get", "(", "name", ")", "if", "old_positive", "is", ...
Registers an Assignment in _positive or _negative.
[ "Registers", "an", "Assignment", "in", "_positive", "or", "_negative", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/partial_solution.py#L141-L169
31,585
sdispater/poetry
poetry/mixology/partial_solution.py
PartialSolution.satisfier
def satisfier(self, term): # type: (Term) -> Assignment """ Returns the first Assignment in this solution such that the sublist of assignments up to and including that entry collectively satisfies term. """ assigned_term = None # type: Term for assignment in self._assignments: if assignment.dependency.name != term.dependency.name: continue if ( not assignment.dependency.is_root and not assignment.dependency.name == term.dependency.name ): if not assignment.is_positive(): continue assert not term.is_positive() return assignment if assigned_term is None: assigned_term = assignment else: assigned_term = assigned_term.intersect(assignment) # As soon as we have enough assignments to satisfy term, return them. if assigned_term.satisfies(term): return assignment raise RuntimeError("[BUG] {} is not satisfied.".format(term))
python
def satisfier(self, term): # type: (Term) -> Assignment """ Returns the first Assignment in this solution such that the sublist of assignments up to and including that entry collectively satisfies term. """ assigned_term = None # type: Term for assignment in self._assignments: if assignment.dependency.name != term.dependency.name: continue if ( not assignment.dependency.is_root and not assignment.dependency.name == term.dependency.name ): if not assignment.is_positive(): continue assert not term.is_positive() return assignment if assigned_term is None: assigned_term = assignment else: assigned_term = assigned_term.intersect(assignment) # As soon as we have enough assignments to satisfy term, return them. if assigned_term.satisfies(term): return assignment raise RuntimeError("[BUG] {} is not satisfied.".format(term))
[ "def", "satisfier", "(", "self", ",", "term", ")", ":", "# type: (Term) -> Assignment", "assigned_term", "=", "None", "# type: Term", "for", "assignment", "in", "self", ".", "_assignments", ":", "if", "assignment", ".", "dependency", ".", "name", "!=", "term", ...
Returns the first Assignment in this solution such that the sublist of assignments up to and including that entry collectively satisfies term.
[ "Returns", "the", "first", "Assignment", "in", "this", "solution", "such", "that", "the", "sublist", "of", "assignments", "up", "to", "and", "including", "that", "entry", "collectively", "satisfies", "term", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/partial_solution.py#L171-L202
31,586
sdispater/poetry
poetry/poetry.py
Poetry.check
def check(cls, config, strict=False): # type: (dict, bool) -> Dict[str, List[str]] """ Checks the validity of a configuration """ result = {"errors": [], "warnings": []} # Schema validation errors validation_errors = validate_object(config, "poetry-schema") result["errors"] += validation_errors if strict: # If strict, check the file more thoroughly # Checking license license = config.get("license") if license: try: license_by_id(license) except ValueError: result["errors"].append("{} is not a valid license".format(license)) if "dependencies" in config: python_versions = config["dependencies"]["python"] if python_versions == "*": result["warnings"].append( "A wildcard Python dependency is ambiguous. " "Consider specifying a more explicit one." ) # Checking for scripts with extras if "scripts" in config: scripts = config["scripts"] for name, script in scripts.items(): if not isinstance(script, dict): continue extras = script["extras"] for extra in extras: if extra not in config["extras"]: result["errors"].append( 'Script "{}" requires extra "{}" which is not defined.'.format( name, extra ) ) return result
python
def check(cls, config, strict=False): # type: (dict, bool) -> Dict[str, List[str]] """ Checks the validity of a configuration """ result = {"errors": [], "warnings": []} # Schema validation errors validation_errors = validate_object(config, "poetry-schema") result["errors"] += validation_errors if strict: # If strict, check the file more thoroughly # Checking license license = config.get("license") if license: try: license_by_id(license) except ValueError: result["errors"].append("{} is not a valid license".format(license)) if "dependencies" in config: python_versions = config["dependencies"]["python"] if python_versions == "*": result["warnings"].append( "A wildcard Python dependency is ambiguous. " "Consider specifying a more explicit one." ) # Checking for scripts with extras if "scripts" in config: scripts = config["scripts"] for name, script in scripts.items(): if not isinstance(script, dict): continue extras = script["extras"] for extra in extras: if extra not in config["extras"]: result["errors"].append( 'Script "{}" requires extra "{}" which is not defined.'.format( name, extra ) ) return result
[ "def", "check", "(", "cls", ",", "config", ",", "strict", "=", "False", ")", ":", "# type: (dict, bool) -> Dict[str, List[str]]", "result", "=", "{", "\"errors\"", ":", "[", "]", ",", "\"warnings\"", ":", "[", "]", "}", "# Schema validation errors", "validation_...
Checks the validity of a configuration
[ "Checks", "the", "validity", "of", "a", "configuration" ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/poetry.py#L220-L265
31,587
sdispater/poetry
poetry/masonry/builders/sdist.py
SdistBuilder.find_packages
def find_packages(self, include): """ Discover subpackages and data. It also retrieves necessary files. """ pkgdir = None if include.source is not None: pkgdir = str(include.base) base = str(include.elements[0].parent) pkg_name = include.package pkg_data = defaultdict(list) # Undocumented distutils feature: # the empty string matches all package names pkg_data[""].append("*") packages = [pkg_name] subpkg_paths = set() def find_nearest_pkg(rel_path): parts = rel_path.split(os.sep) for i in reversed(range(1, len(parts))): ancestor = "/".join(parts[:i]) if ancestor in subpkg_paths: pkg = ".".join([pkg_name] + parts[:i]) return pkg, "/".join(parts[i:]) # Relative to the top-level package return pkg_name, Path(rel_path).as_posix() excluded_files = self.find_excluded_files() for path, dirnames, filenames in os.walk(str(base), topdown=True): if os.path.basename(path) == "__pycache__": continue from_top_level = os.path.relpath(path, base) if from_top_level == ".": continue is_subpkg = "__init__.py" in filenames if is_subpkg: subpkg_paths.add(from_top_level) parts = from_top_level.split(os.sep) packages.append(".".join([pkg_name] + parts)) else: pkg, from_nearest_pkg = find_nearest_pkg(from_top_level) data_elements = [ f.relative_to(self._path) for f in Path(path).glob("*") if not f.is_dir() ] data = [e for e in data_elements if not self.is_excluded(e)] if not data: continue if len(data) == len(data_elements): pkg_data[pkg].append(pjoin(from_nearest_pkg, "*")) else: for d in data: if d.is_dir(): continue pkg_data[pkg] += [pjoin(from_nearest_pkg, d.name) for d in data] # Sort values in pkg_data pkg_data = {k: sorted(v) for (k, v) in pkg_data.items() if v} return pkgdir, sorted(packages), pkg_data
python
def find_packages(self, include): """ Discover subpackages and data. It also retrieves necessary files. """ pkgdir = None if include.source is not None: pkgdir = str(include.base) base = str(include.elements[0].parent) pkg_name = include.package pkg_data = defaultdict(list) # Undocumented distutils feature: # the empty string matches all package names pkg_data[""].append("*") packages = [pkg_name] subpkg_paths = set() def find_nearest_pkg(rel_path): parts = rel_path.split(os.sep) for i in reversed(range(1, len(parts))): ancestor = "/".join(parts[:i]) if ancestor in subpkg_paths: pkg = ".".join([pkg_name] + parts[:i]) return pkg, "/".join(parts[i:]) # Relative to the top-level package return pkg_name, Path(rel_path).as_posix() excluded_files = self.find_excluded_files() for path, dirnames, filenames in os.walk(str(base), topdown=True): if os.path.basename(path) == "__pycache__": continue from_top_level = os.path.relpath(path, base) if from_top_level == ".": continue is_subpkg = "__init__.py" in filenames if is_subpkg: subpkg_paths.add(from_top_level) parts = from_top_level.split(os.sep) packages.append(".".join([pkg_name] + parts)) else: pkg, from_nearest_pkg = find_nearest_pkg(from_top_level) data_elements = [ f.relative_to(self._path) for f in Path(path).glob("*") if not f.is_dir() ] data = [e for e in data_elements if not self.is_excluded(e)] if not data: continue if len(data) == len(data_elements): pkg_data[pkg].append(pjoin(from_nearest_pkg, "*")) else: for d in data: if d.is_dir(): continue pkg_data[pkg] += [pjoin(from_nearest_pkg, d.name) for d in data] # Sort values in pkg_data pkg_data = {k: sorted(v) for (k, v) in pkg_data.items() if v} return pkgdir, sorted(packages), pkg_data
[ "def", "find_packages", "(", "self", ",", "include", ")", ":", "pkgdir", "=", "None", "if", "include", ".", "source", "is", "not", "None", ":", "pkgdir", "=", "str", "(", "include", ".", "base", ")", "base", "=", "str", "(", "include", ".", "elements...
Discover subpackages and data. It also retrieves necessary files.
[ "Discover", "subpackages", "and", "data", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/builders/sdist.py#L189-L259
31,588
sdispater/poetry
poetry/masonry/builders/sdist.py
SdistBuilder.clean_tarinfo
def clean_tarinfo(cls, tar_info): """ Clean metadata from a TarInfo object to make it more reproducible. - Set uid & gid to 0 - Set uname and gname to "" - Normalise permissions to 644 or 755 - Set mtime if not None """ ti = copy(tar_info) ti.uid = 0 ti.gid = 0 ti.uname = "" ti.gname = "" ti.mode = normalize_file_permissions(ti.mode) return ti
python
def clean_tarinfo(cls, tar_info): """ Clean metadata from a TarInfo object to make it more reproducible. - Set uid & gid to 0 - Set uname and gname to "" - Normalise permissions to 644 or 755 - Set mtime if not None """ ti = copy(tar_info) ti.uid = 0 ti.gid = 0 ti.uname = "" ti.gname = "" ti.mode = normalize_file_permissions(ti.mode) return ti
[ "def", "clean_tarinfo", "(", "cls", ",", "tar_info", ")", ":", "ti", "=", "copy", "(", "tar_info", ")", "ti", ".", "uid", "=", "0", "ti", ".", "gid", "=", "0", "ti", ".", "uname", "=", "\"\"", "ti", ".", "gname", "=", "\"\"", "ti", ".", "mode",...
Clean metadata from a TarInfo object to make it more reproducible. - Set uid & gid to 0 - Set uname and gname to "" - Normalise permissions to 644 or 755 - Set mtime if not None
[ "Clean", "metadata", "from", "a", "TarInfo", "object", "to", "make", "it", "more", "reproducible", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/builders/sdist.py#L321-L337
31,589
sdispater/poetry
poetry/utils/shell.py
Shell.get
def get(cls): # type: () -> Shell """ Retrieve the current shell. """ if cls._shell is not None: return cls._shell try: name, path = detect_shell(os.getpid()) except (RuntimeError, ShellDetectionFailure): raise RuntimeError("Unable to detect the current shell.") cls._shell = cls(name, path) return cls._shell
python
def get(cls): # type: () -> Shell """ Retrieve the current shell. """ if cls._shell is not None: return cls._shell try: name, path = detect_shell(os.getpid()) except (RuntimeError, ShellDetectionFailure): raise RuntimeError("Unable to detect the current shell.") cls._shell = cls(name, path) return cls._shell
[ "def", "get", "(", "cls", ")", ":", "# type: () -> Shell", "if", "cls", ".", "_shell", "is", "not", "None", ":", "return", "cls", ".", "_shell", "try", ":", "name", ",", "path", "=", "detect_shell", "(", "os", ".", "getpid", "(", ")", ")", "except", ...
Retrieve the current shell.
[ "Retrieve", "the", "current", "shell", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/utils/shell.py#L27-L41
31,590
sdispater/poetry
poetry/puzzle/provider.py
Provider.search_for
def search_for(self, dependency): # type: (Dependency) -> List[Package] """ Search for the specifications that match the given dependency. The specifications in the returned list will be considered in reverse order, so the latest version ought to be last. """ if dependency.is_root: return PackageCollection(dependency, [self._package]) for constraint in self._search_for.keys(): if ( constraint.name == dependency.name and constraint.constraint.intersect(dependency.constraint) == dependency.constraint ): packages = [ p for p in self._search_for[constraint] if dependency.constraint.allows(p.version) ] packages.sort( key=lambda p: ( not p.is_prerelease() and not dependency.allows_prereleases(), p.version, ), reverse=True, ) return PackageCollection(dependency, packages) if dependency.is_vcs(): packages = self.search_for_vcs(dependency) elif dependency.is_file(): packages = self.search_for_file(dependency) elif dependency.is_directory(): packages = self.search_for_directory(dependency) else: constraint = dependency.constraint packages = self._pool.find_packages( dependency.name, constraint, extras=dependency.extras, allow_prereleases=dependency.allows_prereleases(), ) packages.sort( key=lambda p: ( not p.is_prerelease() and not dependency.allows_prereleases(), p.version, ), reverse=True, ) self._search_for[dependency] = packages return PackageCollection(dependency, packages)
python
def search_for(self, dependency): # type: (Dependency) -> List[Package] """ Search for the specifications that match the given dependency. The specifications in the returned list will be considered in reverse order, so the latest version ought to be last. """ if dependency.is_root: return PackageCollection(dependency, [self._package]) for constraint in self._search_for.keys(): if ( constraint.name == dependency.name and constraint.constraint.intersect(dependency.constraint) == dependency.constraint ): packages = [ p for p in self._search_for[constraint] if dependency.constraint.allows(p.version) ] packages.sort( key=lambda p: ( not p.is_prerelease() and not dependency.allows_prereleases(), p.version, ), reverse=True, ) return PackageCollection(dependency, packages) if dependency.is_vcs(): packages = self.search_for_vcs(dependency) elif dependency.is_file(): packages = self.search_for_file(dependency) elif dependency.is_directory(): packages = self.search_for_directory(dependency) else: constraint = dependency.constraint packages = self._pool.find_packages( dependency.name, constraint, extras=dependency.extras, allow_prereleases=dependency.allows_prereleases(), ) packages.sort( key=lambda p: ( not p.is_prerelease() and not dependency.allows_prereleases(), p.version, ), reverse=True, ) self._search_for[dependency] = packages return PackageCollection(dependency, packages)
[ "def", "search_for", "(", "self", ",", "dependency", ")", ":", "# type: (Dependency) -> List[Package]", "if", "dependency", ".", "is_root", ":", "return", "PackageCollection", "(", "dependency", ",", "[", "self", ".", "_package", "]", ")", "for", "constraint", "...
Search for the specifications that match the given dependency. The specifications in the returned list will be considered in reverse order, so the latest version ought to be last.
[ "Search", "for", "the", "specifications", "that", "match", "the", "given", "dependency", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/puzzle/provider.py#L100-L158
31,591
sdispater/poetry
poetry/puzzle/provider.py
Provider.search_for_vcs
def search_for_vcs(self, dependency): # type: (VCSDependency) -> List[Package] """ Search for the specifications that match the given VCS dependency. Basically, we clone the repository in a temporary directory and get the information we need by checking out the specified reference. """ if dependency.vcs != "git": raise ValueError("Unsupported VCS dependency {}".format(dependency.vcs)) tmp_dir = Path(mkdtemp(prefix="pypoetry-git-{}".format(dependency.name))) try: git = Git() git.clone(dependency.source, tmp_dir) git.checkout(dependency.reference, tmp_dir) revision = git.rev_parse(dependency.reference, tmp_dir).strip() if dependency.tag or dependency.rev: revision = dependency.reference directory_dependency = DirectoryDependency( dependency.name, tmp_dir, category=dependency.category, optional=dependency.is_optional(), ) for extra in dependency.extras: directory_dependency.extras.append(extra) package = self.search_for_directory(directory_dependency)[0] package.source_type = "git" package.source_url = dependency.source package.source_reference = revision except Exception: raise finally: safe_rmtree(str(tmp_dir)) return [package]
python
def search_for_vcs(self, dependency): # type: (VCSDependency) -> List[Package] """ Search for the specifications that match the given VCS dependency. Basically, we clone the repository in a temporary directory and get the information we need by checking out the specified reference. """ if dependency.vcs != "git": raise ValueError("Unsupported VCS dependency {}".format(dependency.vcs)) tmp_dir = Path(mkdtemp(prefix="pypoetry-git-{}".format(dependency.name))) try: git = Git() git.clone(dependency.source, tmp_dir) git.checkout(dependency.reference, tmp_dir) revision = git.rev_parse(dependency.reference, tmp_dir).strip() if dependency.tag or dependency.rev: revision = dependency.reference directory_dependency = DirectoryDependency( dependency.name, tmp_dir, category=dependency.category, optional=dependency.is_optional(), ) for extra in dependency.extras: directory_dependency.extras.append(extra) package = self.search_for_directory(directory_dependency)[0] package.source_type = "git" package.source_url = dependency.source package.source_reference = revision except Exception: raise finally: safe_rmtree(str(tmp_dir)) return [package]
[ "def", "search_for_vcs", "(", "self", ",", "dependency", ")", ":", "# type: (VCSDependency) -> List[Package]", "if", "dependency", ".", "vcs", "!=", "\"git\"", ":", "raise", "ValueError", "(", "\"Unsupported VCS dependency {}\"", ".", "format", "(", "dependency", ".",...
Search for the specifications that match the given VCS dependency. Basically, we clone the repository in a temporary directory and get the information we need by checking out the specified reference.
[ "Search", "for", "the", "specifications", "that", "match", "the", "given", "VCS", "dependency", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/puzzle/provider.py#L160-L200
31,592
sdispater/poetry
poetry/puzzle/provider.py
Provider.incompatibilities_for
def incompatibilities_for( self, package ): # type: (DependencyPackage) -> List[Incompatibility] """ Returns incompatibilities that encapsulate a given package's dependencies, or that it can't be safely selected. If multiple subsequent versions of this package have the same dependencies, this will return incompatibilities that reflect that. It won't return incompatibilities that have already been returned by a previous call to _incompatibilities_for(). """ if package.is_root(): dependencies = package.all_requires else: dependencies = package.requires if not package.python_constraint.allows_all( self._package.python_constraint ): intersection = package.python_constraint.intersect( package.dependency.transitive_python_constraint ) difference = package.dependency.transitive_python_constraint.difference( intersection ) if ( package.dependency.transitive_python_constraint.is_any() or self._package.python_constraint.intersect( package.dependency.python_constraint ).is_empty() or intersection.is_empty() or not difference.is_empty() ): return [ Incompatibility( [Term(package.to_dependency(), True)], PythonCause( package.python_versions, self._package.python_versions ), ) ] dependencies = [ dep for dep in dependencies if dep.name not in self.UNSAFE_PACKAGES and self._package.python_constraint.allows_any(dep.python_constraint) ] return [ Incompatibility( [Term(package.to_dependency(), True), Term(dep, False)], DependencyCause(), ) for dep in dependencies ]
python
def incompatibilities_for( self, package ): # type: (DependencyPackage) -> List[Incompatibility] """ Returns incompatibilities that encapsulate a given package's dependencies, or that it can't be safely selected. If multiple subsequent versions of this package have the same dependencies, this will return incompatibilities that reflect that. It won't return incompatibilities that have already been returned by a previous call to _incompatibilities_for(). """ if package.is_root(): dependencies = package.all_requires else: dependencies = package.requires if not package.python_constraint.allows_all( self._package.python_constraint ): intersection = package.python_constraint.intersect( package.dependency.transitive_python_constraint ) difference = package.dependency.transitive_python_constraint.difference( intersection ) if ( package.dependency.transitive_python_constraint.is_any() or self._package.python_constraint.intersect( package.dependency.python_constraint ).is_empty() or intersection.is_empty() or not difference.is_empty() ): return [ Incompatibility( [Term(package.to_dependency(), True)], PythonCause( package.python_versions, self._package.python_versions ), ) ] dependencies = [ dep for dep in dependencies if dep.name not in self.UNSAFE_PACKAGES and self._package.python_constraint.allows_any(dep.python_constraint) ] return [ Incompatibility( [Term(package.to_dependency(), True), Term(dep, False)], DependencyCause(), ) for dep in dependencies ]
[ "def", "incompatibilities_for", "(", "self", ",", "package", ")", ":", "# type: (DependencyPackage) -> List[Incompatibility]", "if", "package", ".", "is_root", "(", ")", ":", "dependencies", "=", "package", ".", "all_requires", "else", ":", "dependencies", "=", "pac...
Returns incompatibilities that encapsulate a given package's dependencies, or that it can't be safely selected. If multiple subsequent versions of this package have the same dependencies, this will return incompatibilities that reflect that. It won't return incompatibilities that have already been returned by a previous call to _incompatibilities_for().
[ "Returns", "incompatibilities", "that", "encapsulate", "a", "given", "package", "s", "dependencies", "or", "that", "it", "can", "t", "be", "safely", "selected", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/puzzle/provider.py#L393-L449
31,593
sdispater/poetry
poetry/mixology/version_solver.py
VersionSolver.solve
def solve(self): # type: () -> SolverResult """ Finds a set of dependencies that match the root package's constraints, or raises an error if no such set is available. """ start = time.time() root_dependency = Dependency(self._root.name, self._root.version) root_dependency.is_root = True self._add_incompatibility( Incompatibility([Term(root_dependency, False)], RootCause()) ) try: next = self._root.name while next is not None: self._propagate(next) next = self._choose_package_version() return self._result() except Exception: raise finally: self._log( "Version solving took {:.3f} seconds.\n" "Tried {} solutions.".format( time.time() - start, self._solution.attempted_solutions ) )
python
def solve(self): # type: () -> SolverResult """ Finds a set of dependencies that match the root package's constraints, or raises an error if no such set is available. """ start = time.time() root_dependency = Dependency(self._root.name, self._root.version) root_dependency.is_root = True self._add_incompatibility( Incompatibility([Term(root_dependency, False)], RootCause()) ) try: next = self._root.name while next is not None: self._propagate(next) next = self._choose_package_version() return self._result() except Exception: raise finally: self._log( "Version solving took {:.3f} seconds.\n" "Tried {} solutions.".format( time.time() - start, self._solution.attempted_solutions ) )
[ "def", "solve", "(", "self", ")", ":", "# type: () -> SolverResult", "start", "=", "time", ".", "time", "(", ")", "root_dependency", "=", "Dependency", "(", "self", ".", "_root", ".", "name", ",", "self", ".", "_root", ".", "version", ")", "root_dependency...
Finds a set of dependencies that match the root package's constraints, or raises an error if no such set is available.
[ "Finds", "a", "set", "of", "dependencies", "that", "match", "the", "root", "package", "s", "constraints", "or", "raises", "an", "error", "if", "no", "such", "set", "is", "available", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/version_solver.py#L62-L90
31,594
sdispater/poetry
poetry/mixology/version_solver.py
VersionSolver._propagate
def _propagate(self, package): # type: (str) -> None """ Performs unit propagation on incompatibilities transitively related to package to derive new assignments for _solution. """ changed = set() changed.add(package) while changed: package = changed.pop() # Iterate in reverse because conflict resolution tends to produce more # general incompatibilities as time goes on. If we look at those first, # we can derive stronger assignments sooner and more eagerly find # conflicts. for incompatibility in reversed(self._incompatibilities[package]): result = self._propagate_incompatibility(incompatibility) if result is _conflict: # If the incompatibility is satisfied by the solution, we use # _resolve_conflict() to determine the root cause of the conflict as a # new incompatibility. # # It also backjumps to a point in the solution # where that incompatibility will allow us to derive new assignments # that avoid the conflict. root_cause = self._resolve_conflict(incompatibility) # Back jumping erases all the assignments we did at the previous # decision level, so we clear [changed] and refill it with the # newly-propagated assignment. changed.clear() changed.add(str(self._propagate_incompatibility(root_cause))) break elif result is not None: changed.add(result)
python
def _propagate(self, package): # type: (str) -> None """ Performs unit propagation on incompatibilities transitively related to package to derive new assignments for _solution. """ changed = set() changed.add(package) while changed: package = changed.pop() # Iterate in reverse because conflict resolution tends to produce more # general incompatibilities as time goes on. If we look at those first, # we can derive stronger assignments sooner and more eagerly find # conflicts. for incompatibility in reversed(self._incompatibilities[package]): result = self._propagate_incompatibility(incompatibility) if result is _conflict: # If the incompatibility is satisfied by the solution, we use # _resolve_conflict() to determine the root cause of the conflict as a # new incompatibility. # # It also backjumps to a point in the solution # where that incompatibility will allow us to derive new assignments # that avoid the conflict. root_cause = self._resolve_conflict(incompatibility) # Back jumping erases all the assignments we did at the previous # decision level, so we clear [changed] and refill it with the # newly-propagated assignment. changed.clear() changed.add(str(self._propagate_incompatibility(root_cause))) break elif result is not None: changed.add(result)
[ "def", "_propagate", "(", "self", ",", "package", ")", ":", "# type: (str) -> None", "changed", "=", "set", "(", ")", "changed", ".", "add", "(", "package", ")", "while", "changed", ":", "package", "=", "changed", ".", "pop", "(", ")", "# Iterate in revers...
Performs unit propagation on incompatibilities transitively related to package to derive new assignments for _solution.
[ "Performs", "unit", "propagation", "on", "incompatibilities", "transitively", "related", "to", "package", "to", "derive", "new", "assignments", "for", "_solution", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/version_solver.py#L92-L127
31,595
sdispater/poetry
poetry/mixology/version_solver.py
VersionSolver._propagate_incompatibility
def _propagate_incompatibility( self, incompatibility ): # type: (Incompatibility) -> Union[str, _conflict, None] """ If incompatibility is almost satisfied by _solution, adds the negation of the unsatisfied term to _solution. If incompatibility is satisfied by _solution, returns _conflict. If incompatibility is almost satisfied by _solution, returns the unsatisfied term's package name. Otherwise, returns None. """ # The first entry in incompatibility.terms that's not yet satisfied by # _solution, if one exists. If we find more than one, _solution is # inconclusive for incompatibility and we can't deduce anything. unsatisfied = None for term in incompatibility.terms: relation = self._solution.relation(term) if relation == SetRelation.DISJOINT: # If term is already contradicted by _solution, then # incompatibility is contradicted as well and there's nothing new we # can deduce from it. return elif relation == SetRelation.OVERLAPPING: # If more than one term is inconclusive, we can't deduce anything about # incompatibility. if unsatisfied is not None: return # If exactly one term in incompatibility is inconclusive, then it's # almost satisfied and [term] is the unsatisfied term. We can add the # inverse of the term to _solution. unsatisfied = term # If *all* terms in incompatibility are satisfied by _solution, then # incompatibility is satisfied and we have a conflict. if unsatisfied is None: return _conflict self._log( "derived: {}{}".format( "not " if unsatisfied.is_positive() else "", unsatisfied.dependency ) ) self._solution.derive( unsatisfied.dependency, not unsatisfied.is_positive(), incompatibility ) return unsatisfied.dependency.name
python
def _propagate_incompatibility( self, incompatibility ): # type: (Incompatibility) -> Union[str, _conflict, None] """ If incompatibility is almost satisfied by _solution, adds the negation of the unsatisfied term to _solution. If incompatibility is satisfied by _solution, returns _conflict. If incompatibility is almost satisfied by _solution, returns the unsatisfied term's package name. Otherwise, returns None. """ # The first entry in incompatibility.terms that's not yet satisfied by # _solution, if one exists. If we find more than one, _solution is # inconclusive for incompatibility and we can't deduce anything. unsatisfied = None for term in incompatibility.terms: relation = self._solution.relation(term) if relation == SetRelation.DISJOINT: # If term is already contradicted by _solution, then # incompatibility is contradicted as well and there's nothing new we # can deduce from it. return elif relation == SetRelation.OVERLAPPING: # If more than one term is inconclusive, we can't deduce anything about # incompatibility. if unsatisfied is not None: return # If exactly one term in incompatibility is inconclusive, then it's # almost satisfied and [term] is the unsatisfied term. We can add the # inverse of the term to _solution. unsatisfied = term # If *all* terms in incompatibility are satisfied by _solution, then # incompatibility is satisfied and we have a conflict. if unsatisfied is None: return _conflict self._log( "derived: {}{}".format( "not " if unsatisfied.is_positive() else "", unsatisfied.dependency ) ) self._solution.derive( unsatisfied.dependency, not unsatisfied.is_positive(), incompatibility ) return unsatisfied.dependency.name
[ "def", "_propagate_incompatibility", "(", "self", ",", "incompatibility", ")", ":", "# type: (Incompatibility) -> Union[str, _conflict, None]", "# The first entry in incompatibility.terms that's not yet satisfied by", "# _solution, if one exists. If we find more than one, _solution is", "# inc...
If incompatibility is almost satisfied by _solution, adds the negation of the unsatisfied term to _solution. If incompatibility is satisfied by _solution, returns _conflict. If incompatibility is almost satisfied by _solution, returns the unsatisfied term's package name. Otherwise, returns None.
[ "If", "incompatibility", "is", "almost", "satisfied", "by", "_solution", "adds", "the", "negation", "of", "the", "unsatisfied", "term", "to", "_solution", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/version_solver.py#L129-L181
31,596
sdispater/poetry
poetry/mixology/version_solver.py
VersionSolver._choose_package_version
def _choose_package_version(self): # type: () -> Union[str, None] """ Tries to select a version of a required package. Returns the name of the package whose incompatibilities should be propagated by _propagate(), or None indicating that version solving is complete and a solution has been found. """ unsatisfied = self._solution.unsatisfied if not unsatisfied: return # Prefer packages with as few remaining versions as possible, # so that if a conflict is necessary it's forced quickly. def _get_min(dependency): if dependency.name in self._use_latest: # If we're forced to use the latest version of a package, it effectively # only has one version to choose from. return 1 if dependency.name in self._locked: return 1 try: return len(self._provider.search_for(dependency)) except ValueError: return 0 if len(unsatisfied) == 1: dependency = unsatisfied[0] else: dependency = min(*unsatisfied, key=_get_min) locked = self._get_locked(dependency.name) if locked is None or not dependency.constraint.allows(locked.version): try: packages = self._provider.search_for(dependency) except ValueError as e: self._add_incompatibility( Incompatibility([Term(dependency, True)], PackageNotFoundCause(e)) ) return dependency.name try: version = packages[0] except IndexError: version = None else: version = locked if version is None: # If there are no versions that satisfy the constraint, # add an incompatibility that indicates that. self._add_incompatibility( Incompatibility([Term(dependency, True)], NoVersionsCause()) ) return dependency.name version = self._provider.complete_package(version) conflict = False for incompatibility in self._provider.incompatibilities_for(version): self._add_incompatibility(incompatibility) # If an incompatibility is already satisfied, then selecting version # would cause a conflict. # # We'll continue adding its dependencies, then go back to # unit propagation which will guide us to choose a better version. conflict = conflict or all( [ term.dependency.name == dependency.name or self._solution.satisfies(term) for term in incompatibility.terms ] ) if not conflict: self._solution.decide(version) self._log( "selecting {} ({})".format(version.name, version.full_pretty_version) ) return dependency.name
python
def _choose_package_version(self): # type: () -> Union[str, None] """ Tries to select a version of a required package. Returns the name of the package whose incompatibilities should be propagated by _propagate(), or None indicating that version solving is complete and a solution has been found. """ unsatisfied = self._solution.unsatisfied if not unsatisfied: return # Prefer packages with as few remaining versions as possible, # so that if a conflict is necessary it's forced quickly. def _get_min(dependency): if dependency.name in self._use_latest: # If we're forced to use the latest version of a package, it effectively # only has one version to choose from. return 1 if dependency.name in self._locked: return 1 try: return len(self._provider.search_for(dependency)) except ValueError: return 0 if len(unsatisfied) == 1: dependency = unsatisfied[0] else: dependency = min(*unsatisfied, key=_get_min) locked = self._get_locked(dependency.name) if locked is None or not dependency.constraint.allows(locked.version): try: packages = self._provider.search_for(dependency) except ValueError as e: self._add_incompatibility( Incompatibility([Term(dependency, True)], PackageNotFoundCause(e)) ) return dependency.name try: version = packages[0] except IndexError: version = None else: version = locked if version is None: # If there are no versions that satisfy the constraint, # add an incompatibility that indicates that. self._add_incompatibility( Incompatibility([Term(dependency, True)], NoVersionsCause()) ) return dependency.name version = self._provider.complete_package(version) conflict = False for incompatibility in self._provider.incompatibilities_for(version): self._add_incompatibility(incompatibility) # If an incompatibility is already satisfied, then selecting version # would cause a conflict. # # We'll continue adding its dependencies, then go back to # unit propagation which will guide us to choose a better version. conflict = conflict or all( [ term.dependency.name == dependency.name or self._solution.satisfies(term) for term in incompatibility.terms ] ) if not conflict: self._solution.decide(version) self._log( "selecting {} ({})".format(version.name, version.full_pretty_version) ) return dependency.name
[ "def", "_choose_package_version", "(", "self", ")", ":", "# type: () -> Union[str, None]", "unsatisfied", "=", "self", ".", "_solution", ".", "unsatisfied", "if", "not", "unsatisfied", ":", "return", "# Prefer packages with as few remaining versions as possible,", "# so that ...
Tries to select a version of a required package. Returns the name of the package whose incompatibilities should be propagated by _propagate(), or None indicating that version solving is complete and a solution has been found.
[ "Tries", "to", "select", "a", "version", "of", "a", "required", "package", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/version_solver.py#L318-L402
31,597
sdispater/poetry
poetry/utils/env.py
Env.run
def run(self, bin, *args, **kwargs): """ Run a command inside the Python environment. """ bin = self._bin(bin) cmd = [bin] + list(args) shell = kwargs.get("shell", False) call = kwargs.pop("call", False) input_ = kwargs.pop("input_", None) if shell: cmd = list_to_shell_command(cmd) try: if self._is_windows: kwargs["shell"] = True if input_: p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs ) output = p.communicate(encode(input_))[0] elif call: return subprocess.call(cmd, stderr=subprocess.STDOUT, **kwargs) else: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, **kwargs ) except CalledProcessError as e: raise EnvCommandError(e) return decode(output)
python
def run(self, bin, *args, **kwargs): """ Run a command inside the Python environment. """ bin = self._bin(bin) cmd = [bin] + list(args) shell = kwargs.get("shell", False) call = kwargs.pop("call", False) input_ = kwargs.pop("input_", None) if shell: cmd = list_to_shell_command(cmd) try: if self._is_windows: kwargs["shell"] = True if input_: p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs ) output = p.communicate(encode(input_))[0] elif call: return subprocess.call(cmd, stderr=subprocess.STDOUT, **kwargs) else: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT, **kwargs ) except CalledProcessError as e: raise EnvCommandError(e) return decode(output)
[ "def", "run", "(", "self", ",", "bin", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "bin", "=", "self", ".", "_bin", "(", "bin", ")", "cmd", "=", "[", "bin", "]", "+", "list", "(", "args", ")", "shell", "=", "kwargs", ".", "get", "(...
Run a command inside the Python environment.
[ "Run", "a", "command", "inside", "the", "Python", "environment", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/utils/env.py#L345-L381
31,598
sdispater/poetry
poetry/utils/env.py
Env._bin
def _bin(self, bin): # type: (str) -> str """ Return path to the given executable. """ bin_path = (self._bin_dir / bin).with_suffix(".exe" if self._is_windows else "") if not bin_path.exists(): return bin return str(bin_path)
python
def _bin(self, bin): # type: (str) -> str """ Return path to the given executable. """ bin_path = (self._bin_dir / bin).with_suffix(".exe" if self._is_windows else "") if not bin_path.exists(): return bin return str(bin_path)
[ "def", "_bin", "(", "self", ",", "bin", ")", ":", "# type: (str) -> str", "bin_path", "=", "(", "self", ".", "_bin_dir", "/", "bin", ")", ".", "with_suffix", "(", "\".exe\"", "if", "self", ".", "_is_windows", "else", "\"\"", ")", "if", "not", "bin_path",...
Return path to the given executable.
[ "Return", "path", "to", "the", "given", "executable", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/utils/env.py#L391-L399
31,599
sdispater/poetry
poetry/version/helpers.py
format_python_constraint
def format_python_constraint(constraint): """ This helper will help in transforming disjunctive constraint into proper constraint. """ if isinstance(constraint, Version): if constraint.precision >= 3: return "=={}".format(str(constraint)) # Transform 3.6 or 3 if constraint.precision == 2: # 3.6 constraint = parse_constraint( "~{}.{}".format(constraint.major, constraint.minor) ) else: constraint = parse_constraint("^{}.0".format(constraint.major)) if not isinstance(constraint, VersionUnion): return str(constraint) formatted = [] accepted = [] for version in PYTHON_VERSION: version_constraint = parse_constraint(version) matches = constraint.allows_any(version_constraint) if not matches: formatted.append("!=" + version) else: accepted.append(version) # Checking lower bound low = accepted[0] formatted.insert(0, ">=" + ".".join(low.split(".")[:2])) return ", ".join(formatted)
python
def format_python_constraint(constraint): """ This helper will help in transforming disjunctive constraint into proper constraint. """ if isinstance(constraint, Version): if constraint.precision >= 3: return "=={}".format(str(constraint)) # Transform 3.6 or 3 if constraint.precision == 2: # 3.6 constraint = parse_constraint( "~{}.{}".format(constraint.major, constraint.minor) ) else: constraint = parse_constraint("^{}.0".format(constraint.major)) if not isinstance(constraint, VersionUnion): return str(constraint) formatted = [] accepted = [] for version in PYTHON_VERSION: version_constraint = parse_constraint(version) matches = constraint.allows_any(version_constraint) if not matches: formatted.append("!=" + version) else: accepted.append(version) # Checking lower bound low = accepted[0] formatted.insert(0, ">=" + ".".join(low.split(".")[:2])) return ", ".join(formatted)
[ "def", "format_python_constraint", "(", "constraint", ")", ":", "if", "isinstance", "(", "constraint", ",", "Version", ")", ":", "if", "constraint", ".", "precision", ">=", "3", ":", "return", "\"=={}\"", ".", "format", "(", "str", "(", "constraint", ")", ...
This helper will help in transforming disjunctive constraint into proper constraint.
[ "This", "helper", "will", "help", "in", "transforming", "disjunctive", "constraint", "into", "proper", "constraint", "." ]
2d27acd76c165dd49f11934520a7973de7a3762a
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/version/helpers.py#L19-L56