repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
spyder-ide/spyder | spyder/plugins/plots/widgets/figurebrowser.py | FigureThumbnail.setup_gui | def setup_gui(self):
"""Setup the main layout of the widget."""
layout = QGridLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.canvas, 0, 1)
layout.addLayout(self.setup_toolbar(), 0, 3, 2, 1)
layout.setColumnStretch(0, 100)
layout.setColumnStretch(2, 100)
layout.setRowStretch(1, 100) | python | def setup_gui(self):
"""Setup the main layout of the widget."""
layout = QGridLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.canvas, 0, 1)
layout.addLayout(self.setup_toolbar(), 0, 3, 2, 1)
layout.setColumnStretch(0, 100)
layout.setColumnStretch(2, 100)
layout.setRowStretch(1, 100) | [
"def",
"setup_gui",
"(",
"self",
")",
":",
"layout",
"=",
"QGridLayout",
"(",
"self",
")",
"layout",
".",
"setContentsMargins",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"layout",
".",
"addWidget",
"(",
"self",
".",
"canvas",
",",
"0",
",",
"1",
")",
"layout",
".",
"addLayout",
"(",
"self",
".",
"setup_toolbar",
"(",
")",
",",
"0",
",",
"3",
",",
"2",
",",
"1",
")",
"layout",
".",
"setColumnStretch",
"(",
"0",
",",
"100",
")",
"layout",
".",
"setColumnStretch",
"(",
"2",
",",
"100",
")",
"layout",
".",
"setRowStretch",
"(",
"1",
",",
"100",
")"
] | Setup the main layout of the widget. | [
"Setup",
"the",
"main",
"layout",
"of",
"the",
"widget",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L767-L776 | train |
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",
"=",
"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"
] | Setup the toolbar. | [
"Setup",
"the",
"toolbar",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L778-L796 | train |
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",
".",
"canvas",
".",
"setStyleSheet",
"(",
"\"FigureCanvas{border: 1px solid %s;}\"",
"%",
"colorname",
")",
"else",
":",
"self",
".",
"canvas",
".",
"setStyleSheet",
"(",
"\"FigureCanvas{}\"",
")"
] | 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 | train |
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",
".",
"sig_canvas_clicked",
".",
"emit",
"(",
"self",
")",
"return",
"super",
"(",
"FigureThumbnail",
",",
"self",
")",
".",
"eventFilter",
"(",
"widget",
",",
"event",
")"
] | 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 | train |
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 | train |
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",
")",
"context_menu",
".",
"addAction",
"(",
"ima",
".",
"icon",
"(",
"'editcopy'",
")",
",",
"\"Copy Image\"",
",",
"self",
".",
"copy_figure",
",",
"QKeySequence",
"(",
"get_shortcut",
"(",
"'plots'",
",",
"'copy'",
")",
")",
")",
"context_menu",
".",
"popup",
"(",
"self",
".",
"mapToGlobal",
"(",
"pos",
")",
")"
] | Popup context menu. | [
"Popup",
"context",
"menu",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L853-L862 | train |
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",
".",
"upper",
"(",
")",
")",
"QApplication",
".",
"clipboard",
"(",
")",
".",
"setImage",
"(",
"qpixmap",
".",
"toImage",
"(",
")",
")",
"elif",
"self",
".",
"fmt",
"==",
"'image/svg+xml'",
":",
"svg_to_clipboard",
"(",
"self",
".",
"fig",
")",
"else",
":",
"return",
"self",
".",
"blink_figure",
"(",
")"
] | 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 | train |
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",
"(",
")",
"timer",
".",
"singleShot",
"(",
"40",
",",
"self",
".",
"blink_figure",
")"
] | Blink figure once. | [
"Blink",
"figure",
"once",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L878-L885 | train |
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 | train |
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",
"(",
")",
"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",
"(",
")"
] | 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 | train |
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",
"(",
")",
"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",
"(",
")"
] | 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 | train |
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",
"(",
"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"
] | 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 | train |
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>\"",
")",
",",
"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",
")"
] | 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 | train |
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",
"(",
")",
":",
"custom_list",
".",
"append",
"(",
"value",
")",
"self",
".",
"set_option",
"(",
"'custom_interpreters_list'",
",",
"custom_list",
")"
] | 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 | train |
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",
"(",
"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",
")"
] | 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 | train |
spyder-ide/spyder | spyder/api/panel.py | Panel.on_install | def on_install(self, editor):
"""
Extends :meth:`spyder.api.EditorExtension.on_install` method to set the
editor instance as the parent widget.
.. warning:: Don't forget to call **super** if you override this
method!
:param editor: editor instance
:type editor: spyder.plugins.editor.widgets.codeeditor.CodeEditor
"""
EditorExtension.on_install(self, editor)
self.setParent(editor)
self.setPalette(QApplication.instance().palette())
self.setFont(QApplication.instance().font())
self.editor.panels.refresh()
self._background_brush = QBrush(QColor(
self.palette().window().color()))
self._foreground_pen = QPen(QColor(
self.palette().windowText().color()))
if self.position == self.Position.FLOATING:
self.setAttribute(Qt.WA_TransparentForMouseEvents) | python | def on_install(self, editor):
"""
Extends :meth:`spyder.api.EditorExtension.on_install` method to set the
editor instance as the parent widget.
.. warning:: Don't forget to call **super** if you override this
method!
:param editor: editor instance
:type editor: spyder.plugins.editor.widgets.codeeditor.CodeEditor
"""
EditorExtension.on_install(self, editor)
self.setParent(editor)
self.setPalette(QApplication.instance().palette())
self.setFont(QApplication.instance().font())
self.editor.panels.refresh()
self._background_brush = QBrush(QColor(
self.palette().window().color()))
self._foreground_pen = QPen(QColor(
self.palette().windowText().color()))
if self.position == self.Position.FLOATING:
self.setAttribute(Qt.WA_TransparentForMouseEvents) | [
"def",
"on_install",
"(",
"self",
",",
"editor",
")",
":",
"EditorExtension",
".",
"on_install",
"(",
"self",
",",
"editor",
")",
"self",
".",
"setParent",
"(",
"editor",
")",
"self",
".",
"setPalette",
"(",
"QApplication",
".",
"instance",
"(",
")",
".",
"palette",
"(",
")",
")",
"self",
".",
"setFont",
"(",
"QApplication",
".",
"instance",
"(",
")",
".",
"font",
"(",
")",
")",
"self",
".",
"editor",
".",
"panels",
".",
"refresh",
"(",
")",
"self",
".",
"_background_brush",
"=",
"QBrush",
"(",
"QColor",
"(",
"self",
".",
"palette",
"(",
")",
".",
"window",
"(",
")",
".",
"color",
"(",
")",
")",
")",
"self",
".",
"_foreground_pen",
"=",
"QPen",
"(",
"QColor",
"(",
"self",
".",
"palette",
"(",
")",
".",
"windowText",
"(",
")",
".",
"color",
"(",
")",
")",
")",
"if",
"self",
".",
"position",
"==",
"self",
".",
"Position",
".",
"FLOATING",
":",
"self",
".",
"setAttribute",
"(",
"Qt",
".",
"WA_TransparentForMouseEvents",
")"
] | Extends :meth:`spyder.api.EditorExtension.on_install` method to set the
editor instance as the parent widget.
.. warning:: Don't forget to call **super** if you override this
method!
:param editor: editor instance
:type editor: spyder.plugins.editor.widgets.codeeditor.CodeEditor | [
"Extends",
":",
"meth",
":",
"spyder",
".",
"api",
".",
"EditorExtension",
".",
"on_install",
"method",
"to",
"set",
"the",
"editor",
"instance",
"as",
"the",
"parent",
"widget",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/panel.py#L92-L114 | train |
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",
"(",
"QColor",
"(",
"self",
".",
"editor",
".",
"sideareas_color",
")",
")",
"self",
".",
"_foreground_pen",
"=",
"QPen",
"(",
"QColor",
"(",
"self",
".",
"palette",
"(",
")",
".",
"windowText",
"(",
")",
".",
"color",
"(",
")",
")",
")",
"painter",
"=",
"QPainter",
"(",
"self",
")",
"painter",
".",
"fillRect",
"(",
"event",
".",
"rect",
"(",
")",
",",
"self",
".",
"_background_brush",
")"
] | 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 | train |
spyder-ide/spyder | spyder/api/panel.py | Panel.setVisible | def setVisible(self, visible):
"""
Shows/Hides the panel.
Automatically call PanelsManager.refresh_panels.
:param visible: Visible state
"""
logger.debug('%s visibility changed', self.name)
super(Panel, self).setVisible(visible)
if self.editor:
self.editor.panels.refresh() | python | def setVisible(self, visible):
"""
Shows/Hides the panel.
Automatically call PanelsManager.refresh_panels.
:param visible: Visible state
"""
logger.debug('%s visibility changed', self.name)
super(Panel, self).setVisible(visible)
if self.editor:
self.editor.panels.refresh() | [
"def",
"setVisible",
"(",
"self",
",",
"visible",
")",
":",
"logger",
".",
"debug",
"(",
"'%s visibility changed'",
",",
"self",
".",
"name",
")",
"super",
"(",
"Panel",
",",
"self",
")",
".",
"setVisible",
"(",
"visible",
")",
"if",
"self",
".",
"editor",
":",
"self",
".",
"editor",
".",
"panels",
".",
"refresh",
"(",
")"
] | Shows/Hides the panel.
Automatically call PanelsManager.refresh_panels.
:param visible: Visible state | [
"Shows",
"/",
"Hides",
"the",
"panel",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/panel.py#L127-L138 | train |
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",
"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",
")",
")"
] | 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 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/utils/ssh.py | openssh_tunnel | def openssh_tunnel(self, lport, rport, server, remoteip='127.0.0.1',
keyfile=None, password=None, timeout=0.4):
"""
We decided to replace pyzmq's openssh_tunnel method to work around
issue https://github.com/zeromq/pyzmq/issues/589 which was solved
in pyzmq https://github.com/zeromq/pyzmq/pull/615
"""
ssh = "ssh "
if keyfile:
ssh += "-i " + keyfile
if ':' in server:
server, port = server.split(':')
ssh += " -p %s" % port
cmd = "%s -O check %s" % (ssh, server)
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
if not exitstatus:
pid = int(output[output.find("(pid=")+5:output.find(")")])
cmd = "%s -O forward -L 127.0.0.1:%i:%s:%i %s" % (
ssh, lport, remoteip, rport, server)
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
if not exitstatus:
atexit.register(_stop_tunnel, cmd.replace("-O forward",
"-O cancel",
1))
return pid
cmd = "%s -f -S none -L 127.0.0.1:%i:%s:%i %s sleep %i" % (
ssh, lport, remoteip, rport, server, timeout)
# pop SSH_ASKPASS from env
env = os.environ.copy()
env.pop('SSH_ASKPASS', None)
ssh_newkey = 'Are you sure you want to continue connecting'
tunnel = pexpect.spawn(cmd, env=env)
failed = False
while True:
try:
i = tunnel.expect([ssh_newkey, '[Pp]assword:'], timeout=.1)
if i == 0:
host = server.split('@')[-1]
question = _("The authenticity of host <b>%s</b> can't be "
"established. Are you sure you want to continue "
"connecting?") % host
reply = QMessageBox.question(self, _('Warning'), question,
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.Yes:
tunnel.sendline('yes')
continue
else:
tunnel.sendline('no')
raise RuntimeError(
_("The authenticity of the host can't be established"))
if i == 1 and password is not None:
tunnel.sendline(password)
except pexpect.TIMEOUT:
continue
except pexpect.EOF:
if tunnel.exitstatus:
raise RuntimeError(_("Tunnel '%s' failed to start") % cmd)
else:
return tunnel.pid
else:
if failed or password is None:
raise RuntimeError(_("Could not connect to remote host"))
# TODO: Use this block when pyzmq bug #620 is fixed
# # Prompt a passphrase dialog to the user for a second attempt
# password, ok = QInputDialog.getText(self, _('Password'),
# _('Enter password for: ') + server,
# echo=QLineEdit.Password)
# if ok is False:
# raise RuntimeError('Could not connect to remote host.')
tunnel.sendline(password)
failed = True | python | def openssh_tunnel(self, lport, rport, server, remoteip='127.0.0.1',
keyfile=None, password=None, timeout=0.4):
"""
We decided to replace pyzmq's openssh_tunnel method to work around
issue https://github.com/zeromq/pyzmq/issues/589 which was solved
in pyzmq https://github.com/zeromq/pyzmq/pull/615
"""
ssh = "ssh "
if keyfile:
ssh += "-i " + keyfile
if ':' in server:
server, port = server.split(':')
ssh += " -p %s" % port
cmd = "%s -O check %s" % (ssh, server)
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
if not exitstatus:
pid = int(output[output.find("(pid=")+5:output.find(")")])
cmd = "%s -O forward -L 127.0.0.1:%i:%s:%i %s" % (
ssh, lport, remoteip, rport, server)
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
if not exitstatus:
atexit.register(_stop_tunnel, cmd.replace("-O forward",
"-O cancel",
1))
return pid
cmd = "%s -f -S none -L 127.0.0.1:%i:%s:%i %s sleep %i" % (
ssh, lport, remoteip, rport, server, timeout)
# pop SSH_ASKPASS from env
env = os.environ.copy()
env.pop('SSH_ASKPASS', None)
ssh_newkey = 'Are you sure you want to continue connecting'
tunnel = pexpect.spawn(cmd, env=env)
failed = False
while True:
try:
i = tunnel.expect([ssh_newkey, '[Pp]assword:'], timeout=.1)
if i == 0:
host = server.split('@')[-1]
question = _("The authenticity of host <b>%s</b> can't be "
"established. Are you sure you want to continue "
"connecting?") % host
reply = QMessageBox.question(self, _('Warning'), question,
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.Yes:
tunnel.sendline('yes')
continue
else:
tunnel.sendline('no')
raise RuntimeError(
_("The authenticity of the host can't be established"))
if i == 1 and password is not None:
tunnel.sendline(password)
except pexpect.TIMEOUT:
continue
except pexpect.EOF:
if tunnel.exitstatus:
raise RuntimeError(_("Tunnel '%s' failed to start") % cmd)
else:
return tunnel.pid
else:
if failed or password is None:
raise RuntimeError(_("Could not connect to remote host"))
# TODO: Use this block when pyzmq bug #620 is fixed
# # Prompt a passphrase dialog to the user for a second attempt
# password, ok = QInputDialog.getText(self, _('Password'),
# _('Enter password for: ') + server,
# echo=QLineEdit.Password)
# if ok is False:
# raise RuntimeError('Could not connect to remote host.')
tunnel.sendline(password)
failed = True | [
"def",
"openssh_tunnel",
"(",
"self",
",",
"lport",
",",
"rport",
",",
"server",
",",
"remoteip",
"=",
"'127.0.0.1'",
",",
"keyfile",
"=",
"None",
",",
"password",
"=",
"None",
",",
"timeout",
"=",
"0.4",
")",
":",
"ssh",
"=",
"\"ssh \"",
"if",
"keyfile",
":",
"ssh",
"+=",
"\"-i \"",
"+",
"keyfile",
"if",
"':'",
"in",
"server",
":",
"server",
",",
"port",
"=",
"server",
".",
"split",
"(",
"':'",
")",
"ssh",
"+=",
"\" -p %s\"",
"%",
"port",
"cmd",
"=",
"\"%s -O check %s\"",
"%",
"(",
"ssh",
",",
"server",
")",
"(",
"output",
",",
"exitstatus",
")",
"=",
"pexpect",
".",
"run",
"(",
"cmd",
",",
"withexitstatus",
"=",
"True",
")",
"if",
"not",
"exitstatus",
":",
"pid",
"=",
"int",
"(",
"output",
"[",
"output",
".",
"find",
"(",
"\"(pid=\"",
")",
"+",
"5",
":",
"output",
".",
"find",
"(",
"\")\"",
")",
"]",
")",
"cmd",
"=",
"\"%s -O forward -L 127.0.0.1:%i:%s:%i %s\"",
"%",
"(",
"ssh",
",",
"lport",
",",
"remoteip",
",",
"rport",
",",
"server",
")",
"(",
"output",
",",
"exitstatus",
")",
"=",
"pexpect",
".",
"run",
"(",
"cmd",
",",
"withexitstatus",
"=",
"True",
")",
"if",
"not",
"exitstatus",
":",
"atexit",
".",
"register",
"(",
"_stop_tunnel",
",",
"cmd",
".",
"replace",
"(",
"\"-O forward\"",
",",
"\"-O cancel\"",
",",
"1",
")",
")",
"return",
"pid",
"cmd",
"=",
"\"%s -f -S none -L 127.0.0.1:%i:%s:%i %s sleep %i\"",
"%",
"(",
"ssh",
",",
"lport",
",",
"remoteip",
",",
"rport",
",",
"server",
",",
"timeout",
")",
"# pop SSH_ASKPASS from env",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
".",
"pop",
"(",
"'SSH_ASKPASS'",
",",
"None",
")",
"ssh_newkey",
"=",
"'Are you sure you want to continue connecting'",
"tunnel",
"=",
"pexpect",
".",
"spawn",
"(",
"cmd",
",",
"env",
"=",
"env",
")",
"failed",
"=",
"False",
"while",
"True",
":",
"try",
":",
"i",
"=",
"tunnel",
".",
"expect",
"(",
"[",
"ssh_newkey",
",",
"'[Pp]assword:'",
"]",
",",
"timeout",
"=",
".1",
")",
"if",
"i",
"==",
"0",
":",
"host",
"=",
"server",
".",
"split",
"(",
"'@'",
")",
"[",
"-",
"1",
"]",
"question",
"=",
"_",
"(",
"\"The authenticity of host <b>%s</b> can't be \"",
"\"established. Are you sure you want to continue \"",
"\"connecting?\"",
")",
"%",
"host",
"reply",
"=",
"QMessageBox",
".",
"question",
"(",
"self",
",",
"_",
"(",
"'Warning'",
")",
",",
"question",
",",
"QMessageBox",
".",
"Yes",
"|",
"QMessageBox",
".",
"No",
",",
"QMessageBox",
".",
"No",
")",
"if",
"reply",
"==",
"QMessageBox",
".",
"Yes",
":",
"tunnel",
".",
"sendline",
"(",
"'yes'",
")",
"continue",
"else",
":",
"tunnel",
".",
"sendline",
"(",
"'no'",
")",
"raise",
"RuntimeError",
"(",
"_",
"(",
"\"The authenticity of the host can't be established\"",
")",
")",
"if",
"i",
"==",
"1",
"and",
"password",
"is",
"not",
"None",
":",
"tunnel",
".",
"sendline",
"(",
"password",
")",
"except",
"pexpect",
".",
"TIMEOUT",
":",
"continue",
"except",
"pexpect",
".",
"EOF",
":",
"if",
"tunnel",
".",
"exitstatus",
":",
"raise",
"RuntimeError",
"(",
"_",
"(",
"\"Tunnel '%s' failed to start\"",
")",
"%",
"cmd",
")",
"else",
":",
"return",
"tunnel",
".",
"pid",
"else",
":",
"if",
"failed",
"or",
"password",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"_",
"(",
"\"Could not connect to remote host\"",
")",
")",
"# TODO: Use this block when pyzmq bug #620 is fixed",
"# # Prompt a passphrase dialog to the user for a second attempt",
"# password, ok = QInputDialog.getText(self, _('Password'),",
"# _('Enter password for: ') + server,",
"# echo=QLineEdit.Password)",
"# if ok is False:",
"# raise RuntimeError('Could not connect to remote host.')",
"tunnel",
".",
"sendline",
"(",
"password",
")",
"failed",
"=",
"True"
] | We decided to replace pyzmq's openssh_tunnel method to work around
issue https://github.com/zeromq/pyzmq/issues/589 which was solved
in pyzmq https://github.com/zeromq/pyzmq/pull/615 | [
"We",
"decided",
"to",
"replace",
"pyzmq",
"s",
"openssh_tunnel",
"method",
"to",
"work",
"around",
"issue",
"https",
":",
"//",
"github",
".",
"com",
"/",
"zeromq",
"/",
"pyzmq",
"/",
"issues",
"/",
"589",
"which",
"was",
"solved",
"in",
"pyzmq",
"https",
":",
"//",
"github",
".",
"com",
"/",
"zeromq",
"/",
"pyzmq",
"/",
"pull",
"/",
"615"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/utils/ssh.py#L23-L98 | train |
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 properties of variables",
"self",
".",
"sig_var_properties",
".",
"connect",
"(",
"lambda",
"data",
":",
"self",
".",
"namespacebrowser",
".",
"set_var_properties",
"(",
"data",
")",
")"
] | 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 | train |
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.namespace_view_settings = %s\"",
"%",
"settings",
")",
"self",
".",
"silent_execute",
"(",
"code",
")"
] | 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 | train |
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",
"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"
] | 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 | train |
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",
".",
"_reading",
":",
"self",
".",
"kernel_client",
".",
"input",
"(",
"u'!'",
"+",
"code",
")",
"else",
":",
"self",
".",
"silent_execute",
"(",
"code",
")"
] | 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 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/namespacebrowser.py | NamepaceBrowserWidget.remove_value | def remove_value(self, name):
"""Remove a variable"""
code = u"get_ipython().kernel.remove_value('%s')" % name
if self._reading:
self.kernel_client.input(u'!' + code)
else:
self.silent_execute(code) | python | def remove_value(self, name):
"""Remove a variable"""
code = u"get_ipython().kernel.remove_value('%s')" % name
if self._reading:
self.kernel_client.input(u'!' + code)
else:
self.silent_execute(code) | [
"def",
"remove_value",
"(",
"self",
",",
"name",
")",
":",
"code",
"=",
"u\"get_ipython().kernel.remove_value('%s')\"",
"%",
"name",
"if",
"self",
".",
"_reading",
":",
"self",
".",
"kernel_client",
".",
"input",
"(",
"u'!'",
"+",
"code",
")",
"else",
":",
"self",
".",
"silent_execute",
"(",
"code",
")"
] | Remove a variable | [
"Remove",
"a",
"variable"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L121-L127 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/namespacebrowser.py | NamepaceBrowserWidget.copy_value | def copy_value(self, orig_name, new_name):
"""Copy a variable"""
code = u"get_ipython().kernel.copy_value('%s', '%s')" % (orig_name,
new_name)
if self._reading:
self.kernel_client.input(u'!' + code)
else:
self.silent_execute(code) | python | def copy_value(self, orig_name, new_name):
"""Copy a variable"""
code = u"get_ipython().kernel.copy_value('%s', '%s')" % (orig_name,
new_name)
if self._reading:
self.kernel_client.input(u'!' + code)
else:
self.silent_execute(code) | [
"def",
"copy_value",
"(",
"self",
",",
"orig_name",
",",
"new_name",
")",
":",
"code",
"=",
"u\"get_ipython().kernel.copy_value('%s', '%s')\"",
"%",
"(",
"orig_name",
",",
"new_name",
")",
"if",
"self",
".",
"_reading",
":",
"self",
".",
"kernel_client",
".",
"input",
"(",
"u'!'",
"+",
"code",
")",
"else",
":",
"self",
".",
"silent_execute",
"(",
"code",
")"
] | Copy a variable | [
"Copy",
"a",
"variable"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/namespacebrowser.py#L129-L136 | train |
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",
":",
"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",
")"
] | 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 | train |
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 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",
")"
] | 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 | train |
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'",
",",
"''",
")",
"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",
")"
] | 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 | train |
spyder-ide/spyder | spyder/plugins/base.py | PluginWindow.closeEvent | def closeEvent(self, event):
"""Reimplement Qt method."""
self.plugin.dockwidget.setWidget(self.plugin)
self.plugin.dockwidget.setVisible(True)
self.plugin.switch_to_plugin()
QMainWindow.closeEvent(self, event)
self.plugin.undocked_window = None | python | def closeEvent(self, event):
"""Reimplement Qt method."""
self.plugin.dockwidget.setWidget(self.plugin)
self.plugin.dockwidget.setVisible(True)
self.plugin.switch_to_plugin()
QMainWindow.closeEvent(self, event)
self.plugin.undocked_window = None | [
"def",
"closeEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"plugin",
".",
"dockwidget",
".",
"setWidget",
"(",
"self",
".",
"plugin",
")",
"self",
".",
"plugin",
".",
"dockwidget",
".",
"setVisible",
"(",
"True",
")",
"self",
".",
"plugin",
".",
"switch_to_plugin",
"(",
")",
"QMainWindow",
".",
"closeEvent",
"(",
"self",
",",
"event",
")",
"self",
".",
"plugin",
".",
"undocked_window",
"=",
"None"
] | Reimplement Qt method. | [
"Reimplement",
"Qt",
"method",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L38-L44 | train |
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",
".",
"set_option",
"(",
"'first_time'",
",",
"False",
")"
] | 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 | train |
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",
".",
"get",
"(",
"'main'",
",",
"'use_custom_margin'",
")",
":",
"margin",
"=",
"CONF",
".",
"get",
"(",
"'main'",
",",
"'custom_margin'",
")",
"layout",
".",
"setContentsMargins",
"(",
"*",
"[",
"margin",
"]",
"*",
"4",
")",
"else",
":",
"layout",
".",
"setContentsMargins",
"(",
"*",
"self",
".",
"default_margins",
")"
] | Update plugin margins | [
"Update",
"plugin",
"margins"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L91-L100 | train |
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_window",
"else",
":",
"return",
"win",
".",
"setWindowTitle",
"(",
"self",
".",
"get_plugin_title",
"(",
")",
")"
] | 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 | train |
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",
".",
"__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",
")"
] | 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 | train |
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",
"(",
")",
"return",
"configwidget"
] | 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 | train |
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",
"=",
"self",
".",
"FONT_SIZE_DELTA",
"return",
"get_font",
"(",
"option",
"=",
"option",
",",
"font_size_delta",
"=",
"font_size_delta",
")"
] | 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 | train |
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 | train |
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",
"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"
] | 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 | train |
spyder-ide/spyder | spyder/plugins/base.py | BasePluginMixin.toggle_view | def toggle_view(self, checked):
"""Toggle view"""
if not self.dockwidget:
return
if checked:
self.dockwidget.show()
self.dockwidget.raise_()
else:
self.dockwidget.hide() | python | def toggle_view(self, checked):
"""Toggle view"""
if not self.dockwidget:
return
if checked:
self.dockwidget.show()
self.dockwidget.raise_()
else:
self.dockwidget.hide() | [
"def",
"toggle_view",
"(",
"self",
",",
"checked",
")",
":",
"if",
"not",
"self",
".",
"dockwidget",
":",
"return",
"if",
"checked",
":",
"self",
".",
"dockwidget",
".",
"show",
"(",
")",
"self",
".",
"dockwidget",
".",
"raise_",
"(",
")",
"else",
":",
"self",
".",
"dockwidget",
".",
"hide",
"(",
")"
] | Toggle view | [
"Toggle",
"view"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/base.py#L202-L210 | train |
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 Dock",
"# action is pressed",
"self",
".",
"undock_action",
".",
"setDisabled",
"(",
"False",
")",
"self",
".",
"close_plugin_action",
".",
"setDisabled",
"(",
"False",
")"
] | 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 | train |
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",
"(",
")",
"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",
"(",
")"
] | 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 | train |
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 | train |
spyder-ide/spyder | spyder/widgets/reporterror.py | DescriptionWidget.cut | def cut(self):
"""Cut text"""
self.truncate_selection(self.header_end_pos)
if self.has_selected_text():
CodeEditor.cut(self) | python | def cut(self):
"""Cut text"""
self.truncate_selection(self.header_end_pos)
if self.has_selected_text():
CodeEditor.cut(self) | [
"def",
"cut",
"(",
"self",
")",
":",
"self",
".",
"truncate_selection",
"(",
"self",
".",
"header_end_pos",
")",
"if",
"self",
".",
"has_selected_text",
"(",
")",
":",
"CodeEditor",
".",
"cut",
"(",
"self",
")"
] | Cut text | [
"Cut",
"text"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/reporterror.py#L76-L80 | train |
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_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",
")"
] | 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 | train |
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",
")",
":",
"# 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"
] | 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 | train |
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",
":",
"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'",
")",
")"
] | 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 | train |
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",
".",
"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",
")"
] | Activate submit_btn. | [
"Activate",
"submit_btn",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/reporterror.py#L325-L346 | train |
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",
"=",
"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"
] | 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 | train |
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",
"(",
"'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",
")"
] | 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 | train |
jrosebr1/imutils | imutils/convenience.py | build_montages | def build_montages(image_list, image_shape, montage_shape):
"""
---------------------------------------------------------------------------------------------
author: Kyle Hounslow
---------------------------------------------------------------------------------------------
Converts a list of single images into a list of 'montage' images of specified rows and columns.
A new montage image is started once rows and columns of montage image is filled.
Empty space of incomplete montage images are filled with black pixels
---------------------------------------------------------------------------------------------
:param image_list: python list of input images
:param image_shape: tuple, size each image will be resized to for display (width, height)
:param montage_shape: tuple, shape of image montage (width, height)
:return: list of montage images in numpy array format
---------------------------------------------------------------------------------------------
example usage:
# load single image
img = cv2.imread('lena.jpg')
# duplicate image 25 times
num_imgs = 25
img_list = []
for i in xrange(num_imgs):
img_list.append(img)
# convert image list into a montage of 256x256 images tiled in a 5x5 montage
montages = make_montages_of_images(img_list, (256, 256), (5, 5))
# iterate through montages and display
for montage in montages:
cv2.imshow('montage image', montage)
cv2.waitKey(0)
----------------------------------------------------------------------------------------------
"""
if len(image_shape) != 2:
raise Exception('image shape must be list or tuple of length 2 (rows, cols)')
if len(montage_shape) != 2:
raise Exception('montage shape must be list or tuple of length 2 (rows, cols)')
image_montages = []
# start with black canvas to draw images onto
montage_image = np.zeros(shape=(image_shape[1] * (montage_shape[1]), image_shape[0] * montage_shape[0], 3),
dtype=np.uint8)
cursor_pos = [0, 0]
start_new_img = False
for img in image_list:
if type(img).__module__ != np.__name__:
raise Exception('input of type {} is not a valid numpy array'.format(type(img)))
start_new_img = False
img = cv2.resize(img, image_shape)
# draw image to black canvas
montage_image[cursor_pos[1]:cursor_pos[1] + image_shape[1], cursor_pos[0]:cursor_pos[0] + image_shape[0]] = img
cursor_pos[0] += image_shape[0] # increment cursor x position
if cursor_pos[0] >= montage_shape[0] * image_shape[0]:
cursor_pos[1] += image_shape[1] # increment cursor y position
cursor_pos[0] = 0
if cursor_pos[1] >= montage_shape[1] * image_shape[1]:
cursor_pos = [0, 0]
image_montages.append(montage_image)
# reset black canvas
montage_image = np.zeros(shape=(image_shape[1] * (montage_shape[1]), image_shape[0] * montage_shape[0], 3),
dtype=np.uint8)
start_new_img = True
if start_new_img is False:
image_montages.append(montage_image) # add unfinished montage
return image_montages | python | def build_montages(image_list, image_shape, montage_shape):
"""
---------------------------------------------------------------------------------------------
author: Kyle Hounslow
---------------------------------------------------------------------------------------------
Converts a list of single images into a list of 'montage' images of specified rows and columns.
A new montage image is started once rows and columns of montage image is filled.
Empty space of incomplete montage images are filled with black pixels
---------------------------------------------------------------------------------------------
:param image_list: python list of input images
:param image_shape: tuple, size each image will be resized to for display (width, height)
:param montage_shape: tuple, shape of image montage (width, height)
:return: list of montage images in numpy array format
---------------------------------------------------------------------------------------------
example usage:
# load single image
img = cv2.imread('lena.jpg')
# duplicate image 25 times
num_imgs = 25
img_list = []
for i in xrange(num_imgs):
img_list.append(img)
# convert image list into a montage of 256x256 images tiled in a 5x5 montage
montages = make_montages_of_images(img_list, (256, 256), (5, 5))
# iterate through montages and display
for montage in montages:
cv2.imshow('montage image', montage)
cv2.waitKey(0)
----------------------------------------------------------------------------------------------
"""
if len(image_shape) != 2:
raise Exception('image shape must be list or tuple of length 2 (rows, cols)')
if len(montage_shape) != 2:
raise Exception('montage shape must be list or tuple of length 2 (rows, cols)')
image_montages = []
# start with black canvas to draw images onto
montage_image = np.zeros(shape=(image_shape[1] * (montage_shape[1]), image_shape[0] * montage_shape[0], 3),
dtype=np.uint8)
cursor_pos = [0, 0]
start_new_img = False
for img in image_list:
if type(img).__module__ != np.__name__:
raise Exception('input of type {} is not a valid numpy array'.format(type(img)))
start_new_img = False
img = cv2.resize(img, image_shape)
# draw image to black canvas
montage_image[cursor_pos[1]:cursor_pos[1] + image_shape[1], cursor_pos[0]:cursor_pos[0] + image_shape[0]] = img
cursor_pos[0] += image_shape[0] # increment cursor x position
if cursor_pos[0] >= montage_shape[0] * image_shape[0]:
cursor_pos[1] += image_shape[1] # increment cursor y position
cursor_pos[0] = 0
if cursor_pos[1] >= montage_shape[1] * image_shape[1]:
cursor_pos = [0, 0]
image_montages.append(montage_image)
# reset black canvas
montage_image = np.zeros(shape=(image_shape[1] * (montage_shape[1]), image_shape[0] * montage_shape[0], 3),
dtype=np.uint8)
start_new_img = True
if start_new_img is False:
image_montages.append(montage_image) # add unfinished montage
return image_montages | [
"def",
"build_montages",
"(",
"image_list",
",",
"image_shape",
",",
"montage_shape",
")",
":",
"if",
"len",
"(",
"image_shape",
")",
"!=",
"2",
":",
"raise",
"Exception",
"(",
"'image shape must be list or tuple of length 2 (rows, cols)'",
")",
"if",
"len",
"(",
"montage_shape",
")",
"!=",
"2",
":",
"raise",
"Exception",
"(",
"'montage shape must be list or tuple of length 2 (rows, cols)'",
")",
"image_montages",
"=",
"[",
"]",
"# start with black canvas to draw images onto",
"montage_image",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"image_shape",
"[",
"1",
"]",
"*",
"(",
"montage_shape",
"[",
"1",
"]",
")",
",",
"image_shape",
"[",
"0",
"]",
"*",
"montage_shape",
"[",
"0",
"]",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"cursor_pos",
"=",
"[",
"0",
",",
"0",
"]",
"start_new_img",
"=",
"False",
"for",
"img",
"in",
"image_list",
":",
"if",
"type",
"(",
"img",
")",
".",
"__module__",
"!=",
"np",
".",
"__name__",
":",
"raise",
"Exception",
"(",
"'input of type {} is not a valid numpy array'",
".",
"format",
"(",
"type",
"(",
"img",
")",
")",
")",
"start_new_img",
"=",
"False",
"img",
"=",
"cv2",
".",
"resize",
"(",
"img",
",",
"image_shape",
")",
"# draw image to black canvas",
"montage_image",
"[",
"cursor_pos",
"[",
"1",
"]",
":",
"cursor_pos",
"[",
"1",
"]",
"+",
"image_shape",
"[",
"1",
"]",
",",
"cursor_pos",
"[",
"0",
"]",
":",
"cursor_pos",
"[",
"0",
"]",
"+",
"image_shape",
"[",
"0",
"]",
"]",
"=",
"img",
"cursor_pos",
"[",
"0",
"]",
"+=",
"image_shape",
"[",
"0",
"]",
"# increment cursor x position",
"if",
"cursor_pos",
"[",
"0",
"]",
">=",
"montage_shape",
"[",
"0",
"]",
"*",
"image_shape",
"[",
"0",
"]",
":",
"cursor_pos",
"[",
"1",
"]",
"+=",
"image_shape",
"[",
"1",
"]",
"# increment cursor y position",
"cursor_pos",
"[",
"0",
"]",
"=",
"0",
"if",
"cursor_pos",
"[",
"1",
"]",
">=",
"montage_shape",
"[",
"1",
"]",
"*",
"image_shape",
"[",
"1",
"]",
":",
"cursor_pos",
"=",
"[",
"0",
",",
"0",
"]",
"image_montages",
".",
"append",
"(",
"montage_image",
")",
"# reset black canvas",
"montage_image",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"image_shape",
"[",
"1",
"]",
"*",
"(",
"montage_shape",
"[",
"1",
"]",
")",
",",
"image_shape",
"[",
"0",
"]",
"*",
"montage_shape",
"[",
"0",
"]",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"start_new_img",
"=",
"True",
"if",
"start_new_img",
"is",
"False",
":",
"image_montages",
".",
"append",
"(",
"montage_image",
")",
"# add unfinished montage",
"return",
"image_montages"
] | ---------------------------------------------------------------------------------------------
author: Kyle Hounslow
---------------------------------------------------------------------------------------------
Converts a list of single images into a list of 'montage' images of specified rows and columns.
A new montage image is started once rows and columns of montage image is filled.
Empty space of incomplete montage images are filled with black pixels
---------------------------------------------------------------------------------------------
:param image_list: python list of input images
:param image_shape: tuple, size each image will be resized to for display (width, height)
:param montage_shape: tuple, shape of image montage (width, height)
:return: list of montage images in numpy array format
---------------------------------------------------------------------------------------------
example usage:
# load single image
img = cv2.imread('lena.jpg')
# duplicate image 25 times
num_imgs = 25
img_list = []
for i in xrange(num_imgs):
img_list.append(img)
# convert image list into a montage of 256x256 images tiled in a 5x5 montage
montages = make_montages_of_images(img_list, (256, 256), (5, 5))
# iterate through montages and display
for montage in montages:
cv2.imshow('montage image', montage)
cv2.waitKey(0)
---------------------------------------------------------------------------------------------- | [
"---------------------------------------------------------------------------------------------",
"author",
":",
"Kyle",
"Hounslow",
"---------------------------------------------------------------------------------------------",
"Converts",
"a",
"list",
"of",
"single",
"images",
"into",
"a",
"list",
"of",
"montage",
"images",
"of",
"specified",
"rows",
"and",
"columns",
".",
"A",
"new",
"montage",
"image",
"is",
"started",
"once",
"rows",
"and",
"columns",
"of",
"montage",
"image",
"is",
"filled",
".",
"Empty",
"space",
"of",
"incomplete",
"montage",
"images",
"are",
"filled",
"with",
"black",
"pixels",
"---------------------------------------------------------------------------------------------",
":",
"param",
"image_list",
":",
"python",
"list",
"of",
"input",
"images",
":",
"param",
"image_shape",
":",
"tuple",
"size",
"each",
"image",
"will",
"be",
"resized",
"to",
"for",
"display",
"(",
"width",
"height",
")",
":",
"param",
"montage_shape",
":",
"tuple",
"shape",
"of",
"image",
"montage",
"(",
"width",
"height",
")",
":",
"return",
":",
"list",
"of",
"montage",
"images",
"in",
"numpy",
"array",
"format",
"---------------------------------------------------------------------------------------------"
] | 4430083199793bd66db64e574379cbe18414d420 | https://github.com/jrosebr1/imutils/blob/4430083199793bd66db64e574379cbe18414d420/imutils/convenience.py#L238-L301 | train |
jrosebr1/imutils | imutils/convenience.py | adjust_brightness_contrast | def adjust_brightness_contrast(image, brightness=0., contrast=0.):
"""
Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change
"""
beta = 0
# See the OpenCV docs for more info on the `beta` parameter to addWeighted
# https://docs.opencv.org/3.4.2/d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19
return cv2.addWeighted(image,
1 + float(contrast) / 100.,
image,
beta,
float(brightness)) | python | def adjust_brightness_contrast(image, brightness=0., contrast=0.):
"""
Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change
"""
beta = 0
# See the OpenCV docs for more info on the `beta` parameter to addWeighted
# https://docs.opencv.org/3.4.2/d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19
return cv2.addWeighted(image,
1 + float(contrast) / 100.,
image,
beta,
float(brightness)) | [
"def",
"adjust_brightness_contrast",
"(",
"image",
",",
"brightness",
"=",
"0.",
",",
"contrast",
"=",
"0.",
")",
":",
"beta",
"=",
"0",
"# See the OpenCV docs for more info on the `beta` parameter to addWeighted",
"# https://docs.opencv.org/3.4.2/d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19",
"return",
"cv2",
".",
"addWeighted",
"(",
"image",
",",
"1",
"+",
"float",
"(",
"contrast",
")",
"/",
"100.",
",",
"image",
",",
"beta",
",",
"float",
"(",
"brightness",
")",
")"
] | Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change | [
"Adjust",
"the",
"brightness",
"and",
"/",
"or",
"contrast",
"of",
"an",
"image"
] | 4430083199793bd66db64e574379cbe18414d420 | https://github.com/jrosebr1/imutils/blob/4430083199793bd66db64e574379cbe18414d420/imutils/convenience.py#L304-L319 | train |
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",
",",
"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",
")"
] | 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 | train |
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",
"[",
":",
"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",
")"
] | 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 | train |
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",
"]",
"[",
"1",
"]",
",",
"1",
")",
"for",
"kp",
"in",
"corners",
"]",
"return",
"keypoints"
] | 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 | train |
sdispater/poetry | poetry/packages/utils/utils.py | path_to_url | def path_to_url(path):
"""
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
"""
path = os.path.normpath(os.path.abspath(path))
url = urlparse.urljoin("file:", urllib2.pathname2url(path))
return url | python | def path_to_url(path):
"""
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
"""
path = os.path.normpath(os.path.abspath(path))
url = urlparse.urljoin("file:", urllib2.pathname2url(path))
return url | [
"def",
"path_to_url",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"url",
"=",
"urlparse",
".",
"urljoin",
"(",
"\"file:\"",
",",
"urllib2",
".",
"pathname2url",
"(",
"path",
")",
")",
"return",
"url"
] | Convert a path to a file: URL. The path will be made absolute and have
quoted path parts. | [
"Convert",
"a",
"path",
"to",
"a",
"file",
":",
"URL",
".",
"The",
"path",
"will",
"be",
"made",
"absolute",
"and",
"have",
"quoted",
"path",
"parts",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/utils/utils.py#L49-L56 | train |
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",
".",
"path",
".",
"isfile",
"(",
"setup_py",
")",
":",
"return",
"True",
"return",
"False"
] | 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 | train |
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",
"key",
"not",
"in",
"config",
":",
"return",
"default",
"config",
"=",
"config",
"[",
"key",
"]",
"return",
"config"
] | Retrieve a setting value. | [
"Retrieve",
"a",
"setting",
"value",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/config.py#L36-L49 | train |
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",
".",
"package",
".",
"requires",
")",
"return",
"main"
] | 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 | train |
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",
"(",
"poetry",
",",
"SystemEnv",
"(",
"Path",
"(",
"sys",
".",
"prefix",
")",
")",
",",
"NullIO",
"(",
")",
",",
"Path",
"(",
"wheel_directory",
")",
")",
")"
] | 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 | train |
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",
")",
")",
",",
"NullIO",
"(",
")",
")",
".",
"build",
"(",
"Path",
"(",
"sdist_directory",
")",
")",
"return",
"unicode",
"(",
"path",
".",
"name",
")"
] | 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 | train |
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",
"incompatibility",
"in",
"cause",
".",
"conflict",
".",
"external_incompatibilities",
":",
"yield",
"incompatibility",
"for",
"incompatibility",
"in",
"cause",
".",
"other",
".",
"external_incompatibilities",
":",
"yield",
"incompatibility",
"else",
":",
"yield",
"self"
] | 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 | train |
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 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",
")",
")",
")"
] | 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 | train |
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",
",",
"self",
".",
"decision_level",
",",
"len",
"(",
"self",
".",
"_assignments",
")",
",",
")",
")"
] | 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 | train |
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 | train |
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",
">",
"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",
")"
] | 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 | train |
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",
"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"
] | 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 | train |
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",
".",
"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",
")",
")"
] | 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 | train |
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_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"
] | 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 | train |
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",
"[",
"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"
] | 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 | train |
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",
"=",
"normalize_file_permissions",
"(",
"ti",
".",
"mode",
")",
"return",
"ti"
] | 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 | train |
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",
"(",
"RuntimeError",
",",
"ShellDetectionFailure",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to detect the current shell.\"",
")",
"cls",
".",
"_shell",
"=",
"cls",
"(",
"name",
",",
"path",
")",
"return",
"cls",
".",
"_shell"
] | Retrieve the current shell. | [
"Retrieve",
"the",
"current",
"shell",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/utils/shell.py#L27-L41 | train |
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",
"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",
")"
] | 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 | train |
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",
".",
"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",
"]"
] | 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 | train |
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",
"=",
"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",
"]"
] | 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 | train |
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",
".",
"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",
")",
")"
] | 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 | train |
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 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",
")"
] | 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 | train |
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",
"# 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"
] | 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 | train |
sdispater/poetry | poetry/mixology/version_solver.py | VersionSolver._resolve_conflict | def _resolve_conflict(
self, incompatibility
): # type: (Incompatibility) -> Incompatibility
"""
Given an incompatibility that's satisfied by _solution,
The `conflict resolution`_ constructs a new incompatibility that encapsulates the root
cause of the conflict and backtracks _solution until the new
incompatibility will allow _propagate() to deduce new assignments.
Adds the new incompatibility to _incompatibilities and returns it.
.. _conflict resolution: https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution
"""
self._log("conflict: {}".format(incompatibility))
new_incompatibility = False
while not incompatibility.is_failure():
# The term in incompatibility.terms that was most recently satisfied by
# _solution.
most_recent_term = None
# The earliest assignment in _solution such that incompatibility is
# satisfied by _solution up to and including this assignment.
most_recent_satisfier = None
# The difference between most_recent_satisfier and most_recent_term;
# that is, the versions that are allowed by most_recent_satisfier and not
# by most_recent_term. This is None if most_recent_satisfier totally
# satisfies most_recent_term.
difference = None
# The decision level of the earliest assignment in _solution *before*
# most_recent_satisfier such that incompatibility is satisfied by
# _solution up to and including this assignment plus
# most_recent_satisfier.
#
# Decision level 1 is the level where the root package was selected. It's
# safe to go back to decision level 0, but stopping at 1 tends to produce
# better error messages, because references to the root package end up
# closer to the final conclusion that no solution exists.
previous_satisfier_level = 1
for term in incompatibility.terms:
satisfier = self._solution.satisfier(term)
if most_recent_satisfier is None:
most_recent_term = term
most_recent_satisfier = satisfier
elif most_recent_satisfier.index < satisfier.index:
previous_satisfier_level = max(
previous_satisfier_level, most_recent_satisfier.decision_level
)
most_recent_term = term
most_recent_satisfier = satisfier
difference = None
else:
previous_satisfier_level = max(
previous_satisfier_level, satisfier.decision_level
)
if most_recent_term == term:
# If most_recent_satisfier doesn't satisfy most_recent_term on its
# own, then the next-most-recent satisfier may be the one that
# satisfies the remainder.
difference = most_recent_satisfier.difference(most_recent_term)
if difference is not None:
previous_satisfier_level = max(
previous_satisfier_level,
self._solution.satisfier(difference.inverse).decision_level,
)
# If most_recent_identifier is the only satisfier left at its decision
# level, or if it has no cause (indicating that it's a decision rather
# than a derivation), then incompatibility is the root cause. We then
# backjump to previous_satisfier_level, where incompatibility is
# guaranteed to allow _propagate to produce more assignments.
if (
previous_satisfier_level < most_recent_satisfier.decision_level
or most_recent_satisfier.cause is None
):
self._solution.backtrack(previous_satisfier_level)
if new_incompatibility:
self._add_incompatibility(incompatibility)
return incompatibility
# Create a new incompatibility by combining incompatibility with the
# incompatibility that caused most_recent_satisfier to be assigned. Doing
# this iteratively constructs an incompatibility that's guaranteed to be
# true (that is, we know for sure no solution will satisfy the
# incompatibility) while also approximating the intuitive notion of the
# "root cause" of the conflict.
new_terms = []
for term in incompatibility.terms:
if term != most_recent_term:
new_terms.append(term)
for term in most_recent_satisfier.cause.terms:
if term.dependency != most_recent_satisfier.dependency:
new_terms.append(term)
# The most_recent_satisfier may not satisfy most_recent_term on its own
# if there are a collection of constraints on most_recent_term that
# only satisfy it together. For example, if most_recent_term is
# `foo ^1.0.0` and _solution contains `[foo >=1.0.0,
# foo <2.0.0]`, then most_recent_satisfier will be `foo <2.0.0` even
# though it doesn't totally satisfy `foo ^1.0.0`.
#
# In this case, we add `not (most_recent_satisfier \ most_recent_term)` to
# the incompatibility as well, See the `algorithm documentation`_ for
# details.
#
# .. _algorithm documentation: https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution
if difference is not None:
new_terms.append(difference.inverse)
incompatibility = Incompatibility(
new_terms, ConflictCause(incompatibility, most_recent_satisfier.cause)
)
new_incompatibility = True
partially = "" if difference is None else " partially"
bang = "!"
self._log(
"{} {} is{} satisfied by {}".format(
bang, most_recent_term, partially, most_recent_satisfier
)
)
self._log(
'{} which is caused by "{}"'.format(bang, most_recent_satisfier.cause)
)
self._log("{} thus: {}".format(bang, incompatibility))
raise SolveFailure(incompatibility) | python | def _resolve_conflict(
self, incompatibility
): # type: (Incompatibility) -> Incompatibility
"""
Given an incompatibility that's satisfied by _solution,
The `conflict resolution`_ constructs a new incompatibility that encapsulates the root
cause of the conflict and backtracks _solution until the new
incompatibility will allow _propagate() to deduce new assignments.
Adds the new incompatibility to _incompatibilities and returns it.
.. _conflict resolution: https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution
"""
self._log("conflict: {}".format(incompatibility))
new_incompatibility = False
while not incompatibility.is_failure():
# The term in incompatibility.terms that was most recently satisfied by
# _solution.
most_recent_term = None
# The earliest assignment in _solution such that incompatibility is
# satisfied by _solution up to and including this assignment.
most_recent_satisfier = None
# The difference between most_recent_satisfier and most_recent_term;
# that is, the versions that are allowed by most_recent_satisfier and not
# by most_recent_term. This is None if most_recent_satisfier totally
# satisfies most_recent_term.
difference = None
# The decision level of the earliest assignment in _solution *before*
# most_recent_satisfier such that incompatibility is satisfied by
# _solution up to and including this assignment plus
# most_recent_satisfier.
#
# Decision level 1 is the level where the root package was selected. It's
# safe to go back to decision level 0, but stopping at 1 tends to produce
# better error messages, because references to the root package end up
# closer to the final conclusion that no solution exists.
previous_satisfier_level = 1
for term in incompatibility.terms:
satisfier = self._solution.satisfier(term)
if most_recent_satisfier is None:
most_recent_term = term
most_recent_satisfier = satisfier
elif most_recent_satisfier.index < satisfier.index:
previous_satisfier_level = max(
previous_satisfier_level, most_recent_satisfier.decision_level
)
most_recent_term = term
most_recent_satisfier = satisfier
difference = None
else:
previous_satisfier_level = max(
previous_satisfier_level, satisfier.decision_level
)
if most_recent_term == term:
# If most_recent_satisfier doesn't satisfy most_recent_term on its
# own, then the next-most-recent satisfier may be the one that
# satisfies the remainder.
difference = most_recent_satisfier.difference(most_recent_term)
if difference is not None:
previous_satisfier_level = max(
previous_satisfier_level,
self._solution.satisfier(difference.inverse).decision_level,
)
# If most_recent_identifier is the only satisfier left at its decision
# level, or if it has no cause (indicating that it's a decision rather
# than a derivation), then incompatibility is the root cause. We then
# backjump to previous_satisfier_level, where incompatibility is
# guaranteed to allow _propagate to produce more assignments.
if (
previous_satisfier_level < most_recent_satisfier.decision_level
or most_recent_satisfier.cause is None
):
self._solution.backtrack(previous_satisfier_level)
if new_incompatibility:
self._add_incompatibility(incompatibility)
return incompatibility
# Create a new incompatibility by combining incompatibility with the
# incompatibility that caused most_recent_satisfier to be assigned. Doing
# this iteratively constructs an incompatibility that's guaranteed to be
# true (that is, we know for sure no solution will satisfy the
# incompatibility) while also approximating the intuitive notion of the
# "root cause" of the conflict.
new_terms = []
for term in incompatibility.terms:
if term != most_recent_term:
new_terms.append(term)
for term in most_recent_satisfier.cause.terms:
if term.dependency != most_recent_satisfier.dependency:
new_terms.append(term)
# The most_recent_satisfier may not satisfy most_recent_term on its own
# if there are a collection of constraints on most_recent_term that
# only satisfy it together. For example, if most_recent_term is
# `foo ^1.0.0` and _solution contains `[foo >=1.0.0,
# foo <2.0.0]`, then most_recent_satisfier will be `foo <2.0.0` even
# though it doesn't totally satisfy `foo ^1.0.0`.
#
# In this case, we add `not (most_recent_satisfier \ most_recent_term)` to
# the incompatibility as well, See the `algorithm documentation`_ for
# details.
#
# .. _algorithm documentation: https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution
if difference is not None:
new_terms.append(difference.inverse)
incompatibility = Incompatibility(
new_terms, ConflictCause(incompatibility, most_recent_satisfier.cause)
)
new_incompatibility = True
partially = "" if difference is None else " partially"
bang = "!"
self._log(
"{} {} is{} satisfied by {}".format(
bang, most_recent_term, partially, most_recent_satisfier
)
)
self._log(
'{} which is caused by "{}"'.format(bang, most_recent_satisfier.cause)
)
self._log("{} thus: {}".format(bang, incompatibility))
raise SolveFailure(incompatibility) | [
"def",
"_resolve_conflict",
"(",
"self",
",",
"incompatibility",
")",
":",
"# type: (Incompatibility) -> Incompatibility",
"self",
".",
"_log",
"(",
"\"conflict: {}\"",
".",
"format",
"(",
"incompatibility",
")",
")",
"new_incompatibility",
"=",
"False",
"while",
"not",
"incompatibility",
".",
"is_failure",
"(",
")",
":",
"# The term in incompatibility.terms that was most recently satisfied by",
"# _solution.",
"most_recent_term",
"=",
"None",
"# The earliest assignment in _solution such that incompatibility is",
"# satisfied by _solution up to and including this assignment.",
"most_recent_satisfier",
"=",
"None",
"# The difference between most_recent_satisfier and most_recent_term;",
"# that is, the versions that are allowed by most_recent_satisfier and not",
"# by most_recent_term. This is None if most_recent_satisfier totally",
"# satisfies most_recent_term.",
"difference",
"=",
"None",
"# The decision level of the earliest assignment in _solution *before*",
"# most_recent_satisfier such that incompatibility is satisfied by",
"# _solution up to and including this assignment plus",
"# most_recent_satisfier.",
"#",
"# Decision level 1 is the level where the root package was selected. It's",
"# safe to go back to decision level 0, but stopping at 1 tends to produce",
"# better error messages, because references to the root package end up",
"# closer to the final conclusion that no solution exists.",
"previous_satisfier_level",
"=",
"1",
"for",
"term",
"in",
"incompatibility",
".",
"terms",
":",
"satisfier",
"=",
"self",
".",
"_solution",
".",
"satisfier",
"(",
"term",
")",
"if",
"most_recent_satisfier",
"is",
"None",
":",
"most_recent_term",
"=",
"term",
"most_recent_satisfier",
"=",
"satisfier",
"elif",
"most_recent_satisfier",
".",
"index",
"<",
"satisfier",
".",
"index",
":",
"previous_satisfier_level",
"=",
"max",
"(",
"previous_satisfier_level",
",",
"most_recent_satisfier",
".",
"decision_level",
")",
"most_recent_term",
"=",
"term",
"most_recent_satisfier",
"=",
"satisfier",
"difference",
"=",
"None",
"else",
":",
"previous_satisfier_level",
"=",
"max",
"(",
"previous_satisfier_level",
",",
"satisfier",
".",
"decision_level",
")",
"if",
"most_recent_term",
"==",
"term",
":",
"# If most_recent_satisfier doesn't satisfy most_recent_term on its",
"# own, then the next-most-recent satisfier may be the one that",
"# satisfies the remainder.",
"difference",
"=",
"most_recent_satisfier",
".",
"difference",
"(",
"most_recent_term",
")",
"if",
"difference",
"is",
"not",
"None",
":",
"previous_satisfier_level",
"=",
"max",
"(",
"previous_satisfier_level",
",",
"self",
".",
"_solution",
".",
"satisfier",
"(",
"difference",
".",
"inverse",
")",
".",
"decision_level",
",",
")",
"# If most_recent_identifier is the only satisfier left at its decision",
"# level, or if it has no cause (indicating that it's a decision rather",
"# than a derivation), then incompatibility is the root cause. We then",
"# backjump to previous_satisfier_level, where incompatibility is",
"# guaranteed to allow _propagate to produce more assignments.",
"if",
"(",
"previous_satisfier_level",
"<",
"most_recent_satisfier",
".",
"decision_level",
"or",
"most_recent_satisfier",
".",
"cause",
"is",
"None",
")",
":",
"self",
".",
"_solution",
".",
"backtrack",
"(",
"previous_satisfier_level",
")",
"if",
"new_incompatibility",
":",
"self",
".",
"_add_incompatibility",
"(",
"incompatibility",
")",
"return",
"incompatibility",
"# Create a new incompatibility by combining incompatibility with the",
"# incompatibility that caused most_recent_satisfier to be assigned. Doing",
"# this iteratively constructs an incompatibility that's guaranteed to be",
"# true (that is, we know for sure no solution will satisfy the",
"# incompatibility) while also approximating the intuitive notion of the",
"# \"root cause\" of the conflict.",
"new_terms",
"=",
"[",
"]",
"for",
"term",
"in",
"incompatibility",
".",
"terms",
":",
"if",
"term",
"!=",
"most_recent_term",
":",
"new_terms",
".",
"append",
"(",
"term",
")",
"for",
"term",
"in",
"most_recent_satisfier",
".",
"cause",
".",
"terms",
":",
"if",
"term",
".",
"dependency",
"!=",
"most_recent_satisfier",
".",
"dependency",
":",
"new_terms",
".",
"append",
"(",
"term",
")",
"# The most_recent_satisfier may not satisfy most_recent_term on its own",
"# if there are a collection of constraints on most_recent_term that",
"# only satisfy it together. For example, if most_recent_term is",
"# `foo ^1.0.0` and _solution contains `[foo >=1.0.0,",
"# foo <2.0.0]`, then most_recent_satisfier will be `foo <2.0.0` even",
"# though it doesn't totally satisfy `foo ^1.0.0`.",
"#",
"# In this case, we add `not (most_recent_satisfier \\ most_recent_term)` to",
"# the incompatibility as well, See the `algorithm documentation`_ for",
"# details.",
"#",
"# .. _algorithm documentation: https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution",
"if",
"difference",
"is",
"not",
"None",
":",
"new_terms",
".",
"append",
"(",
"difference",
".",
"inverse",
")",
"incompatibility",
"=",
"Incompatibility",
"(",
"new_terms",
",",
"ConflictCause",
"(",
"incompatibility",
",",
"most_recent_satisfier",
".",
"cause",
")",
")",
"new_incompatibility",
"=",
"True",
"partially",
"=",
"\"\"",
"if",
"difference",
"is",
"None",
"else",
"\" partially\"",
"bang",
"=",
"\"!\"",
"self",
".",
"_log",
"(",
"\"{} {} is{} satisfied by {}\"",
".",
"format",
"(",
"bang",
",",
"most_recent_term",
",",
"partially",
",",
"most_recent_satisfier",
")",
")",
"self",
".",
"_log",
"(",
"'{} which is caused by \"{}\"'",
".",
"format",
"(",
"bang",
",",
"most_recent_satisfier",
".",
"cause",
")",
")",
"self",
".",
"_log",
"(",
"\"{} thus: {}\"",
".",
"format",
"(",
"bang",
",",
"incompatibility",
")",
")",
"raise",
"SolveFailure",
"(",
"incompatibility",
")"
] | Given an incompatibility that's satisfied by _solution,
The `conflict resolution`_ constructs a new incompatibility that encapsulates the root
cause of the conflict and backtracks _solution until the new
incompatibility will allow _propagate() to deduce new assignments.
Adds the new incompatibility to _incompatibilities and returns it.
.. _conflict resolution: https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution | [
"Given",
"an",
"incompatibility",
"that",
"s",
"satisfied",
"by",
"_solution",
"The",
"conflict",
"resolution",
"_",
"constructs",
"a",
"new",
"incompatibility",
"that",
"encapsulates",
"the",
"root",
"cause",
"of",
"the",
"conflict",
"and",
"backtracks",
"_solution",
"until",
"the",
"new",
"incompatibility",
"will",
"allow",
"_propagate",
"()",
"to",
"deduce",
"new",
"assignments",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/version_solver.py#L183-L316 | train |
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 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"
] | 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 | train |
sdispater/poetry | poetry/mixology/version_solver.py | VersionSolver._result | def _result(self): # type: () -> SolverResult
"""
Creates a #SolverResult from the decisions in _solution
"""
decisions = self._solution.decisions
return SolverResult(
self._root,
[p for p in decisions if not p.is_root()],
self._solution.attempted_solutions,
) | python | def _result(self): # type: () -> SolverResult
"""
Creates a #SolverResult from the decisions in _solution
"""
decisions = self._solution.decisions
return SolverResult(
self._root,
[p for p in decisions if not p.is_root()],
self._solution.attempted_solutions,
) | [
"def",
"_result",
"(",
"self",
")",
":",
"# type: () -> SolverResult",
"decisions",
"=",
"self",
".",
"_solution",
".",
"decisions",
"return",
"SolverResult",
"(",
"self",
".",
"_root",
",",
"[",
"p",
"for",
"p",
"in",
"decisions",
"if",
"not",
"p",
".",
"is_root",
"(",
")",
"]",
",",
"self",
".",
"_solution",
".",
"attempted_solutions",
",",
")"
] | Creates a #SolverResult from the decisions in _solution | [
"Creates",
"a",
"#SolverResult",
"from",
"the",
"decisions",
"in",
"_solution"
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/version_solver.py#L407-L417 | train |
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",
"(",
"\"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",
")"
] | 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 | train |
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",
".",
"exists",
"(",
")",
":",
"return",
"bin",
"return",
"str",
"(",
"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 | train |
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",
")",
")",
"# 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",
")"
] | 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 | train |
sdispater/poetry | poetry/masonry/utils/tags.py | get_abbr_impl | def get_abbr_impl(env):
"""Return abbreviated implementation name."""
impl = env.python_implementation
if impl == "PyPy":
return "pp"
elif impl == "Jython":
return "jy"
elif impl == "IronPython":
return "ip"
elif impl == "CPython":
return "cp"
raise LookupError("Unknown Python implementation: " + impl) | python | def get_abbr_impl(env):
"""Return abbreviated implementation name."""
impl = env.python_implementation
if impl == "PyPy":
return "pp"
elif impl == "Jython":
return "jy"
elif impl == "IronPython":
return "ip"
elif impl == "CPython":
return "cp"
raise LookupError("Unknown Python implementation: " + impl) | [
"def",
"get_abbr_impl",
"(",
"env",
")",
":",
"impl",
"=",
"env",
".",
"python_implementation",
"if",
"impl",
"==",
"\"PyPy\"",
":",
"return",
"\"pp\"",
"elif",
"impl",
"==",
"\"Jython\"",
":",
"return",
"\"jy\"",
"elif",
"impl",
"==",
"\"IronPython\"",
":",
"return",
"\"ip\"",
"elif",
"impl",
"==",
"\"CPython\"",
":",
"return",
"\"cp\"",
"raise",
"LookupError",
"(",
"\"Unknown Python implementation: \"",
"+",
"impl",
")"
] | Return abbreviated implementation name. | [
"Return",
"abbreviated",
"implementation",
"name",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/utils/tags.py#L15-L28 | train |
sdispater/poetry | poetry/masonry/utils/tags.py | get_impl_ver | def get_impl_ver(env):
"""Return implementation version."""
impl_ver = env.config_var("py_version_nodot")
if not impl_ver or get_abbr_impl(env) == "pp":
impl_ver = "".join(map(str, get_impl_version_info(env)))
return impl_ver | python | def get_impl_ver(env):
"""Return implementation version."""
impl_ver = env.config_var("py_version_nodot")
if not impl_ver or get_abbr_impl(env) == "pp":
impl_ver = "".join(map(str, get_impl_version_info(env)))
return impl_ver | [
"def",
"get_impl_ver",
"(",
"env",
")",
":",
"impl_ver",
"=",
"env",
".",
"config_var",
"(",
"\"py_version_nodot\"",
")",
"if",
"not",
"impl_ver",
"or",
"get_abbr_impl",
"(",
"env",
")",
"==",
"\"pp\"",
":",
"impl_ver",
"=",
"\"\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"get_impl_version_info",
"(",
"env",
")",
")",
")",
"return",
"impl_ver"
] | Return implementation version. | [
"Return",
"implementation",
"version",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/utils/tags.py#L31-L37 | train |
sdispater/poetry | poetry/masonry/utils/tags.py | get_flag | def get_flag(env, var, fallback, expected=True, warn=True):
"""Use a fallback method for determining SOABI flags if the needed config
var is unset or unavailable."""
val = env.config_var(var)
if val is None:
if warn:
warnings.warn(
"Config variable '{0}' is unset, Python ABI tag may "
"be incorrect".format(var),
RuntimeWarning,
2,
)
return fallback()
return val == expected | python | def get_flag(env, var, fallback, expected=True, warn=True):
"""Use a fallback method for determining SOABI flags if the needed config
var is unset or unavailable."""
val = env.config_var(var)
if val is None:
if warn:
warnings.warn(
"Config variable '{0}' is unset, Python ABI tag may "
"be incorrect".format(var),
RuntimeWarning,
2,
)
return fallback()
return val == expected | [
"def",
"get_flag",
"(",
"env",
",",
"var",
",",
"fallback",
",",
"expected",
"=",
"True",
",",
"warn",
"=",
"True",
")",
":",
"val",
"=",
"env",
".",
"config_var",
"(",
"var",
")",
"if",
"val",
"is",
"None",
":",
"if",
"warn",
":",
"warnings",
".",
"warn",
"(",
"\"Config variable '{0}' is unset, Python ABI tag may \"",
"\"be incorrect\"",
".",
"format",
"(",
"var",
")",
",",
"RuntimeWarning",
",",
"2",
",",
")",
"return",
"fallback",
"(",
")",
"return",
"val",
"==",
"expected"
] | Use a fallback method for determining SOABI flags if the needed config
var is unset or unavailable. | [
"Use",
"a",
"fallback",
"method",
"for",
"determining",
"SOABI",
"flags",
"if",
"the",
"needed",
"config",
"var",
"is",
"unset",
"or",
"unavailable",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/utils/tags.py#L50-L63 | train |
sdispater/poetry | poetry/packages/dependency.py | Dependency.accepts | def accepts(self, package): # type: (poetry.packages.Package) -> bool
"""
Determines if the given package matches this dependency.
"""
return (
self._name == package.name
and self._constraint.allows(package.version)
and (not package.is_prerelease() or self.allows_prereleases())
) | python | def accepts(self, package): # type: (poetry.packages.Package) -> bool
"""
Determines if the given package matches this dependency.
"""
return (
self._name == package.name
and self._constraint.allows(package.version)
and (not package.is_prerelease() or self.allows_prereleases())
) | [
"def",
"accepts",
"(",
"self",
",",
"package",
")",
":",
"# type: (poetry.packages.Package) -> bool",
"return",
"(",
"self",
".",
"_name",
"==",
"package",
".",
"name",
"and",
"self",
".",
"_constraint",
".",
"allows",
"(",
"package",
".",
"version",
")",
"and",
"(",
"not",
"package",
".",
"is_prerelease",
"(",
")",
"or",
"self",
".",
"allows_prereleases",
"(",
")",
")",
")"
] | Determines if the given package matches this dependency. | [
"Determines",
"if",
"the",
"given",
"package",
"matches",
"this",
"dependency",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/dependency.py#L166-L174 | train |
sdispater/poetry | poetry/packages/dependency.py | Dependency.deactivate | def deactivate(self):
"""
Set the dependency as optional.
"""
if not self._optional:
self._optional = True
self._activated = False | python | def deactivate(self):
"""
Set the dependency as optional.
"""
if not self._optional:
self._optional = True
self._activated = False | [
"def",
"deactivate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_optional",
":",
"self",
".",
"_optional",
"=",
"True",
"self",
".",
"_activated",
"=",
"False"
] | Set the dependency as optional. | [
"Set",
"the",
"dependency",
"as",
"optional",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/dependency.py#L282-L289 | train |
sdispater/poetry | get-poetry.py | Installer.install | def install(self, version, upgrade=False):
"""
Installs Poetry in $POETRY_HOME.
"""
print("Installing version: " + colorize("info", version))
self.make_lib(version)
self.make_bin()
self.make_env()
self.update_path()
return 0 | python | def install(self, version, upgrade=False):
"""
Installs Poetry in $POETRY_HOME.
"""
print("Installing version: " + colorize("info", version))
self.make_lib(version)
self.make_bin()
self.make_env()
self.update_path()
return 0 | [
"def",
"install",
"(",
"self",
",",
"version",
",",
"upgrade",
"=",
"False",
")",
":",
"print",
"(",
"\"Installing version: \"",
"+",
"colorize",
"(",
"\"info\"",
",",
"version",
")",
")",
"self",
".",
"make_lib",
"(",
"version",
")",
"self",
".",
"make_bin",
"(",
")",
"self",
".",
"make_env",
"(",
")",
"self",
".",
"update_path",
"(",
")",
"return",
"0"
] | Installs Poetry in $POETRY_HOME. | [
"Installs",
"Poetry",
"in",
"$POETRY_HOME",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/get-poetry.py#L453-L464 | train |
sdispater/poetry | get-poetry.py | Installer.make_lib | def make_lib(self, version):
"""
Packs everything into a single lib/ directory.
"""
if os.path.exists(POETRY_LIB_BACKUP):
shutil.rmtree(POETRY_LIB_BACKUP)
# Backup the current installation
if os.path.exists(POETRY_LIB):
shutil.copytree(POETRY_LIB, POETRY_LIB_BACKUP)
shutil.rmtree(POETRY_LIB)
try:
self._make_lib(version)
except Exception:
if not os.path.exists(POETRY_LIB_BACKUP):
raise
shutil.copytree(POETRY_LIB_BACKUP, POETRY_LIB)
shutil.rmtree(POETRY_LIB_BACKUP)
raise
finally:
if os.path.exists(POETRY_LIB_BACKUP):
shutil.rmtree(POETRY_LIB_BACKUP) | python | def make_lib(self, version):
"""
Packs everything into a single lib/ directory.
"""
if os.path.exists(POETRY_LIB_BACKUP):
shutil.rmtree(POETRY_LIB_BACKUP)
# Backup the current installation
if os.path.exists(POETRY_LIB):
shutil.copytree(POETRY_LIB, POETRY_LIB_BACKUP)
shutil.rmtree(POETRY_LIB)
try:
self._make_lib(version)
except Exception:
if not os.path.exists(POETRY_LIB_BACKUP):
raise
shutil.copytree(POETRY_LIB_BACKUP, POETRY_LIB)
shutil.rmtree(POETRY_LIB_BACKUP)
raise
finally:
if os.path.exists(POETRY_LIB_BACKUP):
shutil.rmtree(POETRY_LIB_BACKUP) | [
"def",
"make_lib",
"(",
"self",
",",
"version",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"POETRY_LIB_BACKUP",
")",
":",
"shutil",
".",
"rmtree",
"(",
"POETRY_LIB_BACKUP",
")",
"# Backup the current installation",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"POETRY_LIB",
")",
":",
"shutil",
".",
"copytree",
"(",
"POETRY_LIB",
",",
"POETRY_LIB_BACKUP",
")",
"shutil",
".",
"rmtree",
"(",
"POETRY_LIB",
")",
"try",
":",
"self",
".",
"_make_lib",
"(",
"version",
")",
"except",
"Exception",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"POETRY_LIB_BACKUP",
")",
":",
"raise",
"shutil",
".",
"copytree",
"(",
"POETRY_LIB_BACKUP",
",",
"POETRY_LIB",
")",
"shutil",
".",
"rmtree",
"(",
"POETRY_LIB_BACKUP",
")",
"raise",
"finally",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"POETRY_LIB_BACKUP",
")",
":",
"shutil",
".",
"rmtree",
"(",
"POETRY_LIB_BACKUP",
")"
] | Packs everything into a single lib/ directory. | [
"Packs",
"everything",
"into",
"a",
"single",
"lib",
"/",
"directory",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/get-poetry.py#L466-L490 | train |
sdispater/poetry | get-poetry.py | Installer.update_path | def update_path(self):
"""
Tries to update the $PATH automatically.
"""
if WINDOWS:
return self.add_to_windows_path()
# Updating any profile we can on UNIX systems
export_string = self.get_export_string()
addition = "\n{}\n".format(export_string)
updated = []
profiles = self.get_unix_profiles()
for profile in profiles:
if not os.path.exists(profile):
continue
with open(profile, "r") as f:
content = f.read()
if addition not in content:
with open(profile, "a") as f:
f.write(addition)
updated.append(os.path.relpath(profile, HOME)) | python | def update_path(self):
"""
Tries to update the $PATH automatically.
"""
if WINDOWS:
return self.add_to_windows_path()
# Updating any profile we can on UNIX systems
export_string = self.get_export_string()
addition = "\n{}\n".format(export_string)
updated = []
profiles = self.get_unix_profiles()
for profile in profiles:
if not os.path.exists(profile):
continue
with open(profile, "r") as f:
content = f.read()
if addition not in content:
with open(profile, "a") as f:
f.write(addition)
updated.append(os.path.relpath(profile, HOME)) | [
"def",
"update_path",
"(",
"self",
")",
":",
"if",
"WINDOWS",
":",
"return",
"self",
".",
"add_to_windows_path",
"(",
")",
"# Updating any profile we can on UNIX systems",
"export_string",
"=",
"self",
".",
"get_export_string",
"(",
")",
"addition",
"=",
"\"\\n{}\\n\"",
".",
"format",
"(",
"export_string",
")",
"updated",
"=",
"[",
"]",
"profiles",
"=",
"self",
".",
"get_unix_profiles",
"(",
")",
"for",
"profile",
"in",
"profiles",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"profile",
")",
":",
"continue",
"with",
"open",
"(",
"profile",
",",
"\"r\"",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"if",
"addition",
"not",
"in",
"content",
":",
"with",
"open",
"(",
"profile",
",",
"\"a\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"addition",
")",
"updated",
".",
"append",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"profile",
",",
"HOME",
")",
")"
] | Tries to update the $PATH automatically. | [
"Tries",
"to",
"update",
"the",
"$PATH",
"automatically",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/get-poetry.py#L588-L613 | train |
sdispater/poetry | poetry/mixology/term.py | Term.satisfies | def satisfies(self, other): # type: (Term) -> bool
"""
Returns whether this term satisfies another.
"""
return (
self.dependency.name == other.dependency.name
and self.relation(other) == SetRelation.SUBSET
) | python | def satisfies(self, other): # type: (Term) -> bool
"""
Returns whether this term satisfies another.
"""
return (
self.dependency.name == other.dependency.name
and self.relation(other) == SetRelation.SUBSET
) | [
"def",
"satisfies",
"(",
"self",
",",
"other",
")",
":",
"# type: (Term) -> bool",
"return",
"(",
"self",
".",
"dependency",
".",
"name",
"==",
"other",
".",
"dependency",
".",
"name",
"and",
"self",
".",
"relation",
"(",
"other",
")",
"==",
"SetRelation",
".",
"SUBSET",
")"
] | Returns whether this term satisfies another. | [
"Returns",
"whether",
"this",
"term",
"satisfies",
"another",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/term.py#L36-L43 | train |
sdispater/poetry | poetry/mixology/term.py | Term.relation | def relation(self, other): # type: (Term) -> int
"""
Returns the relationship between the package versions
allowed by this term and another.
"""
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
other_constraint = other.constraint
if other.is_positive():
if self.is_positive():
if not self._compatible_dependency(other.dependency):
return SetRelation.DISJOINT
# foo ^1.5.0 is a subset of foo ^1.0.0
if other_constraint.allows_all(self.constraint):
return SetRelation.SUBSET
# foo ^2.0.0 is disjoint with foo ^1.0.0
if not self.constraint.allows_any(other_constraint):
return SetRelation.DISJOINT
return SetRelation.OVERLAPPING
else:
if not self._compatible_dependency(other.dependency):
return SetRelation.OVERLAPPING
# not foo ^1.0.0 is disjoint with foo ^1.5.0
if self.constraint.allows_all(other_constraint):
return SetRelation.DISJOINT
# not foo ^1.5.0 overlaps foo ^1.0.0
# not foo ^2.0.0 is a superset of foo ^1.5.0
return SetRelation.OVERLAPPING
else:
if self.is_positive():
if not self._compatible_dependency(other.dependency):
return SetRelation.SUBSET
# foo ^2.0.0 is a subset of not foo ^1.0.0
if not other_constraint.allows_any(self.constraint):
return SetRelation.SUBSET
# foo ^1.5.0 is disjoint with not foo ^1.0.0
if other_constraint.allows_all(self.constraint):
return SetRelation.DISJOINT
# foo ^1.0.0 overlaps not foo ^1.5.0
return SetRelation.OVERLAPPING
else:
if not self._compatible_dependency(other.dependency):
return SetRelation.OVERLAPPING
# not foo ^1.0.0 is a subset of not foo ^1.5.0
if self.constraint.allows_all(other_constraint):
return SetRelation.SUBSET
# not foo ^2.0.0 overlaps not foo ^1.0.0
# not foo ^1.5.0 is a superset of not foo ^1.0.0
return SetRelation.OVERLAPPING | python | def relation(self, other): # type: (Term) -> int
"""
Returns the relationship between the package versions
allowed by this term and another.
"""
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
other_constraint = other.constraint
if other.is_positive():
if self.is_positive():
if not self._compatible_dependency(other.dependency):
return SetRelation.DISJOINT
# foo ^1.5.0 is a subset of foo ^1.0.0
if other_constraint.allows_all(self.constraint):
return SetRelation.SUBSET
# foo ^2.0.0 is disjoint with foo ^1.0.0
if not self.constraint.allows_any(other_constraint):
return SetRelation.DISJOINT
return SetRelation.OVERLAPPING
else:
if not self._compatible_dependency(other.dependency):
return SetRelation.OVERLAPPING
# not foo ^1.0.0 is disjoint with foo ^1.5.0
if self.constraint.allows_all(other_constraint):
return SetRelation.DISJOINT
# not foo ^1.5.0 overlaps foo ^1.0.0
# not foo ^2.0.0 is a superset of foo ^1.5.0
return SetRelation.OVERLAPPING
else:
if self.is_positive():
if not self._compatible_dependency(other.dependency):
return SetRelation.SUBSET
# foo ^2.0.0 is a subset of not foo ^1.0.0
if not other_constraint.allows_any(self.constraint):
return SetRelation.SUBSET
# foo ^1.5.0 is disjoint with not foo ^1.0.0
if other_constraint.allows_all(self.constraint):
return SetRelation.DISJOINT
# foo ^1.0.0 overlaps not foo ^1.5.0
return SetRelation.OVERLAPPING
else:
if not self._compatible_dependency(other.dependency):
return SetRelation.OVERLAPPING
# not foo ^1.0.0 is a subset of not foo ^1.5.0
if self.constraint.allows_all(other_constraint):
return SetRelation.SUBSET
# not foo ^2.0.0 overlaps not foo ^1.0.0
# not foo ^1.5.0 is a superset of not foo ^1.0.0
return SetRelation.OVERLAPPING | [
"def",
"relation",
"(",
"self",
",",
"other",
")",
":",
"# type: (Term) -> int",
"if",
"self",
".",
"dependency",
".",
"name",
"!=",
"other",
".",
"dependency",
".",
"name",
":",
"raise",
"ValueError",
"(",
"\"{} should refer to {}\"",
".",
"format",
"(",
"other",
",",
"self",
".",
"dependency",
".",
"name",
")",
")",
"other_constraint",
"=",
"other",
".",
"constraint",
"if",
"other",
".",
"is_positive",
"(",
")",
":",
"if",
"self",
".",
"is_positive",
"(",
")",
":",
"if",
"not",
"self",
".",
"_compatible_dependency",
"(",
"other",
".",
"dependency",
")",
":",
"return",
"SetRelation",
".",
"DISJOINT",
"# foo ^1.5.0 is a subset of foo ^1.0.0",
"if",
"other_constraint",
".",
"allows_all",
"(",
"self",
".",
"constraint",
")",
":",
"return",
"SetRelation",
".",
"SUBSET",
"# foo ^2.0.0 is disjoint with foo ^1.0.0",
"if",
"not",
"self",
".",
"constraint",
".",
"allows_any",
"(",
"other_constraint",
")",
":",
"return",
"SetRelation",
".",
"DISJOINT",
"return",
"SetRelation",
".",
"OVERLAPPING",
"else",
":",
"if",
"not",
"self",
".",
"_compatible_dependency",
"(",
"other",
".",
"dependency",
")",
":",
"return",
"SetRelation",
".",
"OVERLAPPING",
"# not foo ^1.0.0 is disjoint with foo ^1.5.0",
"if",
"self",
".",
"constraint",
".",
"allows_all",
"(",
"other_constraint",
")",
":",
"return",
"SetRelation",
".",
"DISJOINT",
"# not foo ^1.5.0 overlaps foo ^1.0.0",
"# not foo ^2.0.0 is a superset of foo ^1.5.0",
"return",
"SetRelation",
".",
"OVERLAPPING",
"else",
":",
"if",
"self",
".",
"is_positive",
"(",
")",
":",
"if",
"not",
"self",
".",
"_compatible_dependency",
"(",
"other",
".",
"dependency",
")",
":",
"return",
"SetRelation",
".",
"SUBSET",
"# foo ^2.0.0 is a subset of not foo ^1.0.0",
"if",
"not",
"other_constraint",
".",
"allows_any",
"(",
"self",
".",
"constraint",
")",
":",
"return",
"SetRelation",
".",
"SUBSET",
"# foo ^1.5.0 is disjoint with not foo ^1.0.0",
"if",
"other_constraint",
".",
"allows_all",
"(",
"self",
".",
"constraint",
")",
":",
"return",
"SetRelation",
".",
"DISJOINT",
"# foo ^1.0.0 overlaps not foo ^1.5.0",
"return",
"SetRelation",
".",
"OVERLAPPING",
"else",
":",
"if",
"not",
"self",
".",
"_compatible_dependency",
"(",
"other",
".",
"dependency",
")",
":",
"return",
"SetRelation",
".",
"OVERLAPPING",
"# not foo ^1.0.0 is a subset of not foo ^1.5.0",
"if",
"self",
".",
"constraint",
".",
"allows_all",
"(",
"other_constraint",
")",
":",
"return",
"SetRelation",
".",
"SUBSET",
"# not foo ^2.0.0 overlaps not foo ^1.0.0",
"# not foo ^1.5.0 is a superset of not foo ^1.0.0",
"return",
"SetRelation",
".",
"OVERLAPPING"
] | Returns the relationship between the package versions
allowed by this term and another. | [
"Returns",
"the",
"relationship",
"between",
"the",
"package",
"versions",
"allowed",
"by",
"this",
"term",
"and",
"another",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/term.py#L45-L107 | train |
sdispater/poetry | poetry/mixology/term.py | Term.intersect | def intersect(self, other): # type: (Term) -> Union[Term, None]
"""
Returns a Term that represents the packages
allowed by both this term and another
"""
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
if self._compatible_dependency(other.dependency):
if self.is_positive() != other.is_positive():
# foo ^1.0.0 ∩ not foo ^1.5.0 → foo >=1.0.0 <1.5.0
positive = self if self.is_positive() else other
negative = other if self.is_positive() else self
return self._non_empty_term(
positive.constraint.difference(negative.constraint), True
)
elif self.is_positive():
# foo ^1.0.0 ∩ foo >=1.5.0 <3.0.0 → foo ^1.5.0
return self._non_empty_term(
self.constraint.intersect(other.constraint), True
)
else:
# not foo ^1.0.0 ∩ not foo >=1.5.0 <3.0.0 → not foo >=1.0.0 <3.0.0
return self._non_empty_term(
self.constraint.union(other.constraint), False
)
elif self.is_positive() != other.is_positive():
return self if self.is_positive() else other
else:
return | python | def intersect(self, other): # type: (Term) -> Union[Term, None]
"""
Returns a Term that represents the packages
allowed by both this term and another
"""
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
if self._compatible_dependency(other.dependency):
if self.is_positive() != other.is_positive():
# foo ^1.0.0 ∩ not foo ^1.5.0 → foo >=1.0.0 <1.5.0
positive = self if self.is_positive() else other
negative = other if self.is_positive() else self
return self._non_empty_term(
positive.constraint.difference(negative.constraint), True
)
elif self.is_positive():
# foo ^1.0.0 ∩ foo >=1.5.0 <3.0.0 → foo ^1.5.0
return self._non_empty_term(
self.constraint.intersect(other.constraint), True
)
else:
# not foo ^1.0.0 ∩ not foo >=1.5.0 <3.0.0 → not foo >=1.0.0 <3.0.0
return self._non_empty_term(
self.constraint.union(other.constraint), False
)
elif self.is_positive() != other.is_positive():
return self if self.is_positive() else other
else:
return | [
"def",
"intersect",
"(",
"self",
",",
"other",
")",
":",
"# type: (Term) -> Union[Term, None]",
"if",
"self",
".",
"dependency",
".",
"name",
"!=",
"other",
".",
"dependency",
".",
"name",
":",
"raise",
"ValueError",
"(",
"\"{} should refer to {}\"",
".",
"format",
"(",
"other",
",",
"self",
".",
"dependency",
".",
"name",
")",
")",
"if",
"self",
".",
"_compatible_dependency",
"(",
"other",
".",
"dependency",
")",
":",
"if",
"self",
".",
"is_positive",
"(",
")",
"!=",
"other",
".",
"is_positive",
"(",
")",
":",
"# foo ^1.0.0 ∩ not foo ^1.5.0 → foo >=1.0.0 <1.5.0",
"positive",
"=",
"self",
"if",
"self",
".",
"is_positive",
"(",
")",
"else",
"other",
"negative",
"=",
"other",
"if",
"self",
".",
"is_positive",
"(",
")",
"else",
"self",
"return",
"self",
".",
"_non_empty_term",
"(",
"positive",
".",
"constraint",
".",
"difference",
"(",
"negative",
".",
"constraint",
")",
",",
"True",
")",
"elif",
"self",
".",
"is_positive",
"(",
")",
":",
"# foo ^1.0.0 ∩ foo >=1.5.0 <3.0.0 → foo ^1.5.0",
"return",
"self",
".",
"_non_empty_term",
"(",
"self",
".",
"constraint",
".",
"intersect",
"(",
"other",
".",
"constraint",
")",
",",
"True",
")",
"else",
":",
"# not foo ^1.0.0 ∩ not foo >=1.5.0 <3.0.0 → not foo >=1.0.0 <3.0.0",
"return",
"self",
".",
"_non_empty_term",
"(",
"self",
".",
"constraint",
".",
"union",
"(",
"other",
".",
"constraint",
")",
",",
"False",
")",
"elif",
"self",
".",
"is_positive",
"(",
")",
"!=",
"other",
".",
"is_positive",
"(",
")",
":",
"return",
"self",
"if",
"self",
".",
"is_positive",
"(",
")",
"else",
"other",
"else",
":",
"return"
] | Returns a Term that represents the packages
allowed by both this term and another | [
"Returns",
"a",
"Term",
"that",
"represents",
"the",
"packages",
"allowed",
"by",
"both",
"this",
"term",
"and",
"another"
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/term.py#L109-L141 | train |
sdispater/poetry | poetry/masonry/builders/builder.py | Builder.find_files_to_add | def find_files_to_add(self, exclude_build=True): # type: (bool) -> list
"""
Finds all files to add to the tarball
"""
to_add = []
for include in self._module.includes:
for file in include.elements:
if "__pycache__" in str(file):
continue
if file.is_dir():
continue
file = file.relative_to(self._path)
if self.is_excluded(file) and isinstance(include, PackageInclude):
continue
if file.suffix == ".pyc":
continue
if file in to_add:
# Skip duplicates
continue
self._io.writeln(
" - Adding: <comment>{}</comment>".format(str(file)),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(file)
# Include project files
self._io.writeln(
" - Adding: <comment>pyproject.toml</comment>",
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(Path("pyproject.toml"))
# If a license file exists, add it
for license_file in self._path.glob("LICENSE*"):
self._io.writeln(
" - Adding: <comment>{}</comment>".format(
license_file.relative_to(self._path)
),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(license_file.relative_to(self._path))
# If a README is specificed we need to include it
# to avoid errors
if "readme" in self._poetry.local_config:
readme = self._path / self._poetry.local_config["readme"]
if readme.exists():
self._io.writeln(
" - Adding: <comment>{}</comment>".format(
readme.relative_to(self._path)
),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(readme.relative_to(self._path))
# If a build script is specified and explicitely required
# we add it to the list of files
if self._package.build and not exclude_build:
to_add.append(Path(self._package.build))
return sorted(to_add) | python | def find_files_to_add(self, exclude_build=True): # type: (bool) -> list
"""
Finds all files to add to the tarball
"""
to_add = []
for include in self._module.includes:
for file in include.elements:
if "__pycache__" in str(file):
continue
if file.is_dir():
continue
file = file.relative_to(self._path)
if self.is_excluded(file) and isinstance(include, PackageInclude):
continue
if file.suffix == ".pyc":
continue
if file in to_add:
# Skip duplicates
continue
self._io.writeln(
" - Adding: <comment>{}</comment>".format(str(file)),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(file)
# Include project files
self._io.writeln(
" - Adding: <comment>pyproject.toml</comment>",
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(Path("pyproject.toml"))
# If a license file exists, add it
for license_file in self._path.glob("LICENSE*"):
self._io.writeln(
" - Adding: <comment>{}</comment>".format(
license_file.relative_to(self._path)
),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(license_file.relative_to(self._path))
# If a README is specificed we need to include it
# to avoid errors
if "readme" in self._poetry.local_config:
readme = self._path / self._poetry.local_config["readme"]
if readme.exists():
self._io.writeln(
" - Adding: <comment>{}</comment>".format(
readme.relative_to(self._path)
),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(readme.relative_to(self._path))
# If a build script is specified and explicitely required
# we add it to the list of files
if self._package.build and not exclude_build:
to_add.append(Path(self._package.build))
return sorted(to_add) | [
"def",
"find_files_to_add",
"(",
"self",
",",
"exclude_build",
"=",
"True",
")",
":",
"# type: (bool) -> list",
"to_add",
"=",
"[",
"]",
"for",
"include",
"in",
"self",
".",
"_module",
".",
"includes",
":",
"for",
"file",
"in",
"include",
".",
"elements",
":",
"if",
"\"__pycache__\"",
"in",
"str",
"(",
"file",
")",
":",
"continue",
"if",
"file",
".",
"is_dir",
"(",
")",
":",
"continue",
"file",
"=",
"file",
".",
"relative_to",
"(",
"self",
".",
"_path",
")",
"if",
"self",
".",
"is_excluded",
"(",
"file",
")",
"and",
"isinstance",
"(",
"include",
",",
"PackageInclude",
")",
":",
"continue",
"if",
"file",
".",
"suffix",
"==",
"\".pyc\"",
":",
"continue",
"if",
"file",
"in",
"to_add",
":",
"# Skip duplicates",
"continue",
"self",
".",
"_io",
".",
"writeln",
"(",
"\" - Adding: <comment>{}</comment>\"",
".",
"format",
"(",
"str",
"(",
"file",
")",
")",
",",
"verbosity",
"=",
"self",
".",
"_io",
".",
"VERBOSITY_VERY_VERBOSE",
",",
")",
"to_add",
".",
"append",
"(",
"file",
")",
"# Include project files",
"self",
".",
"_io",
".",
"writeln",
"(",
"\" - Adding: <comment>pyproject.toml</comment>\"",
",",
"verbosity",
"=",
"self",
".",
"_io",
".",
"VERBOSITY_VERY_VERBOSE",
",",
")",
"to_add",
".",
"append",
"(",
"Path",
"(",
"\"pyproject.toml\"",
")",
")",
"# If a license file exists, add it",
"for",
"license_file",
"in",
"self",
".",
"_path",
".",
"glob",
"(",
"\"LICENSE*\"",
")",
":",
"self",
".",
"_io",
".",
"writeln",
"(",
"\" - Adding: <comment>{}</comment>\"",
".",
"format",
"(",
"license_file",
".",
"relative_to",
"(",
"self",
".",
"_path",
")",
")",
",",
"verbosity",
"=",
"self",
".",
"_io",
".",
"VERBOSITY_VERY_VERBOSE",
",",
")",
"to_add",
".",
"append",
"(",
"license_file",
".",
"relative_to",
"(",
"self",
".",
"_path",
")",
")",
"# If a README is specificed we need to include it",
"# to avoid errors",
"if",
"\"readme\"",
"in",
"self",
".",
"_poetry",
".",
"local_config",
":",
"readme",
"=",
"self",
".",
"_path",
"/",
"self",
".",
"_poetry",
".",
"local_config",
"[",
"\"readme\"",
"]",
"if",
"readme",
".",
"exists",
"(",
")",
":",
"self",
".",
"_io",
".",
"writeln",
"(",
"\" - Adding: <comment>{}</comment>\"",
".",
"format",
"(",
"readme",
".",
"relative_to",
"(",
"self",
".",
"_path",
")",
")",
",",
"verbosity",
"=",
"self",
".",
"_io",
".",
"VERBOSITY_VERY_VERBOSE",
",",
")",
"to_add",
".",
"append",
"(",
"readme",
".",
"relative_to",
"(",
"self",
".",
"_path",
")",
")",
"# If a build script is specified and explicitely required",
"# we add it to the list of files",
"if",
"self",
".",
"_package",
".",
"build",
"and",
"not",
"exclude_build",
":",
"to_add",
".",
"append",
"(",
"Path",
"(",
"self",
".",
"_package",
".",
"build",
")",
")",
"return",
"sorted",
"(",
"to_add",
")"
] | Finds all files to add to the tarball | [
"Finds",
"all",
"files",
"to",
"add",
"to",
"the",
"tarball"
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/builders/builder.py#L89-L156 | train |
sdispater/poetry | poetry/version/__init__.py | parse | def parse(
version, strict=False # type: str # type: bool
): # type:(...) -> Union[Version, LegacyVersion]
"""
Parse the given version string and return either a :class:`Version` object
or a LegacyVersion object depending on if the given version is
a valid PEP 440 version or a legacy version.
If strict=True only PEP 440 versions will be accepted.
"""
try:
return Version(version)
except InvalidVersion:
if strict:
raise
return LegacyVersion(version) | python | def parse(
version, strict=False # type: str # type: bool
): # type:(...) -> Union[Version, LegacyVersion]
"""
Parse the given version string and return either a :class:`Version` object
or a LegacyVersion object depending on if the given version is
a valid PEP 440 version or a legacy version.
If strict=True only PEP 440 versions will be accepted.
"""
try:
return Version(version)
except InvalidVersion:
if strict:
raise
return LegacyVersion(version) | [
"def",
"parse",
"(",
"version",
",",
"strict",
"=",
"False",
"# type: str # type: bool",
")",
":",
"# type:(...) -> Union[Version, LegacyVersion]",
"try",
":",
"return",
"Version",
"(",
"version",
")",
"except",
"InvalidVersion",
":",
"if",
"strict",
":",
"raise",
"return",
"LegacyVersion",
"(",
"version",
")"
] | Parse the given version string and return either a :class:`Version` object
or a LegacyVersion object depending on if the given version is
a valid PEP 440 version or a legacy version.
If strict=True only PEP 440 versions will be accepted. | [
"Parse",
"the",
"given",
"version",
"string",
"and",
"return",
"either",
"a",
":",
"class",
":",
"Version",
"object",
"or",
"a",
"LegacyVersion",
"object",
"depending",
"on",
"if",
"the",
"given",
"version",
"is",
"a",
"valid",
"PEP",
"440",
"version",
"or",
"a",
"legacy",
"version",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/version/__init__.py#L28-L44 | train |
sdispater/poetry | poetry/packages/locker.py | Locker.is_fresh | def is_fresh(self): # type: () -> bool
"""
Checks whether the lock file is still up to date with the current hash.
"""
lock = self._lock.read()
metadata = lock.get("metadata", {})
if "content-hash" in metadata:
return self._content_hash == lock["metadata"]["content-hash"]
return False | python | def is_fresh(self): # type: () -> bool
"""
Checks whether the lock file is still up to date with the current hash.
"""
lock = self._lock.read()
metadata = lock.get("metadata", {})
if "content-hash" in metadata:
return self._content_hash == lock["metadata"]["content-hash"]
return False | [
"def",
"is_fresh",
"(",
"self",
")",
":",
"# type: () -> bool",
"lock",
"=",
"self",
".",
"_lock",
".",
"read",
"(",
")",
"metadata",
"=",
"lock",
".",
"get",
"(",
"\"metadata\"",
",",
"{",
"}",
")",
"if",
"\"content-hash\"",
"in",
"metadata",
":",
"return",
"self",
".",
"_content_hash",
"==",
"lock",
"[",
"\"metadata\"",
"]",
"[",
"\"content-hash\"",
"]",
"return",
"False"
] | Checks whether the lock file is still up to date with the current hash. | [
"Checks",
"whether",
"the",
"lock",
"file",
"is",
"still",
"up",
"to",
"date",
"with",
"the",
"current",
"hash",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/locker.py#L45-L55 | train |
sdispater/poetry | poetry/packages/locker.py | Locker.locked_repository | def locked_repository(
self, with_dev_reqs=False
): # type: (bool) -> poetry.repositories.Repository
"""
Searches and returns a repository of locked packages.
"""
if not self.is_locked():
return poetry.repositories.Repository()
lock_data = self.lock_data
packages = poetry.repositories.Repository()
if with_dev_reqs:
locked_packages = lock_data["package"]
else:
locked_packages = [
p for p in lock_data["package"] if p["category"] == "main"
]
if not locked_packages:
return packages
for info in locked_packages:
package = poetry.packages.Package(
info["name"], info["version"], info["version"]
)
package.description = info.get("description", "")
package.category = info["category"]
package.optional = info["optional"]
package.hashes = lock_data["metadata"]["hashes"][info["name"]]
package.python_versions = info["python-versions"]
if "marker" in info:
package.marker = parse_marker(info["marker"])
else:
# Compatibility for old locks
if "requirements" in info:
dep = poetry.packages.Dependency("foo", "0.0.0")
for name, value in info["requirements"].items():
if name == "python":
dep.python_versions = value
elif name == "platform":
dep.platform = value
split_dep = dep.to_pep_508(False).split(";")
if len(split_dep) > 1:
package.marker = parse_marker(split_dep[1].strip())
for dep_name, constraint in info.get("dependencies", {}).items():
if isinstance(constraint, list):
for c in constraint:
package.add_dependency(dep_name, c)
continue
package.add_dependency(dep_name, constraint)
if "source" in info:
package.source_type = info["source"]["type"]
package.source_url = info["source"]["url"]
package.source_reference = info["source"]["reference"]
packages.add_package(package)
return packages | python | def locked_repository(
self, with_dev_reqs=False
): # type: (bool) -> poetry.repositories.Repository
"""
Searches and returns a repository of locked packages.
"""
if not self.is_locked():
return poetry.repositories.Repository()
lock_data = self.lock_data
packages = poetry.repositories.Repository()
if with_dev_reqs:
locked_packages = lock_data["package"]
else:
locked_packages = [
p for p in lock_data["package"] if p["category"] == "main"
]
if not locked_packages:
return packages
for info in locked_packages:
package = poetry.packages.Package(
info["name"], info["version"], info["version"]
)
package.description = info.get("description", "")
package.category = info["category"]
package.optional = info["optional"]
package.hashes = lock_data["metadata"]["hashes"][info["name"]]
package.python_versions = info["python-versions"]
if "marker" in info:
package.marker = parse_marker(info["marker"])
else:
# Compatibility for old locks
if "requirements" in info:
dep = poetry.packages.Dependency("foo", "0.0.0")
for name, value in info["requirements"].items():
if name == "python":
dep.python_versions = value
elif name == "platform":
dep.platform = value
split_dep = dep.to_pep_508(False).split(";")
if len(split_dep) > 1:
package.marker = parse_marker(split_dep[1].strip())
for dep_name, constraint in info.get("dependencies", {}).items():
if isinstance(constraint, list):
for c in constraint:
package.add_dependency(dep_name, c)
continue
package.add_dependency(dep_name, constraint)
if "source" in info:
package.source_type = info["source"]["type"]
package.source_url = info["source"]["url"]
package.source_reference = info["source"]["reference"]
packages.add_package(package)
return packages | [
"def",
"locked_repository",
"(",
"self",
",",
"with_dev_reqs",
"=",
"False",
")",
":",
"# type: (bool) -> poetry.repositories.Repository",
"if",
"not",
"self",
".",
"is_locked",
"(",
")",
":",
"return",
"poetry",
".",
"repositories",
".",
"Repository",
"(",
")",
"lock_data",
"=",
"self",
".",
"lock_data",
"packages",
"=",
"poetry",
".",
"repositories",
".",
"Repository",
"(",
")",
"if",
"with_dev_reqs",
":",
"locked_packages",
"=",
"lock_data",
"[",
"\"package\"",
"]",
"else",
":",
"locked_packages",
"=",
"[",
"p",
"for",
"p",
"in",
"lock_data",
"[",
"\"package\"",
"]",
"if",
"p",
"[",
"\"category\"",
"]",
"==",
"\"main\"",
"]",
"if",
"not",
"locked_packages",
":",
"return",
"packages",
"for",
"info",
"in",
"locked_packages",
":",
"package",
"=",
"poetry",
".",
"packages",
".",
"Package",
"(",
"info",
"[",
"\"name\"",
"]",
",",
"info",
"[",
"\"version\"",
"]",
",",
"info",
"[",
"\"version\"",
"]",
")",
"package",
".",
"description",
"=",
"info",
".",
"get",
"(",
"\"description\"",
",",
"\"\"",
")",
"package",
".",
"category",
"=",
"info",
"[",
"\"category\"",
"]",
"package",
".",
"optional",
"=",
"info",
"[",
"\"optional\"",
"]",
"package",
".",
"hashes",
"=",
"lock_data",
"[",
"\"metadata\"",
"]",
"[",
"\"hashes\"",
"]",
"[",
"info",
"[",
"\"name\"",
"]",
"]",
"package",
".",
"python_versions",
"=",
"info",
"[",
"\"python-versions\"",
"]",
"if",
"\"marker\"",
"in",
"info",
":",
"package",
".",
"marker",
"=",
"parse_marker",
"(",
"info",
"[",
"\"marker\"",
"]",
")",
"else",
":",
"# Compatibility for old locks",
"if",
"\"requirements\"",
"in",
"info",
":",
"dep",
"=",
"poetry",
".",
"packages",
".",
"Dependency",
"(",
"\"foo\"",
",",
"\"0.0.0\"",
")",
"for",
"name",
",",
"value",
"in",
"info",
"[",
"\"requirements\"",
"]",
".",
"items",
"(",
")",
":",
"if",
"name",
"==",
"\"python\"",
":",
"dep",
".",
"python_versions",
"=",
"value",
"elif",
"name",
"==",
"\"platform\"",
":",
"dep",
".",
"platform",
"=",
"value",
"split_dep",
"=",
"dep",
".",
"to_pep_508",
"(",
"False",
")",
".",
"split",
"(",
"\";\"",
")",
"if",
"len",
"(",
"split_dep",
")",
">",
"1",
":",
"package",
".",
"marker",
"=",
"parse_marker",
"(",
"split_dep",
"[",
"1",
"]",
".",
"strip",
"(",
")",
")",
"for",
"dep_name",
",",
"constraint",
"in",
"info",
".",
"get",
"(",
"\"dependencies\"",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"constraint",
",",
"list",
")",
":",
"for",
"c",
"in",
"constraint",
":",
"package",
".",
"add_dependency",
"(",
"dep_name",
",",
"c",
")",
"continue",
"package",
".",
"add_dependency",
"(",
"dep_name",
",",
"constraint",
")",
"if",
"\"source\"",
"in",
"info",
":",
"package",
".",
"source_type",
"=",
"info",
"[",
"\"source\"",
"]",
"[",
"\"type\"",
"]",
"package",
".",
"source_url",
"=",
"info",
"[",
"\"source\"",
"]",
"[",
"\"url\"",
"]",
"package",
".",
"source_reference",
"=",
"info",
"[",
"\"source\"",
"]",
"[",
"\"reference\"",
"]",
"packages",
".",
"add_package",
"(",
"package",
")",
"return",
"packages"
] | Searches and returns a repository of locked packages. | [
"Searches",
"and",
"returns",
"a",
"repository",
"of",
"locked",
"packages",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/locker.py#L57-L121 | train |
sdispater/poetry | poetry/packages/locker.py | Locker._get_content_hash | def _get_content_hash(self): # type: () -> str
"""
Returns the sha256 hash of the sorted content of the pyproject file.
"""
content = self._local_config
relevant_content = {}
for key in self._relevant_keys:
relevant_content[key] = content.get(key)
content_hash = sha256(
json.dumps(relevant_content, sort_keys=True).encode()
).hexdigest()
return content_hash | python | def _get_content_hash(self): # type: () -> str
"""
Returns the sha256 hash of the sorted content of the pyproject file.
"""
content = self._local_config
relevant_content = {}
for key in self._relevant_keys:
relevant_content[key] = content.get(key)
content_hash = sha256(
json.dumps(relevant_content, sort_keys=True).encode()
).hexdigest()
return content_hash | [
"def",
"_get_content_hash",
"(",
"self",
")",
":",
"# type: () -> str",
"content",
"=",
"self",
".",
"_local_config",
"relevant_content",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_relevant_keys",
":",
"relevant_content",
"[",
"key",
"]",
"=",
"content",
".",
"get",
"(",
"key",
")",
"content_hash",
"=",
"sha256",
"(",
"json",
".",
"dumps",
"(",
"relevant_content",
",",
"sort_keys",
"=",
"True",
")",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"return",
"content_hash"
] | Returns the sha256 hash of the sorted content of the pyproject file. | [
"Returns",
"the",
"sha256",
"hash",
"of",
"the",
"sorted",
"content",
"of",
"the",
"pyproject",
"file",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/locker.py#L165-L179 | train |
sdispater/poetry | poetry/repositories/installed_repository.py | InstalledRepository.load | def load(cls, env): # type: (Env) -> InstalledRepository
"""
Load installed packages.
For now, it uses the pip "freeze" command.
"""
repo = cls()
freeze_output = env.run("pip", "freeze")
for line in freeze_output.split("\n"):
if "==" in line:
name, version = re.split("={2,3}", line)
repo.add_package(Package(name, version, version))
elif line.startswith("-e "):
line = line[3:].strip()
if line.startswith("git+"):
url = line.lstrip("git+")
if "@" in url:
url, rev = url.rsplit("@", 1)
else:
rev = "master"
name = url.split("/")[-1].rstrip(".git")
if "#egg=" in rev:
rev, name = rev.split("#egg=")
package = Package(name, "0.0.0")
package.source_type = "git"
package.source_url = url
package.source_reference = rev
repo.add_package(package)
return repo | python | def load(cls, env): # type: (Env) -> InstalledRepository
"""
Load installed packages.
For now, it uses the pip "freeze" command.
"""
repo = cls()
freeze_output = env.run("pip", "freeze")
for line in freeze_output.split("\n"):
if "==" in line:
name, version = re.split("={2,3}", line)
repo.add_package(Package(name, version, version))
elif line.startswith("-e "):
line = line[3:].strip()
if line.startswith("git+"):
url = line.lstrip("git+")
if "@" in url:
url, rev = url.rsplit("@", 1)
else:
rev = "master"
name = url.split("/")[-1].rstrip(".git")
if "#egg=" in rev:
rev, name = rev.split("#egg=")
package = Package(name, "0.0.0")
package.source_type = "git"
package.source_url = url
package.source_reference = rev
repo.add_package(package)
return repo | [
"def",
"load",
"(",
"cls",
",",
"env",
")",
":",
"# type: (Env) -> InstalledRepository",
"repo",
"=",
"cls",
"(",
")",
"freeze_output",
"=",
"env",
".",
"run",
"(",
"\"pip\"",
",",
"\"freeze\"",
")",
"for",
"line",
"in",
"freeze_output",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"\"==\"",
"in",
"line",
":",
"name",
",",
"version",
"=",
"re",
".",
"split",
"(",
"\"={2,3}\"",
",",
"line",
")",
"repo",
".",
"add_package",
"(",
"Package",
"(",
"name",
",",
"version",
",",
"version",
")",
")",
"elif",
"line",
".",
"startswith",
"(",
"\"-e \"",
")",
":",
"line",
"=",
"line",
"[",
"3",
":",
"]",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"\"git+\"",
")",
":",
"url",
"=",
"line",
".",
"lstrip",
"(",
"\"git+\"",
")",
"if",
"\"@\"",
"in",
"url",
":",
"url",
",",
"rev",
"=",
"url",
".",
"rsplit",
"(",
"\"@\"",
",",
"1",
")",
"else",
":",
"rev",
"=",
"\"master\"",
"name",
"=",
"url",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
".",
"rstrip",
"(",
"\".git\"",
")",
"if",
"\"#egg=\"",
"in",
"rev",
":",
"rev",
",",
"name",
"=",
"rev",
".",
"split",
"(",
"\"#egg=\"",
")",
"package",
"=",
"Package",
"(",
"name",
",",
"\"0.0.0\"",
")",
"package",
".",
"source_type",
"=",
"\"git\"",
"package",
".",
"source_url",
"=",
"url",
"package",
".",
"source_reference",
"=",
"rev",
"repo",
".",
"add_package",
"(",
"package",
")",
"return",
"repo"
] | Load installed packages.
For now, it uses the pip "freeze" command. | [
"Load",
"installed",
"packages",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/installed_repository.py#L11-L44 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.