<commit_before>"""
    blockpicker
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from PySide import QtGui, QtCore
import logging
from PySide.QtCore import Qt
from PySide.QtGui import QPixmap
from mcedit2.util.load_ui import registerCustomWidget, load_ui
from mcedit2.widgets.blocktype_list import BlockTypePixmap
from mcedit2.widgets.layout import Row, Column
from mcedit2.worldview.iso import IsoWorldView
from mceditlib.blocktypes import BlockType
from mceditlib.schematic import SchematicFileAdapter
from mceditlib.worldeditor import WorldEditor

log = logging.getLogger(__name__)

@registerCustomWidget
class BlockThumbView(QtGui.QWidget):
    def __init__(self, *a, **kw):
        super(BlockThumbView, self).__init__(minimumWidth=48, minimumHeight=48, *a, **kw)
        self.worldView = None

    _editorSession = None
    @property
    def editorSession(self):
        return self._editorSession

    @editorSession.setter
    def editorSession(self, editorSession):
        self._editorSession = editorSession
        self.updateView()

    _block = None
    @property
    def block(self):
        return self._block

    @block.setter
    def block(self, value):
        self._block = value
        self.updateView()

    def updateView(self):
        if None in (self.block, self.editorSession):
            return

        blockworld = SchematicFileAdapter((1, 1, 1), blocktypes=self.editorSession.worldEditor.blocktypes)
        editor = WorldEditor(adapter=blockworld)
        dim = editor.getDimension()
        dim.setBlocks(0, 0, 0, self.block)
        self.worldView = IsoWorldView(dim, self.editorSession.textureAtlas, sharedGLWidget=self.editorSession.editorTab.miniMap)

        self.setLayout(Row(self.worldView))
#
#class BlockTypeItemDelegate(QtGui.QStyledItemDelegate):
#    def __init__(self, model, listView, *args, **kwargs):
#        """
#
#        :type listView: QListView
#        """
#        super(BlockTypeItemDelegate, self).__init__(*args, **kwargs)
#        self.listView = listView
#        self.model = model
#        self.textureAtlas = model.editor.textureAtlas
#
#    def xpaint(self, painter, option, index):
#        """
#
#        :type painter: QtGui.QPainter
#        :type option: QStyleOptionViewItem
#        :type index: QModelIndex
#        """
#        #super(BlockTypeItemDelegate, self).paint(painter, option, index)
#        QtGui.QStyledItemDelegate.paint(self, painter, option, index)
#        #self.listWidget.style().drawPrimitive(QtGui.QStyle.PE_PanelItemViewItem, option, painter, None)
#        return
#
#        if False and option.state & QtGui.QStyle.State_Enabled:
#            widget = BlockTypesItemWidget(self.listView.model().data(index, role=Qt.UserRole), self.textureAtlas)
#            widget.setGeometry(option.rect)
#            widget.setMinimumSize(self.model.baseSize)
#            widget.setBackgroundRole(QtGui.QPalette.NoRole)
#            widget.setAutoFillBackground(False)
#            #painter.drawRoundedRect(option.rect, 0, 0)
#            img = QPixmap(option.rect.size())
#            img.fill(QtGui.QColor(0, 0, 0, 0))
#            #log.info("Paint: Active")
#
#            widget.render(img, renderFlags=widget.DrawChildren)
#
#            #if option.state & QtGui.QStyle.State_Selected:
#            #    brush = option.palette.highlight()
#            #    painter.fillRect(option.rect, brush)
#
#            painter.drawPixmap(option.rect.topLeft(), img)
#            #style = self.listWidget.style()
#            #style.drawPrimitive(style.PE_PanelItemViewItem, option, painter, widget)
#            #style.drawControl(style.CE_ItemViewItem, option, painter)
#
#
#
#    def sizeHint(self, option, index):
#        return QtCore.QSize(self.listView.width(), self.model.baseSize.height())
#
#_widgetWidth = 400
#
#class BlockTypeSetModel(QtCore.QAbstractListModel):
#
#    def __init__(self, editor, *args, **kwargs):
#        super(BlockTypeSetModel, self).__init__(*args, **kwargs)
#        self.allBlocks = list(editor.world.blocktypes)
#        self.editor = editor
#        widget = BlockTypesItemWidget(editor.world.blocktypes.Stone, editor.textureAtlas)
#        self.baseSize = QtCore.QSize(widget.sizeHint().width(), widget.sizeHint().height())
#
#    def rowCount(self, parent=QtCore.QModelIndex()):
#        return len(self.allBlocks)
#
#    def data(self, index, role=Qt.DisplayRole):
#        if role == Qt.DisplayRole:
#            return self.allBlocks[index.row()].displayName
#            #return self.makeIcon(index)
#        elif role == Qt.UserRole:
#            return self.allBlocks[index.row()]
#        else:
#            return None
#
#    def makeIcon(self, index):
#        widget = BlockTypesItemWidget(self.data(index, role=Qt.UserRole), self.editor.textureAtlas)
#        widget.setMinimumSize(self.baseSize)
#        widget.setBackgroundRole(QtGui.QPalette.NoRole)
#        widget.setAutoFillBackground(False)
#        #painter.drawRoundedRect(option.rect, 0, 0)
#        img = QPixmap(self.baseSize)
#        img.fill(QtGui.QColor(0, 0, 0, 0))
#        #log.info("Paint: Active")
#
#        widget.render(img, renderFlags=widget.DrawChildren)
#        return img
#        #icon = QtGui.QIcon(img)
#        #return icon

class BlockTypeIcon(QtGui.QLabel):
    def __init__(self, block, textureAtlas, *args, **kwargs):
        super(BlockTypeIcon, self).__init__(*args, **kwargs)
        pixmap = BlockTypePixmap(block, textureAtlas)
        self.setMinimumSize(32, 32)
        self.setPixmap(pixmap)

class BlockTypesItemWidget(QtGui.QWidget):
    def __init__(self, blocks, textureAtlas):
        super(BlockTypesItemWidget, self).__init__()
        if len(blocks) == 1:
            block = blocks[0]
            self.blockIcon = BlockTypeIcon(block, textureAtlas)

            nameLabel = QtGui.QLabel(block.displayName)

            internalNameLimit = 60
            internalName = block.internalName + block.blockState
            if len(internalName) > internalNameLimit:
                internalName = internalName[:internalNameLimit-3]+"..."

            internalNameLabel = QtGui.QLabel("(%d:%d) %s" % (block.ID, block.meta, internalName), enabled=False)

            parentTypeLabel = QtGui.QLabel("")
            if block.meta != 0:
                parentBlock = block.blocktypeSet[block.internalName]
                if parentBlock.displayName != block.displayName:
                    parentTypeLabel.setText("%s" % parentBlock.displayName)

            labelsColumn = Column(Row(nameLabel, None, parentTypeLabel),
                                  internalNameLabel)

            row = Row(self.blockIcon, (labelsColumn, 1))
            self.setLayout(row)

            # row.setSizeConstraint(QtGui.QLayout.SetFixedSize)
        else:
            frame = QtGui.QFrame()
            frame.setMinimumSize(64, 64)
            iconLimit = 16

            blocksToIcon = blocks[:iconLimit]
            icons = [BlockTypeIcon(b, textureAtlas) for b in blocksToIcon]
            x = 0
            y = 0
            for i, icon in enumerate(icons):
                # icon.setMinimumSize(32, 32)
                icon.setParent(frame)
                icon.setGeometry(x, y, 32, 32)
                icon.setFrameStyle(icon.Box)
                icon.setLineWidth(1)
                x += 18
                if i % 2:
                    x -= 32
                y += 4

            nameLimit = 6
            remaining = len(blocks) - nameLimit
            blocksToName = blocks[:nameLimit]
            iconNames = ", ".join(b.displayName for b in blocksToName)
            if remaining > 0:
                iconNames += " and %d more..." % remaining
            self.setLayout(Row(frame, QtGui.QLabel(iconNames, wordWrap=True)))

        self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
        self.adjustSize()

@registerCustomWidget
class BlockTypeListWidget(QtGui.QListWidget):

    def __init__(self, *args, **kwargs):
        super(BlockTypeListWidget, self).__init__(*args, **kwargs)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

    _textureAtlas = None

    @property
    def textureAtlas(self):
        return self._textureAtlas

    @textureAtlas.setter
    def textureAtlas(self, value):
        oldVal = self._textureAtlas
        self._textureAtlas = value
        if oldVal != value:
            self.updateList()

    _blocktypes = None

    @property
    def blocktypes(self):
        return self._blocktypes

    @blocktypes.setter
    def blocktypes(self, value):
        oldVal = self._blocktypes
        self._blocktypes = value
        if oldVal != value:
            self.updateList()

    _searchValue = None

    def setSearchString(self, val):
        self._searchValue = val
        for item in self.findItems("", Qt.MatchContains):
            item.setHidden(val.lower() not in item.block.displayName.lower())

    def updateList(self):
        if self.textureAtlas is None:
            return
        if self.blocktypes is None:
            return

        self.clear()

        for block in self.blocktypes:
            if self._searchValue:
                for s in block.displayName, block.internalName:
                    if self._searchValue not in s:
                        continue

            item = QtGui.QListWidgetItem()
            itemWidget = BlockTypesItemWidget([block], self.textureAtlas)
            item.setSizeHint(itemWidget.sizeHint())
            item.block = block
            item.widget = itemWidget

            self.addItem(item)
            self.setItemWidget(item, itemWidget)

        self.setMinimumWidth(self.sizeHintForColumn(0)+self.autoScrollMargin())

class BlockTypePicker(QtGui.QDialog):
    def __init__(self, *args, **kwargs):
        super(BlockTypePicker, self).__init__(*args, **kwargs)
        self._editorSession = None

        load_ui("block_picker.ui", baseinstance=self)
        self.selectButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)
        self.searchField.editTextChanged.connect(self.setSearchString)
        assert isinstance(self.listWidget, QtGui.QListWidget)
        self.listWidget.itemSelectionChanged.connect(self.selectionDidChange)
        self.listWidget.doubleClicked.connect(self.accept)
        self.setSizeGripEnabled(True)

    def selectionDidChange(self):
        if not self.multipleSelect:
            if len(self.selectedBlocks):
                block = self.selectedBlocks[0]
                self.nameLabel.setText("%s" % block.displayName)
                self.internalNameLabel.setText("(%d:%d) %s" % (block.ID, block.meta, block.internalName))
                self.brightnessLabel.setText("Brightness: %d" % block.brightness)
                self.opacityLabel.setText("Opacity: %d" % block.opacity)
                self.rendertypeLabel.setText("Render: %d" % block.renderType)
                pixmap = BlockTypePixmap(block, self.editorSession.textureAtlas)
                self.blockThumb.setPixmap(pixmap)
            else:
                self.nameLabel.setText("")
                self.idLabel.setText("")
                self.internalNameLabel.setText("")
                self.brightnessLabel.setText("")
                self.opacityLabel.setText("")
                self.rendertypeLabel.setText("")

    @property
    def multipleSelect(self):
        return self.listWidget.selectionMode() == self.listWidget.MultiSelection

    @multipleSelect.setter
    def multipleSelect(self, value):
        if value:
            self.listWidget.setSelectionMode(self.listWidget.MultiSelection)
        else:
            self.listWidget.setSelectionMode(self.listWidget.SingleSelection)

    @property
    def editorSession(self):
        return self._editorSession

    @editorSession.setter
    def editorSession(self, editorSession):
        """

        :type editorSession: EditorSession
        """
        self._editorSession = editorSession
        if self.editorSession:
            self.listWidget.textureAtlas = self.editorSession.textureAtlas
            self.listWidget.blocktypes = self.editorSession.worldEditor.blocktypes

    @property
    def selectedBlocks(self):
        return [i.block for i in self.listWidget.selectedItems()]

    @selectedBlocks.setter
    def selectedBlocks(self, val):
        self.listWidget.clearSelection()
        found = False
        for item in self.listWidget.findItems("", Qt.MatchContains):
            if item.block in val:
                if self.multipleSelect:
                    self.listWidget.setCurrentItem(item, QtGui.QItemSelectionModel.Current)
                else:
                    self.listWidget.setCurrentItem(item)
                found = True
        if found:
            self.selectionDidChange()

    def setSearchString(self, val):
        self.listWidget.setSearchString(val)

_sharedPicker = None

def getBlockTypePicker():
    global _sharedPicker
    if _sharedPicker is None:
        _sharedPicker = BlockTypePicker()
    return _sharedPicker

@registerCustomWidget
class BlockTypeButton(QtGui.QPushButton):
    def __init__(self, *args, **kwargs):
        super(BlockTypeButton, self).__init__(*args, **kwargs)
        self._blocks = []
        self.clicked.connect(self.showPicker)
        self.picker = getBlockTypePicker()
        self.setLayout(QtGui.QStackedLayout())
        self._viewWidget = None
        self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)

    blocksChanged = QtCore.Signal(list)

    @property
    def multipleSelect(self):
        return self.picker.multipleSelect

    @multipleSelect.setter
    def multipleSelect(self, value):
        self.picker.multipleSelect = value

    _editor = None

    @property
    def editorSession(self):
        return self._editor

    @editorSession.setter
    def editorSession(self, editorSession):
        """

        :type editorSession: EditorSession
        """
        self._editor = editorSession
        self.picker.editorSession = editorSession
        self.updateView()

    def updateView(self):
        if self.editorSession and self.blocks:
            log.info("Updating button with %s", self.blocks)

            layout = self.layout()
            if self._viewWidget:
                layout.removeWidget(self._viewWidget)
            self._viewWidget = BlockTypesItemWidget(self.blocks, self.editorSession.textureAtlas)
            layout.addWidget(self._viewWidget)

            assert isinstance(layout, QtGui.QLayout)
            self.setMinimumHeight(self._viewWidget.sizeHint().height())

    @property
    def block(self):
        return self._blocks[0] if len(self._blocks) else None

    @block.setter
    def block(self, value):
        self.blocks = [value]

    @property
    def blocks(self):
        return self._blocks

    @blocks.setter
    def blocks(self, value):
        value = [self.editorSession.worldEditor.blocktypes[block]
                 if not isinstance(block, BlockType)
                 else block
                 for block in value]

        if self._blocks != value:
            self.blocksChanged.emit(value)
        self._blocks = value
        self.updateView()

    def showPicker(self):
        self.picker.selectedBlocks = self.blocks
        if self.picker.exec_():
            self.blocks = self.picker.selectedBlocks
            log.info("Picked block %s", self.block)
<commit_msg>BlockTypeButton doesn't expand vertically by default, like a regular button<commit_after>"""
    blockpicker
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from PySide import QtGui, QtCore
import logging
from PySide.QtCore import Qt
from PySide.QtGui import QPixmap
from mcedit2.util.load_ui import registerCustomWidget, load_ui
from mcedit2.widgets.blocktype_list import BlockTypePixmap
from mcedit2.widgets.layout import Row, Column
from mcedit2.worldview.iso import IsoWorldView
from mceditlib.blocktypes import BlockType
from mceditlib.schematic import SchematicFileAdapter
from mceditlib.worldeditor import WorldEditor

log = logging.getLogger(__name__)

@registerCustomWidget
class BlockThumbView(QtGui.QWidget):
    def __init__(self, *a, **kw):
        super(BlockThumbView, self).__init__(minimumWidth=48, minimumHeight=48, *a, **kw)
        self.worldView = None

    _editorSession = None
    @property
    def editorSession(self):
        return self._editorSession

    @editorSession.setter
    def editorSession(self, editorSession):
        self._editorSession = editorSession
        self.updateView()

    _block = None
    @property
    def block(self):
        return self._block

    @block.setter
    def block(self, value):
        self._block = value
        self.updateView()

    def updateView(self):
        if None in (self.block, self.editorSession):
            return

        blockworld = SchematicFileAdapter((1, 1, 1), blocktypes=self.editorSession.worldEditor.blocktypes)
        editor = WorldEditor(adapter=blockworld)
        dim = editor.getDimension()
        dim.setBlocks(0, 0, 0, self.block)
        self.worldView = IsoWorldView(dim, self.editorSession.textureAtlas, sharedGLWidget=self.editorSession.editorTab.miniMap)

        self.setLayout(Row(self.worldView))
#
#class BlockTypeItemDelegate(QtGui.QStyledItemDelegate):
#    def __init__(self, model, listView, *args, **kwargs):
#        """
#
#        :type listView: QListView
#        """
#        super(BlockTypeItemDelegate, self).__init__(*args, **kwargs)
#        self.listView = listView
#        self.model = model
#        self.textureAtlas = model.editor.textureAtlas
#
#    def xpaint(self, painter, option, index):
#        """
#
#        :type painter: QtGui.QPainter
#        :type option: QStyleOptionViewItem
#        :type index: QModelIndex
#        """
#        #super(BlockTypeItemDelegate, self).paint(painter, option, index)
#        QtGui.QStyledItemDelegate.paint(self, painter, option, index)
#        #self.listWidget.style().drawPrimitive(QtGui.QStyle.PE_PanelItemViewItem, option, painter, None)
#        return
#
#        if False and option.state & QtGui.QStyle.State_Enabled:
#            widget = BlockTypesItemWidget(self.listView.model().data(index, role=Qt.UserRole), self.textureAtlas)
#            widget.setGeometry(option.rect)
#            widget.setMinimumSize(self.model.baseSize)
#            widget.setBackgroundRole(QtGui.QPalette.NoRole)
#            widget.setAutoFillBackground(False)
#            #painter.drawRoundedRect(option.rect, 0, 0)
#            img = QPixmap(option.rect.size())
#            img.fill(QtGui.QColor(0, 0, 0, 0))
#            #log.info("Paint: Active")
#
#            widget.render(img, renderFlags=widget.DrawChildren)
#
#            #if option.state & QtGui.QStyle.State_Selected:
#            #    brush = option.palette.highlight()
#            #    painter.fillRect(option.rect, brush)
#
#            painter.drawPixmap(option.rect.topLeft(), img)
#            #style = self.listWidget.style()
#            #style.drawPrimitive(style.PE_PanelItemViewItem, option, painter, widget)
#            #style.drawControl(style.CE_ItemViewItem, option, painter)
#
#
#
#    def sizeHint(self, option, index):
#        return QtCore.QSize(self.listView.width(), self.model.baseSize.height())
#
#_widgetWidth = 400
#
#class BlockTypeSetModel(QtCore.QAbstractListModel):
#
#    def __init__(self, editor, *args, **kwargs):
#        super(BlockTypeSetModel, self).__init__(*args, **kwargs)
#        self.allBlocks = list(editor.world.blocktypes)
#        self.editor = editor
#        widget = BlockTypesItemWidget(editor.world.blocktypes.Stone, editor.textureAtlas)
#        self.baseSize = QtCore.QSize(widget.sizeHint().width(), widget.sizeHint().height())
#
#    def rowCount(self, parent=QtCore.QModelIndex()):
#        return len(self.allBlocks)
#
#    def data(self, index, role=Qt.DisplayRole):
#        if role == Qt.DisplayRole:
#            return self.allBlocks[index.row()].displayName
#            #return self.makeIcon(index)
#        elif role == Qt.UserRole:
#            return self.allBlocks[index.row()]
#        else:
#            return None
#
#    def makeIcon(self, index):
#        widget = BlockTypesItemWidget(self.data(index, role=Qt.UserRole), self.editor.textureAtlas)
#        widget.setMinimumSize(self.baseSize)
#        widget.setBackgroundRole(QtGui.QPalette.NoRole)
#        widget.setAutoFillBackground(False)
#        #painter.drawRoundedRect(option.rect, 0, 0)
#        img = QPixmap(self.baseSize)
#        img.fill(QtGui.QColor(0, 0, 0, 0))
#        #log.info("Paint: Active")
#
#        widget.render(img, renderFlags=widget.DrawChildren)
#        return img
#        #icon = QtGui.QIcon(img)
#        #return icon

class BlockTypeIcon(QtGui.QLabel):
    def __init__(self, block, textureAtlas, *args, **kwargs):
        super(BlockTypeIcon, self).__init__(*args, **kwargs)
        pixmap = BlockTypePixmap(block, textureAtlas)
        self.setMinimumSize(32, 32)
        self.setPixmap(pixmap)

class BlockTypesItemWidget(QtGui.QWidget):
    def __init__(self, blocks, textureAtlas):
        super(BlockTypesItemWidget, self).__init__()
        if len(blocks) == 1:
            block = blocks[0]
            self.blockIcon = BlockTypeIcon(block, textureAtlas)

            nameLabel = QtGui.QLabel(block.displayName)

            internalNameLimit = 60
            internalName = block.internalName + block.blockState
            if len(internalName) > internalNameLimit:
                internalName = internalName[:internalNameLimit-3]+"..."

            internalNameLabel = QtGui.QLabel("(%d:%d) %s" % (block.ID, block.meta, internalName), enabled=False)

            parentTypeLabel = QtGui.QLabel("")
            if block.meta != 0:
                parentBlock = block.blocktypeSet[block.internalName]
                if parentBlock.displayName != block.displayName:
                    parentTypeLabel.setText("%s" % parentBlock.displayName)

            labelsColumn = Column(Row(nameLabel, None, parentTypeLabel),
                                  internalNameLabel)

            row = Row(self.blockIcon, (labelsColumn, 1))
            self.setLayout(row)

            # row.setSizeConstraint(QtGui.QLayout.SetFixedSize)
        else:
            frame = QtGui.QFrame()
            frame.setMinimumSize(64, 64)
            iconLimit = 16

            blocksToIcon = blocks[:iconLimit]
            icons = [BlockTypeIcon(b, textureAtlas) for b in blocksToIcon]
            x = 0
            y = 0
            for i, icon in enumerate(icons):
                # icon.setMinimumSize(32, 32)
                icon.setParent(frame)
                icon.setGeometry(x, y, 32, 32)
                icon.setFrameStyle(icon.Box)
                icon.setLineWidth(1)
                x += 18
                if i % 2:
                    x -= 32
                y += 4

            nameLimit = 6
            remaining = len(blocks) - nameLimit
            blocksToName = blocks[:nameLimit]
            iconNames = ", ".join(b.displayName for b in blocksToName)
            if remaining > 0:
                iconNames += " and %d more..." % remaining
            self.setLayout(Row(frame, QtGui.QLabel(iconNames, wordWrap=True)))

        self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
        self.adjustSize()

@registerCustomWidget
class BlockTypeListWidget(QtGui.QListWidget):

    def __init__(self, *args, **kwargs):
        super(BlockTypeListWidget, self).__init__(*args, **kwargs)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

    _textureAtlas = None

    @property
    def textureAtlas(self):
        return self._textureAtlas

    @textureAtlas.setter
    def textureAtlas(self, value):
        oldVal = self._textureAtlas
        self._textureAtlas = value
        if oldVal != value:
            self.updateList()

    _blocktypes = None

    @property
    def blocktypes(self):
        return self._blocktypes

    @blocktypes.setter
    def blocktypes(self, value):
        oldVal = self._blocktypes
        self._blocktypes = value
        if oldVal != value:
            self.updateList()

    _searchValue = None

    def setSearchString(self, val):
        self._searchValue = val
        for item in self.findItems("", Qt.MatchContains):
            item.setHidden(val.lower() not in item.block.displayName.lower())

    def updateList(self):
        if self.textureAtlas is None:
            return
        if self.blocktypes is None:
            return

        self.clear()

        for block in self.blocktypes:
            if self._searchValue:
                for s in block.displayName, block.internalName:
                    if self._searchValue not in s:
                        continue

            item = QtGui.QListWidgetItem()
            itemWidget = BlockTypesItemWidget([block], self.textureAtlas)
            item.setSizeHint(itemWidget.sizeHint())
            item.block = block
            item.widget = itemWidget

            self.addItem(item)
            self.setItemWidget(item, itemWidget)

        self.setMinimumWidth(self.sizeHintForColumn(0)+self.autoScrollMargin())

class BlockTypePicker(QtGui.QDialog):
    def __init__(self, *args, **kwargs):
        super(BlockTypePicker, self).__init__(*args, **kwargs)
        self._editorSession = None

        load_ui("block_picker.ui", baseinstance=self)
        self.selectButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)
        self.searchField.editTextChanged.connect(self.setSearchString)
        assert isinstance(self.listWidget, QtGui.QListWidget)
        self.listWidget.itemSelectionChanged.connect(self.selectionDidChange)
        self.listWidget.doubleClicked.connect(self.accept)
        self.setSizeGripEnabled(True)

    def selectionDidChange(self):
        if not self.multipleSelect:
            if len(self.selectedBlocks):
                block = self.selectedBlocks[0]
                self.nameLabel.setText("%s" % block.displayName)
                self.internalNameLabel.setText("(%d:%d) %s" % (block.ID, block.meta, block.internalName))
                self.brightnessLabel.setText("Brightness: %d" % block.brightness)
                self.opacityLabel.setText("Opacity: %d" % block.opacity)
                self.rendertypeLabel.setText("Render: %d" % block.renderType)
                pixmap = BlockTypePixmap(block, self.editorSession.textureAtlas)
                self.blockThumb.setPixmap(pixmap)
            else:
                self.nameLabel.setText("")
                self.idLabel.setText("")
                self.internalNameLabel.setText("")
                self.brightnessLabel.setText("")
                self.opacityLabel.setText("")
                self.rendertypeLabel.setText("")

    @property
    def multipleSelect(self):
        return self.listWidget.selectionMode() == self.listWidget.MultiSelection

    @multipleSelect.setter
    def multipleSelect(self, value):
        if value:
            self.listWidget.setSelectionMode(self.listWidget.MultiSelection)
        else:
            self.listWidget.setSelectionMode(self.listWidget.SingleSelection)

    @property
    def editorSession(self):
        return self._editorSession

    @editorSession.setter
    def editorSession(self, editorSession):
        """

        :type editorSession: EditorSession
        """
        self._editorSession = editorSession
        if self.editorSession:
            self.listWidget.textureAtlas = self.editorSession.textureAtlas
            self.listWidget.blocktypes = self.editorSession.worldEditor.blocktypes

    @property
    def selectedBlocks(self):
        return [i.block for i in self.listWidget.selectedItems()]

    @selectedBlocks.setter
    def selectedBlocks(self, val):
        self.listWidget.clearSelection()
        found = False
        for item in self.listWidget.findItems("", Qt.MatchContains):
            if item.block in val:
                if self.multipleSelect:
                    self.listWidget.setCurrentItem(item, QtGui.QItemSelectionModel.Current)
                else:
                    self.listWidget.setCurrentItem(item)
                found = True
        if found:
            self.selectionDidChange()

    def setSearchString(self, val):
        self.listWidget.setSearchString(val)

_sharedPicker = None

def getBlockTypePicker():
    global _sharedPicker
    if _sharedPicker is None:
        _sharedPicker = BlockTypePicker()
    return _sharedPicker

@registerCustomWidget
class BlockTypeButton(QtGui.QPushButton):
    def __init__(self, *args, **kwargs):
        super(BlockTypeButton, self).__init__(*args, **kwargs)
        self._blocks = []
        self.clicked.connect(self.showPicker)
        self.picker = getBlockTypePicker()
        self.setLayout(QtGui.QStackedLayout())
        self._viewWidget = None
        self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)

    blocksChanged = QtCore.Signal(list)

    @property
    def multipleSelect(self):
        return self.picker.multipleSelect

    @multipleSelect.setter
    def multipleSelect(self, value):
        self.picker.multipleSelect = value

    _editor = None

    @property
    def editorSession(self):
        return self._editor

    @editorSession.setter
    def editorSession(self, editorSession):
        """

        :type editorSession: EditorSession
        """
        self._editor = editorSession
        self.picker.editorSession = editorSession
        self.updateView()

    def updateView(self):
        if self.editorSession and self.blocks:
            log.info("Updating button with %s", self.blocks)

            layout = self.layout()
            if self._viewWidget:
                layout.removeWidget(self._viewWidget)
            self._viewWidget = BlockTypesItemWidget(self.blocks, self.editorSession.textureAtlas)
            layout.addWidget(self._viewWidget)

            assert isinstance(layout, QtGui.QLayout)
            self.setMinimumHeight(self._viewWidget.sizeHint().height())

    @property
    def block(self):
        return self._blocks[0] if len(self._blocks) else None

    @block.setter
    def block(self, value):
        self.blocks = [value]

    @property
    def blocks(self):
        return self._blocks

    @blocks.setter
    def blocks(self, value):
        value = [self.editorSession.worldEditor.blocktypes[block]
                 if not isinstance(block, BlockType)
                 else block
                 for block in value]

        if self._blocks != value:
            self.blocksChanged.emit(value)
        self._blocks = value
        self.updateView()

    def showPicker(self):
        self.picker.selectedBlocks = self.blocks
        if self.picker.exec_():
            self.blocks = self.picker.selectedBlocks
            log.info("Picked block %s", self.block)
<|endoftext|>


<commit_before>import os
import csv

import logging
log = logging.getLogger(__name__)

def deinterlace(path):
    with open(path) as csvfile:
        raw = [row for row in csv.reader(
            csvfile,
        )]
        l = len(raw)
        data = []
        i = 0
        #  Deinterlace and build list of dictionaries.
        while i < l:
            if (i % 2 == 0):  # zero-indexed rows
                row = raw[i]
                row.extend(raw[i + 1])
                data.append(row)
            else:  # Skip interlaced row; added supra
                pass
            i += 1
        return data

def strip_penalties(output):
    for row in output:
        scores = [6, 7, 8, 10, 11, 12]
        for score in scores:
            try:
                int(row[score])
            except ValueError:
                row[score] = row[score][:3]
    return output

def write_file(path, output):
    basepath = os.path.split(path)[0]
    namepath = os.path.split(path)[1]
    with open(os.path.join(basepath, namepath,), 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for row in output:
            writer.writerow(row)
    return

def parse_chorus(path):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[8].split('[', 1)[1].split(']', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[8] = row[8].split('[', 1)[0]
        # Add round
        row.extend(['1'])
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(2, row.pop(10))
        row.insert(4, row.pop(-1))
        row.pop(10)
        row.pop(9)
        row.insert(-1, row.pop(9))
        row.pop(13)
        row.pop(13)
        row.pop(-1)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def parse_district_chorus(path, district):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[9].split('(', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[9] = row[9].split('(', 1)[0]
        # Add round
        row.extend(['1'])
        # Overwrite district
        row[19] = district
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(2, row.pop(11))
        row.insert(4, row.pop(-1))
        row.insert(-1, row.pop(12))
        row.pop(5)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(13)
        row.pop(13)
        row.pop(14)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def parse_quarters(path):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[7].split('[', 1)[1].split(']', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[7] = row[7].split('[', 1)[0]
        # Add round
        row.extend(['3'])
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(3, row.pop(-2))
        row.insert(4, row.pop(-1))
        row.pop(9)
        row.pop(9)
        row.pop(9)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def parse_semis(path):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[9].split('[', 1)[1].split(']', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[9] = row[9].split('[', 1)[0]
        # Add round
        row.extend(['2'])
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(3, row.pop(-2))
        row.insert(4, row.pop(-1))
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(-1)
        row.pop(-1)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def parse_finals(path):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[9].split('[', 1)[1].split(']', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[9] = row[9].split('[', 1)[0]
        # Add round
        row.extend(['1'])
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(3, row.pop(-2))
        row.insert(4, row.pop(-1))
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(-1)
        row.pop(-1)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def place_round(performances):
    queue = []
    i = 1
    for performance in performances:
        try:
            match = performance.total_raw == queue[0].total_raw
        except IndexError:
            performance.place = i
            performance.save()
            queue.append(performance)
            continue
        if match:
            performance.place = i
            i += len(queue)
            performance.save()
            queue.append(performance)
            continue
        else:
            i += 1
            performance.place = i
            performance.save()
            queue = [performance]
    return
<commit_msg>Add merge_group to utils<commit_after>import os
import csv

import logging
log = logging.getLogger(__name__)

def deinterlace(path):
    with open(path) as csvfile:
        raw = [row for row in csv.reader(
            csvfile,
        )]
        l = len(raw)
        data = []
        i = 0
        #  Deinterlace and build list of dictionaries.
        while i < l:
            if (i % 2 == 0):  # zero-indexed rows
                row = raw[i]
                row.extend(raw[i + 1])
                data.append(row)
            else:  # Skip interlaced row; added supra
                pass
            i += 1
        return data

def strip_penalties(output):
    for row in output:
        scores = [6, 7, 8, 10, 11, 12]
        for score in scores:
            try:
                int(row[score])
            except ValueError:
                row[score] = row[score][:3]
    return output

def write_file(path, output):
    basepath = os.path.split(path)[0]
    namepath = os.path.split(path)[1]
    with open(os.path.join(basepath, namepath,), 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for row in output:
            writer.writerow(row)
    return

def parse_chorus(path):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[8].split('[', 1)[1].split(']', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[8] = row[8].split('[', 1)[0]
        # Add round
        row.extend(['1'])
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(2, row.pop(10))
        row.insert(4, row.pop(-1))
        row.pop(10)
        row.pop(9)
        row.insert(-1, row.pop(9))
        row.pop(13)
        row.pop(13)
        row.pop(-1)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def parse_district_chorus(path, district):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[9].split('(', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[9] = row[9].split('(', 1)[0]
        # Add round
        row.extend(['1'])
        # Overwrite district
        row[19] = district
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(2, row.pop(11))
        row.insert(4, row.pop(-1))
        row.insert(-1, row.pop(12))
        row.pop(5)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(13)
        row.pop(13)
        row.pop(14)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def parse_quarters(path):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[7].split('[', 1)[1].split(']', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[7] = row[7].split('[', 1)[0]
        # Add round
        row.extend(['3'])
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(3, row.pop(-2))
        row.insert(4, row.pop(-1))
        row.pop(9)
        row.pop(9)
        row.pop(9)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def parse_semis(path):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[9].split('[', 1)[1].split(']', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[9] = row[9].split('[', 1)[0]
        # Add round
        row.extend(['2'])
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(3, row.pop(-2))
        row.insert(4, row.pop(-1))
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(-1)
        row.pop(-1)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def parse_finals(path):
    data = deinterlace(path)
    output = []
    # Split first cell and chapter cell
    for row in data:
        row.extend([row[0].split(' ', 1)[0]])
        row.extend([row[9].split('[', 1)[1].split(']', 1)[0]])
        row[0] = row[0].split(' ', 1)[1]
        row[9] = row[9].split('[', 1)[0]
        # Add round
        row.extend(['1'])
        output.append(row)
    # Strip space
    for row in output:
        i = 0
        l = len(row)
        while i < l:
            row[i] = row[i].strip()
            i += 1
    # Reorder in list -- SUPER Kludge!
    for row in output:
        row.insert(0, row.pop(-1))
        row.insert(1, row.pop(-2))
        row.insert(3, row.pop(-2))
        row.insert(4, row.pop(-1))
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(9)
        row.pop(-1)
        row.pop(-1)

    output = strip_penalties(output)

    output = write_file(path, output)

    return

def place_round(performances):
    queue = []
    i = 1
    for performance in performances:
        try:
            match = performance.total_raw == queue[0].total_raw
        except IndexError:
            performance.place = i
            performance.save()
            queue.append(performance)
            continue
        if match:
            performance.place = i
            i += len(queue)
            performance.save()
            queue.append(performance)
            continue
        else:
            i += 1
            performance.place = i
            performance.save()
            queue = [performance]
    return

def merge_groups(from_group, to_group):
    cs = from_group.contestants.all()
    for c in cs:
        c.group = to_group
        c.save()
    from_group.delete()

<|endoftext|>


<commit_before>'''
Created on Oct 21, 2015

@author: hsorby
'''
from zipfile import ZipFile, is_zipfile

import struct
from meshparser.nodepare.pare import NodePare

class STLParser(object):
    '''
    classdocs
    '''

    def __init__(self):
        '''
        Constructor
        '''
        self._points = []
        self._elements = []

    def parse(self, filename):

        if is_zipfile(filename):
            with ZipFile(filename) as stlzip:
                zipinfolist = stlzip.infolist()
                if len(zipinfolist) != 1:
                    print('More than one file in archive ... exiting')
                    return
                zipinfo = zipinfolist[0]
                data = stlzip.read(zipinfo.filename)
                if 'solid' in data[:80].decode("utf-8"):
                    lines = data.decode("utf-8").split('\n')
                    self._parseASCII(lines)
                else:
                    self._parseBinary(data)
        elif _is_ascii_stl(filename):
            with open(filename) as f:
                lines = f.readlines()
                self._parseASCII(lines)
        else:
            with open(filename, 'rb') as f:
                data = f.read()
                self._parseBinary(data)

    def getPoints(self, pared=False):
        """
        Get the points that make up the mesh.
        :param pared: use the pared down list of points
        :return: A list of points
        """
        points = self._points[:]
        if pared:
            np = NodePare()
            np.addPoints(points)
            np.parePoints()
            points = np.getParedPoints()

        return points

    def getElements(self, zero_based=True, pared=False):
        """
        Get the elements of the mesh as a list of point index list.
        :param zero_based: use zero based index of points
        :param pared: use the pared down list of points
        :return: A list of point index lists
        """
        points = self._points[:]
        elements = self._elements[:]
        offset = 0
        if not zero_based:
            offset = 1

        np = None
        if pared:
            np = NodePare()
            np.addPoints(points)
            np.parePoints()

        if pared or not zero_based:
            modified_elements = []
            for element in elements:
                modified_element = [index + offset if np is None else np.getParedIndex(index) + offset for index in element]
                modified_elements.append(modified_element)

            elements = modified_elements

        return elements

    def _parseASCII(self, lines):
        lines.pop(0) # Remove header line
        lines.pop() # remove endsolid
        for line in lines:
            line = line.strip()
            if line.startswith('facet'):
                node_indexes = []
            elif line.startswith('endfacet'):
                self._elements.append(node_indexes)
            elif line.startswith('vertex'):
                components = line.split(' ')
                pt = [float(components[1]), float(components[2]), float(components[3])]
                node_indexes.append(len(self._points))
                self._points.append(pt)

    def _parseBinary(self, data):
        start_byte = 0
        end_byte = 80
        _ = data[start_byte:end_byte] # header data
        start_byte = end_byte
        end_byte += 4
        facet_count = struct.unpack('I', data[start_byte:end_byte])[0]
        for _ in range(facet_count):
            start_byte = end_byte
            end_byte = start_byte + 50
            element_info = struct.unpack('ffffffffffffH', data[start_byte:end_byte])
            pt1 = [element_info[3], element_info[4], element_info[5]]
            pt1_index = len(self._points)
            self._points.append(pt1)
            pt2 = [element_info[6], element_info[7], element_info[8]]
            pt2_index = len(self._points)
            self._points.append(pt2)
            pt3 = [element_info[9], element_info[10], element_info[11]]
            pt3_index = len(self._points)
            self._points.append(pt3)

            self._elements.append([pt1_index, pt2_index, pt3_index])

class _RootState(object):
    pass

def _is_ascii_stl(filename):
    is_ascii = False
    with open(filename, 'rb') as f:
        first_bytes = f.read(80)
        if 'solid' in first_bytes.decode("utf-8"):
            is_ascii = True

    return is_ascii

<commit_msg>Clear the contents of the points and elements arrays before parsing a new file.<commit_after>'''
Created on Oct 21, 2015

@author: hsorby
'''
from zipfile import ZipFile, is_zipfile

import struct
from meshparser.nodepare.pare import NodePare

class STLParser(object):
    '''
    classdocs
    '''

    def __init__(self):
        '''
        Constructor
        '''
        self._clear()

    def _clear(self):
        self._points = []
        self._elements = []

    def parse(self, filename):

        self._clear()
        if is_zipfile(filename):
            with ZipFile(filename) as stlzip:
                zipinfolist = stlzip.infolist()
                if len(zipinfolist) != 1:
                    print('More than one file in archive ... exiting')
                    return
                zipinfo = zipinfolist[0]
                data = stlzip.read(zipinfo.filename)
                if 'solid' in data[:80].decode("utf-8"):
                    lines = data.decode("utf-8").split('\n')
                    self._parseASCII(lines)
                else:
                    self._parseBinary(data)
        elif _is_ascii_stl(filename):
            with open(filename) as f:
                lines = f.readlines()
                self._parseASCII(lines)
        else:
            with open(filename, 'rb') as f:
                data = f.read()
                self._parseBinary(data)

    def getPoints(self, pared=False):
        """
        Get the points that make up the mesh.
        :param pared: use the pared down list of points
        :return: A list of points
        """
        points = self._points[:]
        if pared:
            np = NodePare()
            np.addPoints(points)
            np.parePoints()
            points = np.getParedPoints()

        return points

    def getElements(self, zero_based=True, pared=False):
        """
        Get the elements of the mesh as a list of point index list.
        :param zero_based: use zero based index of points
        :param pared: use the pared down list of points
        :return: A list of point index lists
        """
        points = self._points[:]
        elements = self._elements[:]
        offset = 0
        if not zero_based:
            offset = 1

        np = None
        if pared:
            np = NodePare()
            np.addPoints(points)
            np.parePoints()

        if pared or not zero_based:
            modified_elements = []
            for element in elements:
                modified_element = [index + offset if np is None else np.getParedIndex(index) + offset for index in element]
                modified_elements.append(modified_element)

            elements = modified_elements

        return elements

    def _parseASCII(self, lines):
        lines.pop(0) # Remove header line
        lines.pop() # remove endsolid
        for line in lines:
            line = line.strip()
            if line.startswith('facet'):
                node_indexes = []
            elif line.startswith('endfacet'):
                self._elements.append(node_indexes)
            elif line.startswith('vertex'):
                components = line.split(' ')
                pt = [float(components[1]), float(components[2]), float(components[3])]
                node_indexes.append(len(self._points))
                self._points.append(pt)

    def _parseBinary(self, data):
        start_byte = 0
        end_byte = 80
        _ = data[start_byte:end_byte] # header data
        start_byte = end_byte
        end_byte += 4
        facet_count = struct.unpack('I', data[start_byte:end_byte])[0]
        for _ in range(facet_count):
            start_byte = end_byte
            end_byte = start_byte + 50
            element_info = struct.unpack('ffffffffffffH', data[start_byte:end_byte])
            pt1 = [element_info[3], element_info[4], element_info[5]]
            pt1_index = len(self._points)
            self._points.append(pt1)
            pt2 = [element_info[6], element_info[7], element_info[8]]
            pt2_index = len(self._points)
            self._points.append(pt2)
            pt3 = [element_info[9], element_info[10], element_info[11]]
            pt3_index = len(self._points)
            self._points.append(pt3)

            self._elements.append([pt1_index, pt2_index, pt3_index])

class _RootState(object):
    pass

def _is_ascii_stl(filename):
    is_ascii = False
    with open(filename, 'rb') as f:
        first_bytes = f.read(80)
        if 'solid' in first_bytes.decode("utf-8"):
            is_ascii = True

    return is_ascii

<|endoftext|>


<commit_before># Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models

class StockRequestOrder(models.Model):
    _inherit = 'stock.request.order'

    @api.model
    def _get_default_picking_type(self):
        return self.env['stock.picking.type'].search([
            ('code', '=', 'stock_request_order'),
            ('warehouse_id.company_id', 'in',
             [self.env.context.get('company_id', self.env.user.company_id.id),
              False])],
            limit=1).id

    picking_type_id = fields.Many2one(
        'stock.picking.type', 'Operation Type',
        default=_get_default_picking_type, required=True)

    @api.onchange('warehouse_id')
    def onchange_warehouse_picking_id(self):
        if self.warehouse_id:
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', self.warehouse_id.id)], limit=1)
            if picking_type_id:
                    self._origin.write({'picking_type_id': picking_type_id.id})
<commit_msg>[IMP] Set Picking Type in Create<commit_after># Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models

class StockRequestOrder(models.Model):
    _inherit = 'stock.request.order'

    @api.model
    def _get_default_picking_type(self):
        return self.env['stock.picking.type'].search([
            ('code', '=', 'stock_request_order'),
            ('warehouse_id.company_id', 'in',
             [self.env.context.get('company_id', self.env.user.company_id.id),
              False])],
            limit=1).id

    picking_type_id = fields.Many2one(
        'stock.picking.type', 'Operation Type',
        default=_get_default_picking_type, required=True)

    @api.onchange('warehouse_id')
    def onchange_warehouse_picking_id(self):
        if self.warehouse_id:
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', self.warehouse_id.id)], limit=1)
            if picking_type_id:
                    self._origin.write({'picking_type_id': picking_type_id.id})

    @api.model
    def create(self, vals):
        if vals.get('warehouse_id', False):
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', vals['warehouse_id'])], limit=1)
            if picking_type_id:
                vals.update({'picking_type_id': picking_type_id.id})
        return super().create(vals)
<|endoftext|>


<commit_before>from .Client import Client
from .Base import Base
from .Face import Face
from .Person import Person
from .PersonGroup import PersonGroup
from .Vision import Vision
<commit_msg>Moving to __all__ for pep8/pyflakes cleanup<commit_after>__all__ = [ 'Base', 'Client', 'Face', 'Person', 'PersonGroup', 'Vision']
<|endoftext|>


<commit_before>import io
from typing import BinaryIO, ClassVar

from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer

class OboSerializer(FastoboSerializer, BaseSerializer):

    format = "obo"

    def dump(self, file):
        writer = io.TextIOWrapper(file)
        try:
            # dump the header
            if self.ont.metadata:
                header = self._to_header_frame(self.ont.metadata)
                file.write(str(header).encode("utf-8"))
                if self.ont._terms or self.ont._relationships:
                    file.write(b"\n")
            # dump terms
            if self.ont._terms:
                for i, (id, data) in enumerate(self.ont._terms.items()):
                    frame = self._to_term_frame(Term(self.ont, data))
                    file.write(str(frame).encode("utf-8"))
                    if i < len(self.ont._terms) - 1 or self.ont._relationships:
                        file.write(b"\n")
            # dump typedefs
            if self.ont._relationships:
                for i, (id, data) in enumerate(self.ont._relationships.items()):
                    frame = self._to_typedef_frame(Relationship(self.ont, data))
                    file.write(str(frame).encode("utf-8"))
                    if i < len(self.ont._relationships) - 1:
                        file.write(b"\n")
        finally:
            writer.detach()
<commit_msg>Fix OBO serializer assuming `Ontology._terms` is properly ordered<commit_after>import io
from typing import BinaryIO, ClassVar

from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer

class OboSerializer(FastoboSerializer, BaseSerializer):

    format = "obo"

    def dump(self, file):
        writer = io.TextIOWrapper(file)
        try:
            # dump the header
            if self.ont.metadata:
                header = self._to_header_frame(self.ont.metadata)
                file.write(str(header).encode("utf-8"))
                if self.ont._terms or self.ont._relationships:
                    file.write(b"\n")
            # dump terms
            if self.ont._terms:
                for i, id in enumerate(sorted(self.ont._terms)):
                    data = self.ont._terms[id]
                    frame = self._to_term_frame(Term(self.ont, data))
                    file.write(str(frame).encode("utf-8"))
                    if i < len(self.ont._terms) - 1 or self.ont._relationships:
                        file.write(b"\n")
            # dump typedefs
            if self.ont._relationships:
                for i, id in enumerate(sorted(self.ont._relationships)):
                    data = self.ont._relationships[id]
                    frame = self._to_typedef_frame(Relationship(self.ont, data))
                    file.write(str(frame).encode("utf-8"))
                    if i < len(self.ont._relationships) - 1:
                        file.write(b"\n")
        finally:
            writer.detach()
<|endoftext|>


<commit_before>import prophy
import pytest

@pytest.fixture(scope = 'session')
def Enumeration():
    class Enumeration(prophy.enum):
        __metaclass__ = prophy.enum_generator
        _enumerators = [("Enumeration_One", 1),
                        ("Enumeration_Two", 2),
                        ("Enumeration_Three", 3)]
    return Enumeration

@pytest.fixture(scope = 'session')
def Enumeration8():
    class Enumeration8(prophy.enum8):
        __metaclass__ = prophy.enum_generator
        _enumerators = [("Enumeration_One", 1),
                        ("Enumeration_Two", 2),
                        ("Enumeration_Three", 3)]
    return Enumeration8

@pytest.fixture(scope = 'session')
def Enum(Enumeration):
    class Enum(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("value", Enumeration)]
    return Enum

@pytest.fixture(scope = 'session')
def Enum8(Enumeration8):
    class Enum8(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("value", Enumeration8)]
    return Enum8

@pytest.fixture(scope = 'session')
def EnumFixedArray(Enumeration):
    class EnumFixedArray(prophy.struct_packed):
         __metaclass__ = prophy.struct_generator
         _descriptor = [("value", prophy.array(Enumeration, size = 2))]
    return EnumFixedArray

@pytest.fixture(scope = 'session')
def EnumBoundArray(Enumeration):
    class EnumBoundArray(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("value_len", prophy.u32),
                       ("value", prophy.array(Enumeration, bound = "value_len"))]
    return EnumBoundArray

def test_enum_assignment(Enum):
    x = Enum()
    assert x.value == 1
    x.value = "Enumeration_Two"
    assert x.value == 2
    x.value = 3
    assert x.value == 3

    with pytest.raises(prophy.ProphyError):
        x.value = "Enumeration_Four"
    with pytest.raises(prophy.ProphyError):
        x.value = 4

    y = Enum()
    y.copy_from(x)
    assert y.value == 3

def test_enum_encoding(Enum):
    x = Enum()
    x.value = 2
    assert str(x) == "value: Enumeration_Two\n"

    assert x.encode(">") == "\x00\x00\x00\x02"

    x.decode("\x00\x00\x00\x03", ">")
    assert x.value == 3

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x00\x00\x00\x09", ">")
    assert 'unknown enumerator value' in e.value.message

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x00\x00\x01", ">")
    assert 'too few bytes to decode integer' in e.value.message

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x00\x00\x00\x01\x01", ">")
    assert 'not all bytes read' in e.value.message

def test_enum_exceptions():
    with pytest.raises(Exception):
        class NoEnumerators(prophy.enum):
            __metaclass__ = prophy.enum_generator
    with pytest.raises(Exception):
        class NamesOverlapping(prophy.enum):
            __metaclass__ = prophy.enum_generator
            _enumerators = [("NamesOverlapping_Overlap", 1),
                            ("NamesOverlapping_Overlap", 2)]
    with pytest.raises(Exception):
        class ValueOutOfBounds(prophy.enum):
            __metaclass__ = prophy.enum_generator
            _enumerators = [("OutOfBounds", 0xFFFFFFFF + 1)]

def test_enum8_encoding(Enum8):
    x = Enum8()
    x.value = 2
    assert str(x) == "value: Enumeration_Two\n"

    x.value = 2
    assert x.encode(">") == "\x02"

    x.decode("\x02", ">")
    assert x.value == 2

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x09", ">")
    assert 'unknown enumerator value' in e.value.message

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("", ">")
    assert 'too few bytes to decode integer' in e.value.message

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x01\x01", ">")
    assert 'not all bytes read' in e.value.message

def test_enum_with_overlapping_values():
    class ValuesOverlapping(prophy.enum8):
        __metaclass__ = prophy.enum_generator
        _enumerators = [("ValuesOverlapping_First", 42),
                        ("ValuesOverlapping_Second", 42)]
    class X(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("x", ValuesOverlapping)]

    x = X()
    assert 42 == x.x
    assert "x: ValuesOverlapping_Second\n" == str(x)

    x.x = "ValuesOverlapping_Second"
    assert 42 == x.x
    x.x = "ValuesOverlapping_First"
    assert 42 == x.x
    assert "x: ValuesOverlapping_Second\n" == str(x)

def test_enum_fixed_array_assignment(EnumFixedArray):
    x = EnumFixedArray()
    assert x.value == [1, 1]
    assert x.value[0] == 1
    assert x.value[1] == 1
    x.value[0] = 2
    x.value[1] = "Enumeration_Two"
    assert x.value == [2, 2]

    y = EnumFixedArray()
    y.value[:] = [3, 3]
    y.copy_from(x)
    assert y.value == [2, 2]

def test_enum_fixed_array_encoding(EnumFixedArray):
    x = EnumFixedArray()
    x.value[:] = [2, 2]
    assert str(x) == ("value: Enumeration_Two\n"
                      "value: Enumeration_Two\n")

    x.value[:] = [2, 2]
    assert x.encode(">") == "\x00\x00\x00\x02\x00\x00\x00\x02"

    x.decode("\x00\x00\x00\x02\x00\x00\x00\x02", ">")
    assert x.value[0] == 2
    assert x.value[1] == 2

def test_enum_bound_array_assignment(EnumBoundArray):
    x = EnumBoundArray()
    assert x.value == []
    x.value[:] = [1, "Enumeration_One"]
    assert x.value == [1, 1]
    assert x.value[0] == 1
    assert x.value[1] == 1
    x.value[0] = 2
    x.value[1] = "Enumeration_Two"
    assert x.value == [2, 2]

def test_enum_bound_array_encoding(EnumBoundArray):
    x = EnumBoundArray()
    x.value[:] = [2, 2]
    assert str(x) == ("value: Enumeration_Two\n"
                      "value: Enumeration_Two\n")

    x.value[:] = [2, 2]
    assert x.encode(">") == "\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x02"

    x.decode("\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x02", ">")
    assert x.value[0] == 2
    assert x.value[1] == 2

def test_enum_with_0xFFFFFFFF_value():
    class Enum(prophy.enum):
        __metaclass__ = prophy.enum_generator
        _enumerators = [('Enum_Infinity', 0xFFFFFFFF)]
    class Enclosing(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("value", Enum)]

    assert Enclosing().value == 0xFFFFFFFF

def test_access_to_members():
    class E(prophy.enum):
        __metaclass__ = prophy.enum_generator
        _enumerators = [("E_1", 1),
                        ("E_2", 2),
                        ("E_3", 3)]

    x = E()

    with pytest.raises(Exception) as e:
        x.not_available = 102
    assert "has no attribute" in e.value.message

    class S(prophy.struct):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("a", E),
                       ("b", prophy.array(E))]

    y = S()
    y.b[:] = [1, 1]
    y.b[1] = 1
    y.b.append(1)

    assert y.a.__class__ == E
    assert y.b[0].__class__ == E
    assert y.b[1].__class__ == E
    assert y.b[2].__class__ == E

    assert y.a.name == "E_1"
    assert y.a.number == 1

    y.decode('\x00\x00\x00\x01\x00\x00\x00\x01', '>')
    assert y.a.__class__ == E
    assert y.b[0].__class__ == E

    class U(prophy.union):
        __metaclass__ = prophy.union_generator
        _descriptor = [("a", E, 0)]

    z = U()

    assert z.a.__class__ == E
<commit_msg>test rename<commit_after>import prophy
import pytest

@pytest.fixture(scope = 'session')
def Enumeration():
    class Enumeration(prophy.enum):
        __metaclass__ = prophy.enum_generator
        _enumerators = [("Enumeration_One", 1),
                        ("Enumeration_Two", 2),
                        ("Enumeration_Three", 3)]
    return Enumeration

@pytest.fixture(scope = 'session')
def Enumeration8():
    class Enumeration8(prophy.enum8):
        __metaclass__ = prophy.enum_generator
        _enumerators = [("Enumeration_One", 1),
                        ("Enumeration_Two", 2),
                        ("Enumeration_Three", 3)]
    return Enumeration8

@pytest.fixture(scope = 'session')
def Enum(Enumeration):
    class Enum(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("value", Enumeration)]
    return Enum

@pytest.fixture(scope = 'session')
def Enum8(Enumeration8):
    class Enum8(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("value", Enumeration8)]
    return Enum8

@pytest.fixture(scope = 'session')
def EnumFixedArray(Enumeration):
    class EnumFixedArray(prophy.struct_packed):
         __metaclass__ = prophy.struct_generator
         _descriptor = [("value", prophy.array(Enumeration, size = 2))]
    return EnumFixedArray

@pytest.fixture(scope = 'session')
def EnumBoundArray(Enumeration):
    class EnumBoundArray(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("value_len", prophy.u32),
                       ("value", prophy.array(Enumeration, bound = "value_len"))]
    return EnumBoundArray

def test_enum_assignment(Enum):
    x = Enum()
    assert x.value == 1
    x.value = "Enumeration_Two"
    assert x.value == 2
    x.value = 3
    assert x.value == 3

    with pytest.raises(prophy.ProphyError):
        x.value = "Enumeration_Four"
    with pytest.raises(prophy.ProphyError):
        x.value = 4

    y = Enum()
    y.copy_from(x)
    assert y.value == 3

def test_enum_encoding(Enum):
    x = Enum()
    x.value = 2
    assert str(x) == "value: Enumeration_Two\n"

    assert x.encode(">") == "\x00\x00\x00\x02"

    x.decode("\x00\x00\x00\x03", ">")
    assert x.value == 3

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x00\x00\x00\x09", ">")
    assert 'unknown enumerator value' in e.value.message

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x00\x00\x01", ">")
    assert 'too few bytes to decode integer' in e.value.message

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x00\x00\x00\x01\x01", ">")
    assert 'not all bytes read' in e.value.message

def test_enum_exceptions():
    with pytest.raises(Exception):
        class NoEnumerators(prophy.enum):
            __metaclass__ = prophy.enum_generator
    with pytest.raises(Exception):
        class NamesOverlapping(prophy.enum):
            __metaclass__ = prophy.enum_generator
            _enumerators = [("NamesOverlapping_Overlap", 1),
                            ("NamesOverlapping_Overlap", 2)]
    with pytest.raises(Exception):
        class ValueOutOfBounds(prophy.enum):
            __metaclass__ = prophy.enum_generator
            _enumerators = [("OutOfBounds", 0xFFFFFFFF + 1)]

def test_enum8_encoding(Enum8):
    x = Enum8()
    x.value = 2
    assert str(x) == "value: Enumeration_Two\n"

    x.value = 2
    assert x.encode(">") == "\x02"

    x.decode("\x02", ">")
    assert x.value == 2

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x09", ">")
    assert 'unknown enumerator value' in e.value.message

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("", ">")
    assert 'too few bytes to decode integer' in e.value.message

    with pytest.raises(prophy.ProphyError) as e:
        x.decode("\x01\x01", ">")
    assert 'not all bytes read' in e.value.message

def test_enum_with_overlapping_values():
    class ValuesOverlapping(prophy.enum8):
        __metaclass__ = prophy.enum_generator
        _enumerators = [("ValuesOverlapping_First", 42),
                        ("ValuesOverlapping_Second", 42)]
    class X(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("x", ValuesOverlapping)]

    x = X()
    assert 42 == x.x
    assert "x: ValuesOverlapping_Second\n" == str(x)

    x.x = "ValuesOverlapping_Second"
    assert 42 == x.x
    x.x = "ValuesOverlapping_First"
    assert 42 == x.x
    assert "x: ValuesOverlapping_Second\n" == str(x)

def test_enum_fixed_array_assignment(EnumFixedArray):
    x = EnumFixedArray()
    assert x.value == [1, 1]
    assert x.value[0] == 1
    assert x.value[1] == 1
    x.value[0] = 2
    x.value[1] = "Enumeration_Two"
    assert x.value == [2, 2]

    y = EnumFixedArray()
    y.value[:] = [3, 3]
    y.copy_from(x)
    assert y.value == [2, 2]

def test_enum_fixed_array_encoding(EnumFixedArray):
    x = EnumFixedArray()
    x.value[:] = [2, 2]
    assert str(x) == ("value: Enumeration_Two\n"
                      "value: Enumeration_Two\n")

    x.value[:] = [2, 2]
    assert x.encode(">") == "\x00\x00\x00\x02\x00\x00\x00\x02"

    x.decode("\x00\x00\x00\x02\x00\x00\x00\x02", ">")
    assert x.value[0] == 2
    assert x.value[1] == 2

def test_enum_bound_array_assignment(EnumBoundArray):
    x = EnumBoundArray()
    assert x.value == []
    x.value[:] = [1, "Enumeration_One"]
    assert x.value == [1, 1]
    assert x.value[0] == 1
    assert x.value[1] == 1
    x.value[0] = 2
    x.value[1] = "Enumeration_Two"
    assert x.value == [2, 2]

def test_enum_bound_array_encoding(EnumBoundArray):
    x = EnumBoundArray()
    x.value[:] = [2, 2]
    assert str(x) == ("value: Enumeration_Two\n"
                      "value: Enumeration_Two\n")

    x.value[:] = [2, 2]
    assert x.encode(">") == "\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x02"

    x.decode("\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x02", ">")
    assert x.value[0] == 2
    assert x.value[1] == 2

def test_enum_with_0xFFFFFFFF_value():
    class Enum(prophy.enum):
        __metaclass__ = prophy.enum_generator
        _enumerators = [('Enum_Infinity', 0xFFFFFFFF)]
    class Enclosing(prophy.struct_packed):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("value", Enum)]

    assert Enclosing().value == 0xFFFFFFFF

def test_enum_access_to_members():
    class E(prophy.enum):
        __metaclass__ = prophy.enum_generator
        _enumerators = [("E_1", 1),
                        ("E_2", 2),
                        ("E_3", 3)]

    x = E()

    with pytest.raises(Exception) as e:
        x.not_available = 102
    assert "has no attribute" in e.value.message

    class S(prophy.struct):
        __metaclass__ = prophy.struct_generator
        _descriptor = [("a", E),
                       ("b", prophy.array(E))]

    y = S()
    y.b[:] = [1, 1]
    y.b[1] = 1
    y.b.append(1)

    assert y.a.__class__ == E
    assert y.b[0].__class__ == E
    assert y.b[1].__class__ == E
    assert y.b[2].__class__ == E

    assert y.a.name == "E_1"
    assert y.a.number == 1

    y.decode('\x00\x00\x00\x01\x00\x00\x00\x01', '>')
    assert y.a.__class__ == E
    assert y.b[0].__class__ == E

    class U(prophy.union):
        __metaclass__ = prophy.union_generator
        _descriptor = [("a", E, 0)]

    z = U()

    assert z.a.__class__ == E
<|endoftext|>


<commit_before># Copyright 2016 NEC Corporation.  All rights reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import copy

from tempest.lib.api_schema.response.compute.v2_16 import servers \
    as serversv216
from tempest.lib.api_schema.response.compute.v2_9 import servers as serversv29

list_servers = copy.deepcopy(serversv216.list_servers)

get_server = copy.deepcopy(serversv216.get_server)
get_server['response_body']['properties']['server'][
    'properties'].update({'description': {'type': ['string', 'null']}})
get_server['response_body']['properties']['server'][
    'required'].append('description')

list_servers_detail = copy.deepcopy(serversv216.list_servers_detail)
list_servers_detail['response_body']['properties']['servers']['items'][
    'properties'].update({'description': {'type': ['string', 'null']}})
list_servers_detail['response_body']['properties']['servers']['items'][
    'required'].append('description')

update_server = copy.deepcopy(serversv29.update_server)
update_server['response_body']['properties']['server'][
    'properties'].update({'description': {'type': ['string', 'null']}})
update_server['response_body']['properties']['server'][
    'required'].append('description')

rebuild_server = copy.deepcopy(serversv29.rebuild_server)
rebuild_server['response_body']['properties']['server'][
    'properties'].update({'description': {'type': ['string', 'null']}})
rebuild_server['response_body']['properties']['server'][
    'required'].append('description')

rebuild_server_with_admin_pass = copy.deepcopy(
    serversv29.rebuild_server_with_admin_pass)
rebuild_server_with_admin_pass['response_body']['properties']['server'][
    'properties'].update({'description': {'type': ['string', 'null']}})
rebuild_server_with_admin_pass['response_body']['properties']['server'][
    'required'].append('description')
<commit_msg>Add server schema for microversion 2.19<commit_after># Copyright 2016 NEC Corporation.  All rights reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import copy

from tempest.lib.api_schema.response.compute.v2_16 import servers \
    as serversv216

get_server = copy.deepcopy(serversv216.get_server)
get_server['response_body']['properties']['server'][
    'properties'].update({'description': {'type': ['string', 'null']}})
get_server['response_body']['properties']['server'][
    'required'].append('description')

list_servers_detail = copy.deepcopy(serversv216.list_servers_detail)
list_servers_detail['response_body']['properties']['servers']['items'][
    'properties'].update({'description': {'type': ['string', 'null']}})
list_servers_detail['response_body']['properties']['servers']['items'][
    'required'].append('description')

update_server = copy.deepcopy(serversv216.update_server)
update_server['response_body']['properties']['server'][
    'properties'].update({'description': {'type': ['string', 'null']}})
update_server['response_body']['properties']['server'][
    'required'].append('description')

rebuild_server = copy.deepcopy(serversv216.rebuild_server)
rebuild_server['response_body']['properties']['server'][
    'properties'].update({'description': {'type': ['string', 'null']}})
rebuild_server['response_body']['properties']['server'][
    'required'].append('description')

rebuild_server_with_admin_pass = copy.deepcopy(
    serversv216.rebuild_server_with_admin_pass)
rebuild_server_with_admin_pass['response_body']['properties']['server'][
    'properties'].update({'description': {'type': ['string', 'null']}})
rebuild_server_with_admin_pass['response_body']['properties']['server'][
    'required'].append('description')

# NOTE(gmann): Below are the unchanged schema in this microversion. We need
# to keep this schema in this file to have the generic way to select the
# right schema based on self.schema_versions_info mapping in service client.
# ****** Schemas unchanged since microversion 2.16 ******
list_servers = copy.deepcopy(serversv216.list_servers)
show_server_diagnostics = copy.deepcopy(serversv216.show_server_diagnostics)
get_remote_consoles = copy.deepcopy(serversv216.get_remote_consoles)
<|endoftext|>


<commit_before>"""
Admin role page
"""

from flask import (Blueprint, render_template, request, flash,
        redirect, url_for)
from flask.ext.login import current_user

from noink import mainApp, _
from noink.state import get_state
from noink.user_db import UserDB
from noink.role_db import RoleDB
from noink.exceptions import GroupNotFound, DuplicateGroup

from noink.blueprints.admin_user import _not_auth

admin_role = Blueprint('admin_role', __name__)

@admin_role.route("/admin/role", defaults={'rid':None}, methods=['GET', 'POST'])
@admin_role.route("/admin/role/<int:rid>", methods=['GET', 'POST'])
def admin_role_page(rid):
    """
    Renders the role admin page
    """
    pass
<commit_msg>start fleshing out role admin<commit_after>"""
Admin role page
"""

from flask import (Blueprint, render_template, request, flash,
        redirect, url_for)
from flask.ext.login import current_user

from noink import mainApp, _
from noink.state import get_state
from noink.user_db import UserDB
from noink.role_db import RoleDB

from noink.blueprints.admin_user import _not_auth

admin_role = Blueprint('admin_role', __name__)

@admin_role.route("/admin/role", defaults={'rid':None}, methods=['GET', 'POST'])
@admin_role.route("/admin/role/<int:rid>", methods=['GET', 'POST'])
def admin_role_page(rid):
    """
    Renders the role admin page
    """
    user_db = UserDB()
    role_db = RoleDB()

    if current_user.is_authenticated() and current_user.is_active():
        is_admin = user_db.in_group(current_user, mainApp.config['ADMIN_GROUP'])
        all_activities = set()
        for m in role_db.get_roles(current_user):
            acts = role_db.get_activities(m.role_id)
            for act in acts:
                if acts[act]:
                    all_activities.add(act)

        can_view_roles = 'view_roles' in all_activities
        can_edit_roles = 'edit_roles' in all_activities

        if is_admin or can_view_roles:
            if rid is None:
                pass
            else:
                pass
        else:
            return _not_auth()
    else:
        return _not_auth()
<|endoftext|>


<commit_before># Copyright (C) 2014 Rémi Bèges
# For conditions of distribution and use, see copyright notice in the LICENSE file

from API.Protocol import Protocol
from API.crc import *

class DistantIO():
    def __init__(self,on_tx_frame_callback):
        self.variables = []
        self.on_tx_frame_callback = on_tx_frame_callback

    # Returns the get-descriptors frame
    def get_descriptors_frame(self):
        packet = bytearray(14)
        # Build data frame
        packet[0] = 0x02
        packet[4] = 0xFF
        packet[11] = 0xFF
        # Compute CRC
        crc = crc16(packet[:-2]).to_bytes(2,byteorder='big')
        packet[12] = crc[0]
        packet[13] = crc[1]
        return packet

    def write_variable_frame(self, cmd_id,variable_id,data):
        packet = bytearray(14)
        print(packet)

    def process(self,frame):
        print("RX:"+str(frame))
<commit_msg>Implementing distant io processing<commit_after># Copyright (C) 2014 Rémi Bèges
# For conditions of distribution and use, see copyright notice in the LICENSE file

from API.Protocol import Protocol
from API.crc import *
from struct import *

class DistantIO():
    def __init__(self,on_tx_frame_callback):
        self.variables = []
        self.on_tx_frame_callback = on_tx_frame_callback
        self.payload_size = 14

    # Returns the get-descriptors frame
    def get_descriptors_frame(self):
        packet = bytearray(14)
        # Build data frame
        packet[0] = 0x02
        packet[4] = 0xFF
        packet[11] = 0xFF
        # Compute CRC
        crc = crc16(packet[:-2]).to_bytes(2,byteorder='big')
        packet[12] = crc[0]
        packet[13] = crc[1]
        return packet

    def write_variable_frame(self, cmd_id,variable_id,data):
        packet = bytearray(14)
        print(packet)

    def process(self,frame):
        returned_instruction = dict()
        returned_instruction['type'] = None

        # First, check data size
        if len(frame) != self.payload_size:
            return returned_instruction

        # Second, check crc
        crc_frame = unpack('H',frame[-2:])[0]
        crc_ref = crc16(frame[:-2])

        if crc_frame != crc_ref:
            print("CRC don't match - aborting.")
            print("Frame : "+str(frame))
            print("Local crc : "+str(crc_ref))
            print("Frame crc : "+str(crc_frame))
            return returned_instruction

        # Identify command
        cmd = frame[0]

        # Alive signal
        if cmd == 0x03:
            returned_instruction['type'] = 'alive-signal'
            return returned_instruction
<|endoftext|>


<commit_before>__author__ = 'Calvin.J'

from pyallpay.setting import HASH_IV, HASH_KEY, AIO_SANDBOX_SERVICE_URL, AIO_SERVICE_URL, RETURN_URL, MERCHANT_ID, ORDER_RESULT_URL, PAYMENT_INFO_URL
import time
import datetime
import urllib
import hashlib
import logging

class AllPay():
    # If it is in sandbox mode ?
    is_sandbox = True

    def __init__(self, payment_conf, service_method='post'):
        self.url_dict = dict()

        # basic config.
        self.service_method = service_method
        self.HASH_KEY = HASH_KEY
        self.HASH_IV = HASH_IV
        self.service_url = AIO_SANDBOX_SERVICE_URL if self.is_sandbox else AIO_SERVICE_URL

        self.url_dict['MerchantID'] = MERCHANT_ID
        self.url_dict['ReturnURL'] = RETURN_URL

        self.url_dict['MerchantTradeNo'] = hashlib.sha224(str(datetime.datetime.now())).hexdigest().upper() if not ('MerchantTradeNo' in payment_conf) else payment_conf['MerchantTradeNo']
        self.url_dict['PaymentType'] = 'aio'
        self.url_dict['TotalAmount'] = 300 if not ('TotalAmount' in payment_conf) else payment_conf['TotalAmount']
        self.url_dict['TradeDesc'] = 'Default Description' if not ('TradeDesc' in payment_conf) else payment_conf['TradeDesc']
        self.url_dict['ItemName'] = 'Default Item Name' if not ('ItemName' in payment_conf) else payment_conf['ItemName']
        self.url_dict['ChoosePayment'] = 'ATM' if not ('ChoosePayment' in payment_conf) else payment_conf['ChoosePayment']
        self.url_dict['MerchantTradeDate'] = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time()))
        # self.url_dict['MerchantTradeDate'] = '2014/02/08 15:13:20'
        self.url_dict['ItemURL'] = '' if not ('ItemURL' in payment_conf) else payment_conf['ItemURL']
        self.url_dict['Remark'] = '' if not ('Remark' in payment_conf) else payment_conf['Remark']
        self.url_dict['ChooseSubPayment'] = '' if not ('ChooseSubPayment' in payment_conf) else payment_conf['ChooseSubPayment']
        self.url_dict['OrderResultURL'] = ORDER_RESULT_URL if not ('OrderResultURL' in payment_conf) else payment_conf['OrderResultURL']
        self.url_dict['ClientBackURL'] = ORDER_RESULT_URL if not ('ClientBackURL' in payment_conf) else payment_conf['ClientBackURL']

        if self.url_dict['ChoosePayment'] == 'ATM':
            self.url_dict['ExpireDate'] = '' if not ('ExpireDate' in payment_conf) else payment_conf['ExpireDate']
            self.url_dict['PaymentInfoURL'] = PAYMENT_INFO_URL if not ('PaymentInfoURL' in payment_conf) else payment_conf['PaymentInfoURL']
        elif self.url_dict['ChooseSubPayment'] == 'CVS':
            self.url_dict['Desc_1'] = '' if not ('Desc_1' in payment_conf) else payment_conf['Desc_1']
            self.url_dict['Desc_2'] = '' if not ('Desc_2' in payment_conf) else payment_conf['Desc_2']
            self.url_dict['Desc_3'] = '' if not ('Desc_3' in payment_conf) else payment_conf['Desc_3']
            self.url_dict['Desc_4'] = '' if not ('Desc_4' in payment_conf) else payment_conf['Desc_4']
            self.url_dict['PaymentInfoURL'] = PAYMENT_INFO_URL if not ('PaymentInfoURL' in payment_conf) else payment_conf['PaymentInfoURL']

    @classmethod
    def do_str_replace(cls, string):
        mapping_dict = {'-': '%2d', '_': '%5f', '.': '%2e', '!': '%21', '*': '%2a', '(': '%28', ')': '%29', '%2f': '%252f', '%3a': '%253a'}

        for key, val in mapping_dict.iteritems():
            string = string.replace(val, key)

        return string

    def check_out(self):
        sorted_dict = sorted(self.url_dict.iteritems())

        # insert the HashKey to the head of dictionary & HashIv to the end
        sorted_dict.insert(0, ('HashKey', self.HASH_KEY))
        sorted_dict.append(('HashIV', self.HASH_IV))

        result_request_str = self.do_str_replace(urllib.quote(urllib.urlencode(sorted_dict), '+').lower())

        # md5 encoding
        check_mac_value = hashlib.md5(result_request_str).hexdigest().upper()
        self.url_dict['CheckMacValue'] = check_mac_value
        return self.url_dict

    @classmethod
    def checkout_feedback(cls, post):
        """
        :param post: post is a dictionary which allPay server sent to us.
        :return:
        """
        logging.info('inside the feedback')
        returns = {}
        check_mac_value = ''
        try:
            payment_type_replace_map = {'_CVS': '', '_BARCODE': '', '_Alipay': '', '_Tenpay': '', '_CreditCard': ''}
            period_type_replace_map = {'Y': 'Year', 'M': 'Month', 'D': 'Day'}
            for key, val in post.iteritems():

                print key, val
                if key == 'CheckMacValue':
                    returns[key.lower()] = val
                    check_mac_value = val
                else:
                    if key == 'PaymentType':
                        for origin, replacement in payment_type_replace_map.iteritems():
                            val = val.replace(origin, replacement)
                        returns[key.lower()] = val
                    elif key == 'PeriodType':
                        for origin, replacement in period_type_replace_map.iteritems():
                            val = val.replace(origin, replacement)
                        returns[key.lower()] = val
                    else:
                        returns[key.lower()] = val
            sorted_returns = sorted(returns.iteritems())
            sz_confirm_mac_value = "HashKey=" + HASH_KEY

            for val in sorted_returns:
                sz_confirm_mac_value = "".join((str(sz_confirm_mac_value), "&", str(val[0]), "=", str(val[1])))

            sz_confirm_mac_value = "".join((sz_confirm_mac_value, "&HashIV=", HASH_IV))
            sz_confirm_mac_value = cls.do_str_replace(urllib.quote(sz_confirm_mac_value, '+')).lower()
            sz_confirm_mac_value = hashlib.md5(sz_confirm_mac_value).hexdigest().upper()

            logging.info('sz: %s & check: %s' % (sz_confirm_mac_value, check_mac_value))

            if sz_confirm_mac_value != check_mac_value:
                logging.info('False')
                return False
            else:
                logging.info(str(returns))
            return returns
        except:
            raise NotImplementedError

    @classmethod
    def query_payment_info(cls, merchant_trade_no):
        """
        Implementing ...
        :param merchant_trade_no:
        :return:
        """
        logging.info('== Query the info==')
        returns = {}
        logging.info(merchant_trade_no)

        return returns
<commit_msg>implement get feedback method<commit_after>__author__ = 'Calvin.J'
# -*- coding: UTF-8 -*-
from pyallpay.setting import HASH_IV, HASH_KEY, AIO_SANDBOX_SERVICE_URL, AIO_SERVICE_URL, RETURN_URL, MERCHANT_ID, ORDER_RESULT_URL, PAYMENT_INFO_URL
import time
import datetime
import urllib
import hashlib
import logging

class AllPay():
    # If it is in sandbox mode ?
    is_sandbox = True

    def __init__(self, payment_conf, service_method='post'):
        self.url_dict = dict()

        # basic config.
        self.service_method = service_method
        self.HASH_KEY = HASH_KEY
        self.HASH_IV = HASH_IV
        self.service_url = AIO_SANDBOX_SERVICE_URL if self.is_sandbox else AIO_SERVICE_URL

        self.url_dict['MerchantID'] = MERCHANT_ID
        self.url_dict['ReturnURL'] = RETURN_URL

        self.url_dict['MerchantTradeNo'] = hashlib.sha224(str(datetime.datetime.now())).hexdigest().upper() if not ('MerchantTradeNo' in payment_conf) else payment_conf['MerchantTradeNo']
        self.url_dict['PaymentType'] = 'aio'
        self.url_dict['TotalAmount'] = 300 if not ('TotalAmount' in payment_conf) else payment_conf['TotalAmount']
        self.url_dict['TradeDesc'] = 'Default Description' if not ('TradeDesc' in payment_conf) else payment_conf['TradeDesc']
        self.url_dict['ItemName'] = 'Default Item Name' if not ('ItemName' in payment_conf) else payment_conf['ItemName']
        self.url_dict['ChoosePayment'] = 'ATM' if not ('ChoosePayment' in payment_conf) else payment_conf['ChoosePayment']
        self.url_dict['MerchantTradeDate'] = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time()))
        # self.url_dict['MerchantTradeDate'] = '2014/02/08 15:13:20'
        self.url_dict['ItemURL'] = '' if not ('ItemURL' in payment_conf) else payment_conf['ItemURL']
        self.url_dict['Remark'] = '' if not ('Remark' in payment_conf) else payment_conf['Remark']
        self.url_dict['ChooseSubPayment'] = '' if not ('ChooseSubPayment' in payment_conf) else payment_conf['ChooseSubPayment']
        self.url_dict['OrderResultURL'] = ORDER_RESULT_URL if not ('OrderResultURL' in payment_conf) else payment_conf['OrderResultURL']
        self.url_dict['ClientBackURL'] = ORDER_RESULT_URL if not ('ClientBackURL' in payment_conf) else payment_conf['ClientBackURL']

        if self.url_dict['ChoosePayment'] == 'ATM':
            self.url_dict['ExpireDate'] = '' if not ('ExpireDate' in payment_conf) else payment_conf['ExpireDate']
            self.url_dict['PaymentInfoURL'] = PAYMENT_INFO_URL if not ('PaymentInfoURL' in payment_conf) else payment_conf['PaymentInfoURL']
        elif self.url_dict['ChooseSubPayment'] == 'CVS':
            self.url_dict['Desc_1'] = '' if not ('Desc_1' in payment_conf) else payment_conf['Desc_1']
            self.url_dict['Desc_2'] = '' if not ('Desc_2' in payment_conf) else payment_conf['Desc_2']
            self.url_dict['Desc_3'] = '' if not ('Desc_3' in payment_conf) else payment_conf['Desc_3']
            self.url_dict['Desc_4'] = '' if not ('Desc_4' in payment_conf) else payment_conf['Desc_4']
            self.url_dict['PaymentInfoURL'] = PAYMENT_INFO_URL if not ('PaymentInfoURL' in payment_conf) else payment_conf['PaymentInfoURL']

    @classmethod
    def do_str_replace(cls, string, type_check_out=True):
        if type_check_out:
            mapping_dict = {'-': '%2d', '_': '%5f', '.': '%2e', '!': '%21', '*': '%2a', '(': '%28', ')': '%29', '%2f': '%252f', '%3a': '%253a'}
        else:
            mapping_dict = {'-': '%2d', '_': '%5f', '.': '%2e', '!': '%21', '*': '%2a', '(': '%28', ')': '%29'}
        for key, val in mapping_dict.iteritems():
            string = string.replace(val, key)

        return string

    def check_out(self):
        sorted_dict = sorted(self.url_dict.iteritems())

        # insert the HashKey to the head of dictionary & HashIv to the end
        sorted_dict.insert(0, ('HashKey', self.HASH_KEY))
        sorted_dict.append(('HashIV', self.HASH_IV))

        result_request_str = self.do_str_replace(urllib.quote(urllib.urlencode(sorted_dict), '+').lower())

        # md5 encoding
        check_mac_value = hashlib.md5(result_request_str).hexdigest().upper()
        self.url_dict['CheckMacValue'] = check_mac_value
        return self.url_dict

    @classmethod
    def checkout_feedback(cls, post):
        """
        :param post: post is a dictionary which allPay server sent to us.
        :return:
        """
        logging.info('inside the feedback')
        returns = {}
        ar_parameter = {}
        check_mac_value = ''
        try:
            payment_type_replace_map = {'_CVS': '', '_BARCODE': '', '_Alipay': '', '_Tenpay': '', '_CreditCard': ''}
            period_type_replace_map = {'Y': 'Year', 'M': 'Month', 'D': 'Day'}
            for key, val in post.iteritems():

                print key, val
                if key == 'CheckMacValue':
                    check_mac_value = val
                else:
                    ar_parameter[key.lower()] = val
                    if key == 'PaymentType':
                        for origin, replacement in payment_type_replace_map.iteritems():
                            val = val.replace(origin, replacement)
                    elif key == 'PeriodType':
                        for origin, replacement in period_type_replace_map.iteritems():
                            val = val.replace(origin, replacement)
                    returns[key] = val

            sorted_returns = sorted(ar_parameter.iteritems())
            sz_confirm_mac_value = "HashKey=" + HASH_KEY

            for val in sorted_returns:
                sz_confirm_mac_value = "".join((str(sz_confirm_mac_value), "&", str(val[0]), "=", str(val[1])))

            sz_confirm_mac_value = "".join((sz_confirm_mac_value, "&HashIV=", HASH_IV))

            logging.info(sz_confirm_mac_value)

            sz_confirm_mac_value = cls.do_str_replace((urllib.quote_plus(sz_confirm_mac_value)).lower(), False)

            logging.info("".join(("==== SZ_CONFIRM_VALUE ====\n", sz_confirm_mac_value)))

            sz_confirm_mac_value = hashlib.md5(sz_confirm_mac_value).hexdigest().upper()

            logging.info('sz-value: %s & checkvalue: %s' % (sz_confirm_mac_value, check_mac_value))

            if sz_confirm_mac_value != check_mac_value:
                return False
            else:
                return returns
        except:
            raise NotImplementedError

    @classmethod
    def query_payment_info(cls, merchant_trade_no):
        """
        Implementing ...
        :param merchant_trade_no:
        :return:
        """
        logging.info('== Query the info==')
        returns = {}
        logging.info(merchant_trade_no)

        return returns<|endoftext|>