from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QFileDialog, QMessageBox, QInputDialog
import D_Applicazione
import D_Mixer
import cv2
import glob
import os
import numpy as np

class Ui_MainWindow(object):

    # METODO PER SALVARE IL PERCORSO DEL DATASET
    def salvaDataset (self, pathDataset):
        self.pathDataset = pathDataset

    def salvaNumeroFoto (self, numFoto):
        self.numFoto = numFoto
        print(self.numFoto)

    def setupUi(self, MainWindow):

        # SET DELLA FINESTRA PRINCIPALE DEL PROGRAMMA
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1112, 788)
        MainWindow.setStyleSheet("background-color: rgb(144, 200, 160);")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # SET DELLA GROUPBOX RIFERITA AL CONFRONTO TRAMITE TECNICHE
        self.groupBox_confronto = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_confronto.setGeometry(QtCore.QRect(20, 20, 1081, 391))
        font = QtGui.QFont()
        font.setFamily("OpineHeavy")
        font.setPointSize(18)
        self.groupBox_confronto.setFont(font)
        self.groupBox_confronto.setAutoFillBackground(False)
        self.groupBox_confronto.setStyleSheet("background-color: rgb(200, 200, 200);")
        self.groupBox_confronto.setFlat(True)
        self.groupBox_confronto.setCheckable(False)
        self.groupBox_confronto.setChecked(False)
        self.groupBox_confronto.setObjectName("groupBox_confronto")
        self.groupBox_confrontoInput = QtWidgets.QGroupBox(self.groupBox_confronto)
        self.groupBox_confrontoInput.setGeometry(QtCore.QRect(360, 70, 341, 311))
        font = QtGui.QFont()
        font.setFamily("OpineHeavy")
        font.setPointSize(11)
        self.groupBox_confrontoInput.setFont(font)
        self.groupBox_confrontoInput.setStyleSheet("background-color: rgb(200, 200, 200);")
        self.groupBox_confrontoInput.setFlat(True)
        self.groupBox_confrontoInput.setObjectName("groupBox_confrontoInput")
        self.groupBox_confrontoInput.setTitle("Immagine Input")

        # SET LABEL IN CUI VIENE INSERITA L'IMMAGINE INPUT
        self.label_confrontoFoto = QtWidgets.QLabel(self.groupBox_confrontoInput)
        self.label_confrontoFoto.setGeometry(QtCore.QRect(0, 20, 341, 291))
        self.label_confrontoFoto.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.label_confrontoFoto.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.label_confrontoFoto.setFrameShadow(QtWidgets.QFrame.Plain)
        self.label_confrontoFoto.setLineWidth(1)
        self.label_confrontoFoto.setText("")
        self.label_confrontoFoto.setObjectName("label_confrontoFoto")

        # SET GROUPBOX PER LA VISUALIZZAZIONE DELLE IMMAGINE IN OUTPUT
        self.groupBox_confrontoOutput = QtWidgets.QGroupBox(self.groupBox_confronto)
        self.groupBox_confrontoOutput.setGeometry(QtCore.QRect(720, 70, 331, 311))
        font = QtGui.QFont()
        font.setFamily("OpineHeavy")
        font.setPointSize(11)
        self.groupBox_confrontoOutput.setFont(font)
        self.groupBox_confrontoOutput.setStyleSheet("background-color: rgb(200, 200, 200);")
        self.groupBox_confrontoOutput.setTitle("Immagini Output")
        self.groupBox_confrontoOutput.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.groupBox_confrontoOutput.setFlat(True)
        self.groupBox_confrontoOutput.setObjectName("groupBox_confrontoOutput")

        # SET SCROLL AREA PER LA VISUALIZZAZIONE DELLE IMMAGINI IN OUTPUT
        self.scroll_area_confrontoOutput = QtWidgets.QScrollArea(self.groupBox_confrontoOutput)
        self.scroll_area_confrontoOutput.setGeometry(QtCore.QRect(0, 20, 331, 291))
        self.scroll_area_confrontoOutput.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.scroll_area_confrontoOutput.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.scroll_area_confrontoOutput.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scroll_area_confrontoOutput.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
        self.scroll_area_confrontoOutput.setWidgetResizable(True)
        self.scroll_area_confrontoOutput.setObjectName("scroll_area_confrontoOutput")

        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 329, 289))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.scrollAreaWidgetContents.setFixedWidth(327)
        self.scrollAreaWidgetContents.setAutoFillBackground(True)

        self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)
        self.verticalLayout.setObjectName("verticalLayout")

        # PERMETTERE LA VISIONE DELLA FOTO IN OUTPUT CON LE SCROLL BARS
        self.scroll_area_confrontoOutput.setWidget(self.scrollAreaWidgetContents)

        # SET COMBOBOX (MENU A TENDINA) PER LA SCELTA DELLA TECNICA DI CONFRONTO
        self.comboBox_confronto = QtWidgets.QComboBox(self.groupBox_confronto)
        self.comboBox_confronto.setGeometry(QtCore.QRect(50, 180, 265, 31))
        font = QtGui.QFont()
        font.setFamily("Verdana")
        font.setPointSize(11)
        self.comboBox_confronto.setFont(font)
        self.comboBox_confronto.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.comboBox_confronto.setObjectName("comboBox_confronto")
        self.comboBox_confronto.addItem("")
        self.comboBox_confronto.addItem("")
        self.comboBox_confronto.addItem("")

        # SET LABEL PER IL TITOLO ("Scelta tecnica di confronto...")
        self.label_confronto = QtWidgets.QLabel(self.groupBox_confronto)
        self.label_confronto.setGeometry(QtCore.QRect(10, 70, 341, 61))
        font = QtGui.QFont()
        font.setFamily("Yu Gothic UI Semibold")
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_confronto.setFont(font)
        self.label_confronto.setStyleSheet("background-color: rgb(200, 200, 200);")
        self.label_confronto.setFrameShape(QtWidgets.QFrame.Box)
        self.label_confronto.setFrameShadow(QtWidgets.QFrame.Plain)
        self.label_confronto.setLineWidth(0)
        self.label_confronto.setMidLineWidth(0)
        self.label_confronto.setAlignment(QtCore.Qt.AlignCenter)
        self.label_confronto.setObjectName("label_confronto")

        # SET BOTTONE "cerca" PER L'APPLICAZIONE DELLA TECNICA DI CONFRONTO
        self.pushButton_cercaConfronto = QtWidgets.QPushButton(self.groupBox_confronto)
        self.pushButton_cercaConfronto.setGeometry(QtCore.QRect(130, 310, 100, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_cercaConfronto.setFont(font)
        self.pushButton_cercaConfronto.setStyleSheet("background-color: rgb(47, 141, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"")

        # INSERIMENTO IMMAGINE AL BOTTONE "cerca"
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../Lente nera-trasparente.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        icon.addPixmap(QtGui.QPixmap("D:/Cose DODO/UNI/3^ Anno/Comunicazione Multimediale/Progetto/Lente nera-trasparente.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.pushButton_cercaConfronto.setIcon(icon)
        self.pushButton_cercaConfronto.setIconSize(QtCore.QSize(20, 20))
        self.pushButton_cercaConfronto.setObjectName("pushButton_cercaConfronto")

        # SET LABEL RIFERITA ALL'INSERIMENTO DELL'IMMAGINE INPUT
        self.label_confronto_2 = QtWidgets.QLabel(self.groupBox_confronto)
        self.label_confronto_2.setGeometry(QtCore.QRect(360, 30, 341, 31))
        font = QtGui.QFont()
        font.setFamily("Yu Gothic UI Semibold")
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.label_confronto_2.setFont(font)
        self.label_confronto_2.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.label_confronto_2.setFrameShape(QtWidgets.QFrame.Box)
        self.label_confronto_2.setFrameShadow(QtWidgets.QFrame.Plain)
        self.label_confronto_2.setLineWidth(1)
        self.label_confronto_2.setMidLineWidth(0)
        self.label_confronto_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        self.label_confronto_2.setObjectName("label_confronto_2")

        # SET BOTTONE "browse" PER L'INSERIMENTO DI UN' IMMAGINE INPUT
        self.pushButton_browseInput = QtWidgets.QPushButton(self.groupBox_confronto)
        self.pushButton_browseInput.setGeometry(QtCore.QRect(710, 30, 110, 31))
        font = QtGui.QFont()
        font.setPointSize(7)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_browseInput.setFont(font)
        self.pushButton_browseInput.setStyleSheet("background-color: rgb(47, 141, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;")

        #SET BOTTONE "browse" PER LA SCELTA DEL "file index.csv"
        self.pushButton_browseIndex = QtWidgets.QPushButton(self.groupBox_confronto)
        self.pushButton_browseIndex.setGeometry(QtCore.QRect(830, 30, 110, 31))
        font = QtGui.QFont()
        font.setPointSize(7)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_browseIndex.setFont(font)
        self.pushButton_browseIndex.setStyleSheet("background-color: rgb(47, 141, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;")

        #SET BOTTONE "browse" PER LA SCELTA DEL DATASET
        self.pushButton_browseDataset = QtWidgets.QPushButton(self.groupBox_confronto)
        self.pushButton_browseDataset.setGeometry(QtCore.QRect(950, 30, 110, 31))
        font = QtGui.QFont()
        font.setPointSize(7)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_browseDataset.setFont(font)
        self.pushButton_browseDataset.setStyleSheet("background-color: rgb(47, 141, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;")

        # INSERIMENTO IMMAGINE AL BOTTONE "browse"
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("../simbolo upload-trasparente.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        icon1.addPixmap(QtGui.QPixmap("D:/Cose DODO/UNI/3^ Anno/Comunicazione Multimediale/Progetto/simbolo upload-trasparente.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.pushButton_browseInput.setIcon(icon1)
        self.pushButton_browseInput.setIconSize(QtCore.QSize(15, 15))
        self.pushButton_browseInput.setObjectName("pushButton_browseInput")

        # SET DELLA GROUPBOX RIFERITA AL CONFRONTO TRAMITE LABELS ("parola chiave")
        self.groupBox_sceltaLabel = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_sceltaLabel.setGeometry(QtCore.QRect(20, 450, 701, 281))
        font = QtGui.QFont()
        font.setFamily("OpineHeavy")
        font.setPointSize(18)
        self.groupBox_sceltaLabel.setFont(font)
        self.groupBox_sceltaLabel.setStyleSheet("background-color: rgb(211, 211, 211);")
        self.groupBox_sceltaLabel.setFlat(True)
        self.groupBox_sceltaLabel.setObjectName("groupBox_sceltaLabel")

        # SET COMBOBOX (MENU A TENDINA) PER LA SCELTA DELLA LABEL ("parola chiave") PER IL CONFRONTO
        self.comboBox_sceltaLabel = QtWidgets.QComboBox(self.groupBox_sceltaLabel)
        self.comboBox_sceltaLabel.setGeometry(QtCore.QRect(100, 180, 181, 31))
        font = QtGui.QFont()
        font.setPointSize(11)
        self.comboBox_sceltaLabel.setFont(font)
        self.comboBox_sceltaLabel.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.comboBox_sceltaLabel.setObjectName("comboBox_sceltaLabel")
        self.comboBox_sceltaLabel.addItem("")
        self.comboBox_sceltaLabel.addItem("")
        self.comboBox_sceltaLabel.addItem("")
        self.comboBox_sceltaLabel.addItem("")
        self.comboBox_sceltaLabel.addItem("")

        # SET LABEL PER IL TITOLO ("Scelta label...")
        self.label_sceltaLabel = QtWidgets.QLabel(self.groupBox_sceltaLabel)
        self.label_sceltaLabel.setGeometry(QtCore.QRect(10, 70, 341, 61))
        font = QtGui.QFont()
        font.setFamily("Yu Gothic UI")
        font.setPointSize(17)
        font.setBold(True)
        font.setWeight(75)
        self.label_sceltaLabel.setFont(font)
        self.label_sceltaLabel.setLineWidth(1)
        self.label_sceltaLabel.setMidLineWidth(0)
        self.label_sceltaLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.label_sceltaLabel.setObjectName("label_sceltaLabel")

        # SET BOTTONE "cerca" PER L'APPLICAZIONE DELLA LABEL ("parola chiave")
        self.pushButton_cercaLabel = QtWidgets.QPushButton(self.groupBox_sceltaLabel)
        self.pushButton_cercaLabel.setGeometry(QtCore.QRect(520, 140, 100, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_cercaLabel.setFont(font)
        self.pushButton_cercaLabel.setStyleSheet("background-color: rgb(47, 141, 255);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;\n"
"")

        # INSERIMENTO IMMAGINE AL BOTTONE "cerca"
        self.pushButton_cercaLabel.setIcon(icon)
        self.pushButton_cercaLabel.setIconSize(QtCore.QSize(20, 20))
        self.pushButton_cercaLabel.setObjectName("pushButton_cercaLabel")

        # SET DELLA LABEL CONTENENTE IL LOGO DEL NOSTRO GRUPPO ("4 immagini 1 gruppo")
        self.label_logo = QtWidgets.QLabel(self.centralwidget)
        self.label_logo.setGeometry(QtCore.QRect(830, 450, 181, 181))
        self.label_logo.setFrameShape(QtWidgets.QFrame.Box)
        self.label_logo.setText("")
        self.label_logo.setPixmap(QtGui.QPixmap("/Users/lucacampana/Desktop/4Immagini1Gruppo/4immagini1Gruppo.jpeg"))
        self.label_logo.setScaledContents(True)
        self.label_logo.setObjectName("label_logo")

        # SET BOTTONE "reset"
        self.pushButton_reset = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_reset.setGeometry(QtCore.QRect(870, 700, 101, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_reset.setFont(font)
        self.pushButton_reset.setStyleSheet("background-color: rgb(255, 0, 0);\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 15px;\n"
"border-color: black;\n"
"padding: 4px;")

        # INSERIMENTO IMMAGINE AL BOTTONE "reset"
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("../freccia reset-trasparente.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        icon2.addPixmap(QtGui.QPixmap("D:/Cose DODO/UNI/3^ Anno/Comunicazione Multimediale/Progetto/freccia reset-trasparente.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.pushButton_reset.setIcon(icon2)
        self.pushButton_reset.setObjectName("pushButton_reset")
        MainWindow.setCentralWidget(self.centralwidget)

        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1112, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        # CHIAMATA METODO SET TITLE PER LE COMPONENTI DELL'INTEFACCIA
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        # CHIAMATA METODO CARICAMENTO IMMAGINE BOTTONE "BROWSER" PER L'IMMAGINE
        self.pushButton_browseInput.clicked.connect(self.openImage)

        # CHIAMATA METODO CARICAMENTO IMMAGINE BOTTONE "BROWSER" PER IL FILE "index.csv"
        self.pushButton_browseIndex.clicked.connect(self.openIndex)

        # CHIAMATA METODO CARICAMENTO IMMAGINE BOTTONE "BROWSER" PER IL DATASET
        self.pushButton_browseDataset.clicked.connect(self.openDataset)

        # CHIAMATA METODO CERCA IMMAGINE TRAMITE CONFRONTO BOTTONE "CERCA-CONFRONTO"
        self.pushButton_cercaConfronto.clicked.connect(self.inputNumeroFotoAlg)

        # CHIAMATA METODO CERCA IMMAGINE TRAMITE LABELS
        self.pushButton_cercaLabel.clicked.connect(self.inputNumeroFotoLabels)

        # CHIAMATA METODI PULIZIA BOTTONE "RESET"
        self.pushButton_reset.clicked.connect(self.reset)

    # DEFINIZIONE FUNZIONE PER IL SET DEI TITOLI ALLE COMPONENTI DELL'INTERFACCIA
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.groupBox_confronto.setTitle(_translate("MainWindow", "Input Immagine"))
        self.groupBox_confrontoInput.setTitle(_translate("MainWindow", "Immagine Input"))
        self.comboBox_confronto.setItemText(0, _translate("MainWindow", "..."))
        self.comboBox_confronto.setItemText(1, _translate("MainWindow", "Confronto per istogrammi"))
        self.comboBox_confronto.setItemText(2, _translate("MainWindow", "Tecnica Sift"))
        self.label_confronto.setText(_translate("MainWindow", "Scelta tecnica di confronto..."))
        self.pushButton_cercaConfronto.setText(_translate("MainWindow", "CERCA"))
        self.label_confronto_2.setText(_translate("MainWindow", "premere per inserire foto, index file e dataset -->"))
        self.pushButton_browseInput.setText(_translate("MainWindow", "Browse pic"))
        self.pushButton_browseIndex.setText(_translate("MainWindow", "Browse index"))
        self.pushButton_browseDataset.setText(_translate("MainWindow", "Browse dataset"))
        self.groupBox_sceltaLabel.setTitle(_translate("MainWindow", "Labels"))
        self.comboBox_sceltaLabel.setItemText(0, _translate("MainWindow", "..."))
        self.comboBox_sceltaLabel.setItemText(1, _translate("MainWindow", "Edifici"))
        self.comboBox_sceltaLabel.setItemText(2, _translate("MainWindow", "Calcio"))
        self.comboBox_sceltaLabel.setItemText(3, _translate("MainWindow", "Tramonto"))
        self.comboBox_sceltaLabel.setItemText(4, _translate("MainWindow", "Mare"))
        self.label_sceltaLabel.setText(_translate("MainWindow", "Scelta label..."))
        self.pushButton_cercaLabel.setText(_translate("MainWindow", "CERCA"))
        self.pushButton_reset.setText(_translate("MainWindow", "RESET"))

    # METODO PER VISUALIZZARE UN'IMMAGINE SUL LABEL DELL'IMMAGINE IN INPUT
    def loadImageInput(self, image):
        self.label_confrontoFoto.setPixmap(image)
        self.label_confrontoFoto.setScaledContents(True)

    #METODO PER CARICARE UN FILE IMMAGINE COME INPUT PER IL CONFRONTO
    def openImage(self):
        imagePath, _ = QFileDialog.getOpenFileName(None, "SCEGLI L'IMMAGINE", "", "jpg(*.jpg)")
        print("Path foto input: " + imagePath)

        D_Applicazione.salvaPathInput(self, imagePath)
        D_Mixer.salvaPathInput(self, imagePath)

        pixmap = QPixmap(imagePath)
        self.loadImageInput(pixmap)

    def visualizzaImageInput(self):
        imageImage = self.label_confrontoFoto.pixmap()
        return imageImage

    # METODO PER CARICARE FILE "index.csv" E SALVARE IL SUO PERCORSO
    def openIndex(self):
        indexPath, _ = QFileDialog.getOpenFileName(None, "Only file .csv", "", "csv(*.csv)")

        print("Path index [.cvs]: " + indexPath)

        nomeIndexSift = "index.json"
        pathIndexSift = self.creazionePercorsoFile(indexPath, nomeIndexSift, "")

        print("Path index [.json]: " + pathIndexSift)

        D_Applicazione.salvaPathIndex(self, indexPath)
        D_Mixer.salvaPathIndexIsto(self, indexPath)
        D_Mixer.salvaPathIndexSift(self, pathIndexSift)

    # METODO PER CARICARE IL DATASET E SALVARE IL SUO PERCORSO
    def openDataset(self):
        DatasetPath = QFileDialog.getExistingDirectory()

        print("Path dataset: " + DatasetPath)

        self.salvaDataset(DatasetPath)

    # DEFIZIONE METODO PER IL RESET DELL'INTEFACCIA
    def reset(self):
        indexConfronto = self.comboBox_confronto.findText("...", QtCore.Qt.MatchFixedString)
        self.comboBox_confronto.setCurrentIndex(indexConfronto)
        indexSceltaLabel = self.comboBox_sceltaLabel.findText("...", QtCore.Qt.MatchFixedString)
        self.comboBox_sceltaLabel.setCurrentIndex(indexSceltaLabel)
        self.label_confrontoFoto.clear()

        # PER RIPULIRE LA FINESTRA DI VISUALIZZAZIONE OUTPUT
        for i in reversed(range(self.verticalLayout.count())):
            self.verticalLayout.itemAt(i).widget().deleteLater()

    # FUNZIONE PER DETERMINARE QUALE ALGORITMO E' STATO SCELTO TRAMITE LA COMBOBOX
    def sceltaAlgoritmo(self):
        sceltaComboBox = self.comboBox_confronto.currentText()

        # EVENTO GESTITO NEL CASO IN CUI NELLA PRIMA GROUPBOX VENGA SELEZIONATA "..."
        if sceltaComboBox == "...":
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText('Nessuna tecnica per il confronto selezionata')
            msg.setWindowTitle("!ERRORE!")
            msg.exec_()

        # EVENTO GESTITO NEL CASO IN CUI NELLA PRIMA GROUPBOX VENGA SELEZIONATA "Confronto per istogrammi"
        if sceltaComboBox == "Confronto per istogrammi":
            pix = self.label_confrontoFoto.pixmap()

            if pix == None:
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText('Nessuna immagine in input per il confronto')
                msg.setWindowTitle("!ERRORE!")
                msg.exec_()
            else:
                numeroFoto = self.inputNumeroFotoAlg
                immaginiOutput = D_Applicazione.applicazione(self, self.numFoto)
                print(immaginiOutput)
                self.visualizzazioneMultiplaImmagini(immaginiOutput)

        # EVENTO GESTITO NEL CASO IN CUI NELLA PRIMA GROUPBOX VENGA SELEZIONATA "Tecnica Sift"
        if sceltaComboBox == "Tecnica Sift":
            pix = self.label_confrontoFoto.pixmap()

            if pix == None:
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText('Nessuna immagine in input per il confronto')
                msg.setWindowTitle("!ERRORE!")
                msg.exec_()
            else:
                immaginiOutput = D_Mixer.mixer(self, self.numFoto)
                print(immaginiOutput)
                self.visualizzazioneMultiplaImmagini(immaginiOutput)

    # FUNZIONE PER DETERMINARE QUALE LABEL ("PAROLA CHIAVE") E' STATA SCELTA TRAMITE LA COMBOBOX
    def sceltaLabel(self):
        sceltaComboBox = self.comboBox_sceltaLabel.currentText()
        nomeCartellaLabels = "Labels"

        # EVENTO GESTITO NEL CASO IN CUI NELLA PRIMA GROUPBOX VENGA SELEZIONATA "..."
        if sceltaComboBox == "...":
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText('Nessuna label per il confronto selezionata')
            msg.setWindowTitle("!ERRORE!")
            msg.exec_()

        if sceltaComboBox == "Tramonto":
            # STRINGHE NECESSARIE: foto dell'immagine "fissa" (di un tramonto) per il confronto e il nome della cartella che la contiene
            nomeFoto = "tramonto2.jpg"
            # CHIAMATA DELLA FUNZIONE PER AVERE IL PERCORSO DELLA CARTELLA CHE CONTIENE LE FOTO DA USARE PER LE LABELS
            pathLabel = self.creazionePercorsoFile(self.pathDataset, nomeFoto, nomeCartellaLabels)
            # APPLICAZIONE DELL'ALGORITMO ISTOGRAMMA
            D_Applicazione.salvaPathInput(self, pathLabel)
            immaginiOutput = D_Applicazione.applicazione(self, self.numFoto)
            print(immaginiOutput)
            self.visualizzazioneMultiplaImmagini(immaginiOutput)

        if sceltaComboBox == "Edifici":
            # STRINGHE NECESSARIE: foto dell'immagine "fissa" (di un tramonto) per il confronto e il nome della cartella che la contiene
            nomeFoto = "edificio1.jpg"
            # CHIAMATA DELLA FUNZIONE PER AVERE IL PERCORSO DELLA CARTELLA CHE CONTIENE LE FOTO DA USARE PER LE LABELS
            pathLabel = self.creazionePercorsoFile(self.pathDataset, nomeFoto, nomeCartellaLabels)
            # APPLICAZIONE DELL'ALGORITMO ISTOGRAMMA
            D_Mixer.salvaPathInput(self, pathLabel)
            immaginiOutput = D_Mixer.mixer(self, self.numFoto)
            print(immaginiOutput)
            self.visualizzazioneMultiplaImmagini(immaginiOutput)

        if sceltaComboBox == "Calcio":
            # STRINGHE NECESSARIE: foto dell'immagine "fissa" (di un tramonto) per il confronto e il nome della cartella che la contiene
            nomeFoto = "calcio7.jpg"
            # CHIAMATA DELLA FUNZIONE PER AVERE IL PERCORSO DELLA CARTELLA CHE CONTIENE LE FOTO DA USARE PER LE LABELS
            pathLabel = self.creazionePercorsoFile(self.pathDataset, nomeFoto, nomeCartellaLabels)
            # APPLICAZIONE DELL'ALGORITMO ISTOGRAMMA
            D_Applicazione.salvaPathInput(self, pathLabel)
            immaginiOutput = D_Applicazione.applicazione(self, self.numFoto)
            print(immaginiOutput)
            self.visualizzazioneMultiplaImmagini(immaginiOutput)

        if sceltaComboBox == "Mare":
            # STRINGHE NECESSARIE: foto dell'immagine "fissa" (di un tramonto) per il confronto e il nome della cartella che la contiene
            nomeFoto = "mare28.jpg"
            # CHIAMATA DELLA FUNZIONE PER AVERE IL PERCORSO DELLA CARTELLA CHE CONTIENE LE FOTO DA USARE PER LE LABELS
            pathLabel = self.creazionePercorsoFile(self.pathDataset, nomeFoto, nomeCartellaLabels)
            # APPLICAZIONE DELL'ALGORITMO ISTOGRAMMA
            D_Applicazione.salvaPathInput(self, pathLabel)
            immaginiOutput = D_Applicazione.applicazione(self, self.numFoto)
            print(immaginiOutput)
            self.visualizzazioneMultiplaImmagini(immaginiOutput)

    # FUNZIONI CHE PERMETTONO LA VISUALIZZAZIONE DI PIU' IMMAGINI ALL'INTERNO DELLA LABEL DI VISUALIZZAZIONE OUTPUT
    def visualizzazioneMultiplaImmagini(self, arrayFoto):

        arrayImg = []
        arrayScore = []

        for (score, resultID) in arrayFoto:
            arrayImg.append(resultID)
            val = 100 - score
            num = round(val, 2)
            arrayScore.append(num)

        self.file_it = iter(arrayImg)
        self.score_it = iter(arrayScore)
        self._timer = QtCore.QTimer(MainWindow, interval=1)
        self._timer.timeout.connect(self.on_timeout)
        self._timer.start()

    # FUNZIONE CHE PERMETTE LA VISUALIZZAZIONE DELLE FOTO SCANSIONATE DA UN TIMER PER RIDURRE IL TEMPO DI ATTESA PER IL CARICAMENTO
    def on_timeout(self):

        datasetImg = self.pathDataset

        try:
            file = next(self.file_it)
            punto = next(self.score_it)
            pixmap = QtGui.QPixmap(datasetImg + "/" + file)
            self.add_pixmap(pixmap, punto)
        except StopIteration:
            self._timer.stop()

    # FUNZIONE PER L'AGGIUNTA DELLE FOTO ALL'INTERFACCIA
    def add_pixmap(self, pixmap, score):
        if not pixmap.isNull():

            label = QtWidgets.QLabel(pixmap=pixmap)
            label.setScaledContents(True)
            label.setFixedWidth(285)
            label.setFixedHeight(275)
            label.setToolTip('Precisione: ' + str(score) + "%")
            self.verticalLayout.addWidget(label)

    # FUNZIONE PER RISCRIVERE IL PERCORSO NECCESSARIO USANDO IL NOME DELLA FOTO DI RIFERIMENTO E IL NOME DELLA CARTELLA CONTENENTE TALE FOTO
    def creazionePercorsoFile (self, percorsoStandard, nomeFile, cartellaFile):

        # PERCORSO DEL DATASET
        datasetImg = percorsoStandard
        # SUDDIVIDO IL PERCORCO NELLE VARIE CARTELLE PER RAGGIUNGERE IL DATASET ["/" è il divisore]
        x = datasetImg.split("/")
        # RISCRIVO IL COLLEGAMENTO ANDANDO A PRENDERE SOLO LE PRIME 5 CARTELLE (senza il dataset)
        path = x[0:5]
        # USO IL METODO "join" PER UNIRE OGGETTI IN UNA LISTA IN UNA SINGOLA STRINGA
        string = '/'.join(path)
        # RISCRIVO IL COLLEGMANTO CORRETTO PER APRIRE LA CARTELLA "Labels" CONTENENTE LA FOTO PER IL CONFRONTO
        pathFile = string + "/" + cartellaFile + "/" + nomeFile

        return pathFile

    def inputNumeroFotoAlg(self, limit):
        text, ok = QInputDialog.getText(None, "Numero foto", "da 1 a 20 (numeri maggiori di 20 vengono contati come 20)", QtWidgets.QLineEdit.Normal, "")
        if ok and text != '':
            numero = int(text)
            if(numero > 20):
                self.salvaNumeroFoto(20)
                self.sceltaAlgoritmo()
            if(numero < 1):
                self.salvaNumeroFoto(1)
                self.sceltaAlgoritmo()
            else:
                self.salvaNumeroFoto(numero)
                self.sceltaAlgoritmo()

    def inputNumeroFotoLabels(self, limit):
        text, ok = QInputDialog.getText(None, "Numero foto", "da 1 a 20 (numeri maggiori di 20 vengono contati come 20)", QtWidgets.QLineEdit.Normal, "")
        if ok and text != '':
            numero = int(text)
            if(numero > 20):
                self.salvaNumeroFoto(20)
                self.sceltaLabel()
            if(numero < 1):
                self.salvaNumeroFoto(1)
                self.sceltaLabel()
            else:
                self.salvaNumeroFoto(numero)
                self.sceltaLabel()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


import sys
from collections import defaultdict
from router import Router
from packet import Packet
from json import dumps, loads

class DVrouter(Router):
    """Distance vector routing protocol implementation."""

    def __init__(self, addr, heartbeatTime):
        """TODO: add your own class fields and initialization code here"""
        Router.__init__(self, addr)  # initialize superclass - don't remove
        self.heartbeatTime = heartbeatTime
        self.last_time = 0

        # Hints: initialize local state

        self.nbrs = {}              # dict to store neighbors and their respective costs
        self.routing_table = {}
        self.neighbors = {}         # dict to store neighbors and their respective ports
        self.others_table = {}      # dict to store the routing tables of neighbors

    def handlePacket(self, port, packet):
        """TODO: process incoming packet"""
        if packet.isTraceroute():
            # Hints: this is a normal data packet
            # if the forwarding table contains packet.dstAddr
            #   send packet based on forwarding table, e.g., self.send(port, packet)

            if packet.dstAddr in self.routing_table.keys():

                self.send(self.routing_table[packet.dstAddr]["port"], packet)

        else:
            # Hints: this is a routing packet generated y your routing protocol
            # if the received distance vector is different
            #   update the local copy of the distance vector
            #   update the distance vector of this router
            #   update the forwarding table
            #   broadcast the distance vector of this router to neighbors

            table_recv = loads(packet.content)

            # stores the routing table of the nbr
            self.others_table[packet.srcAddr] = table_recv

            # searches if a node is deleted
            for x in table_recv.keys():
                if table_recv[x]["cost"] == 16:
                    deleted = x
                    self.remove_node(deleted)

            self.recompute_table()
            self.broadcast_handle_packet(packet.srcAddr, table_recv)

    def handleNewLink(self, port, endpoint, cost):
        """TODO: handle new link"""
        # update the distance vector of this router
        # update the forwarding table
        # broadcast the distance vector of this router to neighbors

        self.routing_table[endpoint] = {"cost":cost, "nextHop":endpoint, "port":port}
        self.neighbors[endpoint] = port
        self.nbrs[endpoint] = cost
        self.broadcast(endpoint)

    def handleRemoveLink(self, port):
        """TODO: handle removed link"""
        # update the distance vector of this router
        # update the forwarding table
        # broadcast the distance vector of this router to neighbors

        # finds the endpoint to be deleted through it's port
        endpoint_remove = list(self.neighbors.keys())[list(self.neighbors.values()).index(port)]
        self.routing_table[endpoint_remove]["cost"] = 16
        self.nbrs[endpoint_remove] = 16
        del self.neighbors[endpoint_remove]
        self.remove_node(endpoint_remove)
        self.recompute_table()
        self.broadcast(-16)

    def handleTime(self, timeMillisecs):
        """TODO: handle current time"""
        if timeMillisecs - self.last_time >= self.heartbeatTime:
            self.last_time = timeMillisecs

            # broadcast the distance vector of this router to neighbors
            self.broadcast(-16)

    def debugString(self):
        """TODO: generate a string for debugging in network visualizer"""
        return dumps(self.routing_table)

    def broadcast(self, node):

        packet_to_send = Packet(kind = Packet.ROUTING, srcAddr= self.addr, dstAddr= self.addr, content=dumps( self.routing_table ))

        for x in self.neighbors.keys():

            # if the node is same as the one from which the packet is recv then don't resend to it
            if x == node:
                continue
            else:
                self.send(self.neighbors[x], packet_to_send)

    def broadcast_handle_packet(self, node, table):

        packet_to_send = Packet(kind = Packet.ROUTING, srcAddr= self.addr, dstAddr= self.addr, content=dumps( self.routing_table ))

        for x in self.neighbors.keys():

            if x == node:
                continue

            # if the packet src and you have mutual nbrs then don't send because packet src has already send it to them
            elif x in table.keys():
                continue

            else:
                self.send(self.neighbors[x], packet_to_send)

    # node is the deleted link, function traverses table of each router and change this node's cost in each table to 16
    def remove_node(self, node):

        for x in self.others_table.keys():

            if node in self.others_table[x].keys():

                self.others_table[x][node]["cost"] = 16

    # reconstruct the table without the node which has been deleted
    def recompute_table(self):

        self.routing_table.clear()

        # inserting nbrs into table
        for x in self.nbrs.keys():

            if self.nbrs[x] == 16:
                continue

            self.routing_table[x] = {"cost":self.nbrs[x], "nextHop":x, "port":self.neighbors[x]}

        # inserting all other nodes in the table from stored tables of other routers
        for x, y in self.others_table.items():

            table_recv = y
            srcAddr = x

            if self.nbrs[x] == 16:
                continue

            for endpoint in table_recv.keys():

                if table_recv[endpoint]["cost"] == 16:
                    continue

                if endpoint == self.addr:
                    continue

                if endpoint not in self.routing_table.keys():

                    new_cost = self.nbrs[srcAddr] + table_recv[endpoint]["cost"]
                    hop =srcAddr
                    self.routing_table[endpoint] = {"cost":new_cost, "nextHop":hop, "port":self.neighbors[hop]}

                elif endpoint in self.routing_table.keys():

                    new_cost = self.nbrs[srcAddr] + table_recv[endpoint]["cost"]
                    hop = srcAddr

                    if self.routing_table[endpoint]["cost"] >= new_cost:
                        self.routing_table[endpoint] = {"cost":new_cost, "nextHop":hop, "port":self.neighbors[hop]}

Assignment 2 - Intra-Domain Routing Algorithms/Submission/DVrouter.py


# coding:utf-8

from django.conf.urls import url
from blog.views import *

urlpatterns = [
    url(r'^$', home, name="home"),
    url(r"^archive/",archive,name="archive"),
    url(r"^category/",category,name="category"),
    url(r"^article/(?P<id>[0-9]+)$",article,name="article"),
    url(r"^comment_post/$",comment_post,name="comment_post"),
    url(r"^login/$",do_login,name="login"),
    url(r"^logout/$",do_logout,name="logout"),
    url(r"^reg/$",reg,name="reg"), # 注册
    ]


import random
from functools import reduce
from itertools import combinations

from .Robot import Robot
from .Encuentro import Encuentro

class Ronda(object):
    TRACKS = 1
    NUMERO = 1
    def __init__(self, encuentros, promovidos=None, tct=False, nombre=None):
        self.numero = Ronda.NUMERO
        Ronda.NUMERO = Ronda.NUMERO + 1
        self.encuentros = encuentros
        self.promovidos = promovidos or []
        self.tct = tct
        self.nombre = nombre or (self.tct and "Ronda Todos vs Todos" or "Ronda %s" % self.numero);

    #Generar nueva ronda
    @staticmethod
    def generar(robots, tct=False, esc=True, allow_none=False, shuffle=True):
        tct = len(robots) > 2 and tct
        tuplas = [list(combine) for combine in combinations(robots, 2)]
        ronda_tuplas = []
        if shuffle:
            random.shuffle(tuplas)
        if esc:
            distinta_escuela = [e for e in tuplas if e[0].escuela != e[1].escuela]
            misma_escuela = [e for e in tuplas if e[0].escuela == e[1].escuela]
            tuplas = distinta_escuela + misma_escuela
        for tupla in tuplas:
            if tct or all([not (tupla[0] in encuentro or tupla[1] in encuentro) for encuentro in ronda_tuplas]):
                ronda_tuplas.append(tupla)
            if not tct and len(ronda_tuplas) == len(robots) // 2:
                break
        # Ahora creamos la ronda
        promovidos = set(robots).difference(set(reduce(lambda a, t: a + t, ronda_tuplas, [])))
        if promovidos and allow_none:
            ronda_tuplas = ronda_tuplas + [(p, None) for p in promovidos]
            promovidos = []
        encuentros = [Encuentro(*t) for t in ronda_tuplas]
        return Ronda(encuentros, list(promovidos), tct)

    # Robots
    def get_robots(self):
        return list(reduce(lambda a, e: a.union([e.robot_1, e.robot_2]), self.encuentros, set(self.promovidos)))

    def ganadores(self):
        if self.tct:
            # En una ronda todos contra todos los robots solo son ranqueados,
            # hay que ordenarlos por puntos y obtener una lista de merito
            return self.get_robots()
        else:
            return [e.ganador() for e in self.encuentros] + self.promovidos

    def ganador(self):
        ganadores = self.ganadores()
        if self.finalizado() and len(ganadores) == 1:
            return ganadores.pop()

    def perdedores(self):
        if self.tct:
            # En una ronda todos contra todos los robots solo son ranqueados,
            # hay que ordenarlos por puntos y obtener una lista de merito
            return self.get_robots()
        else:
            return [e.perdedor() for e in self.encuentros]

    def perdedor(self):
        perdedores = self.perdedores()
        if self.finalizado() and len(perdedores) == 1:
            return perdedores.pop()

    # Encuentros
    def get_encuentros(self):
        return self.encuentros[:]

    def get_encuentro(self, numero):
        encuentros = [encuentro for encuentro in self.get_encuentros() if encuentro.numero == numero]
        if encuentros:
            return encuentros.pop()

    def get_encuentros_actuales(self):
        encuentros = [encuentro for encuentro in self.get_encuentros() if not encuentro.finalizado()]
        return encuentros[:self.TRACKS]

    # Serialize
    def to_dict(self):
        return {
            "encuentros": [ encuentro.to_dict() for encuentro in self.encuentros ],
            "promovidos": self.promovidos,
            "tct": self.tct,
            "nombre": self.nombre
        }

    # Estados
    def iniciado(self):
        return any([e.iniciado() for e in self.get_encuentros()])

    def finalizado(self):
        return all([e.finalizado() for e in self.get_encuentros()])

    def compitiendo(self):
        return self.iniciado() and not self.finalizado()

    def jugadas(self):
        return sum([e.jugadas() for e in self.get_encuentros()])

    # Score de la ronda
    def score(self, robot):
        """Retorna el *score* de un robot dentro de la ronda
        score es una n-upla de la forma (jugados, triunfos, empates, derrotas, a favor, en contra, diferencia, puntos)
        """
        encuentros = [encuentro for encuentro in self.encuentros if encuentro.finalizado()]
        resultados = [encuentro.score(robot) for encuentro in encuentros if encuentro.participa(robot)]
        resultados = [resultado for resultado in resultados if None not in resultado ]
        triunfos = len([resultado for resultado in resultados if resultado[0] > resultado[1]])
        derrotas = len([resultado for resultado in resultados if resultado[0] < resultado[1]])
        empates = len([resultado for resultado in resultados if resultado[0] == resultado[1]])
        puntos = triunfos * 3 + empates * 1 + derrotas * 0
        a_favor = reduce(lambda acumulador, resultado: acumulador + resultado[0], resultados, 0)
        en_contra = reduce(lambda acumulador, resultado: acumulador + resultado[1], resultados, 0)
        return (triunfos + derrotas + empates, triunfos, empates, derrotas, a_favor, en_contra, a_favor - en_contra, puntos)


# ! /usr/bin/env python
# - * - coding:utf-8 - * -
# __author__ : KingWolf
# createtime : 2019/11/12 3:21

import time
import os
from selenium import webdriver
from baseview.element_processing import Elemnet

class KeyWord_function(object):

    def __init__(self,browser):

        self.browser = browser

    def driver_init(self):
        """
        打开浏览器
        :param browser:
        :return:
        """

        if self.browser == 'chrome':

            """

                谷歌浏览器的设置

            """
            #设置user-data-dir的路径
            new_options = webdriver.ChromeOptions()
            new_options.add_argument(r"user-data-dir=F:\data_profile")

            #设置谷歌浏览器的驱动路径
            driver_path = os.path.dirname(os.path.dirname(__file__)) + '/browser_driver/chromedriver.exe'

            self.driver = webdriver.Chrome(executable_path=driver_path,options=new_options)

        elif self.browser == 'firefox':

            """

                火狐浏览器的设置

            """
            # #设置火狐浏览器驱动路径
            driver_path = os.path.dirname(os.path.dirname(__file__)) + '/browser_driver/geckodriver.exe'

            self.driver = webdriver.Firefox(executable_path=driver_path)

        else:

            """

                edge浏览器的设置

            """
            # #设置edge浏览器驱动路径
            driver_path = os.path.dirname(os.path.dirname(__file__)) + '/browser_driver/MicrosoftWebDriver.exe'
            self.driver = webdriver.Edge(executable_path=driver_path)

        return self.driver

    def get_init_url(self,url):
        """
        输入url地址
        :param browser:
        :param url:
        :return:
        """
        self.driver.get(url)
        self.driver.implicitly_wait(10)
        self.driver.maximize_window()

    def get_element(self,selection,key):
        """
        定位元素
        :param selection:
        :param key:
        :return:
        """
        get_ele = Elemnet(self.driver)
        element = get_ele.ele_processing(selection,key)
        return element

    def send_keys_element(self,selection,key,value):
        """
        输入元素
        :param selection:
        :param key:
        :param value:
        :return:
        """
        element = self.get_element(selection,key)
        element.send_keys(value)

    def click_element(self,selection,key):
        """
        点击元素
        :param selection:
        :param key:
        :return:
        """
        self.get_element(selection,key).click()

    def sleep_time(self):
        """
        延时处理
        :return:
        """
        time.sleep(3)

    def close_driver(self):
        """
        关闭浏览器
        :return:
        """
        self.driver.close()

if __name__ == '__main__':

    dd = KeyWord_function('chrome')
    dd.driver_init()
    dd.get_init_url("http://www.5itest.cn/register?goto=/")


from colorama import Fore,Back
class stuff:
    def __init__(self):

        self._shape = [[' ']]
        self._uy = 0
        self._ay = 0
        self._ux = 0
        self._ax = 0
        self._x = 26
        self._y = 2

        self._minx = 0
        self._miny = 5

        self._height = 1
        self._width = 1

        self._maxy = 48
        self._maxx = 204

    def get_dim(self):
        return self._width,self._height

    def get_shape(self):
        return self._shape

    def get_posit(self,speedBoost):

        self._y += self._uy + self._ay/2
        self._x += self._ux + self._ax/2
        self._ux += self._ax

        if self._x < self._minx:
            self._x = self._minx

        if self._x > self._maxx:
            self._x = self._maxx

        if self._y == self._maxy and self._uy>0:
            self._uy = 0
        if self._y == self._miny and self._uy<0:
            self._uy = 0
        self._uy += self._ay
        if self._y < self._miny:
            self._y = self._miny

        if self._y > self._maxy:
            self._y = self._maxy

        return self._x, self._y

class bullets(stuff):
    def __init__(self, x, y):
        super().__init__()

        self._maxx = 250
        self._y = y
        self._x = x

class shell(bullets):
    def __init__(self, x, y):
        super().__init__(x,y)

        self._shape = ['=>']
        self._width = 2
        self._ux = 2.5


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('task', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='task',
            name='finalized',
            field=models.BooleanField(default=False, verbose_name='finalizado'),
            preserve_default=True,
        ),
    ]


from auto_scan_test import OPConvertAutoScanTest, BaseNet
from hypothesis import reproduce_failure
import hypothesis.strategies as st
import numpy as np
import unittest
import paddle

op_api_map = {
    "abs": paddle.abs,
    "acos": paddle.acos,
    "asin": paddle.asin,
    "atan": paddle.atan,
    "ceil": paddle.ceil,
    "cos": paddle.cos,
    "cosh": paddle.cosh,
    "erf": paddle.erf,
    "exp": paddle.exp,
    "floor": paddle.floor,
    "hard_shrink": paddle.nn.functional.hardshrink,
    "brelu": paddle.nn.functional.hardtanh,
    "log": paddle.log,
    "log1p": paddle.log1p,
    "log2": paddle.log2,
    "log10": paddle.log10,
    "reciprocal": paddle.reciprocal,
    "relu": paddle.nn.functional.relu,
    "relu6": paddle.nn.functional.relu6,
    "round": paddle.round,
    "rsqrt": paddle.rsqrt,
    "selu": paddle.nn.functional.selu,
    "sigmoid": paddle.nn.functional.sigmoid,
    "sign": paddle.sign,
    "sin": paddle.sin,
    "sinh": paddle.sinh,
    "softplus": paddle.nn.functional.softplus,
    "softsign": paddle.nn.functional.softsign,
    "sqrt": paddle.sqrt,
    "square": paddle.square,
    "swish": paddle.nn.functional.swish,
    "silu": paddle.nn.functional.silu,
    "tanh": paddle.tanh,
    "tan": paddle.tan,
}

opset_version_map = {
    "abs": [7, 13, 15],
    "acos": [7, 15],
    "asin": [7, 15],
    "atan": [7, 15],
    "ceil": [7, 13, 15],
    "cos": [7, 15],
    "cosh": [9, 15],
    "erf": [9, 13, 15],
    "exp": [7, 13, 15],
    "floor": [7, 13, 15],
    "hard_shrink": [9, 15],
    "brelu": [9, 15],
    "log": [7, 13, 15],
    "log1p": [7, 13, 14, 15],
    "log2": [7, 13, 15],
    "log10": [7, 13, 15],
    "reciprocal": [7, 13, 15],
    "relu": [7, 13, 14, 15],
    "relu6": [7, 13, 14, 15],
    "round": [11, 15],
    "rsqrt": [7, 13, 15],
    "selu": [7, 15],
    "sigmoid": [7, 13, 15],
    "sign": [9, 13, 15],
    "sin": [7, 15],
    "sinh": [9, 15],
    "softplus": [7, 15],
    "softsign": [7, 15],
    "sqrt": [7, 13, 15],
    "square": [7, 13, 14, 15],
    "swish": [7, 13, 14, 15],
    "tanh": [7, 13, 15],
    "tan": [7, 15],
    "silu": [7, 15],
}

class Net(BaseNet):
    def forward(self, inputs):
        return op_api_map[self.config["op_names"]](inputs)

class TestUnaryOPConvert(OPConvertAutoScanTest):
    """Testcases for all the unary operators."""

    def sample_convert_config(self, draw):
        input_shape = draw(
            st.lists(
                st.integers(
                    min_value=2, max_value=20), min_size=0, max_size=4))
        data_shapes = input_shape
        dtype = draw(st.sampled_from(["float32"]))
        config = {
            "op_names": "",
            "test_data_shapes": [data_shapes],
            "test_data_types": [[dtype]],
            "opset_version": [7, 9, 15],
            "input_spec_shape": [],
        }
        models = list()
        op_names = list()
        opset_versions = list()
        for op_name, i in op_api_map.items():
            config["op_names"] = op_name
            models.append(Net(config))
            op_names.append(op_name)
        for op_name, vs in opset_version_map.items():
            opset_versions.append(vs)
        config["op_names"] = op_names
        config["opset_version"] = opset_versions
        return (config, models)

    def test(self):
        self.run_and_statis(max_examples=40, max_duration=600)

if __name__ == "__main__":
    unittest.main()


import urllib.request
import urllib.parse
import urllib.error
import xml.etree.ElementTree as ET

# serviceurl = 'http://maps.googleapis.com/maps/api/geocode/xml?'
# http://py4e-data.dr-chuck.net/comments_42.xml

url = input('Enter location: ')

# url = urllib.parse.urlencode({'address': address})
print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read()
print('Retrieved', len(data), 'characters')
# print(data.decode())
tree = ET.fromstring(data)
counts = tree.findall('.//count')

print('Count: ', len(counts))

sum_total = 0
for count in counts:
    sum_total = sum_total + int(count.text)

print('Sum: ', sum_total)
'''
    results = tree.findall('result')
    lat = results[0].find('geometry').find('location').find('lat').text
    lng = results[0].find('geometry').find('location').find('lng').text
    location = results[0].find('formatted_address').text

    print('lat', lat, 'lng', lng)
    print(location)
'''


import warnings
from abc import ABCMeta, abstractmethod
from typing import Tuple, Callable, Dict

import numpy as np
import xarray as xr
from numba import njit, prange

import pandora.constants as cst

class AbstractRefinement:
    """
    Abstract Refinement class
    """

    __metaclass__ = ABCMeta

    subpixel_methods_avail: Dict = {}
    _refinement_method_name = None
    cfg = None

    def __new__(cls, **cfg: dict):
        """
        Return the plugin associated with the refinement_method given in the configuration

        :param cfg: configuration {'refinement_method': value}
        :type cfg: dictionary
        """
        if cls is AbstractRefinement:
            if isinstance(cfg["refinement_method"], str):
                try:
                    return super(AbstractRefinement, cls).__new__(cls.subpixel_methods_avail[cfg["refinement_method"]])
                except:
                    raise KeyError("No refinement method named {} supported".format(cfg["refinement_method"]))
            else:
                if isinstance(cfg["refinement_method"], unicode):  # type: ignore # pylint: disable=undefined-variable
                    # creating a plugin from registered short name given as unicode (py2 & 3 compatibility)
                    try:
                        return super(AbstractRefinement, cls).__new__(
                            cls.subpixel_methods_avail[cfg["refinement_method"].encode("utf-8")]
                        )
                    except:
                        raise KeyError("No refinement method named {} supported".format(cfg["refinement_method"]))
        else:
            return super(AbstractRefinement, cls).__new__(cls)
        return None

    def subpixel_refinement(self, cv: xr.Dataset, disp: xr.Dataset) -> None:
        """
        Subpixel refinement of disparities and costs.

        :param cv: the cost volume dataset with the data variables:

                - cost_volume 3D xarray.DataArray (row, col, disp)
                - confidence_measure 3D xarray.DataArray (row, col, indicator)
        :type cv: xarray.Dataset
        :param disp: Dataset with the variables :

            - disparity_map 2D xarray.DataArray (row, col)
            - confidence_measure 3D xarray.DataArray (row, col, indicator)
            - validity_mask 2D xarray.DataArray (row, col)
        :type disp: xarray.Dataset
        :return: None
        """
        d_min = cv.coords["disp"].data[0]
        d_max = cv.coords["disp"].data[-1]
        subpixel = cv.attrs["subpixel"]
        measure = cv.attrs["type_measure"]

        # This silences numba's TBB threading layer warning
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore")
            # Conversion to numpy array ( .data ), because Numba does not support Xarray
            (
                itp_coeff,
                disp["disparity_map"].data,
                disp["validity_mask"].data,
            ) = self.loop_refinement(
                cv["cost_volume"].data,
                disp["disparity_map"].data,
                disp["validity_mask"].data,
                d_min,
                d_max,
                subpixel,
                measure,
                self.refinement_method,
            )

        disp.attrs["refinement"] = self._refinement_method_name
        disp["interpolated_coeff"] = xr.DataArray(
            itp_coeff,
            coords=[("row", disp.coords["row"].data), ("col", disp.coords["col"].data)],
            dims=["row", "col"],
        )

    def approximate_subpixel_refinement(self, cv_left: xr.Dataset, disp_right: xr.Dataset) -> xr.Dataset:
        """
        Subpixel refinement of the right disparities map, which was created with the approximate method : a diagonal
        search for the minimum on the left cost volume

        :param cv_left: the left cost volume dataset with the data variables:

                - cost_volume 3D xarray.DataArray (row, col, disp)
                - confidence_measure 3D xarray.DataArray (row, col, indicator)
        :type cv_left: xarray.Dataset
        :param disp_right: right disparity map with the variables :

            - disparity_map 2D xarray.DataArray (row, col)
            - confidence_measure 3D xarray.DataArray (row, col, indicator)
            - validity_mask 2D xarray.DataArray (row, col)
        :type disp_right: xarray.Dataset
        :return: disp_right Dataset with the variables :

                - disparity_map 2D xarray.DataArray (row, col) that contains the refined disparities
                - confidence_measure 3D xarray.DataArray (row, col, indicator) (unchanged)
                - validity_mask 2D xarray.DataArray (row, col) with the value of bit 3 ( Information: \
                calculations stopped at the pixel step, sub-pixel interpolation did not succeed )
                - interpolated_coeff 2D xarray.DataArray (row, col) that contains the refined cost
        :rtype: xarray.Dataset
        """
        d_min = cv_left.coords["disp"].data[0]
        d_max = cv_left.coords["disp"].data[-1]
        subpixel = cv_left.attrs["subpixel"]
        measure = cv_left.attrs["type_measure"]

        # This silences numba's TBB threading layer warning
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore")
            # Conversion to numpy array ( .data ), because Numba does not support Xarray
            (
                itp_coeff,
                disp_right["disparity_map"].data,
                disp_right["validity_mask"].data,
            ) = self.loop_approximate_refinement(
                cv_left["cost_volume"].data,
                disp_right["disparity_map"].data,
                disp_right["validity_mask"].data,
                d_min,
                d_max,
                subpixel,
                measure,
                self.refinement_method,
            )

        disp_right.attrs["refinement"] = self._refinement_method_name
        disp_right["interpolated_coeff"] = xr.DataArray(
            itp_coeff,
            coords=[
                ("row", disp_right.coords["row"].data),
                ("col", disp_right.coords["col"].data),
            ],
            dims=["row", "col"],
        )
        return disp_right

    @classmethod
    def register_subclass(cls, short_name: str):
        """
        Allows to register the subclass with its short name

        :param short_name: the subclass to be registered
        :type short_name: string
        """

        def decorator(subclass):
            """
            Registers the subclass in the available methods

            :param subclass: the subclass to be registered
            :type subclass: object
            """
            cls.subpixel_methods_avail[short_name] = subclass
            return subclass

        return decorator

    @abstractmethod
    def desc(self) -> None:
        """
        Describes the subpixel method
        :return: None
        """
        print("Subpixel method description")

    @staticmethod
    @njit(parallel=True)
    def loop_refinement(
        cv: np.ndarray,
        disp: np.ndarray,
        mask: np.ndarray,
        d_min: int,
        d_max: int,
        subpixel: int,
        measure: str,
        method: Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray, str], Tuple[int, int, int]],
    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
        """
         Apply for each pixels the refinement method

        :param cv: cost volume to refine
        :type cv: 3D numpy array (row, col, disp)
        :param disp: disparity map
        :type disp: 2D numpy array (row, col)
        :param mask: validity mask
        :type mask: 2D numpy array (row, col)
        :param d_min: minimal disparity
        :type d_min: int
        :param d_max: maximal disparity
        :type d_max: int
        :param subpixel: subpixel precision used to create the cost volume
        :type subpixel: int ( 1 | 2 | 4 )
        :param measure: the measure used to create the cot volume
        :param measure: string
        :param method: the refinement method
        :param method: function
        :return: the refine coefficient, the refine disparity map, and the validity mask
        :rtype: tuple(2D numpy array (row, col), 2D numpy array (row, col), 2D numpy array (row, col))
        """
        n_row, n_col, _ = cv.shape
        itp_coeff = np.zeros((n_row, n_col), dtype=np.float64)

        for row in prange(n_row):
            for col in prange(n_col):
                # No interpolation on invalid points
                if (mask[row, col] & cst.PANDORA_MSK_PIXEL_INVALID) != 0:
                    itp_coeff[row, col] = np.nan
                else:
                    # conversion to numpy indexing
                    dsp = int((disp[row, col] - d_min) * subpixel)
                    itp_coeff[row, col] = cv[row, col, dsp]
                    if not np.isnan(cv[row, col, dsp]):
                        if (disp[row, col] != d_min) and (disp[row, col] != d_max):
                            sub_disp, sub_cost, valid = method(  # type: ignore
                                [
                                    cv[row, col, dsp - 1],
                                    cv[row, col, dsp],
                                    cv[row, col, dsp + 1],
                                ],  # type: ignore
                                disp[row, col],
                                measure,  # type: ignore
                            )

                            disp[row, col] = disp[row, col] + (sub_disp / subpixel)
                            itp_coeff[row, col] = sub_cost
                            mask[row, col] += valid
                        else:
                            # If Information: calculations stopped at the pixel step, sub-pixel interpolation did
                            # not succeed
                            mask[row, col] += cst.PANDORA_MSK_PIXEL_STOPPED_INTERPOLATION

        return itp_coeff, disp, mask

    @staticmethod
    @abstractmethod
    @njit(cache=True)
    def refinement_method(cost: np.ndarray, disp: float, measure: str) -> Tuple[float, float, int]:
        """
        Return the subpixel disparity and cost

        :param cost: cost of the values disp - 1, disp, disp + 1
        :type cost: 1D numpy array : [cost[disp -1], cost[disp], cost[disp + 1]]
        :param disp: the disparity
        :type disp: float
        :param measure: the type of measure used to create the cost volume
        :type measure: string = min | max
        :return: the refined disparity (disp + (sub_disp/subpix)), the refined cost and the state of the pixel
         ( Information: calculations stopped at the pixel step, sub-pixel interpolation did not succeed )
        :rtype: float, float, int
        """

    @staticmethod
    @njit(parallel=True)
    def loop_approximate_refinement(
        cv: np.ndarray,
        disp: np.ndarray,
        mask: np.ndarray,
        d_min: int,
        d_max: int,
        subpixel: int,
        measure: str,
        method: Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray, str], Tuple[int, int, int]],
    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
        """
         Apply for each pixels the refinement method on the right disparity map which was created with the approximate
          method : a diagonal search for the minimum on the left cost volume

        :param cv: the left cost volume
        :type cv: 3D numpy array (row, col, disp)
        :param disp: right disparity map
        :type disp: 2D numpy array (row, col)
        :param mask: right validity mask
        :type mask: 2D numpy array (row, col)
        :param d_min: minimal disparity
        :type d_min: int
        :param d_max: maximal disparity
        :type d_max: int
        :param subpixel: subpixel precision used to create the cost volume
        :type subpixel: int ( 1 | 2 | 4 )
        :param measure: the type of measure used to create the cost volume
        :type measure: string = min | max
        :param method: the refinement method
        :type method: function
        :return: the refine coefficient, the refine disparity map, and the validity mask
        :rtype: tuple(2D numpy array (row, col), 2D numpy array (row, col), 2D numpy array (row, col))
        """
        n_row, n_col, _ = cv.shape
        itp_coeff = np.zeros((n_row, n_col), dtype=np.float64)

        for row in prange(n_row):
            for col in prange(n_col):
                # No interpolation on invalid points
                if (mask[row, col] & cst.PANDORA_MSK_PIXEL_INVALID) != 0:
                    itp_coeff[row, col] = np.nan
                else:
                    # Conversion to numpy indexing
                    dsp = int((-disp[row, col] - d_min) * subpixel)
                    # Position of the best cost in the left cost volume is cv[r, diagonal, d]
                    diagonal = int(col + disp[row, col])
                    itp_coeff[row, col] = cv[row, diagonal, dsp]
                    if not np.isnan(cv[row, diagonal, dsp]):
                        if (
                            (disp[row, col] != -d_min)
                            and (disp[row, col] != -d_max)
                            and (diagonal != 0)
                            and (diagonal != (n_col - 1))
                        ):
                            # (1 * subpixel) because in fast mode, we can not have sub-pixel disparity for the right
                            # image.
                            # We therefore interpolate between pixel disparities
                            sub_disp, cost, valid = method(  # type:ignore
                                [
                                    cv[row, diagonal - 1, dsp + (1 * subpixel)],
                                    cv[row, diagonal, dsp],
                                    cv[row, diagonal + 1, dsp - (1 * subpixel)],
                                ],  # type: ignore
                                disp[row, col],
                                measure,  # type: ignore
                            )

                            disp[row, col] = disp[row, col] + (sub_disp / subpixel)
                            itp_coeff[row, col] = cost
                            mask[row, col] += valid
                        else:
                            # If Information: calculations stopped at the pixel step, sub-pixel interpolation did
                            # not succeed
                            mask[row, col] += cst.PANDORA_MSK_PIXEL_STOPPED_INTERPOLATION

        return itp_coeff, disp, mask


#!/usr/bin/python3
import rospy,cv2,time,os,sys
os.chdir(os.path.dirname(__file__))
import numpy as np
from multiprocessing import Process, Queue
from std_msgs.msg import Float32,String
from sensor_msgs.msg import CompressedImage
from include.lib_tdtu import Detect,Control
import yolo

def call_terminal(data):
    global terminal
    if str(data)[7] == "t": terminal=1
    else: terminal = 0

def call_speed(data):
    global pv_sp
    pv_sp = data

def get_p(data):
	try:
		while 1:IM.get(False)
	except: IM.put(data)
	temp,temp2 = 50,0
	while not RL.empty():temp = RL.get()
	RL.put(temp)
	while not ST.empty():temp2 = ST.get()
	ST.put(temp2)
	return temp,temp2

def call_image(data):
	global img
	temp = np.fromstring(data.data,np.uint8)
	img = cv2.imdecode(temp,cv2.IMREAD_COLOR)
	rl,tn = get_p(img)
	point = lane.process_image(img,50)
	speed,steer = control.drive(rl,point,tn)
	sp.publish(speed)
	st.publish(steer)

def setup(Team,debug):
    global terminal, pv_sp
    terminal, pv_sp = 0, 0
    rospy.init_node(Team)
    speed = rospy.Publisher("/"+Team+"_speed", Float32, queue_size=1)
    steer = rospy.Publisher("/"+Team+"_steerAngle", Float32, queue_size=1)
    rospy.Subscriber("/"+Team+"_image/compressed",CompressedImage,call_image)
    rospy.Subscriber("/restart",String,call_terminal)
    #rospy.Subscriber("/get_speed",Float32,call_speed)
    lane = Detect(debug)
    control = Control(debug)
    return speed,steer,lane,control

debug = 0
def main(IM,RL,ST):
    global sp,st,lane,control,terminal
    sp,st,lane,control = setup("TDTU",debug)
    try: rospy.spin()
    finally: pass

def decision(obs,rl):
	# (-) slide left
	temp,tn = 48,0
	if obs[1]>0.1: temp+= -8
	if obs[2]>0.4:
		tn = -1
		temp+= -8
	if obs[3]>0.4:
		tn = 1
		temp+= +12
	temp = 0.5*rl+0.5*temp
	ST.put(tn)
	RL.put(temp)
	return temp

def You_only_look_once(Yolo):
	obstacle = [0,0,0,0,0,0]
	rl = 50
	while 1:
		res,boxes,score,classes,timer = Yolo.detect_image(IM.get())

		for i in range(len(classes)):
			obstacle[classes[i]] = score[i]\
			if score[i]>obstacle[classes[i]] else obstacle[classes[i]]
		for i in range(6):obstacle[i]*=0.96
		rl = decision(obstacle,rl)
		cv2.imshow('res',res)
		cv2.waitKey(1)
		#print(1/timer)
		#if np.amax(obstacle)>0.9: cv2.imwrite('detect_img/'+str(time.time())+'.jpg',res)

try:
	print('\nWait for initial setup...\n')
	IM,RL,ST = Queue(),Queue(),Queue()
	Yolo = yolo.YOLO()
	Process(target=main,args=(IM,RL,ST)).start()
	print('\nTesting CNN detection.\n')
	Yolo.detect_image(cv2.imread('Training/Data/Training/1_1.jpg'))
	print('\nOK, all done.. Please restart simulation\n')
	You_only_look_once(Yolo)

finally:
	cv2.destroyAllWindows()
	#os.system('killall -9 python3')


import vk_photos
import ya_uploader
from pprint import pprint

def run_program():
    vk_user_id = input('Hi! Please enter your VK id.')
    yandex_token = input('Please enter your Yandex token.')
    user_vk = vk_photos.VK(vk_access_token, vk_user_id)
    user_disk = ya_uploader.Yandex(yandex_token)
    folder = input('Enter a new folder name.')
    user_disk.create_folder(folder)
    pprint(user_vk.log_photos_data(user_vk))
    user_disk.upload_photos(folder)
    return

if __name__ == '__main__':
    with open('token.txt', 'rt') as file:
        vk_access_token = file.readline()

    run_program()


import json
import mailbox
import shutil
import socket
from hashlib import sha256
from datetime import datetime, timezone
from email.mime.text import MIMEText
from getpass import getuser
from pathlib import Path

from github3.notifications import Thread
from mnotifications.db import Database

DATE_FMT = '%a, %d %b %Y %H:%M:%S %z'

class Mail:
    MDIR_PATH = Path.home().joinpath('.mail', 'github-notifications')

    @staticmethod
    def empty(maildir_path: Path=None) -> None:
        """Empty the current maildir to start fresh."""
        maildir_path = maildir_path or Mail.MDIR_PATH
        if maildir_path.exists():
            shutil.rmtree(maildir_path)
        Database.delete()

    @staticmethod
    def get_maildir(maildir_path: Path=None) -> mailbox.Maildir:
        maildir_path = maildir_path or Mail.MDIR_PATH
        m = mailbox.Maildir(maildir_path, create=True)
        if 'INBOX' not in m.list_folders():
            m.add_folder('INBOX')
        return m.get_folder('INBOX')

    def __init__(self, maildir_path: Path=None):
        self.db = Database()
        self.maildir_path = maildir_path or self.MDIR_PATH

    def connect(self):
        self.maildir_path.mkdir(parents=True, exist_ok=True)
        self.maildir = Mail.get_maildir(self.maildir_path)
        self.db.connect()

    def add_notification(self, notification: Thread) -> None:
        text_msg = self.build_from_notification(notification)
        message_id = text_msg.get('Message-ID')
        if self.db.mail_exists(message_id):
            key = self.db.mail_key(message_id)
            mail = self.maildir.get(key)
            if notification.unread:
                mail.set_flags(['S'])
            else:
                mail.remove_flag('S')
            return

        message = mailbox.MaildirMessage(message=text_msg)
        if not notification.unread:
            message.set_flags(['S'])
        key = self.maildir.add(message)
        self.maildir.flush()
        self.db.add(text_msg.get('Message-ID'), key, notification.updated_at)

    def build_from_notification(self, notification: Thread) -> MIMEText:
        text = MIMEText(json.dumps(notification.as_dict(), indent=2))
        text['Date'] = notification.updated_at.strftime(DATE_FMT)
        text['From'] = '{0}/{1}'.format(notification.repository.owner, notification.repository.name)
        text['To'] = getuser()
        text['Subject'] = notification.subject['title']
        text['Received'] = 'from github.com by {0} with maildir-notifications; {1}'.format(
            socket.gethostname(),
            datetime.now(tz=timezone.utc).strftime(DATE_FMT)
        )
        text['Message-ID'] = sha256(notification.url.encode('utf-8')).hexdigest()
        if notification.subject['type'] == 'PullRequest':
            pass

        return text


#!/usr/bin/env python
# encoding: utf-8
'''
@File  : 006_sum_of_list.py
@Date  : 2021/11/2 23:04
@Author: Cxs
@Email: Cxs1103@163.com
@Desc  :
'''

def sum_of_list(param_list):
    total = 0
    for item in param_list:
        total += item
    return total

list1 = [2, 3, 4, 7]
list2 = [26, 35, 34, 27]

print(f'list1 sum is :' , sum_of_list(list1))
print(f'list2 sum is :' , sum_of_list(list2))

print(f'list2 sum is :' , sum(list1))
print(f'list2 sum is :' , sum(list2))


# https://leetcode.com/problems/lru-cache/description/
from collections import defaultdict
import time

class LRUCache:
    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.cache = defaultdict(list)
        self.cap = capacity

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        # print("Getting the value corresponding to key ", key)
        if len(self.cache) == 0:
            return -1

        for k, v in self.cache.items():
            if k == key:
                return self.cache[k][0]

        return -1

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: void
        """
        print("Putting the foll key value {0} {1}".format(key, value))
        res = self.get(key)
        if res != -1:
            self.cache[key] = [value, time.time()]

        len_cache = len(self.cache)
        if len_cache < self.cap:
            self.cache[key] = [value, time.time()]
        else:
            kk = next(iter(self.cache))
            mintime = self.cache[kk][1]
            for k, v in self.cache.items():
                if v[1] < mintime:
                    mintime = v[1]
                    kk = k
            del self.cache[kk]
            self.cache[key] = [value, time.time()]

        print(self.cache)

# Your LRUCache object will be instantiated and called as such:

'''
["LRUCache","put","put","get","put","get","put","get","get","get"]
[[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
'''
obj = LRUCache(2)
obj.put(1, 1)
obj.put(2, 2)
print("Getting value corresponding to key {0} -> {1}".format(1, obj.get(1)))
obj.put(3, 3)
print("Getting value corresponding to key {0} -> {1}".format(2, obj.get(2)))
obj.put(4, 4)
print("Getting value corresponding to key {0} -> {1}".format(1, obj.get(1)))
print("Getting value corresponding to key {0} -> {1}".format(3, obj.get(3)))
print("Getting value corresponding to key {0} -> {1}".format(4, obj.get(4)))
print(obj.cache)


import datetime
import decimal

class Utils:

    def __init__(self):
        # set up alias for deprecated function name for backward compat
        self.serialize = self.result_to_dict

    def rows_to_dict(self, rows):
        """
        Converts SQLAlchemy column query results (KeyedTuples) to a list of dictionaries
        :param rows: query result
        :returns: (dict[]) list of dictionaries
        """
        # initialize list to return
        data = []
        # loop rows and add each rows worth of data to a dictionary
        try:
            for row in rows:
                d = {}
                for column in row.__table__.columns:
                    d[column.name] = getattr(row, column.name)
                # append dictionary object to array
                data.append(d)
        except:
            for row in rows:
                row_as_dict = row.__dict__
                data.append(row_as_dict)

        return data

    def result_to_dict(self, obj, flatten=False, exclude=None):
        """
        Utility method that converts result objects/lists to embedded dict/lists for easy serialization, works with
        KeyedTuple objects (from ORM queries where columns are selected explicitly) DeclarativeBase objects (from
        entity queries), and ResultProxy objects (from raw queries executed by the sqlalchemy session or results
        of SQLAlchemy core queries)
        :param obj: (object or list) the SQLAlchemy result (single object or list of objects)
        :param flatten: (boolean) flag to flatten the structure of resultant dictionaries if they contain child
                        dictionaries (from converting DeclarativeBase objects)
        :param exclude: (object) object/type in tree to exclude from serialization. Primarily used internally to prevent
                        infinite recursion errors caused by bi-directional relationships
        :return: (list or dict) representation of SQLAlchemy result(s) as a python dictionary or list of dictionaries
        """
        # set up keyword args for use in recursive calls
        kwargs = {'flatten': flatten, 'exclude': exclude}
        # check to see if this is a list or a single object and call function recursively on objects if it's a list
        if isinstance(obj, list):
            return [self.result_to_dict(row, **kwargs) for row in obj]
        elif hasattr(obj, "__table__"):
            # this is an SQLAlchemy (DeclarativeBase mapper) object
            result_dict = {}
            for key, val in obj.__dict__.items():
                if key is None or key.startswith("_"):
                    continue
                if isinstance(val, list):
                    # skip this attribute if this collection points back at instances of a parent object
                    #  or we are excluding it (prevent infinte loop)
                    if len(val) and (isinstance(val[0], obj.__class__) or (isinstance(val[0], exclude.__class__))):
                        continue
                    # otherwise embed a list into the dict key, excluding any descendants of the same type
                    else:
                        kwargs['exclude'] = obj
                        element = self.result_to_dict(val, **kwargs)
                # see if this element is a child object (excluding anything that references back to the parent)
                elif hasattr(val, "__dict__"):
                    # exclude any child objects that refer back to parent
                    if isinstance(val, obj.__class__) or isinstance(val, exclude.__class__):
                        continue
                    element = self.result_to_dict(val, **kwargs)
                else:
                    element = self.format_value(val)
                if isinstance(element, dict) and flatten:
                    # if this property is a child object (dictionary) and we're flattening, merge the child dict into
                    # the parent dict, without overwriting any keys in the parent (why a simple .update() is not used)
                    result_dict.update(dict([(k, v) for k, v in element.items() if k not in result_dict]))
                    # this would be for keeping all keys and namespacing child subkeys under parent keys
                    # result_dict.update(dict([(key + "." + k, v) for k, v in element.iteritems()]))
                else:
                    result_dict[key] = element
            return result_dict
        else:  # this is not the result of an entity query, so should be column query or raw query
            return self.query_result_to_dict(obj)

    def query_result_to_dict(self, obj):
        """
        Formats results from SQLAlchemy ORM column queries or raw SQL queries from session.execute()
        :param obj: The result of an SQLAlchemy query that isn't a DeclarativeBase object or list of
                    these. Covers ResultProxy, RowProxy, and KeyedTuple results
        """
        if obj.__class__.__name__ == 'ResultProxy':
            # if this is a ResultProxy object return a list of one dict for each row
            return [{this_property: self.format_value(row[this_property]) for this_property in list(row.keys())} for row in obj]
        elif obj.__class__.__name__ == 'RowProxy':
            # this is a RowProxy object which is one result from a ResultProxy object
            return {key: self.format_value(obj[key]) for key in list(obj.keys())}
        elif obj.__class__.__name__ == 'result':
            # this is a list of lightweight KeyedTuple objects for column ORM queries
            return {key: self.format_value(obj._asdict()[key]) for key in list(obj._asdict().keys())}
        elif hasattr(obj, '__dict__'):
            # this is a plain python object
            return {key: self.format_value(obj.__dict__[key]) for key in obj.__dict__}
        return obj  # by default just return the object

    def format_value(self, value):
        """
        Formats a result value so that it can be json serialized. Takes care of converting dates and
        decimal values to JSON-serializable formats.
        :param value:
        :return: the formatted value
        """
        # if this property is a date or datetime, set the value as the string representation
        if isinstance(value, datetime.datetime):
            value = value.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(value, datetime.date):
            value = value.strftime('%Y-%m-%d')
        elif isinstance(value, datetime.time):
            value = value.strftime('%I:%M')
        elif isinstance(value, decimal.Decimal):
            # have to convert decimals to floats because some json encoders can't encode Decimal types
            value = float(value)
        return value

    def get_sort_column(self, Model, obj_property, direction):
        """
        Returns the sort column and direction for grid sorting when passed in a SQLAlchemy object
        property and a direction. Enables dynamic argument for order_by() method on a query object
        in SQLAlchemy.
        :param Model: the DeclarativeBase class (db.Model when using Flask-SQLAlchemy extension)
        :param obj_property: the object property in the format 'Class.property'
        :param direction: 'asc' or 'desc'
        :return: A column property with either the .asc() or .desc() method to pass into an order_by()
        """
        sort_class, sort_property = obj_property.split(".")
        # use the registry of class names in declarative to get the class that the sorted property belongs to
        sort_table = Model._decl_class_registry[sort_class]
        # use getattr to dynamically get the property to sort by
        sort_column = getattr(sort_table, sort_property)

        # dynamic way of calling .asc() or .desc() methods for sorting on the given property
        column_sorted = getattr(sort_column, direction)()

        return column_sorted


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

from sklearn.metrics import roc_auc_score, log_loss, accuracy_score
import os
import pandas as pd
import numpy as np
import logging
from sklearn import metrics

def calc_auc(df, col_name):
    scores = df[col_name].to_numpy()
    clicks = df['click'].to_numpy()
    AUC = metrics.roc_auc_score(clicks, scores)
    return AUC

def calc_mrr(df, col_name):
    def apply_func(x_df):
        x_df = x_df.sort_values(by=[col_name], ascending=False)
        x_df = x_df.reset_index(drop=True)
        if x_df['click'].sum() == 0:
            return np.nan
        else:
            return x_df['click'].ne(0).idxmax() + 1
    mrr_df_group = df.groupby(['qid'])[['click', col_name]]
    mrr_df = mrr_df_group.apply(apply_func)
    ranks = mrr_df.to_numpy()
    ranks = ranks[~np.isnan(ranks)]
    reciprocal_ranks = 1 / ranks
    meanRR = reciprocal_ranks.mean()
    return meanRR

def calc_map(df, col_name):
    def apply_func(x_df):
        x_df = x_df.sort_values(by=[col_name], ascending=False)
        scores = x_df[col_name].to_numpy()
        clicks = x_df['click'].to_numpy()
        if clicks.sum() == 0:
            AP = np.nan
        else:
            AP = metrics.average_precision_score(clicks, scores)
        return AP
    df_group = df.groupby(['qid'])[['rank', 'click', col_name]]
    df = df_group.apply(apply_func)
    MAP = df.mean()
    return MAP

def calc_ndcg(df, col_name):
    def apply_func(x_df):
        x_df = x_df.sort_values(by=[col_name], ascending=False)
        scores = x_df[col_name].to_numpy().reshape(1, -1)
        clicks = x_df['click'].to_numpy().reshape(1, -1)
        if clicks.shape[-1] == 1 or clicks.sum() == 0:
            NDCG = np.nan
        else:
            NDCG = metrics.ndcg_score(clicks, scores)
        return NDCG
    df_group = df.groupby(['qid'])[['rank', 'click', col_name]]
    df = df_group.apply(apply_func)
    NDCG = df.mean()
    return NDCG

def rerank(df, col_name):
    def apply_func(x_df):
        x_df = x_df.sort_values(by=[col_name], ascending=False)
        x_df.reset_index(drop=True, inplace=True)
        x_df['rank'] = x_df.index
        x_df['rank'] = x_df['rank'] + 1
        return x_df
    df_group = df[['qid', 'docid', 'y_pred']].groupby(['qid'], group_keys=False)
    df = df_group.apply(apply_func)
    return df

def evaluate_metrics(y_true, y_pred, metrics, **kwargs):
    result = dict()
    if 'RERANK' in metrics and 'csv_dir' in kwargs and kwargs['csv_dir'] is not None:
        normal_metrics = False
    else:
        normal_metrics = True

    for metric in metrics:
        if metric in ['logloss', 'binary_crossentropy'] and normal_metrics:
            result[metric] = log_loss(y_true, y_pred, eps=1e-7)
        elif metric == 'AUC' and normal_metrics:
            result[metric] = roc_auc_score(y_true, y_pred)
        elif metric == "ACC" and normal_metrics:
            y_pred = np.argmax(y_pred, axis=1)
            result[metric] = accuracy_score(y_true, y_pred)
        else:
            if 'csv_dir' not in kwargs or kwargs['csv_dir'] is None:
                continue
            tsv_path = os.path.join(kwargs['csv_dir'], 'test.csv')
            df = pd.read_csv(tsv_path, skipinitialspace=True)
            df = df.join(pd.DataFrame(y_pred, columns=['y_pred']))

            file_y_true = df['click'].to_numpy()
            y_true = y_true.astype(int)
            assert (y_true == file_y_true).all()

            if metric == "MAP":
                result[metric] = calc_map(df, 'y_pred')

            elif metric == "NDCG":
                result['NDCG'] = calc_ndcg(df, 'y_pred')

            elif metric == "MRR":
                result[metric] = calc_mrr(df, 'y_pred')

            elif metric == "RERANK":
                expid = kwargs['expid']

                print('Writing model predictions ...')
                df.to_csv(f'model_predictions-{expid}.csv', index=False)

                df = rerank(df, 'y_pred')
                print('Writing RERANK output ...')
                with open(f'rerank_output-{expid}.txt', 'w') as fh:
                    for index, row in df.iterrows():
                        score = format(row['y_pred'], '.50f')
                        out = [row['qid'], '_', row['docid'],
                            row['rank'], score, 'FuxiCTR']
                        out = map(str, out)
                        print('\t'.join(out), file=fh)
                        fh.flush()

            #elif metric == "RERANK":
            #    df = df[['qid', 'docid', 'rank', 'y_pred']]
            #    expid = kwargs['expid']
            #    df.to_csv(f'rank_marginal-{expid}.txt')

    logging.info('[Metrics] ' + ' - '.join('{}: {:.6f}'.format(k, v) for k, v in result.items()))
    return result


class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict ={};
        for i,x in enumerate(numbers):
            dict.setdefault(x,i);

        for i,x in enumerate(numbers):
            complement = target - x;
            if(dict.__contains__(complement) and dict.get(complement) != i):
                pos = dict.get(complement);
                ans = [i+1,pos+1]
                ans.sort()
                return ans;


class Solution:
    def maxNumOfMarkedIndices(self, nums: List[int]) -> int:
        nums = sorted(nums)
        count = 0
        idx1, idx2 = 0, (len(nums)+1) // 2
        while idx2 < len(nums):
            if nums[idx1] * 2 <= nums[idx2]:
                idx1 += 1
            idx2 += 1
        return idx1 * 2


#!/usr/bin/python
import time
import json
import datetime
import decimal
import boto3
from boto3.dynamodb.conditions import Key, Attr

start = time.time()

dynamodb = boto3.resource('dynamodb', region_name='eu-west-1')

table = dynamodb.Table('BUD-BCN')

def show_price(date):
	response = table.query(
		KeyConditionExpression=Key('date').eq(date.strftime("%Y-%m-%d"))
	)

	print("--- ",date.strftime("%Y-%m-%d"))
	prev_price = 0
	for i in response['Items']:
		if i['price'] != prev_price:
			print(time.strftime('%Y %b %d %H:%M:%S', time.localtime(i['query_date'])), i['price'])
		prev_price = i['price']

date_end = datetime.datetime(2019,2,2,0,0)
d = datetime.datetime(2018,10,11,0,0)
td = datetime.timedelta(days=1)

while d < date_end:
	show_price(d)
	d = d + td


# The Nature of Code
# Daniel Shiffman
# http://natureofcode.com
#
# Modified by Filipe Calegario

# Draws a "vehicle" on the screen

from Vehicle import Vehicle
from Food import Food

def setup():
    global vehicle
    global food
    size(640, 360)
    velocity = PVector(0, 0)
    vehicle = Vehicle(width/2, height/2, velocity)
    food = Food(width, height)

def draw():
    background(255)
    targetPos = food.position

    vehicle.update(targetPos, food.intercept)
    vehicle.display()

    food.update(vehicle.position)
    food.display()


from os import getpid
from random import randint
from time import sleep, time
from multiprocessing import Process
from threading import Thread, Lock

def download_task(filename):
 print('启动下载任务, [%d].' % getpid())
 print('开始下载%s' % filename)
 time_to_download = randint(5, 10)
 print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))

def download_test ():
  start = time()
  p1 = Process(target=download_task, args=("Test.pdf"))
  p1.start()
  p2 = Process(target=download_task, args=("Test2.pdf"))
  p2.start()

  p1.join()
  p2.join()

  end = time()
  print('总共耗费了%.2f秒.' % (end - start))

# 多个线程之前的共享数据
"""
因为多个线程可以共享进程的内存空间，因此要实现多个线程间的通信相对简单，大家能想到的最直接的办法就是设置一个全局变量，多个线程共享这个全局变量即可。
但是当多个线程共享同一个变量（我们通常称之为“资源”）的时候，很有可能产生不可控的结果从而导致程序失效甚至崩溃
如果一个资源被多个线程竞争使用，那么我们通常称之为“临界资源”，对“临界资源”的访问需要加上保护，否则资源会处于“混乱”的状态。
"""

class Account(object):
    def __init__(self, *args):
      self._balance = 0
      self._lock = Lock()

    def deposit (self, money):
      self._lock.acquire() # 先获取锁才能执行后续的代码
      """
      我们可以通过“锁”来保护“临界资源”，只有获得“锁”的线程才能访问“临界资源”，
      而其他没有得到“锁”的线程只能被阻塞起来，直到获得“锁”的线程释放了“锁”，其他线程才有机会获得“锁”，
      进而访问被保护的“临界资源”。
      """
      try:
        new_balance = self.balance + money
        sleep(0.01) # 异步的耗时操作
        self._balance = new_balance
      finally:
        self._lock.release()

    @property
    def balance(self):
      return self._balance

class AddMoneyThread(Thread):
  def __init__(self, account, money):
    super().__init__()
    self._account = account
    self._money = money

  def run(self):
    self._account.deposit(self._money)

def share_data():
  account = Account()
  threads = []
  for index in range(100):
    t = AddMoneyThread(account, 1)
    threads.append(t)
    t.start()

  for item in threads:
    t.join()

  print('Balance is: %d ' % account.balance)

def main():
  print("Thread test")
  share_data()
if __name__ == '__main__':
    main()


#Math Library for PadmeBot
#Released under the BSD-new (3 clause) license. See COPYING for more information
import math
import padpreventionlib

class Physics:
    def get_weight(mass):
        preventor = padpreventionlib.Preventor
        is_number = preventor.is_number(str(mass))

        if is_number is True:
            return 'Weight: ' + str(float(mass) * 9.8) + ' N'

        else:
            return 'That is not a number!'

    def get_speed(distance, time):
        preventor = padpreventionlib.Preventor
        is_number1 = preventor.is_number(str(distance))
        is_number2 = preventor.is_number(str(time))

        if is_number1 is True and is_number2 is True:
            return 'Speed in km/h: ' + str(float(distance) / float(time))

        else:
            return 'That is not a number!'

    def get_kinetic_energy(mass, velocity):
        preventor = padpreventionlib.Preventor
        is_number1 = preventor.is_number(str(mass))
        is_number2 = preventor.is_number(str(velocity))

        if is_number1 is True and is_number2 is True:
            return 'Kinetic Energy: ' + str(0.5 * float(mass) * math.pow(float(velocity), 2))

        else:
            return 'That is not a number!'


#!/usr/bin/env python

# Improvements:
# List should be a dictionary that matches the MX record to their IP

import sys,os,json
import dns.resolver as dr
import nmap as nm

domains = []
serverNames = []

nmScan = nm.PortScanner()
port = 25

def getMXDN():
    for domain in domains:
        print('\b')
        print('='*30)
        print(f'{domain}')
        print('-'*30)
        try:
            for x in dr.resolve(domain, 'MX'):
                t = x.to_text()
                i = t.find(' ')
                n = t[i+1:-1]
                serverNames.append(n)
                print(n)
        except dr.NoAnswer:
            print('Error querying the domain')
        except dr.NXDOMAIN:
            print('DNS query name does not exist')
    print('Server MX names found: \b' + str(serverNames) + '\b')
    print('\b')

def getIP():
    serverIP = []
    for name in serverNames:
        for y in dr.resolve(name, 'A'):
            z = y.to_text()
            serverIP.append(z)
    serverIP = list(set(serverIP))
    return serverIP

def serverScan():
    for ip in getIP():
        print('='*30)
        nmScan.scan(ip, str(port))

        print("IP: " + ip)
        print("IP Status: ", nmScan[ip].state())
        print("Port state: ", nmScan[ip]['tcp'][port]['state'] if nmScan[ip].get('tcp')  else "")
        print('\b')

if len(sys.argv) > 1:
    #expect file path
    domain_list_file=sys.argv[1]
    if not os.path.exists(domain_list_file):
        print(f"The path {domain_list_file} doesn't contain a file")
        sys.exit(1)

    with open(domain_list_file,'r') as f:
        for line in f.readlines():
            domains.append(line.strip())
else:
    print(f"Missing positional argument domain_list_file.\nPlease specify path to a file containing new line delimitated domain names")
    sys.exit(1)
getMXDN()
serverScan()


import tabulate

import numpy as np

def make_table(y, x, yx, xsqr,y_pred,error):
    table = []
    for i in range(0, len(y)):
        table.append([y[i], x[i], yx[i], xsqr[i], y_pred[i],error[i]])
    return table

def main():
    y = np.asarray([240, 181, 193, 155, 172, 110, 113, 75, 94])
    x = np.asarray([1.6, 9.4, 15.5, 20.0, 22.0, 35.5, 43.0, 40.5, 33.0])
    n = len(y)
    sigma_x = np.sum(x)
    x_avg = sigma_x / n
    sigma_y = np.sum(y)
    y_avg = sigma_y / n
    yx = y * x
    xsqr = x * x
    sigma_yx = np.sum(yx)
    sigma_xsqr = np.sum(xsqr)
    b1 = (sigma_yx - sigma_y * sigma_x / n)/ (sigma_xsqr - (sigma_x)**2 /n)
    b0 =  y_avg - b1 * x_avg
    y_pred = b0 + b1 * x
    error = y - y_pred
    table = make_table(y,x,yx,xsqr,y_pred,error)
    print(tabulate.tabulate(table, headers=['yi','xi','yixi','xisqr','y_pred','error=y - y_pred']))
    print('sigma x = %f sigma y = %f sigma yx = %f sigma xsqr = %f'%(sigma_x,sigma_y,sigma_yx,sigma_xsqr))
    print('b0 = %f , b1 = %f'%(b0,b1))

if __name__ == '__main__':
    main()