prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def <|fim_middle|>(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
_setupUI
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def <|fim_middle|>(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
show
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def <|fim_middle|>(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
addStringFromLineEdit
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def <|fim_middle|>(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
removeSelected
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def <|fim_middle|>(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
restoreDefaults
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def <|fim_middle|>(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
onTestStringButtonClicked
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def <|fim_middle|>(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
reset_input_style
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def <|fim_middle|>(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
reset_table_style
<|file_name|>exclude_list_dialog.py<|end_file_name|><|fim▁begin|># This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def <|fim_middle|>(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br> Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) ) <|fim▁end|>
display_help_message
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None)<|fim▁hole|> if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main()<|fim▁end|>
dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : <|fim_middle|> COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : <|fim_middle|> def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): <|fim_middle|> def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): <|fim_middle|> def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : <|fim_middle|> def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : <|fim_middle|> def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): <|fim_middle|> for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
""" instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): <|fim_middle|> COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): <|fim_middle|> def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : <|fim_middle|> if __name__ == "__main__" : main() <|fim▁end|>
""" Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: <|fim_middle|> self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], ))
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: <|fim_middle|> if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
path = '.'
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: <|fim_middle|> if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile))
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: <|fim_middle|> dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: <|fim_middle|> if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
name = dockerfile
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: <|fim_middle|> pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): <|fim_middle|> else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
return pattern
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: <|fim_middle|> return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
match = pattern.match(path) if match: return match.group(name)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: <|fim_middle|> return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
return match.group(name)
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: <|fim_middle|> raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : <|fim_middle|> return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
return imgBuilder.buildTag()
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): <|fim_middle|> def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
names = [names]
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: <|fim_middle|> for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) )
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: <|fim_middle|> for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
tags = ['latest']
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: <|fim_middle|> import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:])
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : <|fim_middle|> <|fim▁end|>
main()
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def <|fim_middle|>(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
__init__
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def <|fim_middle|>(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
get_matching_pattern
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def <|fim_middle|>(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
getImage
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def <|fim_middle|>(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
imageTag
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def <|fim_middle|>(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
build
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def <|fim_middle|>(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
iter_buildable_deps
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def <|fim_middle|>(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
tag
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def <|fim_middle|>(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def main(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
add_options
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger(type(self).__name__) self.kwds = kwds self.images = {} if config is None: config = Config() config.update(dict( images= [ { 'path': 'docker/*', } ], )) self.patterns = [] for image in config['images']: # When path is provided and globbed, Dockerfile refers to its location # When path is provided but not globbed, Dockerfile refers to the current path # When Dockerfile is provided and globbed, path must not be globbed, both # refers to the current directory path = image.get('path', None) dockerfile = image.get('Dockerfile', 'Dockerfile') name = image.get('name', None) if path is None: path = '.' if '*' in path: if '*' in dockerfile: raise ValueError('Ambiguity in your configuration for %r, globbing can' 'be done either in "Dockerfile" or "path" key but not both at the' 'same time' % image) dockerfile = os.path.join(path, dockerfile) path = re.compile(re.sub('^.*/([^*]*)$', r'(?P<path>.*)/\1', dockerfile)) if name is None: name = dockerfile if '*' in name: start = re.sub('^([^*]*/|).*', r'^\1(?P<name>.*)', dockerfile) end = re.sub('^.*\*(?:|[^/]*)(/.*)$', r'\1$', dockerfile) name = re.compile(start + end) pattern = { 'name': name, 'path': path, 'Dockerfile': dockerfile, } self.patterns.append(pattern) self.config = config def get_matching_pattern(self, pattern, name, path): pattern = pattern[name] if isinstance(pattern, six.string_types): return pattern else: match = pattern.match(path) if match: return match.group(name) return None def getImage(self, image_name): try: return self.images[image_name] except KeyError: self.logger.debug('image builder cache miss, try to find it') for img_cfg in self.patterns: for path in glob.glob(img_cfg['Dockerfile']): found_image_name = self.get_matching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, dockerfile=path, tagResolver=self, **self.kwds ) self.images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, client, names=None, child_images=[]) : if isinstance(names, six.string_types): names = [names] def iter_buildable_deps(name): """ instanciates a builder for each image dependency does nothing when the image cannot be build """ for dep_name, _ in self.getImage(name).imageDeps(): try: self.getImage(dep_name) yield dep_name except KeyError: continue for name in names: if name in child_images: raise RuntimeError("dependency loop detected, %s some how depends on itself %s" % (name, ' -> '.join(child_images + [name])) ) for dep_name in iter_buildable_deps(name): self.build(client, dep_name, child_images=child_images+[name]) for name in names: self.getImage(name).build(client) def tag(self, client, tags, images, **kwds): if tags is None: tags = ['latest'] for image in images: self.getImage(image).tag(client, tags, **kwds) COMMAND_NAME='build' def add_options(parser): from . import addCommonOptions, commonSetUp from .dockerfile import addDockerfileOptions from .image import addImageOptions try: add = parser.add_argument except AttributeError: add = parser.add_option add("image", nargs="*", help="images to build") add("-t", "--tag", dest="tag", default=None, action='append', help="tag(s) to be applied to the resulting image in case of success") add("--registry", dest="registry", default=[], action='append', help="Registry on which the image should tagged (<registry>/<name>:<tag>)") addCommonOptions(parser) addDockerfileOptions(parser) addImageOptions(parser) def <|fim_middle|>(argv=sys.argv, args=None) : """ Builds a list of images """ from . import commonSetUp if not args: import argparse parser = argparse.ArgumentParser() add_options(parser) args = parser.parse_args(argv[1:]) import sys, os import yaml from docker import Client from . import commonSetUp commonSetUp(args) builder = Builder() builder.build(Client.from_env(), args.image) builder.tag(Client.from_env(), args.tag, args.image, registries=args.registry) if __name__ == "__main__" : main() <|fim▁end|>
main
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings <|fim▁hole|> root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)<|fim▁end|>
def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade')
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): <|fim_middle|> class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e) <|fim▁end|>
path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): <|fim_middle|> <|fim▁end|>
""" Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): <|fim_middle|> def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e) <|fim▁end|>
"""Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False)
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): <|fim_middle|> <|fim▁end|>
if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): <|fim_middle|> else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e) <|fim▁end|>
print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`')
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: <|fim_middle|> <|fim▁end|>
translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def <|fim_middle|>(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e) <|fim▁end|>
get_modules
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def <|fim_middle|>(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e) <|fim▁end|>
add_arguments
<|file_name|>run_upgrade.py<|end_file_name|><|fim▁begin|>import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def <|fim_middle|>(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e) <|fim▁end|>
handle
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 <|fim▁hole|> button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
# Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0)
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): <|fim_middle|> def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
camera.capture(imagefile) image1 = Image.open(imagefile) return image1
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): <|fim_middle|> def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): <|fim_middle|> def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): <|fim_middle|> def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): <|fim_middle|> def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): <|fim_middle|> # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": <|fim_middle|> count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
dofilter(lastfilter,image1)
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def <|fim_middle|>(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
takephoto
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def <|fim_middle|>(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
photoloop
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def <|fim_middle|>(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
newphoto
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def <|fim_middle|>(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
invert
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def <|fim_middle|>(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
grayscale
<|file_name|>camera_try.py<|end_file_name|><|fim▁begin|># quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def <|fim_middle|> (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()<|fim▁end|>
dofilter
<|file_name|>euler.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os from pygal import * def listeEuler(f, x0, y0, pas, n): x, y, L = x0, y0, [] for k in range(n): L += [(x, y)] x += pas y += pas * f(x, y) return L def euler(f, x0, y0, xf, n):<|fim▁hole|> courbe.title = "Methode d Euler" courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n)) courbe.render_to_file("courbeEulerPython.svg") os.system("pause")<|fim▁end|>
pas = (xf - x0) / n courbe = XY()
<|file_name|>euler.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os from pygal import * def listeEuler(f, x0, y0, pas, n): <|fim_middle|> def euler(f, x0, y0, xf, n): pas = (xf - x0) / n courbe = XY() courbe.title = "Methode d Euler" courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n)) courbe.render_to_file("courbeEulerPython.svg") os.system("pause") <|fim▁end|>
x, y, L = x0, y0, [] for k in range(n): L += [(x, y)] x += pas y += pas * f(x, y) return L
<|file_name|>euler.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os from pygal import * def listeEuler(f, x0, y0, pas, n): x, y, L = x0, y0, [] for k in range(n): L += [(x, y)] x += pas y += pas * f(x, y) return L def euler(f, x0, y0, xf, n): <|fim_middle|> os.system("pause") <|fim▁end|>
pas = (xf - x0) / n courbe = XY() courbe.title = "Methode d Euler" courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n)) courbe.render_to_file("courbeEulerPython.svg")
<|file_name|>euler.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os from pygal import * def <|fim_middle|>(f, x0, y0, pas, n): x, y, L = x0, y0, [] for k in range(n): L += [(x, y)] x += pas y += pas * f(x, y) return L def euler(f, x0, y0, xf, n): pas = (xf - x0) / n courbe = XY() courbe.title = "Methode d Euler" courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n)) courbe.render_to_file("courbeEulerPython.svg") os.system("pause") <|fim▁end|>
listeEuler
<|file_name|>euler.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os from pygal import * def listeEuler(f, x0, y0, pas, n): x, y, L = x0, y0, [] for k in range(n): L += [(x, y)] x += pas y += pas * f(x, y) return L def <|fim_middle|>(f, x0, y0, xf, n): pas = (xf - x0) / n courbe = XY() courbe.title = "Methode d Euler" courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n)) courbe.render_to_file("courbeEulerPython.svg") os.system("pause") <|fim▁end|>
euler
<|file_name|>typegroups.py<|end_file_name|><|fim▁begin|>import array import numbers real_types = [numbers.Real] int_types = [numbers.Integral] iterable_types = [set, list, tuple, array.array]<|fim▁hole|> try: import numpy except ImportError: pass else: real_types.extend([numpy.float32, numpy.float64]) int_types.extend([numpy.int32, numpy.int64]) iterable_types.append(numpy.ndarray) # use these with isinstance to test for various types that include builtins # and numpy types (if numpy is available) real_types = tuple(real_types) int_types = tuple(int_types) iterable_types = tuple(iterable_types)<|fim▁end|>
<|file_name|>typegroups.py<|end_file_name|><|fim▁begin|>import array import numbers real_types = [numbers.Real] int_types = [numbers.Integral] iterable_types = [set, list, tuple, array.array] try: import numpy except ImportError: pass else: <|fim_middle|> # use these with isinstance to test for various types that include builtins # and numpy types (if numpy is available) real_types = tuple(real_types) int_types = tuple(int_types) iterable_types = tuple(iterable_types) <|fim▁end|>
real_types.extend([numpy.float32, numpy.float64]) int_types.extend([numpy.int32, numpy.int64]) iterable_types.append(numpy.ndarray)
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") report=1 else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists")<|fim▁hole|> bam=1 else: errors.append(' ERROR: no bam') if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam') else: print(sample+'\t'+' '.join(errors)) else: print("Family ID is not starting with digital")<|fim▁end|>
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: <|fim_middle|> else: print("Family ID is not starting with digital") <|fim▁end|>
prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") report=1 else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists") bam=1 else: errors.append(' ERROR: no bam') if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam') else: print(sample+'\t'+' '.join(errors))
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") <|fim_middle|> else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists") bam=1 else: errors.append(' ERROR: no bam') if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam') else: print(sample+'\t'+' '.join(errors)) else: print("Family ID is not starting with digital") <|fim▁end|>
report=1
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") report=1 else: <|fim_middle|> if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists") bam=1 else: errors.append(' ERROR: no bam') if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam') else: print(sample+'\t'+' '.join(errors)) else: print("Family ID is not starting with digital") <|fim▁end|>
errors.append('Error: no report')
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") report=1 else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists") <|fim_middle|> else: errors.append(' ERROR: no bam') if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam') else: print(sample+'\t'+' '.join(errors)) else: print("Family ID is not starting with digital") <|fim▁end|>
bam=1
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") report=1 else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists") bam=1 else: <|fim_middle|> if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam') else: print(sample+'\t'+' '.join(errors)) else: print("Family ID is not starting with digital") <|fim▁end|>
errors.append(' ERROR: no bam')
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") report=1 else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists") bam=1 else: errors.append(' ERROR: no bam') if (bam==1 and report==1): <|fim_middle|> else: print(sample+'\t'+' '.join(errors)) else: print("Family ID is not starting with digital") <|fim▁end|>
print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam')
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") report=1 else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists") bam=1 else: errors.append(' ERROR: no bam') if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam') else: <|fim_middle|> else: print("Family ID is not starting with digital") <|fim▁end|>
print(sample+'\t'+' '.join(errors))
<|file_name|>cre.locate_sample.py<|end_file_name|><|fim▁begin|>#!/hpf/largeprojects/ccmbio/naumenko/tools/bcbio/anaconda/bin/python """ Looks for a specific sample """ import re import sys import os import os.path sample = sys.argv[1] family,sample_only = sample.split("_") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print("Report exists") report=1 else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print("Bam exists") bam=1 else: errors.append(' ERROR: no bam') if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+"/"+report_path+"\t"+os.getcwd()+"/"+report_path+'/'+sample+'.bam') else: print(sample+'\t'+' '.join(errors)) else: <|fim_middle|> <|fim▁end|>
print("Family ID is not starting with digital")
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat"<|fim▁hole|> subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented")<|fim▁end|>
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): <|fim_middle|> def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): <|fim_middle|> def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): <|fim_middle|> def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) <|fim_middle|> def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): <|fim_middle|> def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): <|fim_middle|> def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0])
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): <|fim_middle|> def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): <|fim_middle|> def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): <|fim_middle|> if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): <|fim_middle|> #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
pdb_files.append(line)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: <|fim_middle|> if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: <|fim_middle|> if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: <|fim_middle|> print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
print ("For q>1 is not implemented now \n") sys.exit(0)
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import listdir import os import re import sys from argparse import ArgumentParser import random import subprocess from math import sqrt import ast from adderror import adderror """ENSAMBLE, -d directory -n number of models """ """-k number of selected structure""" """-r repet of program""" files = [] pdb_files = [] exp_file = [] list_of_random_items_modified = [] list_of_random_items = [] selected_files_for_ensamble = [] def argument(): parser = ArgumentParser() parser.add_argument("-d", "--dir", dest="myDirVariable", help="Choose dir", metavar="DIR", required=True) parser.add_argument("-n", metavar='N', type=int, dest="number_of_selected_files", help="Number of selected structure", required=True) parser.add_argument("-k", metavar='K', type=int, dest="k_number_of_options", help="Number of possibility structure, less then selected files", required=True) parser.add_argument("-q", metavar='Q', type=int, dest="mixing_koeficient", help="Mixing koeficient", default=1) parser.add_argument("-r", metavar='R', type=int, dest="repeat", help="Number of repetitions", default=1) parser.add_argument("--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() global files global list_of_random_items_modified files = listdir(args.myDirVariable) list_of_random_items_modified = [None]*args.k_number_of_options return(args) def rmsd_pymol(structure_1, structure_2): with open("file_for_pymol.pml", "w") as file_for_pymol: file_for_pymol.write(""" load {s1} load {s2} align {s3}, {s4} quit """.format(s1=structure_1, s2=structure_2, s3=os.path.splitext(structure_1)[0], s4=os.path.splitext(structure_2)[0])) out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for home: out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True) #part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True) rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1]) print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd) return rmsd def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files) def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items) def using_adderror(): for i in range(args.k_number_of_options): list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat') str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified) str2 = ''.join(str(e)+"\n" for e in list_of_random_items) print(str1) print(str2) return(str1, str2) def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0]) def ensamble_fit(): ensable_output=[None]*args.k_number_of_options for i in range(k_number_of_options): command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat" subprocess.call(command,shell=True) ensable_output[i] = result_rmsd() return(ensable_output) def result_rmsd(): with open('result', 'r') as f: (f.readline()) result = f.readline() values_of_index_result = result.split(',')[4:] return(values_of_index_result) def pymol_processing(ensable_output): sum_rmsd = 0 values_of_index_result = ensable_output[0] dictionary_index_and_structure = dict() for i, j in enumerate(selected_files_for_ensamble): dictionary_index_and_structure[i] = j for i, j in enumerate(values_of_index_result): f = float(j) if f != 0: <|fim_middle|> print('Sum of RMSD', sum_rmsd) if __name__ == '__main__': args = argument() total_number_of_pdb_files = searching_pdb() for i in range(args.repeat): argument_processing(args, total_number_of_pdb_files) strings = using_adderror() #find_index(strings) # ensamble_output = ensamble-fit() ensamble_output=[None]*2 ensamble_output[0] = result_rmsd() if args.k_number_of_options ==1: pymol_processing(ensamble_output) else: print("not implemented") <|fim▁end|>
computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i], list_of_random_items[0]) print('Adjusted rmsd ', f*computed_rmsd, '\n') sum_rmsd += f*computed_rmsd