# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
import sys
total=0
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_ResistorLab(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
    def setupUi(self, ResistorLab):
        ResistorLab.setObjectName(_fromUtf8("ResistorLab"))
        ResistorLab.resize(384, 424)
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
        brush = QtGui.QBrush(QtGui.QColor(170, 170, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 191))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
        brush = QtGui.QBrush(QtGui.QColor(212, 212, 159))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
        brush = QtGui.QBrush(QtGui.QColor(85, 85, 63))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
        brush = QtGui.QBrush(QtGui.QColor(113, 113, 84))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(170, 170, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
        brush = QtGui.QBrush(QtGui.QColor(212, 212, 191))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
        brush = QtGui.QBrush(QtGui.QColor(170, 170, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 191))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
        brush = QtGui.QBrush(QtGui.QColor(212, 212, 159))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
        brush = QtGui.QBrush(QtGui.QColor(85, 85, 63))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
        brush = QtGui.QBrush(QtGui.QColor(113, 113, 84))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(170, 170, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
        brush = QtGui.QBrush(QtGui.QColor(212, 212, 191))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
        brush = QtGui.QBrush(QtGui.QColor(85, 85, 63))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
        brush = QtGui.QBrush(QtGui.QColor(170, 170, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 191))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
        brush = QtGui.QBrush(QtGui.QColor(212, 212, 159))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
        brush = QtGui.QBrush(QtGui.QColor(85, 85, 63))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
        brush = QtGui.QBrush(QtGui.QColor(113, 113, 84))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
        brush = QtGui.QBrush(QtGui.QColor(85, 85, 63))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
        brush = QtGui.QBrush(QtGui.QColor(85, 85, 63))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
        brush = QtGui.QBrush(QtGui.QColor(170, 170, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(170, 170, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
        brush = QtGui.QBrush(QtGui.QColor(170, 170, 127))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
        ResistorLab.setPalette(palette)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("MS UI Gothic"))
        ResistorLab.setFont(font)
        self.ThirdColor5 = QtGui.QComboBox(ResistorLab)
        self.ThirdColor5.currentIndexChanged.connect(self.Total5)
        self.ThirdColor5.setGeometry(QtCore.QRect(260, 100, 69, 22))
        self.ThirdColor5.setObjectName(_fromUtf8("ThirdColor5"))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.ThirdColor5.addItem(_fromUtf8(""))
        self.FourthColor5 = QtGui.QComboBox(ResistorLab)
        self.FourthColor5.currentIndexChanged.connect(self.Total5)
        self.FourthColor5.setGeometry(QtCore.QRect(100, 130, 69, 22))
        self.FourthColor5.setObjectName(_fromUtf8("FourthColor5"))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.FourthColor5.addItem(_fromUtf8(""))
        self.Cores4 = QtGui.QLabel(ResistorLab)
        self.Cores4.setGeometry(QtCore.QRect(150, 190, 181, 61))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Levenim MT"))
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.Cores4.setFont(font)
        self.Cores4.setTextFormat(QtCore.Qt.PlainText)
        self.Cores4.setObjectName(_fromUtf8("Cores4"))
        self.Cores5 = QtGui.QLabel(ResistorLab)
        self.Cores5.setGeometry(QtCore.QRect(140, 30, 241, 61))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Eras Demi ITC"))
        font.setPointSize(14)
        font.setBold(True)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(75)
        self.Cores5.setFont(font)
        self.Cores5.setObjectName(_fromUtf8("Cores5"))
        self.FirstColor4 = QtGui.QComboBox(ResistorLab)
        self.FirstColor4.currentIndexChanged.connect(self.Total4)
        self.FirstColor4.setGeometry(QtCore.QRect(120, 240, 69, 22))
        self.FirstColor4.setObjectName(_fromUtf8("FirstColor4"))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.FirstColor4.addItem(_fromUtf8(""))
        self.SecondColor4 = QtGui.QComboBox(ResistorLab)
        self.SecondColor4.currentIndexChanged.connect(self.Total4)
        self.SecondColor4.setGeometry(QtCore.QRect(200, 240, 69, 22))
        self.SecondColor4.setObjectName(_fromUtf8("SecondColor4"))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.SecondColor4.addItem(_fromUtf8(""))
        self.Titulo = QtGui.QLabel(ResistorLab)
        self.Titulo.setGeometry(QtCore.QRect(100, 0, 201, 51))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("KaiTi"))
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.Titulo.setFont(font)
        self.Titulo.setObjectName(_fromUtf8("Titulo"))
        self.ThirdColor4 = QtGui.QComboBox(ResistorLab)
        self.ThirdColor4.currentIndexChanged.connect(self.Total4)
        self.ThirdColor4.setGeometry(QtCore.QRect(110, 280, 69, 22))
        self.ThirdColor4.setObjectName(_fromUtf8("ThirdColor4"))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.ThirdColor4.addItem(_fromUtf8(""))
        self.FourthColor4 = QtGui.QComboBox(ResistorLab)
        self.FourthColor4.currentIndexChanged.connect(self.Tolerancia4)
        self.FourthColor4.setGeometry(QtCore.QRect(220, 280, 69, 22))
        self.FourthColor4.setObjectName(_fromUtf8("FourthColor4"))
        self.FourthColor4.addItem(_fromUtf8(""))
        self.FourthColor4.addItem(_fromUtf8(""))
        self.FourthColor4.addItem(_fromUtf8(""))
        self.FourthColor4.addItem(_fromUtf8(""))
        self.FourthColor4.addItem(_fromUtf8(""))
        self.FourthColor4.addItem(_fromUtf8(""))
        self.FourthColor4.addItem(_fromUtf8(""))
        self.FourthColor4.addItem(_fromUtf8(""))
        self.FirstColor5 = QtGui.QComboBox(ResistorLab)
        self.FirstColor5.currentIndexChanged.connect(self.Total5)
        self.FirstColor5.setGeometry(QtCore.QRect(60, 100, 69, 22))
        self.FirstColor5.setObjectName(_fromUtf8("FirstColor5"))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.FirstColor5.addItem(_fromUtf8(""))
        self.SecondColor5 = QtGui.QComboBox(ResistorLab)
        self.SecondColor5.currentIndexChanged.connect(self.Total5)
        self.SecondColor5.setGeometry(QtCore.QRect(160, 100, 69, 22))
        self.SecondColor5.setObjectName(_fromUtf8("SecondColor5"))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.SecondColor5.addItem(_fromUtf8(""))
        self.FifthColor5 = QtGui.QComboBox(ResistorLab)
        self.FifthColor5.currentIndexChanged.connect(self.Tolerancia5)
        self.FifthColor5.setGeometry(QtCore.QRect(220, 130, 69, 22))
        self.FifthColor5.setObjectName(_fromUtf8("FifthColor5"))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.FifthColor5.addItem(_fromUtf8(""))
        self.Result5cores = QtGui.QPushButton(ResistorLab)
        self.Result5cores.setDisabled(True)
        self.Result5cores.setGeometry(QtCore.QRect(110, 160, 75, 23))
        self.Result5cores.setCheckable(False)
        self.Result5cores.setDefault(False)
        self.Result5cores.setObjectName(_fromUtf8("Result5cores"))
        self.Result4cores = QtGui.QPushButton(ResistorLab)
        self.Result4cores.setDisabled(True)
        self.Result4cores.setGeometry(QtCore.QRect(100, 340, 75, 23))
        self.Result4cores.setAutoDefault(True)
        self.Result4cores.setDefault(False)
        self.Result4cores.setObjectName(_fromUtf8("Result4cores"))
        self.Result5cores_2 = QtGui.QPushButton(ResistorLab)
        self.Result5cores_2.setDisabled(True)
        self.Result5cores_2.setGeometry(QtCore.QRect(200, 160, 75, 23))
        self.Result5cores_2.setCheckable(False)
        self.Result5cores_2.setDefault(False)
        self.Result5cores_2.setObjectName(_fromUtf8("Result5cores_2"))
        self.Result5cores_3 = QtGui.QPushButton(ResistorLab)
        self.Result5cores_3.setDisabled(True)
        self.Result5cores_3.setGeometry(QtCore.QRect(220, 340, 75, 23))
        self.Result5cores_3.setCheckable(False)
        self.Result5cores_3.setDefault(False)
        self.Result5cores_3.setObjectName(_fromUtf8("Result5cores_3"))

        self.retranslateUi(ResistorLab)
        QtCore.QMetaObject.connectSlotsByName(ResistorLab)

    def retranslateUi(self, ResistorLab):
        ResistorLab.setWindowTitle(_translate("ResistorLab", "WizardPage", None))
        self.ThirdColor5.setItemText(0, _translate("ResistorLab", "PRETO", None))
        self.ThirdColor5.setItemText(1, _translate("ResistorLab", "MARROM", None))
        self.ThirdColor5.setItemText(2, _translate("ResistorLab", "VERMELHO", None))
        self.ThirdColor5.setItemText(3, _translate("ResistorLab", "LARANJA", None))
        self.ThirdColor5.setItemText(4, _translate("ResistorLab", "AMARELO", None))
        self.ThirdColor5.setItemText(5, _translate("ResistorLab", "VERDE", None))
        self.ThirdColor5.setItemText(6, _translate("ResistorLab", "AZUL", None))
        self.ThirdColor5.setItemText(7, _translate("ResistorLab", "VIOLETA", None))
        self.ThirdColor5.setItemText(8, _translate("ResistorLab", "CINZA", None))
        self.ThirdColor5.setItemText(9, _translate("ResistorLab", "BRANCO", None))
        self.FourthColor5.setItemText(0, _translate("ResistorLab", "PRETO", None))
        self.FourthColor5.setItemText(1, _translate("ResistorLab", "MARROM", None))
        self.FourthColor5.setItemText(2, _translate("ResistorLab", "VERMELHO", None))
        self.FourthColor5.setItemText(3, _translate("ResistorLab", "LARANJA", None))
        self.FourthColor5.setItemText(4, _translate("ResistorLab", "AMARELO", None))
        self.FourthColor5.setItemText(5, _translate("ResistorLab", "VERDE", None))
        self.FourthColor5.setItemText(6, _translate("ResistorLab", "AZUL", None))
        self.FourthColor5.setItemText(7, _translate("ResistorLab", "VIOLETA", None))
        self.FourthColor5.setItemText(8, _translate("ResistorLab", "DOURADO", None))
        self.FourthColor5.setItemText(9, _translate("ResistorLab", "PRATEADO", None))
        self.Cores4.setText(_translate("ResistorLab", "4 CORES", None))
        self.Cores5.setText(_translate("ResistorLab", "5 CORES", None))
        self.FirstColor4.setItemText(0, _translate("ResistorLab", "PRETO", None))
        self.FirstColor4.setItemText(1, _translate("ResistorLab", "MARROM", None))
        self.FirstColor4.setItemText(2, _translate("ResistorLab", "VERMELHO", None))
        self.FirstColor4.setItemText(3, _translate("ResistorLab", "LARANJA", None))
        self.FirstColor4.setItemText(4, _translate("ResistorLab", "AMARELO", None))
        self.FirstColor4.setItemText(5, _translate("ResistorLab", "VERDE", None))
        self.FirstColor4.setItemText(6, _translate("ResistorLab", "AZUL", None))
        self.FirstColor4.setItemText(7, _translate("ResistorLab", "VIOLETA", None))
        self.FirstColor4.setItemText(8, _translate("ResistorLab", "CINZA", None))
        self.FirstColor4.setItemText(9, _translate("ResistorLab", "BRANCO", None))
        self.SecondColor4.setItemText(0, _translate("ResistorLab", "PRETO", None))
        self.SecondColor4.setItemText(1, _translate("ResistorLab", "MARROM", None))
        self.SecondColor4.setItemText(2, _translate("ResistorLab", "VERMELHO", None))
        self.SecondColor4.setItemText(3, _translate("ResistorLab", "LARANJA", None))
        self.SecondColor4.setItemText(4, _translate("ResistorLab", "AMARELO", None))
        self.SecondColor4.setItemText(5, _translate("ResistorLab", "VERDE", None))
        self.SecondColor4.setItemText(6, _translate("ResistorLab", "AZUL", None))
        self.SecondColor4.setItemText(7, _translate("ResistorLab", "VIOLETA", None))
        self.SecondColor4.setItemText(8, _translate("ResistorLab", "CINZA", None))
        self.SecondColor4.setItemText(9, _translate("ResistorLab", "BRANCO", None))
        self.Titulo.setText(_translate("ResistorLab", "Resistor Lab", None))
        self.ThirdColor4.setItemText(0, _translate("ResistorLab", "PRETO", None))
        self.ThirdColor4.setItemText(1, _translate("ResistorLab", "MARROM", None))
        self.ThirdColor4.setItemText(2, _translate("ResistorLab", "VERMELHO", None))
        self.ThirdColor4.setItemText(3, _translate("ResistorLab", "LARANJA", None))
        self.ThirdColor4.setItemText(4, _translate("ResistorLab", "AMARELO", None))
        self.ThirdColor4.setItemText(5, _translate("ResistorLab", "VERDE", None))
        self.ThirdColor4.setItemText(6, _translate("ResistorLab", "AZUL", None))
        self.ThirdColor4.setItemText(7, _translate("ResistorLab", "VIOLETA", None))
        self.ThirdColor4.setItemText(8, _translate("ResistorLab", "DOURADO", None))
        self.ThirdColor4.setItemText(9, _translate("ResistorLab", "PRATEADO", None))
        self.FourthColor4.setItemText(0, _translate("ResistorLab", "MARROM", None))
        self.FourthColor4.setItemText(1, _translate("ResistorLab", "VERMELHO", None))
        self.FourthColor4.setItemText(2, _translate("ResistorLab", "VERDE", None))
        self.FourthColor4.setItemText(3, _translate("ResistorLab", "AZUL", None))
        self.FourthColor4.setItemText(4, _translate("ResistorLab", "VIOLETA", None))
        self.FourthColor4.setItemText(5, _translate("ResistorLab", "CINZA", None))
        self.FourthColor4.setItemText(6, _translate("ResistorLab", "DOURADO", None))
        self.FourthColor4.setItemText(7, _translate("ResistorLab", "PRATEADO", None))
        self.FirstColor5.setItemText(0, _translate("ResistorLab", "PRETO", None))
        self.FirstColor5.setItemText(1, _translate("ResistorLab", "MARROM", None))
        self.FirstColor5.setItemText(2, _translate("ResistorLab", "VERMELHO", None))
        self.FirstColor5.setItemText(3, _translate("ResistorLab", "LARANJA", None))
        self.FirstColor5.setItemText(4, _translate("ResistorLab", "AMARELO", None))
        self.FirstColor5.setItemText(5, _translate("ResistorLab", "VERDE", None))
        self.FirstColor5.setItemText(6, _translate("ResistorLab", "AZUL", None))
        self.FirstColor5.setItemText(7, _translate("ResistorLab", "VIOLETA", None))
        self.FirstColor5.setItemText(8, _translate("ResistorLab", "CINZA", None))
        self.FirstColor5.setItemText(9, _translate("ResistorLab", "BRANCO", None))
        self.SecondColor5.setItemText(0, _translate("ResistorLab", "PRETO", None))
        self.SecondColor5.setItemText(1, _translate("ResistorLab", "MARROM", None))
        self.SecondColor5.setItemText(2, _translate("ResistorLab", "VERMELHO", None))
        self.SecondColor5.setItemText(3, _translate("ResistorLab", "LARANJA", None))
        self.SecondColor5.setItemText(4, _translate("ResistorLab", "AMARELO", None))
        self.SecondColor5.setItemText(5, _translate("ResistorLab", "VERDE", None))
        self.SecondColor5.setItemText(6, _translate("ResistorLab", "AZUL", None))
        self.SecondColor5.setItemText(7, _translate("ResistorLab", "VIOLETA", None))
        self.SecondColor5.setItemText(8, _translate("ResistorLab", "CINZA", None))
        self.SecondColor5.setItemText(9, _translate("ResistorLab", "BRANCO", None))
        self.FifthColor5.setItemText(0, _translate("ResistorLab", "PRETO", None))
        self.FifthColor5.setItemText(1, _translate("ResistorLab", "MARROM", None))
        self.FifthColor5.setItemText(2, _translate("ResistorLab", "VERMELHO", None))
        self.FifthColor5.setItemText(3, _translate("ResistorLab", "LARANJA", None))
        self.FifthColor5.setItemText(4, _translate("ResistorLab", "AMARELO", None))
        self.FifthColor5.setItemText(5, _translate("ResistorLab", "VERDE", None))
        self.FifthColor5.setItemText(6, _translate("ResistorLab", "AZUL", None))
        self.FifthColor5.setItemText(7, _translate("ResistorLab", "VIOLETA", None))
        self.FifthColor5.setItemText(8, _translate("ResistorLab", "DOURADO", None))
        self.FifthColor5.setItemText(9, _translate("ResistorLab", "PRATEADO", None))
        self.Result5cores.setText(_translate("ResistorLab", "Valor ", None))
        self.Result4cores.setText(_translate("ResistorLab", "Valor", None))
        self.Result5cores_2.setText(_translate("ResistorLab", "Tolerância", None))
        self.Result5cores_3.setText(_translate("ResistorLab", "Tolerância", None))

    def Total4(self):
        total1=0
        cor1 = self.FirstColor4.currentIndex()
        if cor1==0:
            total1+=0
        elif cor1==1:
            total1+=10
        elif cor1==2:
            total1+=20
        elif cor1==3:
            total1+=30
        elif cor1==4:
            total1+=40
        elif cor1==5:
            total1+=50
        elif cor1==6:
            total1+=60
        elif cor1==7:
            total1+=70
        elif cor1==8:
            total1+=80
        elif cor1==9:
            total1+=90
        total2=0
        cor2 = self.SecondColor4.currentIndex()
        if cor2==0:
            total2+=0
        elif cor2==1:
            total2+=1
        elif cor2==2:
            total2+=2
        elif cor2==3:
            total2+=3
        elif cor2==4:
            total2+=4
        elif cor2==5:
            total2+=5
        elif cor2==6:
            total2+=6
        elif cor2==7:
            total2+=7
        elif cor2==8:
            total2+=8
        elif cor2==9:
            total2+=9
        multiplicador= self.ThirdColor4.currentIndex()
        if multiplicador==0:
            mult = 1
        elif multiplicador==1:
            mult=10
        elif multiplicador==2:
            mult=100
        elif multiplicador==3:
            mult=1000
        elif multiplicador==4:
            mult=10000
        elif multiplicador==5:
            mult=100000
        elif multiplicador==6:
            mult=1000000
        elif multiplicador==7:
            mult=10000000
        elif multiplicador==8:
            mult=0.1
        elif multiplicador==9:
            mult=0.01
        total = (total1 + total2)*mult
        self.Result4cores.setStyleSheet('color: black')
        self.Result4cores.setText('{0}'.format(total))

    def Tolerancia4(self):
        tolerancia = self.FourthColor4.currentIndex()
        if tolerancia==0:
            toleran=1
        elif tolerancia==1:
            toleran=2
        elif tolerancia==2:
            toleran=0.5
        elif tolerancia==3:
            toleran=0.25
        elif tolerancia==4:
            toleran=0.1
        elif tolerancia==5:
            toleran=0.05
        elif tolerancia==6:
            toleran=5
        elif tolerancia==7:
            toleran=10
        self.Result5cores_3.setStyleSheet('color: black')
        self.Result5cores_3.setText('{0}'.format(toleran))

    def Total5(self):
        total1=0
        cor1 = self.FirstColor5.currentIndex()
        if cor1==0:
            total1+=0
        elif cor1==1:
            total1+=100
        elif cor1==2:
            total1+=200
        elif cor1==3:
            total1+=300
        elif cor1==4:
            total1+=400
        elif cor1==5:
            total1+=500
        elif cor1==6:
            total1+=600
        elif cor1==7:
            total1+=700
        elif cor1==8:
            total1+=800
        elif cor1==9:
            total1+=900
        total2=0
        cor2 = self.SecondColor5.currentIndex()
        if cor2==0:
            total2+=0
        elif cor2==1:
            total2+=10
        elif cor2==2:
            total2+=20
        elif cor2==3:
            total2+=30
        elif cor2==4:
            total2+=40
        elif cor2==5:
            total2+=50
        elif cor2==6:
            total2+=60
        elif cor2==7:
            total2+=70
        elif cor2==8:
            total2+=80
        elif cor2==9:
            total2+=90
        total3=0
        cor3 = self.ThirdColor5.currentIndex()
        if cor3==0:
            total3+=0
        elif cor3==1:
            total3+=10
        elif cor3==2:
            total3+=20
        elif cor3==3:
            total3+=30
        elif cor3==4:
            total3+=40
        elif cor3==5:
            total3+=50
        elif cor3==6:
            total3+=60
        elif cor3==7:
            total3+=70
        elif cor3==8:
            total3+=80
        elif cor3==9:
            total3+=90
        multiplicador= self.FourthColor5.currentIndex()
        if multiplicador==0:
            mult = 1
        elif multiplicador==1:
            mult=10
        elif multiplicador==2:
            mult=100
        elif multiplicador==3:
            mult=1000
        elif multiplicador==4:
            mult=10000
        elif multiplicador==5:
            mult=100000
        elif multiplicador==6:
            mult=1000000
        elif multiplicador==7:
            mult=10000000
        elif multiplicador==8:
            mult=0.1
        elif multiplicador==9:
            mult=0.01
        total = (total1 + total2 + total3)*mult
        self.Result5cores.setStyleSheet('color: black')
        self.Result5cores.setText('{0}'.format(total))

    def Tolerancia5(self):
        tolerancia = self.FifthColor5.currentIndex()
        if tolerancia==0:
            toleran=1
        elif tolerancia==1:
            toleran=2
        elif tolerancia==2:
            toleran=0.5
        elif tolerancia==3:
            toleran=0.25
        elif tolerancia==4:
            toleran=0.1
        elif tolerancia==5:
            toleran=0.05
        elif tolerancia==6:
            toleran=5
        elif tolerancia==7:
            toleran=10
        self.Result5cores_2.setStyleSheet('color: black')
        self.Result5cores_2.setText('{0}'.format(toleran))

print("Rodou com sucesso")
if __name__	== "__main__":
	app	=     QtGui.QApplication(sys.argv)
	win	=	Ui_ResistorLab()
	win.show()
	sys.exit(app.exec_())


# encoding=utf-8
'''
Author: Haitaifantuan
Create Date: 2020-09-08 23:47:11
Author Email: 47970915@qq.com
Description: Should you have any question, do not hesitate to contact me via E-mail.
'''
import numpy as np
import random
import time

class First_Visit_Monte_Carlo_Policy_Evaluation(object):
    def __init__(self):
        self.total_rows = 4
        self.total_columns = 4
        self.total_action_num = 4  # 0代表上，1代表右，2代表下，3代表左
        self.reward_each_step = -1
        self.action_dict = {0: '上', 1: '右', 2: '下', 3: '左'}
        self.reversed_action_dict = {'上': 0, '右':1, '下':2, '左': 3}
        # 分别是走上、下、左、右的概率。随机数命中某个数字如49，那就是向右。随机数只在0-100随机选数字。
        self.four_action_probability = {'上': range(0, 25), '右': range(25, 50), '下': range(50, 75), '左': range(75, 100)}
        self.idx_change_dict = {'上': (-1, 0), '右': (0, 1), '下': (1, 0), '左': (0, -1)}  # 左边这个是行的索引的改变，右边这个是列的索引的改变
        self.episode = 100000  # 共采集TOTAL_ITERATION幕数据

        # 初始化状态价值函数V
        maze = np.zeros((self.total_rows, self.total_columns))  # 用0代表迷宫的每一格，这个maze只是方便我们看迷宫，没有其他作用。
        print(maze)

    def get_current_reward_and_next_state(self, current_state, action):
        '''
        根据当前的状态，以及行为，计算当前行为的奖励以及下一个状态
        '''
        row_idx, column_idx = current_state

        # 计算下下一步的state和reward
        next_row_idx = row_idx + self.idx_change_dict[action][0]
        next_column_idx = column_idx + self.idx_change_dict[action][1]

        # 先判断是否到了终点，如果是终点，不管执行什么操作
        # 奖励都是0，并且都会回到终点

        if (next_row_idx == 0 and next_column_idx == 0):
            return 0, (0, 0)

        if (next_row_idx == 3 and next_column_idx == 3):
            return 0, (3, 3)

        # 再判断是否在边缘，如果是的话，那就回到该位置。
        if next_row_idx < 0 or next_row_idx > self.total_rows - 1 or next_column_idx < 0 or next_column_idx > self.total_columns - 1:
            return self.reward_each_step, (row_idx, column_idx)
        else:
            return self.reward_each_step, (next_row_idx, next_column_idx)

    def generate_initial_state(self, total_rows, total_columns):
        row_idx = random.randint(0, total_rows - 1)
        column_idx = random.randint(0, total_columns - 1)

        while (row_idx == 0 and column_idx == 0) or (row_idx == 3 and column_idx == 3):
            row_idx = random.randint(0, total_rows - 1)
            column_idx = random.randint(0, total_columns - 1)

        return (row_idx, column_idx)

    def generate_one_episode_data(self, init_state):
        one_episode_data = []
        current_state = init_state
        while not ((current_state[0] == 0 and current_state[1] == 0) or (current_state[0] == 3 and current_state[1] == 3)):
            # 根据概率产生一个动作
            rand_int = random.randint(0, 99)
            for each in self.four_action_probability.items():
                if rand_int in each[1]:
                    action = each[0]
                    break

            # 根据要走的动作得到奖励以及获取下一个状态
            reward, next_state = self.get_current_reward_and_next_state(current_state, action)
            # （当前状态，当前行为，当前行为的奖励）
            one_episode_data.append((current_state, self.reversed_action_dict[action], reward))

            current_state = next_state

        # while循环出来的时候，最后一个terminal状态没加进去。
        one_episode_data.append((current_state, None, None))

        return one_episode_data

    def fire_calculation(self):
        # 计算“状态-动作价值”
        # 创建一个字典保存出现的状态-动作以及奖励
        begin_time = time.time()

        episode_record_dict = {}
        final_state_action_reward_dict = {}  # 这个和state_action_reward_dict是有区别的，它是记录总体的。
        final_state_action_count_dict = {}
        for episode in range(self.episode):
            # 生成每一幕的数据
            all_episode_list = []
            # 随机生成一个起始状态
            init_state = self.generate_initial_state(self.total_rows, self.total_columns)
            # 生成一幕数据
            episode_record_dict[episode] = self.generate_one_episode_data(init_state)
            # 对这幕数据进行遍历，然后将出现过的状态进行统计
            has_been_counted = {}  # 记录状态是否在该幕出现过
            state_action_reward_dict = {}  # 记录每一个状态当前的总共的reward
            for idx, eachTuple in enumerate(episode_record_dict[episode]):
                # 先判断是不是到了终点，如果是的话就跳出循环
                if idx == len(episode_record_dict[episode])-1:
                    break

                # 将state和action组合成字符串，方便作为dict的key
                state_action_combination = str(eachTuple[0][0]) + str(eachTuple[0][1]) + str(eachTuple[1])

                # 对state_action_reward_dict()里的所有的key都累加当前的reward。
                for key in state_action_reward_dict.keys():
                    state_action_reward_dict[key] += eachTuple[2]

                # 检测当前这一幕该状态和动作组合是否出现过
                if state_action_combination not in has_been_counted.keys():
                    # 如果不存在在state_count_dict.keys()里，说明是第一次碰到该状态。
                    has_been_counted[state_action_combination] = 1  # 随便赋值一个value
                    state_action_reward_dict[state_action_combination] = eachTuple[2]

            # 将该募最后统计到总的变量里。
            for state_action, reward in state_action_reward_dict.items():
                if state_action not in final_state_action_reward_dict.keys():
                    final_state_action_reward_dict[state_action] = reward  # 将该状态-动作计数设为reward
                    final_state_action_count_dict[state_action] = 1  # 将该状态-动作计数设为1
                else:
                    # 否则说明其他幕中出现过该状态-动作，并且曾经统计到final_state_action_reward_dict和final_state_action_count_dict变量里面
                    # 直接累加就好了。
                    final_state_action_reward_dict[state_action] += reward
                    final_state_action_count_dict[state_action] += 1

            if episode % 100 == 0:
                print("第{}个episode已完成=====已花费{}分钟".format(episode, (time.time() - begin_time) / 60))

        # 计算下最终的状态-动作价值
        # 由于是按概率采样，因此可能会导致某些动作-状态没有出现过，这个时候就需要一些方法去解决了。
        # 一种方法是增加采样次数，这种方法相当于是暴力解决。
        # 另一种方法可以参考sutton的《强化学习第二版》的98页的5.4内容
        self.averaged_state_action_value_dict = {}
        for state_action, reward in final_state_action_reward_dict.items():
            self.averaged_state_action_value_dict[state_action] = reward / final_state_action_count_dict[state_action]

        # print(self.averaged_state_action_value_dict)

    def show_policy(self):
        policy_dict = {}
        for state_action, value in self.averaged_state_action_value_dict.items():
            if state_action[0:2] not in policy_dict.keys():
                policy_dict[state_action[0:2]] = {self.action_dict[int(state_action[2])]: value}
            else:
                policy_dict[state_action[0:2]][self.action_dict[int(state_action[2])]] = value

        print(policy_dict)

obj = First_Visit_Monte_Carlo_Policy_Evaluation()
obj.fire_calculation()
obj.show_policy()

强化学习中的蒙特卡罗应用（贝尔曼方程）（含代码）-《强化学习系列专栏第2篇》/首次访问型蒙特卡罗策略估计.py

首次访问型蒙特卡罗策略估计.py


import pandas as pd

replay_data = pd.read_csv('ReplayCharacters 2015-12-30 - 2016-01-29.csv')
hero_info = pd.read_csv('hero_info.csv')
replay_info = pd.read_csv('Replays 2015-12-30 - 2016-01-29.csv')
map_info = pd.read_csv('map_info.csv')

all_games = replay_data.merge(replay_info, how='left', on='ReplayID')
all_games = all_games.merge(hero_info, how='left', on='HeroID')
print('Merging done')

a = all_games.head(100000)

a[['ReplayID', 'PrimaryName']].loc[a['PrimaryName'] == 'Leoric'].groupby([])


from django.core.exceptions import ValidationError
from rest_framework import serializers

from reviews.models import Category, Comment, Genre, Review, Title, User

class ConfirmationTokenSerializer(serializers.Serializer):
    """Serializing verification data to provide full user registration"""

    username = serializers.CharField(required=True)
    confirmation_code = serializers.CharField(required=True)

class RegistrationSerializer(serializers.Serializer):
    """Serializing data to provide a user creation"""

    email = serializers.EmailField(required=True)
    username = serializers.CharField(required=True)

    def validate(self, data):
        if data["username"] == "me":
            raise ValidationError("Пользователь не может иметь имя 'me'")
        return data

class UserSerializer(serializers.ModelSerializer):
    """Serializing data for work with user and his profile"""

    class Meta:
        model = User
        fields = (
            "username",
            "first_name",
            "last_name",
            "email",
            "bio",
            "role",
        )

class CategorySerializer(serializers.ModelSerializer):
    """Serializer for categories."""

    class Meta:
        model = Category
        fields = ("name", "slug")
        lookup_field = 'slug'

class GenreSerializer(serializers.ModelSerializer):
    """Serializer for genres."""

    class Meta:
        model = Genre
        fields = ("name", "slug")

class WriteTitleSerializer(serializers.ModelSerializer):
    """Serializer for write request for titles."""

    category = serializers.SlugRelatedField(
        slug_field="slug",
        queryset=Category.objects.all(),
    )
    genre = serializers.SlugRelatedField(
        many=True,
        slug_field="slug",
        queryset=Genre.objects.all(),
    )
    rating = serializers.SerializerMethodField()

    class Meta:
        model = Title
        fields = "__all__"

    def get_rating(self, obj):
        """Return 0 after creation."""
        return 0

class ReadTitleSerializer(serializers.ModelSerializer):
    """Serializer for read requests for titles."""

    genre = GenreSerializer(many=True)
    category = CategorySerializer()
    rating = serializers.SerializerMethodField()

    class Meta:
        model = Title
        fields = "__all__"
        read_only_fields = ("name", "year", "description", "genre", "category")

    def get_rating(self, obj):
        """Return object rating calculated in viewset."""
        return obj.rating

class ReviewSerializer(serializers.ModelSerializer):
    """Serializer for reviews."""
    score = serializers.IntegerField(max_value=10, min_value=0)
    author = serializers.SlugRelatedField(
        slug_field="username",
        read_only=True,
        default=serializers.CurrentUserDefault(),  # добавил новое
    )

    class Meta:
        model = Review
        fields = ("id", "text", "author", "score", "pub_date")

    def validate(self, attrs):
        """Check that each author can have only one review
        for particular title.
        """
        if not self.context["request"].method == "POST":
            return attrs
        if Review.objects.filter(
            title_id=self.context["view"].kwargs.get("title_id"),
            author=self.context["request"].user,
        ).exists():
            raise serializers.ValidationError(
                (
                    "Автор может оставлять ревью на каждое произведение "
                    "только один раз"
                )
            )
        return attrs

class CommentSerializer(serializers.ModelSerializer):
    """Serializer for comments."""

    author = serializers.SlugRelatedField(
        slug_field="username",
        read_only=True,
    )

    class Meta:
        model = Comment
        fields = ("id", "text", "author", "pub_date")


from pathlib import Path

import joblib

IS_KAGGLE = True

if IS_KAGGLE:
    DATA_DIR = Path("/kaggle/working/chap5-data")
    OUTPUT_DIR = Path("/kaggle/working/")
else:
    DATA_DIR = Path("../data")  # Path(os.getenv("QQP_DATA_DIR", "/data"))
    OUTPUT_DIR = Path("../outputs")

INPUT_DIR = DATA_DIR / "input"
TRAIN_CSV_PATH = INPUT_DIR / "train.csv"
TEST_CSV_PATH = INPUT_DIR / "test.csv"
EMBEDDING_DIR = DATA_DIR / "embeddings"
GLOVE_PATH = EMBEDDING_DIR / "glove.840B.300d.bin"

FEATURE_MEMORY = joblib.Memory(DATA_DIR / "cache")

SPLIT_RANDOM_SEED = 1
EPS = 1e-10
NUM_PROCESSES = 4  # int(os.getenv("NUM_PROCESSES", 1))
NUM_TRAIN_SAMPLES = 404290
NUM_TEST_SAMPLES = 2345796
NUM_DRYRUN_SAMPLES = 1000


from db import session, UniqueVictims, Victims
from sqlalchemy.sql import func

def calc_totals():
    """
    Calculate the total time frame the IP appears in and the udp/tcp/icmp packet
    count as well as the packets/s rate
    :return:
    """
    all_victims = session.query(UniqueVictims).all()

    for victim in all_victims:
        ip = victim.ip
        victim.time_frame_count = session.query(Victims).filter_by(ip=ip).count()
        victim.tcp_count = session.query(func.sum(Victims.tcp_count).filter(Victims.ip == ip)).scalar()
        victim.udp_count = session.query(func.sum(Victims.udp_count).filter(Victims.ip == ip)).scalar()
        victim.icmp_count = session.query(func.sum(Victims.icmp_count).filter(Victims.ip == ip)).scalar()
        victim.rate = (victim.udp_count + victim.tcp_count + victim.icmp_count)/(victim.time_frame_count * 60)

    session.commit()

if __name__ == '__main__':
    calc_totals()


import os
from app import app
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from pneumonia_prediction import predict
import tensorflow as tf

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
physical_devices = tf.config.list_physical_devices('CPU')
mariaunet = tf.keras.models.load_model('mariaunet')

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def upload_form():
    """
    	display upload page
    """
    return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_image():
	"""
    	display image with the tensorflow model prediction
	"""
	if 'file' not in request.files:
		flash('No file part')
		return redirect(request.url)
	file = request.files['file']
	if file.filename == '':
		flash('No image selected for uploading')
		return redirect(request.url)
	elif file and allowed_file(file.filename):
		filename = secure_filename(file.filename)
		filepath = os.path.join(app.config['UPLOAD_FOLDER'], 'xray.jpg')
		if os.path.exists(filepath):
			os.remove(filepath)
		file.save(filepath)
		flash('Image successfully uploaded and displayed below')
		predict(filepath, mariaunet)
		return render_template('upload.html', filename='xray.jpg')
	else:
		flash('Allowed image types are -> png, jpg, jpeg')
		return redirect(request.url)

@app.route('/display/<filename>')
def display_image(filename):
	"""
        display image
    """
	return redirect(url_for('static', filename='uploads/' + filename), code=301)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8000)


from django.urls import path, include
from . import views
from rest_framework import routers

route = routers.DefaultRouter()
route.register("user", views.UserViewSet, basename='user')
route.register("tuyenxe", views.TuyenXeViewset, basename='tuyenxe')
route.register("chuyenxe", views.ChuyenXeViewset, basename='chuyenxe')
route.register("datve", views.DatVeViewset, basename='datve')
route.register(prefix='comments', viewset=views.CommentViewSet, basename='comment')
# route.register("thongke", views.ThongKeViewSet, basename='thongke')

urlpatterns = [
    path('', include(route.urls)),
]


import numpy as np
import pickle
import string
import sys
import math

class RNN:
    def __init__(self, input_dim, output_dim, sentence_length, initializer="normal", optimizer="gd", hidden_dim=64, learning_rate=0.001, momentum=0.9, beta=0.9):
        # Checking if the optimizer is a valid optimizer
        valid_optimizers = ["gd", "momentum", "rmsprop"]
        try:
            assert(optimizer in valid_optimizers)
        except:
            print("Available optimizers are : {}".format(valid_optimizers))
            raise ValueError("Cannot recognize optimizer : {}".format(optimizer))

        # Checking if the initializer is a valid initializer
        valid_initializers = ["normal", "xavier"]
        try:
            assert(initializer in valid_initializers)
        except:
            print("Available initializers are : {}".format(valid_initializers))
            raise ValueError("Cannot recognize initializer : {}".format(initializer))

        self.minibatches = 1
        self.beta1 = momentum
        self.beta2 = beta
        self.optimizer = optimizer
        self.initializer = initializer
        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.output_dim = output_dim
        self.learning_rate = learning_rate
        self.sentence_length = sentence_length

        # Calculating xavier initializer constants
        if(self.initializer == "xavier"):
            whx = math.sqrt(6) / math.sqrt(self.hidden_dim + self.input_dim)
            whh = math.sqrt(6) / math.sqrt(self.hidden_dim + self.hidden_dim)
            wyh = math.sqrt(6) / math.sqrt(self.output_dim + self.hidden_dim)

            # Creating the initial weights
            self.Whx = np.random.uniform(-whx, whx, (hidden_dim, input_dim))
            self.Whh = np.random.uniform(-whh, whh, (hidden_dim, hidden_dim))
            self.Wyh = np.random.uniform(-wyh, wyh, (output_dim, hidden_dim))

            # Creating the initial biases
            self.bh   = np.random.normal(0, 1, (hidden_dim, 1))
            self.by = np.random.normal(0, 1, (output_dim, 1))

        elif(self.initializer == "normal"):
            # Creating the initial weights
            self.Whx = np.random.normal(0, 1, (hidden_dim, input_dim))
            self.Whh = np.random.normal(0, 1, (hidden_dim, hidden_dim))
            self.Wyh = np.random.normal(0, 1, (output_dim, hidden_dim))

            # Creating the initial biases
            self.bh   = np.random.normal(0, 1, (hidden_dim, 1))
            self.by   = np.random.normal(0, 1, (output_dim, 1))

        # Creating variables to store exponential averages for momentum
        if(self.optimizer == "momentum"):
            self.dWhx = np.zeros((hidden_dim, input_dim))
            self.dWhh = np.zeros((hidden_dim, hidden_dim))
            self.dWyh = np.zeros((output_dim, hidden_dim))
            self.dbh = np.zeros((hidden_dim, 1))
            self.dby  = np.zeros((output_dim, 1))

        # Creating variables to save exponential averages for RMS prop
        elif(self.optimizer == "rmsprop"):
            self.sWhx = np.zeros((hidden_dim, input_dim))
            self.sWhh = np.zeros((hidden_dim, hidden_dim))
            self.sWyh = np.zeros((output_dim, hidden_dim))
            self.sbh = np.zeros((hidden_dim, 1))
            self.sby  = np.zeros((output_dim, 1))

    # Performs feed forward on the RNN
    def forward(self, data):
        # Getting dimensions from the input
        try:
            assert(data.shape[0] == self.sentence_length)
            assert(data.shape[1] == self.input_dim)
        except:
            raise ValueError("Expected data with dims of : {} but got data with dims : {}").format(
                (self.sentence_length, self.input_dim, None), data.shape)

        batch_size = data.shape[2]

        # Fixing the initial state as a zero vector
        h = np.zeros((self.hidden_dim,  batch_size))

        # Storing all states
        states = [h]
        for words in data:
            assert(np.array(words).shape == (self.input_dim, batch_size))
            h = np.tanh(np.matmul(self.Whh, h) +
                        np.matmul(self.Whx, words) + self.bh)
            states.append(h)

        # Shape of states : (sentence_length + 1, self.hidden_dim, batch_size)
        states = np.array(states)

        # Calculating the output using state
        # Shape (self.output_dim, batch_size)
        output = np.matmul(self.Wyh, states[-1]) + self.by
        output = np.array(self.softmax(output)).reshape(
            (self.output_dim, batch_size))

        return output, states

    # Calculates softmax of the outputs
    def softmax(self, data):
        # Clipping the data
        np.clip(data, -200, 200, out=data)

        # Calculating softmax
        data = np.exp(data)
        data /= np.sum(data, axis=0)
        return data

    # Performs back propagation
    def backPropagate(self, train_X, train_Y, preds, states, batch_size):
        # Shape (self.output_dim, batch_size)
        dL_dY = preds.T
        for index, pred in enumerate(dL_dY):
            pred[train_Y[index]] -= 1
        dL_dY = dL_dY.T

        # Timesteps
        T = len(states) - 1

        # Calculating gradients for Wyh and by
        # Shape (self.output_dim, self.hidden_dim)
        dL_dWyh = np.matmul(dL_dY, states[-1].T)
        dL_dby = np.sum(dL_dY, axis=1).reshape(self.output_dim, 1)

        # Calculating gradients for Whx, Whh, bh
        dL_dWhh = np.zeros(shape=self.Whh.shape)
        dL_dWhx = np.zeros(shape=self.Whx.shape)
        dL_dbh = np.zeros(shape=self.bh.shape)

        # Calculating dL / dh
        # Shape(self.hidden_dim, batch_size)
        dL_dh = np.matmul(self.Wyh.T, dL_dY)

        for t in reversed(range(T)):
            dL_dWhh += np.matmul(dL_dh *
                                 (1 - (states[t + 1] ** 2)), states[t].T)
            dL_dWhx += np.matmul(dL_dh *
                                 (1 - (states[t + 1] ** 2)), train_X[t].T)

            dL_dbh += np.sum(dL_dh * (1 - (states[t + 1] ** 2)),
                             axis=1).reshape(self.hidden_dim, 1)

            # Updating dL_dh
            dL_dh = np.matmul(self.Whh, dL_dh * (1 - states[t + 1] ** 2))

        if(self.optimizer == "gd"):
            # Clipping the gradients for exploding gradients
            for updates in [dL_dWhh, dL_dWhx, dL_dWyh, dL_dbh, dL_dby]:
                np.clip(updates, -1, 1, out=updates)

            # Updating the weights and biases
            self.Whh -= self.learning_rate * dL_dWhh
            self.Whx -= self.learning_rate * dL_dWhx
            self.Wyh -= self.learning_rate * dL_dWyh
            self.bh  -= self.learning_rate * dL_dbh
            self.by  -= self.learning_rate * dL_dby

        # Applying momentum and normalizing
        elif(self.optimizer == "momentum"):
            # Calculating exponential averages
            normalization_factor = 1 - (self.beta1 ** min(self.minibatches, 100))
            self.dWhh = (self.beta1 * self.dWhh + (1 - self.beta1) * (dL_dWhh)) / normalization_factor
            self.dWhx = (self.beta1 * self.dWhx + (1 - self.beta1) * (dL_dWhx)) / normalization_factor
            self.dWyh = (self.beta1 * self.dWyh + (1 - self.beta1) * (dL_dWyh)) / normalization_factor
            self.dbh  = (self.beta1 * self.dbh + (1 - self.beta1) * (dL_dbh)) / normalization_factor
            self.dby  = (self.beta1 * self.dby + (1 - self.beta1) * (dL_dby)) / normalization_factor

            # Clipping the gradients for exploding gradients
            for updates in [self.dWhh, self.dWhx, self.dWyh, self.dbh, self.dby]:
                np.clip(updates, -1, 1, out=updates)

            # Updating the weights and biases
            self.Whh -= self.learning_rate * self.dWhh
            self.Whx -= self.learning_rate * self.dWhx
            self.Wyh -= self.learning_rate * self.dWyh
            self.bh  -= self.learning_rate * self.dbh
            self.by  -= self.learning_rate * self.dby

        # Applying RMS Prop
        elif(self.optimizer == "rmsprop"):
            self.sWhh = (self.beta2 * self.sWhh + (1 - self.beta2) * (dL_dWhh ** 2))
            self.sWhx = (self.beta2 * self.sWhx + (1 - self.beta2) * (dL_dWhx ** 2))
            self.sWyh = (self.beta2 * self.sWyh + (1 - self.beta2) * (dL_dWyh ** 2))
            self.sbh  = (self.beta2 * self.sbh + (1 - self.beta2) * (dL_dbh ** 2))
            self.sby  = (self.beta2 * self.sby + (1 - self.beta2) * (dL_dby ** 2))

            # Clipping the gradients for exploding gradients
            for updates in [self.sWhh, self.sWhx, self.sWyh, self.sbh, self.sby]:
                np.clip(updates, -1, 1, out=updates)

            # Updating the weights and biases
            self.Whh -= self.learning_rate * (dL_dWhh / np.sqrt(self.sWhh))
            self.Whx -= self.learning_rate * (dL_dWhx / np.sqrt(self.sWhx))
            self.Wyh -= self.learning_rate * (dL_dWyh / np.sqrt(self.sWyh))
            self.bh  -= self.learning_rate * (dL_dbh  / np.sqrt(self.sbh))
            self.by  -= self.learning_rate * (dL_dby  / np.sqrt(self.sby))

    def train(self, train_X, train_Y, test_X, test_Y, epochs, verbose=False, batch_size=32):
        # Checking params
        train_X = np.array(train_X)
        train_Y = [int(target) for target in train_Y]
        test_X = np.array(test_X)
        test_Y = [int(target) for target in test_Y]

        # Checking that train_X and train_Y have equal data points
        try:
            assert(train_X.shape[0] == len(train_Y))
        except:
            print("Number of training samples in train_X and train_Y are not equal. Number of samples in train_X is {} and {} in train_Y".format(
                train_X.shape[0], len(train_Y)))

        # Checking that test_X and test_Y have equal data points
        try:
            assert(test_X.shape[0] == len(test_Y))
        except:
            print("Number of training samples in train_X and train_Y are not equal. Number of samples in train_X is {} and {} in train_Y".format(
                test_X.shape[0], len(test_Y)))

        # Calculating training and testing data size
        training_size = train_X.shape[0]
        testing_size = test_X.shape[0]

        # Conforming batch size to a maximum of training_size / 2
        batch_size = min(batch_size, training_size / 2)

        # Checking that the dimensions of the training data are correct
        try:
            assert(train_X.shape[1] == self.sentence_length)
            assert(train_X.shape[2] == self.input_dim)
        except:
            print("Expected training data shape to be {} but got {}".format(
                training_size, self.sentence_length, self.input_dim))

        # Checking that the dimensions of the testing data are correct
        try:
            assert(test_X.shape[1] == self.sentence_length)
            assert(test_X.shape[2] == self.input_dim)
        except:
            print("Expected testing data shape to be {} but got {}".format(
                testing_size, self.sentence_length, self.input_dim))

        # Transposing the testing data
        test_X = np.transpose(test_X, (1, 2, 0))

        # Array to store metrics
        losses = []
        correct_ans = []
        log_frequency = max(int(float(epochs) / 100), 1)

        # Converting training and testing data into numpy arrays
        print("Size of training data : {}".format(
            sys.getsizeof(train_X) + sys.getsizeof(train_Y)))
        print("Size of testing data : {}".format(
            sys.getsizeof(test_X) + sys.getsizeof(test_Y)))

        # Splitting the training data into batches of size batchsize
        batches = int(math.ceil(float(training_size) / batch_size))
        batch_training_X = []
        batch_training_Y = []

        # Splitting training data into batches
        for batch in range(batches):
            start_index = batch_size * batch
            end_index = min(batch_size * (batch + 1), training_size)
            temp_batch_size = end_index - start_index
            batch_train_X = train_X[start_index: end_index]

            # Creating an np array of size (batch_size, max_batch_length, self.hidden_dim)
            batch_train_X = np.array(batch_train_X).reshape(
                (temp_batch_size, self.sentence_length, self.input_dim))
            batch_train_Y = np.array(train_Y[start_index: end_index])
            batch_training_X.append(batch_train_X)
            batch_training_Y.append(batch_train_Y)

        # Checking if the correct number of batches were inserted
        assert(len(batch_training_X) == batches)

        # Deleting variables to clear RAM
        del train_X, train_Y

        # Training the net
        for epoch in range(epochs):
            loss = 0
            num_correct = 0

            # Iterating through each training batch
            for batch in range(batches):
                # Picking out one batch of training samples
                train_X = batch_training_X[batch]
                train_Y = batch_training_Y[batch]

                # Train_X from (batch_size, sentence_length, self.input_dim) to (sentence_length, self.input_dim, batch_size)
                train_X = np.transpose(train_X, (1, 2, 0))

                # Feed Forwarding
                preds, states = self.forward(train_X)

                loss -= np.sum(np.log([pred[train_Y[index]]
                                       for index, pred in enumerate(preds.T)]))
                num_correct += np.sum(np.argmax(preds, axis=0) == train_Y)

                # Back propagating the error
                self.backPropagate(train_X, train_Y, preds, states, batch_size)

                # Updating the mini batch number
                self.minibatches += 1

            # Appending loss to training data
            losses.append(loss)
            correct_ans.append((float(num_correct) / training_size) * 100)

            # Printing loss and number of correctly classified values
            if(verbose and epoch % log_frequency == 0):

                print("\n\n\n Epoch : {} \n".format(epoch))
                print("TRAINING_DATA")
                print("Loss : {}".format(loss / training_size))
                print("Correctly classified : {} percent of data".format(
                    100 * float(num_correct) / training_size))

                # Resetting loss and correct answers
                loss = 0
                num_correct = 0

                # Feed Forwarding
                preds, states = self.forward(test_X)

                # Calculating the loss and correct classifications
                loss -= np.sum(np.log([pred[test_Y[index]]
                                       for index, pred in enumerate(preds.T)]))
                num_correct += np.sum(np.argmax(preds, axis=0) == test_Y)

                print("                            ")
                print("TESTING_DATA")
                print("Loss : {}".format(loss / testing_size))
                print("Correctly classified : {} percent of data".format(
                    100 * float(num_correct) / testing_size))

        return losses, correct_ans

    def summary(self):
        total_params = (self.hidden_dim * self.hidden_dim) + (self.input_dim * self.hidden_dim) + (
            self.output_dim * self.hidden_dim) + (self.hidden_dim) + (self.output_dim)
        print("                                                    ")
        print(" ====================================================")
        print(" Total trainable parameters : {}".format(total_params))
        print(" Learning Rate : {}".format(self.learning_rate))
        print(" Optimizer : {}".format(self.optimizer))
        print(" Beta1 : {}".format(self.beta1))
        print(" Beta2 : {}".format(self.beta2))
        print(" Input dimension : {}".format(self.input_dim))
        print(" Output dimension : {}".format(self.output_dim))
        print(" Hidden dimension : {}".format(self.hidden_dim))
        print(" ====================================================")
        print("                                                    ")

    def save_weights(self, save_path):
        weights = {
            'input_dim': self.input_dim,
            'output_dim': self.output_dim,
            'hidden_dim': self.hidden_dim,
            'sentence_length': self.sentence_length,
            'minibatches' : self.minibatches,
            'Whh': self.Whh,
            'Whx': self.Whx,
            'Wyh': self.Wyh,
            'bh': self.bh,
            'by': self.by
        }

        weights_file = open(save_path, "wb")
        pickle.dump(weights, weights_file)

        print("Saved weights to path : {} successfully".format(save_path))

    def load_weights(self, save_path):
        weights_file = open(save_path, "rb")
        weights = pickle.load(weights_file)

        # Checking whether model created has input and output dims the same as the loaded file
        if(self.input_dim != weights['input_dim'] or self.hidden_dim != weights['hidden_dim'] or self.output_dim != weights['output_dim']):
            print(
                "Warning : The dimensions of your current model and the loaded model do not match")
            print("Your model dimensions : ")
            print("Input Dimension : {}".format(self.input_dim))
            print("Hidden Dimension : {}".format(self.hidden_dim))
            print("Output Dimension : {} ".format(self.output_dim))

            print(" Loaded model's dimensions")
            print("Input Dimension : {}".format(weights['input_dim']))
            print("Hidden Dimension : {}".format(weights['hidden_dim']))
            print("Output Dimension : {} ".format(weights['output_dim']))

            text = raw_input(" Enter [Y] to continue to load model : \t")

            if(text != "Y" and text != "y"):
                print("                        ")
                print("Aborting model loading")
                sys.exit()

        # Checking if the sentence length of loaded model matches the current model
        if(weights['sentence_length'] != self.sentence_length):
            print(
                "Warning : The sentence length of your current model and the loaded model do not match")

            text = raw_input(" Enter [Y] to continue to load model : \t")

            if(text != "Y" and text != "y"):
                print("                        ")
                print("Aborting model loading")
                sys.exit()

        # Resassigning weights to correct locations
        self.Whh = weights['Whh']
        self.Whx = weights['Whx']
        self.Wyh = weights['Wyh']
        self.bh = weights['bh']
        self.by = weights['by']
        self.minibatches = weights['minibatches']
        self.input_dim = weights['input_dim']
        self.output_dim = weights['output_dim']
        self.hidden_dim = weights['hidden_dim']
        self.sentence_length = weights['sentence_length']

        print("Loaded weights from path : {} successfully".format(save_path))

    def predict(self, words):
        words = np.array(words)
        data_size = words.shape[0]

        try:
            assert(words.shape[1] == self.sentence_length)
            assert(words.shape[2] == self.input_dim)
        except:
            raise ValueError("Expected dimesion of input as {} but received dimensions {}".format(
                (data_size, self.sentence_length, self.input_dim), words.shape))

        inputs = words.reshape(data_size, self.sentence_length, self.input_dim)
        inputs = np.transpose(inputs, (1, 2, 0))
        preds, _ = self.forward(inputs)
        return preds


import Image
import PSDraw

#-*- coding:utf-8 -*-
def text2png(text):

    adtexts = [ ]
    textcolor = "#000000"
    adcolor = "#FF0000"

    import Image, ImageDraw, ImageFont, uuid

    ad = []
    for adtext in adtexts:
        ad += [(adtext.encode('gbk'), adcolor)]

    wraptext = [""]
    l = 0
    for i in text.decode('utf-8'):
        fi = i.encode('gbk')
        delta = len(fi)
        if i == '\n':
            wraptext += [""]
            l = 0
        elif l + delta > 40:
            wraptext += [fi]
            l = delta
        else:
            wraptext[-1] += fi
            l += delta

    wrap = [(text, textcolor) for text in wraptext]
    wrap += ad

    i = Image.new("RGB", (15, len(wrap) * 17 + 5), "#FFFFFF")
    d = ImageDraw.Draw(i)
    f = ImageFont.truetype("1.ttf", 16)
    for num, (text, color) in enumerate(wrap):
        d.text((2, 17 * num + 1), text.decode('gbk'), font = f, fill = color)

    filename = text + ".png"
    with open( "letter/"+ filename, "wb") as s:
        i.save(s, "PNG")
    return filename

for i in range(ord("a"), ord("z")):
    text2png(chr(i))
for i in range(ord("A"), ord("Z")+1):
    text2png(chr(i))


"""This is my attempt to solve the random numbers challenge in python game"""
import random

# Display welcome message to player
print("Welcome Code Breaker! Lets see if you can break my 3 digit number!")
print("Code has been generated, please guess a 3 digit number ")
guess = list(input("What is your guess?: "))
print(guess)

# Create a range of numbers and shuffle to create a list of 3 random numbers
digits = list(range(10))
random.shuffle(digits)

# Create an mty list and assign numbers from ordinal list to a new list
games_list = []
for x in digits[:3]:
    games_list.append(x)

playersMatch = []  # May not need this list
print(games_list)
while guess != games_list:
    for i in guess:
        if i == games_list[0] or i == games_list[1] or i == games_list[2]:
            print(games_list[i])
            print("Close")
        elif i != games_list[0] and i != games_list[1] and i != games_list[2]:
            print(i)
            print(games_list)
            print("Nope ")
            list(input("Please try and enter a new guess  "))
            continue
        else:

            print(games_list)
            print("Nope!")
            guess = list(input("Please try again to enter a correct digit: "))

# ----------------------------------------------- Below this line are possible functions and
# other code that may possibly be correct to use and solve the problem
# return a[-(len(b)):] == b or a == b[-(len(a)):]:
# for x in guess:
#     if guess[0] == games_list[0] or guess[1] == games_list[1] or guess[2] == games_list[2]:
#         print("close")
def code_cracker(my_list):
    if my_list[2] == 1:
        print("Don't do anything for now")


from string import printable
from keras.models import  Model,  load_model
from keras import regularizers
from keras.layers.core import Dense, Dropout, Lambda
from keras.layers import Input, ELU,  Embedding, \
BatchNormalization, Convolution1D,concatenate
from keras.preprocessing import sequence
from keras.optimizers import Adam
from keras import backend as K
from keras.callbacks import CSVLogger
from utils import load_model, save_model
from keras.utils.vis_utils import plot_model

class CNNC:

    def __init__(self, max_len=75, emb_dim=32, max_vocab_len=100, w_reg=regularizers.l2(1e-4)):
        self.max_len = max_len
        self.csv_logger = CSVLogger('CNN_log.csv', append=True, separator=';')
        main_input = Input(shape=(max_len,), dtype='int32', name='main_input')
        # Embedding layer
        emb = Embedding(input_dim=max_vocab_len, output_dim=emb_dim, input_length=max_len,
                        W_regularizer=w_reg)(main_input)
        emb = Dropout(0.25)(emb)

        def sum_1d(X):
            return K.sum(X, axis=1)

        def get_conv_layer(emb, kernel_size=5, filters=256):
            # Conv layer
            conv = Convolution1D(kernel_size=kernel_size, filters=filters, \
                                 border_mode='same')(emb)
            conv = ELU()(conv)

            conv = Lambda(sum_1d, output_shape=(filters,))(conv)
            # conv = BatchNormalization(mode=0)(conv)
            conv = Dropout(0.5)(conv)
            return conv

        # Multiple Conv Layers

        # calling custom conv function from above
        conv1 = get_conv_layer(emb, kernel_size=2, filters=256)
        conv2 = get_conv_layer(emb, kernel_size=3, filters=256)
        conv3 = get_conv_layer(emb, kernel_size=4, filters=256)
        conv4 = get_conv_layer(emb, kernel_size=5, filters=256)

        # Fully Connected Layers
        merged = concatenate([conv1, conv2, conv3, conv4], axis=1)

        hidden1 = Dense(1024)(merged)
        hidden1 = ELU()(hidden1)
        hidden1 = BatchNormalization(mode=0)(hidden1)
        hidden1 = Dropout(0.5)(hidden1)

        hidden2 = Dense(1024)(hidden1)
        hidden2 = ELU()(hidden2)
        hidden2 = BatchNormalization(mode=0)(hidden2)
        hidden2 = Dropout(0.5)(hidden2)

        # Output layer (last fully connected layer)
        output = Dense(1, activation='sigmoid', name='output')(hidden2)

        # Compile model and define optimizer
        self.model = Model(input=[main_input], output=[output])
        self.adam = Adam(lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
        self.model.compile(optimizer=self.adam, loss='binary_crossentropy', metrics=['accuracy'])

    def save_model(self, fileModelJSON, fileWeights):
        save_model(self.model, fileModelJSON, fileWeights)

    def load_model(self, fileModelJSON, fileWeights):
        self.model = load_model(fileModelJSON, fileWeights)
        self.model.compile(optimizer=self.adam, loss='binary_crossentropy', metrics=['accuracy'])

    def train_model(self, x_train, target_train, epochs=5, batch_size=32):
        print("Training CNN model with  " + str(epochs) + " epochs and batches of size " + str(batch_size))
        self.model.fit(x_train, target_train, epochs=epochs, batch_size=batch_size, verbose=1, callbacks=[self.csv_logger])

    def test_model(self, x_test, target_test):
        print("testing CNN model")
        return self.model.evaluate(x_test, target_test, verbose=1)

    def predict(self, x_input):
        url_int_tokens = [[printable.index(x) + 1 for x in x_input if x in printable]]
        X = sequence.pad_sequences(url_int_tokens, maxlen=self.max_len)
        p = self.model.predict(X, batch_size=1)
        return "benign" if p < 0.5 else "malicious"

    def export_plot(self):
        plot_model(self.model, to_file='CNN.png')


from __future__ import unicode_literals

import frappe
from frappe.utils.make_random import add_random_children, get_random, how_many, can_make
from frappe.utils import cstr
from erpnext.setup.utils import get_exchange_rate
from erpnext.accounts.party import get_party_account_currency

def run_sales(current_date):
	if can_make("Opportunity"):
		for i in xrange(how_many("Opportunity")):
			make_opportunity(current_date)

	if can_make("Quotation"):
		for i in xrange(how_many("Quotation")):
			make_quotation(current_date)

	if can_make("Sales Order"):
		for i in xrange(how_many("Sales Order")):
			make_sales_order(current_date)

def make_opportunity(current_date):
	b = frappe.get_doc({
		"creation": current_date,
		"doctype": "Opportunity",
		"enquiry_from": "Customer",
		"customer": get_random("Customer"),
		"enquiry_type": "Sales",
		"transaction_date": current_date,
	})

	add_random_children(b, "items", rows=4, randomize = {
		"qty": (1, 5),
		"item_code": ("Item", {"has_variants": "0"})
	}, unique="item_code")

	b.insert()
	frappe.db.commit()

def make_quotation(current_date):
	# get open opportunites
	opportunity = get_random("Opportunity", {"status": "Open"})

	if opportunity:
		from erpnext.crm.doctype.opportunity.opportunity import make_quotation
		qtn = frappe.get_doc(make_quotation(opportunity))
		qtn.insert()
		frappe.db.commit()
		qtn.submit()
		frappe.db.commit()
	else:
		# make new directly

		# get customer, currency and exchange_rate
		customer = get_random("Customer")

		company_currency = frappe.db.get_value("Company", "Wind Power LLC", "default_currency")
		party_account_currency = get_party_account_currency("Customer", customer, "Wind Power LLC")
		if company_currency == party_account_currency:
			exchange_rate = 1
		else:
			exchange_rate = get_exchange_rate(party_account_currency, company_currency)

		qtn = frappe.get_doc({
			"creation": current_date,
			"doctype": "Quotation",
			"quotation_to": "Customer",
			"customer": customer,
			"currency": party_account_currency or company_currency,
			"conversion_rate": exchange_rate,
			"order_type": "Sales",
			"transaction_date": current_date,
		})

		add_random_children(qtn, "items", rows=3, randomize = {
			"qty": (1, 5),
			"item_code": ("Item", {"has_variants": "0"})
		}, unique="item_code")

		qtn.insert()
		frappe.db.commit()
		qtn.submit()
		frappe.db.commit()

def make_sales_order(current_date):
	q = get_random("Quotation", {"status": "Submitted"})
	if q:
		from erpnext.selling.doctype.quotation.quotation import make_sales_order
		so = frappe.get_doc(make_sales_order(q))
		so.transaction_date = current_date
		so.delivery_date = frappe.utils.add_days(current_date, 10)
		so.insert()
		frappe.db.commit()
		so.submit()
		frappe.db.commit()


# 第一列不能有 4
import pandas as pd
import numpy as np

TRUTH_PATH = "/Users/luminshen/Documents/代码/PycharmProjects/Research/-GAN-/Table-GAN/tableGAN/data/Adult/Adult.csv"
SAVE_PATH = "./data_with_rule_single_rule.csv"

def single_cell_rule():
    file = pd.read_csv(TRUTH_PATH, sep=',')
    file = list(np.array(file))
    res = []
    for row in file:
        if row[1] == 4:
            row[1] = 6
        res.append(row)
    res = np.array(res)
    rsf_out = pd.DataFrame(res)
    rsf_out.to_csv(
        "/Users/luminshen/Documents/代码/PycharmProjects/Research/-GAN-/Table-GAN/tableGAN/data/Adult/Adult_rule.csv",
        index=False, sep=',')
    print("输出完成！", res.shape)

def combine_rule():
    file = pd.read_csv(TRUTH_PATH, sep=',')
    labels = pd.read_csv(
        "/Users/luminshen/Documents/代码/PycharmProjects/Research/-GAN-/Table-GAN/tableGAN/data/Adult/Adult_labels.csv",
        sep=',')
    labels_ = list(np.array(labels))
    file = list(np.array(file))
    positive = []
    labels = []
    negative = []
    col_1 = 0
    col_2 = 9
    for (i, _), label in zip(enumerate(file), labels_):
        is_true = True
        threshold = 0
        for j, _ in enumerate(file):
            if file[i][col_1] == file[j][col_1] and file[i][col_2] == file[j][col_2]:
                threshold -= 1
                if threshold <= 0:
                    is_true = False
                    negative.append(file[i])
                    labels.append([1])
                    break
        if is_true:
            positive.append(file[i])
            labels.append([0])
            # labels.append(label[0])
    X = np.array(positive + negative)
    # X = np.array(positive)
    y = np.array(labels)
    X_out = pd.DataFrame(X)
    y_out = pd.DataFrame(y)
    X_out.to_csv(
        "/Users/luminshen/Documents/代码/PycharmProjects/Research/-GAN-/Table-GAN/tableGAN/data/Adult/Adult_rule.csv",
        index=False, sep=',')
    y_out.to_csv(
        "/Users/luminshen/Documents/代码/PycharmProjects/Research/-GAN-/Table-GAN/tableGAN/data/Adult/Adult_rule_labels.csv",
        index=False, sep=',')

    # print(res)
    file_rule = pd.read_csv(
        "/Users/luminshen/Documents/代码/PycharmProjects/Research/-GAN-/Table-GAN/tableGAN/data/Adult/Adult_rule.csv",
        sep=',')
    file = list(np.array(file_rule))
    error = 0
    for i, _ in enumerate(file):
        for j, _ in enumerate(file):
            if j <= i:
                continue
            if file[i][col_1] == file[j][col_1] and file[i][col_2] > file[j][col_2]:
                error += 1
    print(
        "输出完成！X_shape:{}, y_shape:{}, error: {}, error rate:{}".format(X.shape, y.shape, error, error / len(file) ** 2))

# single_cell_rule()
combine_rule()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def ui_input() -> str:
    """This function takes player's cards"""
    return input('Enter all your cards (with spaces): ')

def blackjack(cards: str) -> int:
    """This function counts points"""
    cards_values = { '2': 2, '3': 3, '4': 4,
                     '5': 5, '6': 6, '7': 7,
                     '8': 8, '9': 9, 'T': 10,
                     'J': 10, 'Q': 10, 'K': 10
                   }
    a_num = 0
    points = 0
    for card in cards.split():
        if card in cards_values:
            points = points + cards_values[card]
        elif card == 'A':
            a_num = a_num + 1

    if a_num > 0:
        for _ in  range(a_num):
            if a_num > 1:
                points = points + 1
                a_num = a_num - 1
            else:
                if points + 11 < 22:
                    points = points + 11
                else:
                    points = points + 1

    return points

def ui_output(points: int) -> None:
    """This function prints the result"""
    if points <= 21:
        print('Your points: ', points)
    else:
        print('Bust')

ui_output(blackjack(ui_input()))


from ..utils import Object

class ChatStatisticsMessageSenderInfo(Object):
    """
    Contains statistics about messages sent by a user

    Attributes:
        ID (:obj:`str`): ``ChatStatisticsMessageSenderInfo``

    Args:
        user_id (:obj:`int`):
            User identifier
        sent_message_count (:obj:`int`):
            Number of sent messages
        average_character_count (:obj:`int`):
            Average number of characters in sent messages; 0 if unknown

    Returns:
        ChatStatisticsMessageSenderInfo

    Raises:
        :class:`telegram.Error`
    """
    ID = "chatStatisticsMessageSenderInfo"

    def __init__(self, user_id, sent_message_count, average_character_count, **kwargs):

        self.user_id = user_id  # int
        self.sent_message_count = sent_message_count  # int
        self.average_character_count = average_character_count  # int

    @staticmethod
    def read(q: dict, *args) -> "ChatStatisticsMessageSenderInfo":
        user_id = q.get('user_id')
        sent_message_count = q.get('sent_message_count')
        average_character_count = q.get('average_character_count')
        return ChatStatisticsMessageSenderInfo(user_id, sent_message_count, average_character_count)


# Adapted from https://github.com/mimoralea/gdrl
from helpers.utils.action_selection import GreedyStrategy, NormalNoiseStrategy
from helpers.utils.priority_replay import Memory
from helpers.nn.network import FCQV, FCDP
from itertools import count
import torch.optim as optim
import numpy as np
import torch
import time
import glob
import os
import gc

LEAVE_PRINT_EVERY_N_SECS = 300
RESULTS_DIR = os.path.join('..', 'results')
ERASE_LINE = '\x1b[2K'

class DDPG_agent:
    def __init__(self, policy_info={}, value_info={}, env_info={}, training_info={}, buffer_info={}):
        # set device target
        self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

        ### POLICY NETWORK PARAMETERS
        self.online_policy_model = FCDP(env_info["state_size"], env_info["bounds"],
                                    policy_info["hidden_dims"], device=self.device)
        self.target_policy_model = FCDP(env_info["state_size"], env_info["bounds"],
                                    policy_info["hidden_dims"], device=self.device)
        self.policy_optimizer = optim.Adam(self.online_policy_model.parameters(), lr=policy_info["learning_rate"])
        self.policy_max_grad_norm = policy_info["max_grad_norm"]

        ### VALUE NETWORK PARAMETERS
        self.online_value_model = FCQV(env_info["state_size"], env_info["action"],
                                    value_info["hidden_dims"], device=self.device)
        self.target_value_model = FCQV(env_info["state_size"], env_info["action"],
                                    value_info["hidden_dims"], device=self.device)
        self.value_optimizer = optim.Adam(self.online_value_model.parameters(), lr=value_info["learning_rate"])
        self.value_max_grad_norm = value_info["max_grad_norm"]

        # TRAINING AND EVALUATION STRATEGY
        self.training_strategy = NormalNoiseStrategy(env_info["bounds"], training_info["exploration_noise_ratio"])
        self.update_target_every_steps  = training_info["update_every_step"]
        self.evaluation_strategy = GreedyStrategy(env_info["bounds"])
        self.n_warmup_batches = training_info["n_warmup_batches"]
        self.soft_weight_tau = training_info.get("weight_mix_ratio", None)

        # MEMORY INITIALIZATION
        self.replay_buffer = Memory(capacity=buffer_info["size"], seed=training_info["seed"])
        self.batch_size = buffer_info["batch_size"]

        # seed
        torch.manual_seed(training_info["seed"]);
        self.rand_generator = np.random.RandomState(training_info["seed"])

        # lower and upper action value bounds
        self.low_bounds, self.high_bounds = env_info["bounds"]

    def prepopulate(self, brain_name, env):
        """
            First thing called after environment has been setup
            To aviod the empty memory problem we randomly pre populate the memory. This is done
            by taking random actions and storing them as experiences
            Args:
                brain_name: (string) name of agent we are using
                env: (object) Environment we are operating in
        """
        # flag for when to reset the environment [when we hit a terminal state]
        reset_check, last_state = False, None

        for idx in range(self.replay_buffer.tree.capacity):
            # if idx is the first step get state or we have to reset
            if idx == 0 or reset_check:
                # change reset check back to false
                reset_check = False
                # resent environment and extract current state
                env_info   = env.reset(train_mode=True)[brain_name]
                last_state = env_info.vector_observations[0]

            # take random actions within acceptable bounds
            action = self.rand_generator.uniform(low=self.low_bounds,
                                                 high=self.high_bounds,
                                                 size=len(self.high_bounds))
            # take the action, recod reward, and terminal status
            env_info = env.step(action)[brain_name]
            reward   = env_info.rewards[0]
            done     = env_info.local_done[0]

            # checking status
            if done:
                # set reset flag
                reset_check = True
                state = np.zeros(last_state.shape)
                # store in replay
                self.replay_buffer.store(last_state, action, reward, state, done)
            else:
                # get next state from the environment
                state = env_info.vector_observations[0]
                # store in replay
                self.replay_buffer.store(last_state, action, reward, state, done)
                # update state
                last_state = state

    def update_networks(self, tau=0.1):
        tau = self.soft_weight_tau if self.soft_weight_tau is not None else tau
        # copy value model
        for target, online in zip(self.target_value_model.parameters(),
                                  self.online_value_model.parameters()):
            target_ratio = (1.0 - tau) * target.data
            online_ratio = tau * online.data
            mixed_weights = target_ratio + online_ratio
            target.data.copy_(mixed_weights)

        # copy policy model
        for target, online in zip(self.target_policy_model.parameters(),
                                  self.online_policy_model.parameters()):
            target_ratio = (1.0 - tau) * target.data
            online_ratio = tau * online.data
            mixed_weights = target_ratio + online_ratio
            target.data.copy_(mixed_weights)

    def load(self, states, actions, rewards, next_states, is_terminals):
        # convert to torch tensors
        states = torch.from_numpy(states).float().to(self.device)
        actions = torch.from_numpy(actions).float().to(self.device)
        next_states = torch.from_numpy(next_states).float().to(self.device)
        rewards = torch.from_numpy(rewards).float().to(self.device)
        is_terminals = torch.from_numpy(is_terminals).float().to(self.device)

        # returns tensors
        return states, actions, rewards, next_states, is_terminals

    def optimize_model(self):
        # priotized replay used so we can update optimize on the go: we get the batch indexes, memory,
        # importance sampling
        idx_batch, memory_batch, ISweights = self.replay_buffer.sample_per(self.batch_size)

        # convert sampling weights to tensor
        ISweights = torch.from_numpy(ISweights).float().to(self.device)
        # unwrap
        states, actions, rewards, next_states, is_terminals = self.replay_buffer.unwrap_experiences(memory_batch)
        # convert to torch
        states, actions, rewards, next_states, is_terminals = self.load(states, actions, rewards, next_states, is_terminals)

        ## Target policy
        # get maximum policy over all states
        argmax_a_q_sp = self.target_policy_model(next_states)
        # calculate the q values corresponding to the policy above
        max_a_q_sp = self.target_value_model(next_states, argmax_a_q_sp)
        # calculate the TD target q_state action values
        target_q_sa = rewards + self.gamma * max_a_q_sp * (1 - is_terminals)
        ## Online value
        # for each state action pair we calculate the q_values
        q_sa = self.online_value_model(states, actions)

        ## Loss calculations
        td_error_loss = q_sa - target_q_sa.detach()
        # calculate absolute error: convert to numpy
        abs_error = torch.abs(td_error_loss).cpu().detach().numpy()
        # update PER
        self.replay_buffer.batch_update(idx_batch, abs_error.squeeze())
        # calculate value loss using weight mean square error
        value_loss = (ISweights * td_error_loss).mul(0.5).pow(2).mean()

        # zero optimizer, do a backward pass, clip gradients, and finally optimizer
        self.value_optimizer.zero_grad()
        value_loss.backward()
        torch.nn.utils.clip_grad_norm_(self.online_value_model.parameters(),
                                        self.value_max_grad_norm)
        self.value_optimizer.step()

        ## ONLINE POLICY
        argmax_a_q_s = self.online_policy_model(states)
        max_a_q_s = self.online_value_model(states, argmax_a_q_s)

        ## calculate loss using weighted mean
        policy_loss = -(ISweights * max_a_q_s).mean()
        self.policy_optimizer.zero_grad()
        policy_loss.backward()
        torch.nn.utils.clip_grad_norm_(self.online_policy_model.parameters(),
                                        self.policy_max_grad_norm)
        self.policy_optimizer.step()

    def interaction_step(self, last_state, env, brain_name):
        # initially we randomly explore the sample space
        check = self.replay_buffer.current_storage_size <  self.n_warmup_batches * self.batch_size
        action = self.training_strategy.select_action(self.online_policy_model, last_state, check)

        # get environment values
        env_info  = env.step(action)[brain_name]
        state     = env_info.vector_observations[0]
        reward    = env_info.rewards[0]
        done      = env_info.local_done[0]

        # store into replay buffer
        self.replay_buffer.store(last_state, action, reward, state, done)

        # update tracking parameters
        self.episode_reward[-1] += reward
        self.episode_timestep[-1] += 1
        self.episode_exploration[-1] += self.training_strategy.ratio_noise_injected

        # return values
        return state, done

    def train(self, env, brain_name, gamma, max_minutes, max_episodes, goal_mean_100_reward):
        # initialize tracking parameters
        self.episode_timestep = []
        self.episode_reward = []
        self.episode_seconds = []
        self.evaluation_scores = []
        self.episode_exploration = []
        self.gamma = gamma

        # loop parameters
        total_steps = 0
        training_time = 0
        training_start, last_debug_time = time.time(), float("-inf")

        # storage for results
        results = np.empty((max_episodes, 5))
        results[:] = np.nan

        # start training loop
        for episode in range(1, max_episodes + 1):
            # episode start tick
            episode_start = time.time()

            # refresh environment
            state = env.reset(train_mode=True)[brain_name].vector_observations[0]
            is_terminal =  False
            self.episode_reward.append(0.0)
            self.episode_timestep.append(0.0)
            self.episode_exploration.append(0.0)

            for step in count():
                state, is_terminal = self.interaction_step(state, env, brain_name)
                # after making random steps
                check = self.replay_buffer.current_storage_size >  (self.n_warmup_batches * self.batch_size)
                if check:
                    # run optimization
                    self.optimize_model()

                # updates every episode
                if np.sum(self.episode_timestep) % self.update_target_every_steps == 0:
                    self.update_networks()

                if is_terminal:
                    gc.collect()
                    break

            # stat tracking
            episode_elapsed = time.time() - episode_start
            self.episode_seconds.append(episode_elapsed)
            training_time += episode_elapsed
            evaluation_score, _ = self.evaluate(self.online_policy_model, env, brain_name)
            self.save_checkpoint(episode - 1, self.online_policy_model)

            total_steps = int(np.sum(self.episode_timestep))
            self.evaluation_scores.append(evaluation_score)

            # mean and std calculations
            mean_10_reward = np.mean(self.episode_reward[-10:])
            std_10_reward = np.std(self.episode_reward[-10:])
            mean_100_reward = np.mean(self.episode_reward[-100:])
            std_100_reward = np.std(self.episode_reward[-100:])

            mean_100_eval_score = np.mean(self.evaluation_scores[-100:])
            std_100_eval_score = np.std(self.evaluation_scores[-100:])

            lst_100_exp_rat = np.array(self.episode_exploration[-100:]) / np.array(self.episode_timestep[-100:])
            mean_100_exp_rat = np.mean(lst_100_exp_rat)
            std_100_exp_rat = np.std(lst_100_exp_rat)

            wallclock_elapsed = time.time() - training_start
            results[episode - 1] = total_steps, mean_100_reward, mean_100_eval_score, \
                                training_time, wallclock_elapsed

            reached_debug_time = time.time() - last_debug_time >= LEAVE_PRINT_EVERY_N_SECS
            # termination criteria check
            reached_max_minutes = wallclock_elapsed >= max_minutes * 60
            reached_max_episodes = episode >= max_episodes
            reached_goal_mean_reward = mean_100_eval_score >= goal_mean_100_reward
            training_over = reached_max_minutes or reached_max_episodes or reached_goal_mean_reward

            # message string
            elapsed_str = time.strftime("%H:%M:%S", time.gmtime(time.time() - training_start))
            debug_message = 'el {}, ep {:04}, ts {:07}, '
            debug_message += 'ar_10 ts {:05.1f} \u00B1 {:05.1f}, '
            debug_message += 'ar_100 ts {:05.1f} \u00B1 {:05.1f}, '
            debug_message += 'ex 100 {:02.1f} \u00B1 {:02.1f}, '
            debug_message += 'ev {:05.1f} \u00B1 {:05.1f}'
            debug_message = debug_message.format(elapsed_str, episode - 1, total_steps,
                                                 mean_10_reward, std_10_reward,
                                                 mean_100_reward, std_100_reward,
                                                 mean_100_exp_rat, std_100_exp_rat,
                                                 mean_100_eval_score, std_100_eval_score)
            print(debug_message, flush=True)
            if reached_debug_time or training_over:
                print("Debug Message")
                print(debug_message, flush=True)
                last_debug_time = time.time()

            if training_over:
                if reached_max_minutes: print(u'--> reached_max_minutes \u2715')
                if reached_max_episodes: print(u'--> reached_max_episodes \u2715')
                if reached_goal_mean_reward: print(u'--> reached_goal_mean_reward \u2713')
                break

        # get score for last round
        final_eval_score, score_std = self.evaluate(self.online_policy_model, env, brain_name, n_episodes=100)
        wallclock_time = time.time() - training_start
        print("Training complete.")
        print('Final evaluation score {:.2f}\u00B1{:.2f} in {:.2f}s training time,'
              ' {:.2f}s wall-clock time.\n'.format(
                  final_eval_score, score_std, training_time, wallclock_time))

        # close and delete the environment
        env.close() ; del env
        self.get_cleaned_checkpoints()
        return results, final_eval_score, training_time, wallclock_time

    def evaluate(self, eval_policy_model, eval_env, brain_name, n_episodes=1):
        rs = []

        for _ in range(n_episodes):
            env_info   = eval_env.reset(train_mode=True)[brain_name]
            state, done = env_info.vector_observations[0], False
            rs.append(0)
            for _ in count():
                action = self.evaluation_strategy.select_action(eval_policy_model, state)
                env_info = eval_env.step(action)[brain_name]
                state    = env_info.vector_observations[0]
                reward   = env_info.rewards[0]
                done     = env_info.local_done[0]
                rs[-1] += reward

                if done: break

        # return mean and standard deviation
        return np.mean(rs), np.std(rs)

    def save_checkpoint(self, episode_idx, model):
        torch.save(model.state_dict(),
                   os.path.join("results", "checkpoint_models", 'model.{}.tar'.format(episode_idx)))

    def get_cleaned_checkpoints(self, n_checkpoints=4):
        try:
            return self.checkpoint_paths
        except AttributeError:
            self.checkpoint_paths = {}

        paths = glob.glob(os.path.join("results", "checkpoint_models", '*.tar'))
        paths_dic = {int(path.split('.')[-2]): path for path in paths}
        last_ep = max(paths_dic.keys())
        checkpoint_idxs = np.linspace(1, last_ep + 1, n_checkpoints, endpoint=True, dtype=np.int) - 1

        for idx, path in paths_dic.items():
            if idx in checkpoint_idxs:
                self.checkpoint_paths[idx] = path
            else:
                os.unlink(path)


# -*- coding: utf-8 -*-

from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand

class PyTest(TestCommand):
    ptest_args = []

    def initialize_options(self):
        TestCommand.initialize_options(self)
        self.pytest_args = []

    def run(self):
        import pytest
        pytest.main(self.pytest_args)

setup(
    name='PyIEProxy',
    version='0.1.0',
    description='Python IE Proxy Switch',
    url='https://github.com/magichan-lab/pyieproxy',
    author='Magichan',
    author_email='magichan.lab@gmail.com',
    maintainer='Magichan',
    maintainer_email='magichan.lab@gmail.com',
    license='MIT',
    packages=find_packages(exclude=["*.tests"]),
    install_requires=['wheel', 'requests'],
    zip_safe=False,
    entry_points={
        'console_scripts': [
            'ie-proxy = bin.command:main',
        ]},
    extras_require={
        'test': ['pytest-cov',
                 'pytest-pep8',
                 'coverage',
                 'pep8',
                 'pytest'],
        'docs': ['sphinx'],
    },
    cmdclass={'test': PyTest},
)