import os
import pygtk
pygtk.require('2.0')
import gtk, gtk.glade, time
from ventana import Ventana
from framework import pclases
import utils
import cmdgtk

class Trazabilidad(Ventana):
    """
    Ventana de trazabilidad interna de objetos.
    Acepta tanto códigos de trazabilidad como consultas a la BD de SQLObject.
    """
    def __init__(self, objeto = None, usuario = None, ventana_padre = None, locals_adicionales = {}):
        try:
            Ventana.__init__(self, 'trazabilidad.glade', objeto)
        except:     # Tal vez me estén llamando desde otro directorio
            Ventana.__init__(self, os.path.join('..', 'formularios', 'trazabilidad.glade'), objeto)
        connections = {'b_salir/clicked': self.salir,
                       'b_buscar/clicked': self.buscar}
        self.add_connections(connections)
        cols = (('ID', 'gobject.TYPE_STRING', False, False, False, None),
                ('campo', 'gobject.TYPE_STRING', False, False, False, None),
                ('valor', 'gobject.TYPE_STRING', True, False, True, self.cambiar_valor),
                ('clase', 'gobject.TYPE_STRING', False, False, False, None))
        utils.ui.preparar_treeview(self.wids['tv_datos'], cols)
        self.wids['e_num'].connect("key_press_event", self.pasar_foco)
        self.wids['tv_datos'].connect("row-expanded", self.expandir)
        self.wids['tv_datos'].connect("row-collapsed", self.cerrar)
        self.wids['e_search'].set_property("visible", False)
        import pyconsole
        vars_locales = locals()
        for k in locals_adicionales:
            vars_locales[k] = locals_adicionales[k]
        pyconsole.attach_console(self.wids['contenedor_consola'],
                                 banner = "Consola python de depuración GINN",
                                 script_inicio = """import sys, os, pygtk, gtk, gtk.glade, utils
from framework import pclases
import datetime
if os.path.realpath(os.path.curdir).split(os.path.sep)[-1] == "formularios":
    os.chdir("..")
sys.path.append(".")
from formularios.ventana_generica import VentanaGenerica as Ver
dir()
#Ver(self.objeto)
""",
                                            locals = vars_locales)
        if objeto != None:
            self.rellenar_datos(objeto)
        cmd_gtk = cmdgtk.CmdGTK()
        cmd_gtk.attach_to(self.wids['boxcmd'])
        #-----------------------------------------------------------------------------------------------#
        def comprobar_que_no_me_hace_el_gato(paned, scrolltype_or_allocation_or_requisition = None):    #
            width = self.wids['ventana'].get_size()[0]                                                  #
            MIN =  width / 2                                                                            #
            MAX = width - 100                                                                           #
            posactual = paned.get_position()                                                            #
            if posactual < MIN:                                                                         #
                paned.set_position(MIN)                                                                 #
            elif posactual > MAX:                                                                       #
                paned.set_position(MAX)                                                                 #
        #-----------------------------------------------------------------------------------------------#
        self.wids['hpaned1'].connect("size_request", comprobar_que_no_me_hace_el_gato)
        self.wids['ventana'].resize(800, 600)
        self.wids['hpaned1'].set_position(self.wids['ventana'].get_size()[0] / 2)
        self.wids['ventana'].set_position(gtk.WIN_POS_CENTER)
        gtk.main()

    def pasar_foco(self, widget, event):
        if event.keyval == 65293 or event.keyval == 65421:
            self.wids['b_buscar'].grab_focus()

    def chequear_cambios(self):
        pass

    def buscar(self, b):
        a_buscar = self.wids['e_num'].get_text()
        if "pclases." in a_buscar and ("select" in a_buscar or "get" in a_buscar):
            try:
                self.rellenar_datos(eval(a_buscar))
            except:
                utils.ui.dialogo_info(titulo = "ERROR EN CONSULTA",
                                   texto = "La consulta:\n%s\nprovocó una excepción." % a_buscar,
                                   padre = self.wids['ventana'])
        else:
            import seeker
            buscador = seeker.Seeker()
            buscador.buscar(a_buscar)
            if buscador.resultados:
                self.rellenar_datos(buscador.resultados[0].resultado)

    def rellenar_datos(self, articulo):
        model = self.wids['tv_datos'].get_model()
        model.clear()
        iter = self.insertar_rama(articulo, None, model)

    def insertar_rama(self, objeto, padre, model):
        iter = self.insertar_nombre(objeto, padre, model)
        self.insertar_campos(objeto, iter, model)
        self.insertar_ajenos(objeto, iter, model)
        self.insertar_multiples(objeto, iter, model)
        return iter

    def insertar_nombre(self, objeto, padre, model, nombre_opcional = ""):
        if objeto == None:
            iter = model.append(padre, ("",
                                        nombre_opcional,
                                        "",
                                        ""))
            return None
        else:
            try:
                nombretabla = objeto.sqlmeta.table
            except AttributeError: # SQLObject <= 0.6.1
                nombretabla = objeto._table
            iter = model.append(padre, (objeto.id,
                                        nombretabla,
                                        "",
                                        objeto.__class__.__name__))
            return iter

    def insertar_campos(self, objeto, padre, model):
        """
        Inserta los campos del objeto colgando de la rama "iter".
        Siempre empieza por el ID y el nombre de la tabla del objeto y
        a continuación sus campos.
        Devuelve el iter del objeto insertado.
        """
        if padre == None: return
        try:
            campos = [c for c in objeto._SO_columnDict
                      if not c.upper().endswith('ID')]
        except AttributeError:  # SQLObject > 0.6.1
            campos = [c for c in objeto.sqlmeta.columns
                      if not c.upper().endswith("ID")]
        for campo in campos:
            model.append(padre, ("", campo, getattr(objeto, campo), ""))
        # return iter

    def insertar_ajenos(self, objeto, padre, model):
        """
        Inserta los nombres de las claves ajenas del objeto
        con un "child" vacío para poder mostrar el desplegable y
        rellenar los campos de la clave ajena en cuestión en caso
        de que se despliegue.
        """
        if padre == None: return
        try:
            ajenas = [c for c in objeto._SO_columnDict
                      if c.upper().endswith('ID')]
        except AttributeError:  # SQLObject > 0.6.1
            ajenas = [c for c in objeto.sqlmeta.columns
                      if c.upper().endswith('ID')]
        for ajena in ajenas:
            reg_ajena = ajena[:-2]
            obj_d = getattr(objeto, reg_ajena)
            iter = self.insertar_nombre(obj_d, padre, model, reg_ajena)
            model.append(iter, ("", "", "", ""))

    def insertar_multiples(self, objeto, padre, model):
        """
        Inserta un campo con desplegable por cada relación a muchos
        del objeto, y dentro de éste tantos nombres de la tabla ajena
        como tuplas relacionadas que tenga.
        Además, por cada tupla creará un "child" vacío que se susituirá
        por los datos de este registro cuando expanda la fila.
        """
        if padre == None: return
        try:
            multiples = objeto._SO_joinList
        except AttributeError:  # SQLObject > 0.6.1
            multiples = objeto.sqlmeta.joins
        for multiple in multiples:
            lista_objs = getattr(objeto, multiple.joinMethodName)
            # print multiple.joinMethodName, lista_objs
            for obj_d in lista_objs:
                iter = self.insertar_nombre(obj_d, padre, model, multiple.otherClassName)
                model.append(iter, ("", "", "", ""))

    def expandir(self, tv, iter, path):
        model = tv.get_model()
        child = model[path].iterchildren().next()
        if child[0] == "" and \
           child[1] == "" and \
           child[2] == "" and \
           child[3] == "":
            model.remove(child.iter)
            id = int(model[path][0])
            clase = model[path][-1]
#            print clase, id
            try:
                objeto = eval('pclases.%s.get(%d)' % (clase, id))
            except pclases.SQLObjectNotFound:
                utils.ui.dialogo_info(titulo = "ERROR",
                    texto = "El objeto %s con ID %d no existe." % (clase, id))
            padre = model.get_iter(path)
            try:
                objeto.sync()
            except pclases.SQLObjectNotFound:
                model[path][0] = ""
                model[path][2] = ""
                model[path][3] = ""
            self.insertar_campos(objeto, padre, model)
            self.insertar_ajenos(objeto, padre, model)
            self.insertar_multiples(objeto, padre, model)
            tv.expand_row(path, False)

    def cerrar(self, tv, iter, path):
        model = tv.get_model()
        iterador = model[path].iterchildren()
        try:
            hijo = iterador.next()
            while (1):
                model.remove(hijo.iter)
                hijo = iterador.next()
        except StopIteration:
            pass
        model.append(iter, ("", "", "", ""))

    def cambiar_valor(self, cell, path, text):
        model = self.wids['tv_datos'].get_model()
        if model[path][0] == "":
            if model[path].parent != None:
                id = model[path].parent[0]
                clase = model[path].parent[-1]
                campo = model[path][1]
                objeto = eval("pclases.%s.get(%d)" % (clase, int(id)))
                objeto.syncUpdate()
                try:
                    setattr(objeto, campo, text)
                    model[path][2] = getattr(objeto, campo)
                except:
                    utils.ui.dialogo_info(titulo = "ERROR",
                        texto = "Valor incorrecto para este campo.")

if __name__ == '__main__':
    t = Trazabilidad()


import chess
import chess.svg
from chessboard import display
from chess import Move
import time
import random
import math

board = chess.Board("8/8/8/8/8/8/8/8 w - - 0 1")

# Erste Königing setzen
"""board.set_piece_at(16,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(9,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(34,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(27,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(20,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(13,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(6,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(23,chess.Piece(chess.QUEEN,chess.WHITE))"""

"""board.set_piece_at(16,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(9,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(50,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(35,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(12,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(29,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(6,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(7,chess.Piece(chess.QUEEN,chess.WHITE))"""

"""board.set_piece_at(8,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(25,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(50,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(27,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(60,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(37,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(38,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(15,chess.Piece(chess.QUEEN,chess.WHITE))"""

"""board.set_piece_at(8,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(25,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(26,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(3,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(5,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(14,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(31,chess.Piece(chess.QUEEN,chess.WHITE))
board.set_piece_at(36,chess.Piece(chess.QUEEN,chess.WHITE))"""

def test(i):
    if i == 1:
        board.set_piece_at(16,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(9,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(34,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(27,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(20,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(13,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(6,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(23,chess.Piece(chess.QUEEN,chess.WHITE))

    if i == 2:
        board.set_piece_at(16,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(9,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(50,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(35,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(12,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(29,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(6,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(7,chess.Piece(chess.QUEEN,chess.WHITE))
    if i == 3:
        board.set_piece_at(8,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(25,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(50,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(27,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(60,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(37,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(38,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(15,chess.Piece(chess.QUEEN,chess.WHITE))
    if i == 4:
        board.set_piece_at(8,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(25,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(26,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(3,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(5,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(14,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(31,chess.Piece(chess.QUEEN,chess.WHITE))
        board.set_piece_at(36,chess.Piece(chess.QUEEN,chess.WHITE))

#schauen wo meine damen sind
#print(board.piece_map().keys())
"""
alle damen felder
for square in chess.SQUARES:
    piece = board.piece_at(square)
    if piece is not None:
        # Den Feldnamen der Figur ausgeben
        print(chess.square_name(square))
"""

#
#print(board.piece_at(7))
#print(ord('a'))
#print(chr(97))
#print(chess.square_rank(16))

class Queen:
    notPossibleMoves = []
    transModel = []
    initialState = None
    arrVisited = []
    totalFitness = 0
    populationsArr = []

    #genetic algorithm
    population = []

    def __init__(self, initialState = None, transModel = None):
        if initialState is None:
            self.initialState = [0,0,0,0,0,0,0,0]

        if transModel is None:
            for i in range(0,64):
                if i not in self.notPossibleMoves and i not in self.transModel:
                    self.transModel.append(i)

    def checkNotInArray(self, i):
        if i not in self.notPossibleMoves:
            self.notPossibleMoves.append(i)

    def possibleMoves(self):
        self.notPossibleMoves = []
        for i in range(0, 64):
            if board.piece_at(i) != None:
                self.checkRowQueen(i,True)
                self.checkColumnQueen(i,True)
                self.checkDiagonalQueen(i,True)

        return self.notPossibleMoves

    def actions(self, state):
        # aktion um den zustand zu ändern
        # Figur bewegen
        #move = Move.from_uci(state)
        #board.push(move)
        board.set_piece_at(state,chess.Piece(chess.QUEEN,chess.WHITE))

    def checkRowQueen(self, state,justNotPossibleMoves = False):
        # überprüft wie viele threads in der zeile sind
        # mit Parameterwert True werden mit der Methode checkNotInFunction in das Array notPossibleMoves alle werte geschrieben die nicht mehr möglich sind
        counter = 0
        rowNumber = chess.square_rank(state)

        rowBeginning = (rowNumber * 8)
        rowEnd = (((rowNumber + 1) * 8) -1)

        #print("rowNumber: " + str(rowNumber))
        #print("rowBeginning: " + str(rowBeginning))
        #print("rowEnd: " + str(rowEnd))

        #ZEILE ÜBERPRÜFEN
        test = False
        for cnt in range(rowBeginning , rowEnd + 1):

            if board.piece_at(cnt) != None :

                    test = True
                    counter = counter + 1
                    #print("Row Collision mit: " + str(cnt) + " = COUNTER:  " + str(counter))
            if justNotPossibleMoves == True:
                #print(justNotPossibleMoves)
                self.checkNotInArray(cnt)

        if test == True:
            return counter -1
        else:
            return 0

    def checkColumnQueen(self, state, justNotPossibleMoves = False):
        # überprüft wie viele threads in der spalte sind
        # mit Parameterwert True werden mit der Methode checkNotInFunction in das Array notPossibleMoves alle werte geschrieben die nicht mehr möglich sind
        columnBegin = state
        columnEnd = state
        counter = 0
        while columnBegin > 0:
            if (columnBegin - 8) >= 0:
                columnBegin = columnBegin-8
            if columnBegin >= 0 and columnBegin <= 7:
                break

        while columnEnd <= 63:
            if (columnEnd + 8 ) <= 63:
                columnEnd = columnEnd + 8
            if columnEnd >= 56 and columnEnd <= 63:
                break

        test = False

        for cnt in range(columnBegin , columnEnd + 1, 8):
                if board.piece_at(cnt) != None:
                    test = True
                    counter = counter + 1
                    #print("counter : " + str(counter))
                    self.arrVisited.append(cnt)
                    #print(self.arrVisited)
                    #print("Column Collision mit: " + str(cnt) + " = COUNTER:  " + str(counter))
                if justNotPossibleMoves == True:
                    self.checkNotInArray(cnt)
        #print("BEFORE RETURN COUNTER: " + str(counter))

        if test == True:
            #print("RETURN COUNTER: " + str(counter))
            return counter - 1
        else:
            return 0

    def LBU(self, state, justNotPossibleMoves = False):
        counter = 0
        yBorderLeft = []
        yBorderRight = []
        xBorderUnder = []
        xBorderAbove = []

        leftBeginUnder = state
        rightEndAbove = state

        for cnt in range(0,57,8):
            yBorderLeft.append(cnt)
        for cnt in range(7,64,8):
            yBorderRight.append(cnt)
        for cnt in range(0,8,1):
            xBorderUnder.append(cnt)
        for cnt in range(56,64,1):
            xBorderAbove.append(cnt)

        if leftBeginUnder not in yBorderLeft:
            while leftBeginUnder not in yBorderLeft:
                if ((leftBeginUnder - 8) - 1) < 0:
                    break
                leftBeginUnder = (leftBeginUnder - 8) - 1

        if rightEndAbove not in yBorderRight:
            while rightEndAbove not in yBorderRight:
                if ((rightEndAbove +8) +1) > 63:
                    break
                rightEndAbove = (rightEndAbove + 8) + 1

        checkFirst = False
        #schaut diagonal von unten links nach oben rechts ob eine dame gesetzt ist
        if justNotPossibleMoves == True:
                self.checkNotInArray(leftBeginUnder)

        #print("LeftBeginUnder: " + str(leftBeginUnder))
        #print("rightEndAbove: " + str(rightEndAbove))
        #print()

        while (leftBeginUnder + 1) + 8 < rightEndAbove + 1:

            if board.piece_at(leftBeginUnder) is not None:
                checkFirst = True
                counter = counter + 1
                #print("LBU: " + str(leftBeginUnder) + " :::: " + str(counter) )
            leftBeginUnder = (leftBeginUnder + 8) +1

            if justNotPossibleMoves == True:
                self.checkNotInArray(leftBeginUnder)

        #print("KOLLISION MIT DIAGONAL: " + str(leftBeginUnder) + " -" + str(counter))

        if checkFirst == True:
            counter = counter - 1
        return counter

    def LBA(self, state, justNotPossibleMoves = False):
             # überprüft wie viele threads in der diagonale sind
        # mit Parameterwert True werden mit der Methode checkNotInFunction in das Array notPossibleMoves alle werte geschrieben die nicht mehr möglich sind
        counter = 0
        yBorderLeft = []
        yBorderRight = []
        xBorderUnder = []
        xBorderAbove = []

        leftBeginUnder = state
        rightEndAbove = state
        leftBeginAbove = state
        rightEndUnder = state

        for cnt in range(0,57,8):
            yBorderLeft.append(cnt)
        for cnt in range(7,64,8):
            yBorderRight.append(cnt)
        for cnt in range(0,8,1):
            xBorderUnder.append(cnt)
        for cnt in range(56,64,1):
            xBorderAbove.append(cnt)

        if leftBeginAbove not in yBorderLeft:
            while leftBeginAbove not in yBorderLeft:
                if ((leftBeginAbove + 8) - 1) > 63:
                    break
                leftBeginAbove = (leftBeginAbove + 8 ) - 1

        if rightEndUnder not in yBorderRight:
                while rightEndUnder not in yBorderRight:
                    if ((rightEndUnder - 8) +1) < 0:
                        break
                    rightEndUnder = (rightEndUnder - 8) + 1

        checkSecond = False
        #print("LeftBeginAbove: " + str(leftBeginAbove))
        #print("rightEndAbove: " + str(rightEndUnder))
        # print()
        # schaut diagonal von oben links nach unten rechts ob eine dame gesetzt ist
        if justNotPossibleMoves == True:
                self.checkNotInArray(leftBeginAbove)

        test = False
        while (leftBeginAbove - 8 ) + 1 >= rightEndAbove :
            if board.piece_at(leftBeginAbove) is not None:
                #print(leftBeginAbove)
                checkSecond = True
                counter = counter + 1

                #print("LBA: " + str(leftBeginAbove) + " :::: " + str(counter))

            #print(leftBeginUnder)

            #print("T: " + str(leftBeginAbove))
            if justNotPossibleMoves == True:
                self.checkNotInArray(leftBeginAbove)

            leftBeginAbove = (leftBeginAbove - 8) + 1

        if board.piece_at(leftBeginAbove) is not None:
                #print(leftBeginAbove)

                checkSecond = True
                counter = counter+1
                #print("LBA: " + str(leftBeginAbove) + " :::: " + str(counter))

        #print("KOLLISION MIT DIAGONAL: " + str(leftBeginUnder) + " ::::: " + str(counter))

        if checkSecond == True:
            counter = counter - 1

        #print(self.notPossibleMoves)
        return counter

    def checkDiagonalQueen(self, state, justNotPossibleMoves = False):
        # überprüft wie viele threads in der diagonale sind
        # mit Parameterwert True werden mit der Methode checkNotInFunction in das Array notPossibleMoves alle werte geschrieben die nicht mehr möglich sind

        #leftbeginAbove#############################rightEndAbove
        #########################################################
        #########################################################
        #########################################################
        #########################################################
        #########################################################
        #########################################################
        #########################################################
        #########################################################
        #########################################################
        #leftBeginUnder#############################rightEndUnder

        c = self.LBA(state)
        d = self.LBU(state)

        #print(self.notPossibleMoves)
        return c + d

    def heuristic(self, state):
        # pairs of threatening queens
        # state sollte ein integer sein!!!

        #board.piece_at(1) prüft ob sich das Feld belegt ist wenn nein dann None

        #zeile in der sich die queen befindet
        rowThreadingCount = self.checkRowQueen(state)
        columnThreadingCount = self.checkColumnQueen(state)
        diagonalThreadUA = self.checkDiagonalQueen(state)

        #zähle die Threads zusammen

        counter = rowThreadingCount  + columnThreadingCount + diagonalThreadUA

        return counter
        #return rowThreadingCount

    def cost(self, state, action):
        # berechnet die kosten der aktion
        # previousCost sind die Kosten von der letzten platzierung der Dame und expectedCost sind die Kosten
        # von der aktuellen position wenn ich die Dame auf das Feld setzen möchte. Wenn die Kosten höher sind
        # als davor dann soll ein neues feld gesucht werden
        previousCost = self.heuristic(state)
        exceptedCost = self.heuristic(action)
        return previousCost + exceptedCost

    def boardASCII(self):
        #ASCII vom Board ausgeben
        print(board)

    def threadeningLBUCount(self):
            val = 64
            t = False
            counter = 0
            while t == False:
                if (val-8) >= 0:
                    val = val -8
                else:
                    val = val + 1
                #print(val)

                counter = counter + queen.LBU(val)
                #print("Bei " + str(val) + " wurden so viele Threadings entdeckt : " + str(cnt) )
                if val == 7:
                    t = True

            return counter
    def threadeningLBACount(self):
            val = 0
            t = False
            counter = 0
            while t == False:
                if (val + 1) < 8:
                    val = val + 1
                else:
                    val = val + 8
                #print(val)

                counter = counter + queen.LBA(val)
                #print("Bei " + str(val) + " wurden so viele Threadings entdeckt : " + str(cnt) )
                if val == 63:
                    t = True

            return counter

    def threadeningRowCount(self):
            counter = 0
            spalteX = []

            for i in range(0,64):
                if board.piece_at(i) != None:
                    if chess.square_rank(i) not in spalteX:
                        if queen.checkRowQueen(i) >= 1:
                            counter = queen.checkRowQueen(i) + counter
                    spalteX.append(chess.square_rank(i))
            return counter
    def threadeningColumnCount(self):
           counter = 0
           for i in range(0,8):
                #spalte 1 bis 7 geben um pro spalte zuschauen
                counter  = queen.checkColumnQueen(i) + counter
           return counter

    def countOfThreadeningQueens(self):

            counter = self.threadeningLBUCount() + self.threadeningRowCount() + self.threadeningLBACount() + self.threadeningColumnCount()

            return counter

    def fitnessFunctionPercentage(self, val):
        # val ist die anzahl der threatenings

        if self.totalFitness != 0:
            val = round((val / self.totalFitness) * 100, 2)

            return val

    def fitnessFunction(self, setTotalFitnessCalc = False):
                fitness = self.threadeningLBUCount() + self.threadeningRowCount() + self.threadeningLBACount() + self.threadeningColumnCount()
                return 28 - (fitness)

    def setTotalFitnessCalc(self, fitness):
        # berechnet die gesamsumme der fitness
        #print(str(self.totalFitness) + " + (28 - " + str(fitness) + " )")
        #self.totalFitness = self.totalFitness + (28 -  fitness)
        fitnessVal = 0
        for i in self.populationsArr:
            fitnessVal = fitnessVal + int(i["fitness"])

        #print(fitnessVal)
        self.totalFitness = fitnessVal

    def is_valid_state(self, state):
            # Überprüfen, ob das gegebene state eine gültige Lösung für das 8-Damen-Problem ist
            n = len(state)
            if len(set(state)) != n:
                return False
            if len(set(i+state[i] for i in range(n))) != n:
                return False
            if len(set(i-state[i] for i in range(n))) != n:
                return False
            return True

    def generate_valid_state(self):
    # zufällige generierte states
        while True:
            state = random.sample(range(8), 8)
            if self.is_valid_state(state):
                return state

    def populations(self, k):
        randValArr = []
        for i in range(k):
            randValArr.append(self.generate_valid_state())
        return randValArr

    def printPopulations(self):
         for i in self.populationsArr:
              fitness = int(i["fitness"])
              fitnessPercentage = float(self.fitnessFunctionPercentage(fitness))
              i["fitnessPercentage"]  = fitnessPercentage
              print("\nPopulationnumber: " + str(i["populationNumber"]))
              print("Fitness: " + str(i["fitness"]))
              print("TotalFitness: "  + str(self.totalFitness))
              print("Fitnesspercentage: " + str(fitnessPercentage) + " % ")

    def printAndCheckBestOnBoard(self,popNewArr):
        fitness = 0
        populationNumber = 0
        sieg  = False
        for i in popNewArr:
            fitness = i["fitness"]
            if fitness == 28:
                populationNumber = int(i["populationNumber"])
                sieg = True
                break

        columnCounter = 0
        check = 0

        for i in popNewArr:
            queens = i["population"]
            if int(i["populationNumber"]) == populationNumber and sieg == True:
                for j in queens:
                    if columnCounter == 8:
                            columnCounter = 0

                    board.set_piece_at((( 8 * j) + columnCounter),chess.Piece(chess.QUEEN,chess.WHITE))

                    columnCounter = columnCounter + 1

        for i in popNewArr:
             if int(i["populationNumber"]) == populationNumber and sieg == True:
                print()
                print("''''''''''''''''''''''''''''''''''''''''''''''''''''''''''")
                print("Gewonnen hat: " +str(i["populationNumber"]))
                print("Population: " +str(i["population"]))
                print("Mit einer Fitness von: "+ str(i["fitness"]))
                print("Mit einer Fitness Percentage: " + str(i["fitnessPercentage"]))
                break

        print()

    def selection(self):
            popArr = self.populationsArr
            #print(self.populationsArr)
            popNewArr = []
            solutionArr = []
            for i in range(0, len(self.populationsArr)):
                rand = random.randrange(0,len(self.populationsArr))
                #print(rand)
                popNewArr.append(popArr[rand])

            #print(popNewArr)
            newRand = 0
            ungerade = False
            for i in range(0,len(popNewArr)):
                population1 = None
                population2 = None
                if (len(popNewArr) % 2) != 0 and i == len(popNewArr[len(popNewArr)-1]):
                    newRand = random.randrange(0,len(popNewArr))
                    ungerade = True

                if i == len(popNewArr) - 1 and ungerade == True:

                    population1 = popNewArr[len(popNewArr)-1]["population"]
                    population2 = popNewArr[newRand]["population"]
                    #print("Pop1: " + str(population1))
                    #print("Pop2: " + str(population2))
                    #print("LAST: " + str( len(popNewArr)-1))
                    #print("NEWRAND: " + str(newRand))
                    arr = self.crossover(population1, population2)

                    popNewArr[len(popNewArr)-1]["population"] = arr[0]
                    popNewArr[newRand]["population"] = arr[1]

                    #print("AFTER CROSS " + str(popNewArr[len(popNewArr)-1]["population"]))
                    #print(popNewArr[newRand]["population"])
                else:
                    newRand = random.randrange(0,len(popNewArr))
                    newRand2 = newRand
                    while newRand == newRand2:
                        newRand2 = random.randrange(0,len(popNewArr))
                    population1 = popNewArr[newRand]["population"]
                    population2 = popNewArr[newRand2]["population"]

                    arr = self.crossover(population1,population2)

                    popNewArr[newRand]["population"] = arr[0]
                    popNewArr[newRand2]["population"] = arr[1]

                rand = random.randrange(0,len(popNewArr))

            popNewArr = self.mutation(popNewArr)
            self.printAndCheckBestOnBoard(popNewArr)

    def crossover(self, arr1, arr2):
        splitt = random.sample(range(1, 7), 1)
        tmpArr1 = []
        tmpArr2 = []
        for i in range(0,8):
            if i <= splitt[0]:
                #print(arr1)
                #print(arr2)
                #print("SPLITT: " + str(splitt))
                tmpArr1.append(arr1[i])
                tmpArr2.append(arr2[i])
            else:
                tmpArr1.append(arr2[i])
                tmpArr2.append(arr1[i])

        arr1 = tmpArr1
        arr2 = tmpArr2

        return [arr1, arr2]

    def mutation(self, arr):
        randomVal = random.randrange(8)
        rand = random.randrange(8)

        while randomVal == rand:
            rand = random.randrange(8)
        for i in arr:
            #print("BEFORE: " + str(i["population"]))
            newArr = i["population"]
            newArr[randomVal] = rand
            i["population"] = newArr
            #print("aFter: " + str(i["population"]))
        return arr

    def orderPopulationArray(self):
        # ordnet das assoziative array nach fitnessfunction größe
        self.populationsArr.sort(key=lambda x: x["fitnessPercentage"], reverse=True)

    def setQueens(self, populationsAnzahl, Test = False):
         popuArr = self.populations( populationsAnzahl)
         arr = []
         counter = 0
         columnCounter = 0
         populationNumber = 0
         print(popuArr)
         for i in popuArr:
            new_arr = arr.copy()

            #print("Counter: " + str(counter))
            if Test == False:
                for j in i:
                    new_arr.append(j)
                    if columnCounter == 8:
                        columnCounter = 0

                    #print("COLUMNCOUNTER: " + str(columnCounter) + " j: " + str(j))

                    board.set_piece_at((( 8 * j) + columnCounter),chess.Piece(chess.QUEEN,chess.WHITE))
                    columnCounter = columnCounter + 1

                #print(arr)
                self.populationsArr.append({
                            "populationNumber" : populationNumber ,
                            "fitness" : self.fitnessFunction(),
                            "population" : new_arr,
                            "fitnessPercentage" : 0
                })
                #print(self.populationsArr)

                print("PopulationNumber: " + str(populationNumber))
                self.boardASCII()

                self.setTotalFitnessCalc(self.fitnessFunction())
                        #print(self.populationsArr)
                        #self.fitnessFunctionPercentage(populations)
                print()
                #print("HIER: "+ str(self.populationsArr))
                board.clear()

                counter = counter + 1
                populationNumber = populationNumber +1

                queen.orderPopulationArray()

            else:
                for i in range(1,5):
                    test(i)
                    self.boardASCII()

                    self.populationsArr.append({
                        "populationNumber" : populationNumber ,
                        "fitness" : self.fitnessFunction(),
                        "population" : arr,
                        "fitnessPercentage" : 0
                    })

                    self.setTotalFitnessCalc(self.fitnessFunction())
                    #print(self.populationsArr)
                    #self.fitnessFunctionPercentage(populations)
                    print()

                    board.clear()

                    counter = counter + 1
                    populationNumber = populationNumber +1

         #self.printPopulations()
         self.selection()

         #print(selected)
         #board.set_piece_at(8,chess.Piece(chess.QUEEN,chess.WHITE))

    def geneticAlgorithm(self):

        return

queen = Queen()

#print("Fitness: " + str(queen.fitnessFunction()))
#print("Threadening: "  +str(queen.countOfThreadeningQueens()))
#print("TotalFitness: " + str(queen.totalFitness))
#print("TotalFitness: " + str(queen.populations(1)))

# test
#queen.setQueens(1, True)

queen.setQueens(100)

#arr1 = [3,2,7,5,2,4,1,1]
#arr2 = [2,4,7,4,8,5,5,2]
#print(queen.crossover(arr1,arr2))

#print("BEFORE: " + str(arr1))
#rint("AFTER:  " + str(queen.mutation(arr1)))

#queen.possibleMoves()
#print(queen.heuristic(17))
#print(queen.fitnessFunction())
#print(queen.geneticAlgorithm(100,100,1000))

# Fen ist eine Notation um die Posititon der Schachfiguren auf einem Schabrett darzustellen
valid_fen = board.fen()
game_board = display.start()

n = 0
while True:
    #valid_fen = board.fen()
    #n = (n + 8)
    #board.set_piece_at(n,chess.Piece(chess.QUEEN,chess.WHITE))

    display.check_for_quit()
    display.update(valid_fen, game_board)
    time.sleep(0.5)

display.terminate()


import matplotlib.pyplot as plt
import random
import pandas as pd
import numpy as np

df = pd.DataFrame()

df['y'] = [random.random() for _ in range(200)]

df['I'] =  [random.random() for _ in range(200)]

df['II'] = df['y']  + ( [random.random()/4 for _ in range(200)] )
df['IIa'] = np.where( df['II'] <1.0, df['II'], df['II']-0.2 )

df['II'] = (1-df['y'])  + ( [random.random()/4 for _ in range(200)] )
df['IIb'] = np.where( df['II'] <1.0, df['II'], df['II']-0.2 )

df['III'] =  np.where( df['IIa'] < 0.5, df['IIa'], 0.5+ (df['I']/2) )

df['IV'] =  np.where( df['y'] > 0.4, np.where( df['y'] < 0.6, 0.5, 0.5+(df['I']/2) ), 0.5-(df['I']/2) )

df['V'] =  df['y']*df['y']  + ( [random.random()/10 for _ in range(200)] )

df['VI'] = np.where( df['I'] < 0.5, 0.5 - (np.sqrt(df['y'])/2) + (df['I']/10 ), 0.5 + (np.sqrt(df['y'])/2) + (df['I']/10 ) )

df['VII'] = np.where( df['y'] < 0.3, 0.5 + pow(df['IIb'], 2)/4 , np.where( df['y'] > 0.7, 0.5+ pow(df['IIa'],2)/4, 0.7 - pow(df['IIa'],3) ) )

###############################
# Create Figure and Subplots

fig, axes = plt.subplots(4,2, figsize=(10,8), sharex=True, sharey=True, dpi=120)

axes[0,0].scatter(df['I'], df['y'], alpha=0.5)
axes[0,0].set_title('1 - Random')

axes[0,1].scatter(df['IIa'], df['y'], alpha=0.5)
axes[0,1].set_title('2a - Linear Correlation')

axes[1,0].scatter(df['IIb'], df['y'], alpha=0.5)
axes[1,0].set_title('2b - Linear Anticorrelation')

axes[1,1].scatter(df['III'], df['y'], alpha=0.5)
axes[1,1].set_title('3 - Partial Linear Correlation')

axes[2,0].scatter(df['IV'], df['y'], alpha=0.5)
axes[2,0].set_title('4 - Step Function')

axes[2,1].scatter(df['V'], df['y'], alpha=0.5)
axes[2,1].set_title('5 - Nonlinear Monotonic')

axes[3,0].scatter(df['VI'], df['y'], alpha=0.5)
axes[3,0].set_title('6 - Nonlinear Nonmonotonic')

axes[3,1].scatter(df['VII'], df['y'], alpha=0.5)
axes[3,1].set_title('7 - Nonbijective')

#plt.savefig('univariate_relationships.svg', format='svg', dpi=300)
plt.savefig('univariate_relationships.png',  dpi=300)
#plt.savefig('univariate_relationships.eps', format='eps')


'''manifest.py'''
import json
from datetime import datetime
from typing import List, Union

from fonty.models.font import FontFamily, InstalledFont
from fonty.lib.constants import APP_DIR, MANIFEST_PATH, JSON_DUMP_OPTS
from fonty.lib.list_fonts import get_user_fonts, get_user_fonts_count
from fonty.lib.json_encoder import FontyJSONEncoder
from fonty.lib.variants import FontAttribute
from fonty.lib import utils

class Manifest:
    '''Manifest is a class to manage a manifest list of installed fonts on the user's system.'''

    # Class Attributes

    schema_version: str = "0.1.0"
    families: List[FontFamily]
    last_modified: datetime
    font_count: int

    # Constructor

    def __init__(
        self,
        families: List[FontFamily],
        last_modified: Union[str, datetime] = None,
        font_count: int = 0
    ) -> None:
        self.families = families
        self.last_modified = utils.parse_date(last_modified)
        self.font_count = font_count

    # Class Methods

    def add(self, font: InstalledFont) -> int:
        '''Add a font to the manifest.'''

        family_name = font.get_family_name()

        # Load existing or create a FontFamily object
        family = self.get(family_name)
        family_idx = self.get_index(family_name)
        if family is None:
            family = FontFamily(name=family_name, fonts=[])

        # Check if font is already in manifest
        existing_variants = [str(variant) for variant in family.get_variants()]
        variant = str(font.get_variant())
        if variant in existing_variants:
            return 0

        # Add font to FontFamily object
        family.fonts.append(font)

        # Update manifest instance
        if family_idx is None:
            self.families.append(family)
        else:
            self.families[family_idx] = family

        self.font_count += 1
        return 1

    def remove(self, font: InstalledFont) -> int:
        '''Remove a font from the manifest.'''

        # Load FontFamily
        family = self.get(font.family)
        family_idx = self.get_index(font.family)
        if family is None:
            return 0

        # Remove font from FontFamily
        font_idx = next((
            i for i, val in enumerate(family.fonts) if val.variant == font.variant
        ), None)
        if font_idx is None:
            return 0
        family.fonts.pop(font_idx)

        # Update the instance with the updated FontFamily
        if family.fonts:
            self.families[family_idx] = family
        else:
            del self.families[family_idx]

        self.font_count -= 1
        return 1

    def get(self, name: str) -> FontFamily:
        '''Load a font family from the manifest.'''
        return next((val for val in self.families if val.name.lower() == name.lower()), None)

    def get_index(self, name: str) -> int:
        '''Get the index position of the font family in the manifest.'''
        return next((idx for idx, val in enumerate(self.families) if val.name.lower() == name.lower()), None)

    def save(self, path: str = None) -> None:
        '''Save the manifest list to disk.'''
        utils.check_dirs(APP_DIR)
        path = path if path else MANIFEST_PATH

        data = {
            'schema_version': self.schema_version,
            'last_modified': datetime.now().isoformat(),
            'font_count': self.font_count,
            'font_families': self.families
        }

        # Write to file (manifest.json)
        with open(path, 'w') as f:
            json.dump(data, f, cls=FontyJSONEncoder, **JSON_DUMP_OPTS)

    def is_stale(self) -> bool:
        '''Returns `true` if the total number of fonts in the manifest does not
           match the total number of fonts in the system.
        '''
        return get_user_fonts_count() != self.font_count

    # Static Methods

    @staticmethod
    def load(path: str = None) -> 'Manifest':
        '''Load the manifest file from disk.'''
        path = path if path else MANIFEST_PATH

        with open(path, encoding='utf-8') as f:
            data = json.loads(f.read())

        # Create FontFamily instances
        families = []
        for family in data['font_families']:
            fonts: List[InstalledFont] = [InstalledFont(
                installed_path=font.get('local_path'),
                registry_name=font.get('registryName', None),
                family=family.get('name'),
                variant=FontAttribute.parse(font.get('variant'))
            ) for font in family['fonts']]
            families.append(FontFamily(name=family.get('name'), fonts=fonts))

        return Manifest(
            families=families,
            font_count=data['font_count'],
            last_modified=data['last_modified']
        )

    @staticmethod
    def generate() -> 'Manifest':
        '''Generate a manifest list from the user's installed fonts.'''
        return Manifest(
            families=get_user_fonts(),
            font_count=get_user_fonts_count(),
            last_modified=datetime.now()
        )


from django.contrib import admin
from sofia.admin import sofia_admin_site
from .models import Cart, CartItem

class CartAdmin(admin.ModelAdmin):
    empty_value_display = '-empty-'
    list_display = ['id', 'customer']
    list_display_links = None
    list_filter = ['customer']

class CartItemAdmin(admin.ModelAdmin):
    empty_value_display = '-empty-'
    list_display = ['id', 'cart', 'product_entry', 'quantity', 'created_at']
    list_display_links = None
    list_filter = ['created_at']

sofia_admin_site.register(Cart, CartAdmin)
sofia_admin_site.register(CartItem, CartItemAdmin)


from crm.capsule_crm import util
from crm.capsule_crm.entities.capsulecrm_contact import CapsulecrmContact
from crm.capsule_crm.entities.capsulecrm_deal import CapsulecrmDeal
from crm.capsule_crm.entities.capsulecrm_case import CapsulecrmCase
from crm.capsule_crm.entities.capsulecrm_tag import CapsulecrmTag
from crm.capsule_crm.entities.capsulecrm_task import CapsulecrmTask
import json

class CapsulecrmApi:
    def contacts(self, context, params):
        '''List of contacts'''

        return self.parties(context, params)

    def parties(self, context, params):
        '''List of parties'''

        access_token = util.get_access_token(context['headers'])
        url = "parties"
        respose_obj = util.rest("GET", url, access_token)
        parties_list = json.loads(respose_obj.text)['parties']
        return self.party_mappings(parties_list), respose_obj.status_code

    def party_mappings(self, parties_list):
        # Unifies party response

        parties = []
        for party in parties_list:
            party_obj = CapsulecrmContact(
                party_id=party['id'],
                account_id=party.get('organisation').get(
                    'id') if party.get('organisation') else None,
                first_name=party.get('firstName'),
                last_name=party.get('lastName'),
                email=party.get('emailAddresses')[0].get(
                    'address') if party.get('emailAddresses') else None,
                business_phone=party.get('phoneNumbers')[0].get(
                    'phoneNumbers') if party.get('phoneNumbers') else None,
                owner_id=party.get('owner'),
                mailing_city=party.get('addresses')[0].get(
                    'city') if party.get('addresses') else None,
                mailing_country=party.get('addresses')[0].get(
                    'country') if party.get('addresses') else None,
                mailing_state=party.get('addresses')[0].get(
                    'state') if party.get('addresses') else None,
                mailing_street=party.get('addresses')[0].get(
                    'street') if party.get('addresses') else None,
                mailing_zip=party.get('addresses')[0].get(
                    'zip') if party.get('addresses') else None,
                title=party.get('title'),
                job_title=party.get('jobTitle'),
                website=party.get('websites')
            )
            parties.append(party_obj.__dict__)
        return json.dumps(parties)

    def contact(self, context, params):
        '''get details of contact'''

        return self.party(context, params)

    def party(self, context, params):
        '''get details of pary'''

        access_token = util.get_access_token(context['headers'])

        if params.get('id') is None or params.get('party_id') == '':
            raise Exception('Provide party id')

        url = f"parties/{int(params.get('id'))}"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied party id')

        party = json.loads(respose_obj.text)['party']
        party_obj = CapsulecrmContact(
            party_id=party['id'],
            account_id=party.get('organisation').get(
                'id') if party.get('organisation') else None,
            first_name=party.get('firstName'),
            last_name=party.get('lastName'),
            email=party.get('emailAddresses')[0].get(
                'address') if party.get('emailAddresses') else None,
            business_phone=party.get('phoneNumbers')[0].get(
                'phoneNumbers') if party.get('phoneNumbers') else None,
            owner_id=party.get('owner'),
            mailing_city=party.get('addresses')[0].get(
                'city') if party.get('addresses') else None,
            mailing_country=party.get('addresses')[0].get(
                'country') if party.get('addresses') else None,
            mailing_state=party.get('addresses')[0].get(
                'state') if party.get('addresses') else None,
            mailing_street=party.get('addresses')[0].get(
                'street') if party.get('addresses') else None,
            mailing_zip=party.get('addresses')[0].get(
                'zip') if party.get('addresses') else None,
            title=party.get('title'),
            job_title=party.get('jobTitle'),
            website=party.get('websites')
        )

        return party_obj.__dict__, respose_obj.status_code

    def party_by_name(self, context, params):
        '''get details of party by name'''

        access_token = util.get_access_token(context['headers'])

        if params.get('name') is None or params.get('name') == '':
            raise Exception('Provide name')

        url = f"parties/search?q={params.get('name')}"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied name')

        parties_list = json.loads(respose_obj.text)['parties']
        return self.party_mappings(parties_list), respose_obj.status_code

    def party_by_email(self, context, params):
        '''get details of party by Email'''

        access_token = util.get_access_token(context['headers'])

        if params.get('email') is None or params.get('email') == '':
            raise Exception('Provide email')

        url = f"parties/search?q={params.get('email')}"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied Email')

        parties_list = json.loads(respose_obj.text)['parties']
        return self.party_mappings(parties_list), respose_obj.status_code

    def cases(self, context, params):
        '''List of cases'''

        access_token = util.get_access_token(context['headers'])
        activity = "kases"
        respose_obj = util.rest("GET", activity, access_token)
        cases_list = json.loads(respose_obj.text)['kases']
        return self.case_mapping(cases_list), respose_obj.status_code

    def case(self, context, params):
        '''get details of case'''

        access_token = util.get_access_token(context['headers'])

        if params.get('id') is None or params.get('id') == '':
            raise Exception('Provide case id')

        activity = f"kases/{params.get('id')}"
        respose_obj = util.rest("GET", activity, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied case id')

        case = []
        case.append(json.loads(respose_obj.text)['kase'])
        return self.case_mapping(case), respose_obj.status_code

    def case_mapping(self, case_list):
        # unifies case response'''

        cases = []
        for case in case_list:
            case_obj = CapsulecrmCase(
                case_id=case['id'],
                contact_id=case['party'].get(
                    'id') if case.get('party') else None,
                name=case.get('name'),
                description=case.get('description'),
                status=case.get('status'),
                owner_id=case['owner']['id']
            )
            cases.append(case_obj.__dict__)
        return json.dumps(cases)

    def opportunities(self, context, params):
        '''list of opportunities'''

        access_token = util.get_access_token(context['headers'])
        url = "opportunities"
        respose_obj = util.rest("GET", url, access_token)
        parties_list = json.loads(respose_obj.text)['opportunities']

        return self.opportunity_mappings(parties_list), respose_obj.status_code

    def opportunity(self, context, params):
        '''get opportunities details'''

        access_token = util.get_access_token(context['headers'])

        if params.get('opportunity_id') is None or params.get('opportunity_id') == '':
            raise Exception('Provide case id')

        url = f"opportunities/{params.get('opportunity_id')}"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied opportunity id')

        data = []
        data.append(json.loads(respose_obj.text)['opportunity'])

        return self.opportunity_mappings(data), respose_obj.status_code

    def opportunity_mappings(self, opportunities_list):
        # unifies opportunities response

        opportunities = []
        for opportunity in opportunities_list:
            opportunity_obj = CapsulecrmDeal(
                deal_id=opportunity['id'],
                name=opportunity.get('name'),
                close_date=opportunity.get('expectedCloseOn'),
                description=opportunity.get('description'),
                stage_id=opportunity.get('milestone').get(
                    'id') if opportunity.get('milestone') else None,
                value=opportunity.get('value').get(
                    'amount') if opportunity.get('value') else None,
                probability=opportunity.get('probability'),
                owner_id=opportunity['owner'].get('id'),
                contact_id=opportunity['party'].get('id'),
                currency_id=opportunity['value'].get(
                    'currency') if opportunity.get('value') else None
            )
            opportunities.append(opportunity_obj.__dict__)
        return json.dumps(opportunities)

    def tags(self, context, params):
        '''list of tags in parties, opportunities and kases'''

        access_token = util.get_access_token(context['headers'])

        if params.get('entity') is None or params.get('entity') == '':
            raise Exception(
                'Provide required entity. Supported entites are parties, opportunities and kases')

        url = f"{params.get('entity')}/tags"
        respose_obj = util.rest("GET", url, access_token)

        if respose_obj.status_code != 200:
            raise Exception('Check providied entites')

        tag_list = json.loads(respose_obj.text)['tags']
        tags = []
        for tag in tag_list:
            tag_obj = CapsulecrmTag(
                tag_id=tag['id'],
                tag=tag.get('name'),
                description=tag.get('description')
            )
            tags.append(tag_obj.__dict__)

        return json.dumps(tags), respose_obj.status_code

    def tasks(self, context, params):
        '''list of tasks'''

        access_token = util.get_access_token(context['headers'])
        activity = "tasks"
        respose_obj = util.rest("GET", activity, access_token)
        task_list = json.loads(respose_obj.text)['tasks']

        return self.task_mapping(task_list), respose_obj.status_code

    def task_mapping(self, task_list):
        # unifies task response

        tasks = []
        for task in task_list:
            task_obj = CapsulecrmTask(
                name=task.get('description'),
                description=task.get('detail'),
                category_id=task['category'].get(
                    'id') if task.get('category') else None,
                owner_id=task['owner'].get(
                    'id') if task.get('owner') else None,
                due_date=task.get('dueOn')
            )
            tasks.append(task_obj.__dict__)

        return json.dumps(tasks)

    def profile(self, context, payload):
        '''Details of authenticated user'''

        access_token = util.get_access_token(context['headers'])
        url = "users/current"
        response = util.rest("GET", url, access_token).json()['user']
        profile = {
            'id':response['id'],
            'name':response['username']
        }

        # party is contact
        party = response.get('party')
        if party:
            params = {
                "id":party.get('id')
            }
            email_obj = self.party(context, params)
            profile['email']=email_obj[0]['email']

        return profile


import json
from flask import Flask, request
import json, os
import resource

app = Flask(__name__)

map = {}
# 30 MB can store => 10,000 so 1/MB it will be 333 records now assuming
# 1 gib of RAM which 1000MB net net we can store 333, 000 records and after that we
# can clear the map and write it in file
map_counter = 333000
# map_counter = 10

def write_map_file(out_file):
    global map_counter
    for url, val in map.items():
        tmp = f"{url}, {val}\n"
        out_file.write(tmp)
    #clear the map, and set again counter to 0
    map.clear()
    map_counter = 0

def process_scan(line, page_rank_threshold, out_file):
    parts = line.split(",")
    try:
        url, page_score = parts[0], int(parts[1])
        if page_score > page_rank_threshold:
            tmp = f"{url}, {page_score} \n"
            out_file.write(tmp)
    except Exception as e:
        pass
        # print("Iseeueee :::", line)

def process_agre(line, page_rank_threshold, out_file):
    global map_counter
    '''
    - to aggregate we need to lookup if the current element was seen.
    - now if we need to check if current element was always seen we can use hashmap
    - this is bad cause it will blow out in memory, instead we create hash function which
    always gives same number when passed same string and we write on that number which will be our line number
     in FILE
    '''
    parts = line.split(",")
    try:
        ip, rev = parts[0], float(parts[3])

        if ip not in map:
            map[ip] = rev
        else:
            map[ip] += rev
        if(map_counter >= 0):
            map_counter -= 1
        else:
            write_map_file(out_file)
        # tmp = f"{ip}, {rev} \n"
        # print(tmp)
        # out_file.write(tmp)
    except Exception as e:
        print(f"Some error : {e}, line : {line}")
        pass

def process_data(line, page_rank_threshold, out_file, query_type):
    if query_type == 'scan':
        process_scan(line, page_rank_threshold, out_file)
    else:
        process_agre(line, page_rank_threshold, out_file)
        # print("Iseeueee :::", line)

def read_in_chunks(file_object, chunk_size=4024):
    """Lazy function (generator) to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data

def perform_external_read(list_of_files, page_rank_threshold, query_type):
    # base_path = f"../../mapper/page_rank_data/data_{query_type}"
    base_path = f"/app/page_rank_data/data_{query_type}"
    op_file = os.path.join(base_path, f"output_file_query_{query_type}")
    #remove existing file if exists
    if os.path.exists(op_file): os.remove(op_file)
    with open(op_file, 'a+') as out_file:
        for file in list_of_files:
            file_path = os.path.join(base_path, file)
            with open(file_path) as f:
                if 'output' not in file:
                    for line in f: #by default iterator is lazy in this case doesnt read in memory
                        process_data(line, page_rank_threshold, out_file, query_type)
                # if line is not split into newlines use below generator: https://stackoverflow.com/questions/519633/lazy-method-for-reading-big-file-in-python
                # for line in read_in_chunks(f):
                #     process_data(line, page_rank_threshold)
        if len(map):
            write_map_file(out_file)

@app.route("/consume", methods=["POST"])
def consume():
    data = json.loads(request.data)
    # print(data)
    #https://stackoverflow.com/questions/938733/total-memory-used-by-python-process
    print("*************************")
    print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
    print("*************************")
    perform_external_read(data['payload'], data['page_rank_threshold'], data['query_type'])
    print("*************************")
    print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
    print("*************************")
    print("Length of map : ", len(map))
    return 'Receieved', 200

@app.route("/health")
def health():
    return 'Am up X!'

if __name__ == "__main__":
    '''
    - receive the name of file to read
    - load part by part of file in memory and check the number of file above threshold
    - write lines with values more than threshold in op file
    '''
    app.run("0.0.0.0", port=8080, debug=True)


import os
from board import Board, OutOfBoardException
from collections import namedtuple

coordinates = namedtuple('coordinated', ['x', 'y'])

class GameOfLife:
    def __init__(self, board: Board) -> None:
        self.board: Board = board

    def board_after_lifecycle(self) -> None:
        new_board = Board(rows=self.board.rows, columns=self.board.columns)
        for y in range(self.board.rows):
            for x in range(self.board.columns):
                neighbours_number = self.check_living_neighbours_number(x=x, y=y)
                if self.board.get(x=x, y=y) == 1 and neighbours_number in (2, 3):
                    new_board.set(x=x, y=y, value=1)
                elif self.board.get(x=x, y=y) == 0 and neighbours_number == 3:
                    new_board.set(x=x, y=y, value=1)
                else:
                    new_board.set(x=x, y=y, value=0)
        self.board = new_board

    def check_living_neighbours_number(self, y: int, x: int) -> int:
        number_of_neighbours = 0
        neighbors = [(-1, 1), (0, 1), (1, 1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)]
        for neighbour_x, neighbour_y in neighbors:
            final_x = x + neighbour_x
            final_y = y + neighbour_y
            try:
                if self.board.get(y=final_y, x=final_x) == 1:
                    number_of_neighbours += 1
            except OutOfBoardException:
                continue
        return number_of_neighbours

    @staticmethod
    def choose_coordinates():
        while True:
            try:
                print("Jeśli chcesz wyjść naciśnij enter\n")
                x = int(input("Podaj kolumne\n"))
                if x is None:
                    break
                print()
                y = int(input("Podaj wiersz\n"))
                if y is None:
                    break
                return coordinates(x-1, y-1)
            except ValueError:
                print("Podana wartość jest nieprawidłowa! Spróbuj jeszcze raz\n")

def main():
    board = Board(20, 20)
    game = GameOfLife(board)
    print(game.board)
    while True:
        choice = input("\nNaciśnij enter aby kontynuować"
                       "\nJedynke aby zmienić wartość punktu,"
                       "\nl, aby wczytać z pliku"
                       "\nlub wpisz cokolwiek innego aby wyjść\n")
        if choice == "":
            os.system("clear")
            game.board_after_lifecycle()
            print(game.board)
        elif choice == "l":
            filename = input("Podaj nazwę pliku: ")
            try:
                with open(filename) as f:
                    board_string = ''.join(f.readlines())
                    board = Board.from_string(board_string)
                    game = GameOfLife(board)
            except FileNotFoundError:
                print(f'Plik o nazwie "{filename}" nie istnieje.')
        elif choice == "1":
            try:
                coordinates = game.choose_coordinates()
                value = game.board.get(coordinates.x, coordinates.y)
                game.board.set(coordinates.x, coordinates.y, 1 if value == 0 else 0)
                print(game.board)
            except OutOfBoardException:
                print("Podane koordynaty nie mieszczą się w skali planszy, spróbuj jeszcze raz!\n")
        else:
            break

if __name__ == "__main__":
    main()


from torch.utils.data import Dataset
from pathlib import Path
import numpy as np
from PIL import Image
import h5py
import data.MVSDataset
import torch
from torch.nn import functional as F

class MVSDataset(data.MVSDataset.MVSDataset):
    def __init__(self, datapath, listfile, mode, nviews, return_depth=False, **kwargs):
        super().__init__()
        assert mode in ["train", "val", "test"]

        if mode == "val":
            self.p = Path(datapath) / "test"
        else:
            self.p = Path(datapath) / mode

        self.height = 512
        self.width = 512
        self.img_idx = []
        self.scene_idx = []
        for scene in listfile:
            if (self.p / scene).exists():
                for cpt in range(1000): # hardcoded max size of dataset
                    b = True
                    for i in range(nviews):
                        b = b and (self.p / scene / f"im_{cpt}_{i}.jpg").exists()
                    b = b and (self.p / scene / f"infos_{cpt}.npz").exists()
                    if mode == "test":
                        if not (self.p / scene / f"depth_{cpt}.h5").exists():
                            for i in range(nviews):
                                b = b and (self.p / scene / f"depth_{cpt}_{i}.h5").exists()

                    else:
                        if return_depth:
                            b = b and (self.p / scene / f"depth_{cpt}.h5").exists()

                    if b:
                        self.img_idx.append(cpt)
                        self.scene_idx.append(scene)

        self.listfile = listfile
        self.mode = mode
        self.nviews = nviews
        self.return_depth = return_depth

        nb_report = 50
        self.visu_idx = (np.arange(nb_report) * (len(self.img_idx) / nb_report)).astype(int)

        self.rands = None

    def __len__(self):
        return len(self.img_idx)

    def __getitem__(self, idx):
        imgs = []
        scene = self.scene_idx[idx]

        infos_filename = self.p / scene / f"infos_{self.img_idx[idx]}.npz"

        npz = np.load(infos_filename)
        depth_train = self.return_depth and self.mode == "train"

        if depth_train:
            with h5py.File(self.p / scene / f"depth_{self.img_idx[idx]}.h5", 'r') as f:
                depth = torch.tensor(np.array(f["depth"]))

        K, R, t = npz["K"].astype(np.float32), npz["R"].astype(np.float32), npz["t"].astype(np.float32)

        K, R, t = K[:self.nviews], R[:self.nviews], t[:self.nviews]

        proj_matrices = np.zeros((self.nviews, 4, 4), dtype=np.float32)
        proj_matrices[:, 3, 3] = 1

        for i in range(self.nviews):
            img_filename = self.p / scene / f"im_{self.img_idx[idx]}_{i}.jpg"

            im, resize_ratio = self.read_img(img_filename)
            new_K = self.rescale_calib(resize_ratio, K=K[i])
            if depth_train and i == 0:
                th, tw = depth.shape
                depth = F.interpolate(depth.view(1, 1, th, tw), size=im.shape[:-1], mode="nearest").squeeze(0)
                im, new_K, depth = self.center_crop(im, K=new_K, idx=idx, depth=depth)
            else:
                im, new_K = self.center_crop(im, K=new_K, idx=idx)

            if i == 0:
                f = img_filename

            imgs.append(im)
            K[i] = new_K

        res = {"f": str(f),
               "K": K,
               "R": R,
               "t": t,
               "depth_min": npz["min_d"].astype(np.float32),
               "depth_max": npz["max_d"].astype(np.float32)}

        if self.mode != "test":
            res["imgs"] = np.stack([im.transpose([2, 0, 1]) for im in imgs], axis=0)
            if self.return_depth:
                res["depth"] = depth
                res["mask"] = (depth >= npz["min_d"][0]) & (depth < npz["max_d"][0])

        else:
            res["imgs"] = [im.transpose([2, 0, 1]) for im in imgs]
            depths = list()
            masks = list()
            try:
                for i in range(self.nviews):
                    # not clean but i don't want to regen a full dataset
                    with h5py.File(self.p / scene / f"depth_{self.img_idx[idx]}_{i}.h5", 'r') as f:
                        depth = np.array(f["depth"])
                        depths.append(depth)
                        masks.append(depth > 0)
            except OSError:
                with h5py.File(self.p / scene / f"depth_{self.img_idx[idx]}.h5", 'r') as f:
                    depth = np.array(f["depth"]).astype(np.float)
                    depths.append(depth)
                    masks.append(depth > 0)

            res["mask"] = masks
            res["depth"] = depths

        return res


from django.core.urlresolvers import reverse

from rest_framework import status
from rest_framework.test import APITestCase

from clubs.models import Club
from courses.models import Course, CourseInstruction
from qualifications.models import Certificate, Qualification
from users.models import User

class UserCoursesTestCase(APITestCase):
    def setUp(self):
        self.staff = User.objects.create_user('Staff', 'Member', is_staff=True)
        club = Club.objects.create(name='UCC')
        self.member = User.objects.create_user('Club', 'Member', club=club)
        cert = Certificate.objects.create(name='Trainee Diver')
        course = Course.objects.create(
          certificate=cert,
          creator=self.staff,
          organizer=self.member,
        )
        CourseInstruction.objects.create(user=self.member, course=course)

    def test_user_can_view_own_courses_organized(self):
        self.client.force_authenticate(self.member)
        response = self.client.get(reverse('user-courses-organized', args=[self.member.id]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)

    def test_user_can_view_own_courses_taught(self):
        self.client.force_authenticate(self.member)
        response = self.client.get(reverse('user-courses-taught', args=[self.member.id]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)


import sqlite3
import helpers

conn = sqlite3.connect(helpers.get_file_path('../databases/flights.db'))
cur = conn.cursor()
cur.execute("SELECT * FROM airlines LIMIT 15;")
results = cur.fetchall()
cur.close()
conn.close()

for row in results:
    print(row)


from flask import Flask, request
from flask_cors import CORS
import cv2
import numpy as np
app = Flask(__name__)
cors = CORS(app)
drawing = False
import os
import time
import threading
import sys
from Controls.controller_manager import ControllerManager
import Controls.presets as presets
import numpy as np

curr_frame = np.zeros((480,640,3))

SCALE_SIZE = 300
control = ControllerManager()
#control = None

def calculate_lstsq_error(points):
    x = points[:,0]
    y = points[:,1]
    A = np.vstack([x, np.ones(len(x))]).T
    return np.sum(np.abs(np.linalg.lstsq(A, y, rcond=None)[1]))

def interpolate_points(points, DIST_THRES = 5, LSTSQ_THRES = 1, errors = []):
    new_points = []

    line_start = 0
    line_end = 1
    for i in range(0,len(points)):
        if i ==0:
            new_points.append(points[i])
        else:
            error = calculate_lstsq_error(points[line_start:line_end])
            errors.append(error)
            if abs(error) >= LSTSQ_THRES:
                new_points.append(points[line_end])
                line_start = line_end

            line_end = min(line_end + 1, len(points)-1) # incr last index by 1
        if i == len(points) - 1: # add last point to finish line
            new_points.append(points[i])
    return np.array(new_points)

def transform(point, old_dim, new_dim = SCALE_SIZE):
    min_value = min(np.min(point[:,1]), np.min(point[:,0]))
    scale = new_dim/old_dim if min_value >= 0 else (new_dim/2)/(old_dim)
    old_dim = np.array(old_dim)
    new_dim = np.array(new_dim)
    point = np.array(point)
    temp =  scale*(point - old_dim/2) + new_dim/2
    temp[:,0] = -temp[:,0] + new_dim

    min_value = min(np.min(temp[:,1]), np.min(temp[:,0]))
    if min_value < 0:
        # shift values
        temp -= min_value

    return temp

def draw_async(points, control = control):
    global drawing
    print("start draw")
    control.draw_points(points)
    print(control.is_done())
    while not control.is_done():
        control.update_manager()
        time.sleep(0.005)
    drawing = False
    print("end draw")

def draw_points(points, size, interpolate = True):
    global drawing
    if not drawing:
        drawing = True
        if interpolate:
            points = interpolate_points([transform(pt, size[0]) for pt in points])
            print(points)
        thread = threading.Thread(target=draw_async, args=(points,))
        thread.start()

@app.route(f'/api/draw_preset', methods=['POST'])
def set_preset():
    '''
    Start drawing process with set of points
    '''
    global drawing
    if not drawing and request.is_json:
        data = request.get_json()
        name = data['preset']
        offset = data.get("offset", 0)
        if name == 'swirl':
            rt = data.get('rt', 15/180*np.pi)
            rr = data.get('rr', 3)
            draw_points(*presets.swirl_preset(rt, rr, offset=offset))
        elif name == 'demo':
            rt = data.get('rt', 15/180*np.pi)
            rr = data.get('rr', 3)
            pts, size = presets.swirl_preset(rt, rr, offset=offset)
            pts.extend(pts[::-1])
            draw_points(pts, size)
        elif name == "cardiod":
            pts, size = presets.cardiod_preset(offset=offset)
            draw_points(pts, size)
        elif name == "lisajous":
            pts, size = presets.lisajous_preset(offset=offset)
            print(pts)
            draw_points(pts, size)

        return {
                "status": "S" #started
                }, 200
    return {
                "status": "P" #already started
                }, 200

@app.route(f'/api/post_points', methods = ["POST"])
def set_points():
    '''
    Start drawing process with set of points
    '''
    global drawing
    if not drawing and request.is_json:
        data = request.get_json()
        points = data['points']
        size = data['size'] ## [width, height]
        draw_points(points, size)

        return {
                "status": "S" #started
                }, 200
    return {
                "status": "P" #already started
                }, 200

@app.route(f'/api/get_status', methods = ["GET"])
def get_status():
    ## Get percent done of drawing process
    proportion_done = 0 ## TODO: Add code here to calculate percent done as a proportion
    try:
        proportion_done = control.get_progress()
    except Exception as e:
        print(e)
        pass
    return {"percent": str(round(proportion_done*100, 2))}, 200

if __name__=="__main__":
    if not (len(sys.argv) > 1 and sys.argv[1] == "--naive"):
        print("non naive")
        app.run(host='0.0.0.0')


#!/usr/bin/python

#Execute this script in the folder with your node-00XX.log outputs to get a graph of initial and final images

import numpy as np
import matplotlib.pyplot as plt
import math

########## INPUT #####################
nodes = 16 #Number of string nodes
######################################
end_lines = list()
end_data = list()
start_lines = list()
start_data = list()

for i in range(0, nodes):
    if i <= 9:
        fileName = "node-000{0}.log".format(i)
    else:
        fileName = "node-00{0}.log".format(i)

    fileHandle = open(fileName)
    lineList = fileHandle.readlines()
    end_lines.append(lineList[-1])
    start_lines.append(lineList[0])
    fileHandle.close()

for line in end_lines:
    end_data.append(line.split(' '))

for line in start_lines:
    start_data.append(line.split(' '))

end_x = list()
end_y = list()
start_x = list()
start_y = list()

for line in end_data:
    end_x.append(line[2])
    end_y.append(line[4])

for line in start_data:
    start_x.append(line[2])
    start_y.append(line[4])

fig = plt.figure()

ax1 = fig.add_subplot(111)

converter = 1.0
end_xdegree = converter*np.array(end_x, dtype=float)
end_ydegree = converter*np.array(end_y, dtype=float)
start_xdegree = converter*np.array(start_x, dtype=float)
start_ydegree = converter*np.array(start_y, dtype=float)

ax1.set_title("Langevin Particle")
ax1.set_xlabel('X')
ax1.set_ylabel('Y')

ax1.plot(end_xdegree,end_ydegree, 'ro-', label='Final Images')
ax1.plot(start_xdegree, start_ydegree, 'bo-', label='Initial Images')

#leg = ax1.legend()

plt.show()


from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.urls import reverse_lazy
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from accounts.models import User, Student
from institution.models import Session, Trimester
from course.models import Course
from accounts.decorators import lecturer_required, student_required
from .models import UsersCourses, Result
from .models import *

@login_required
@lecturer_required
def provisional_score(request):
    current_session = Session.objects.get(is_current_session=True)
    current_trimester = get_object_or_404(Trimester, is_current_trimester=True, session=current_session)
    courses = Course.objects.filter(allocated_course__lecturer__pk=request.user.id).filter(trimester=current_trimester)
    context = {
        "current_session": current_session,
        "current_trimester": current_trimester,
        "courses": courses,
    }
    return render(request, 'scores/provisional_score.html', context)

@login_required
@lecturer_required
def lecturer_confirm_score(request, id):
    """
    Shows a page where a lecturer will add score for students that are taking courses allocated to him
    in a specific trimester and session
    """
    current_session = Session.objects.get(is_current_session=True)
    current_trimester = get_object_or_404(Trimester, is_current_trimester=True, session=current_session)
    if request.method == 'GET':
        courses = Course.objects.filter(allocated_course__lecturer__pk=request.user.id).filter(
            trimester=current_trimester)
        course = Course.objects.get(pk=id)
        students = UsersCourses.objects.filter(course__allocated_course__lecturer__pk=request.user.id).filter(
            course__id=id).filter(course__trimester=current_trimester)
        context = {
            "title": "Submit Score",
            "courses": courses,
            "course": course,
            "students": students,
            "current_session": current_session,
            "current_trimester": current_trimester,
        }
        return render(request, 'scores/lecturer_confirm_score.html', context)

    if request.method == 'POST':
        ids = ()
        data = request.POST.copy()
        data.pop('csrfmiddlewaretoken', None)  # remove csrf_token
        for key in data.keys():
            ids = ids + (str(key),)  # gather all the all students id (i.e the keys) in a tuple
        for s in range(0, len(ids)):  # iterate over the list of student ids gathered above
            student = UsersCourses.objects.get(id=ids[s])
            courses = Course.objects.filter(level=student.student.level).filter(program__pk=student.student.department.id).filter(
                trimester=current_trimester)
            total_credit_in_trimester = 0
            for i in courses:
                if i == courses.count():
                    break
                else:
                    total_credit_in_trimester += int(i.credit)
            score = data.getlist(ids[s])
            print(score, score[0])
            assignment = score[0]
            obj = UsersCourses.objects.get(pk=ids[s])  # get the current student data
            obj.assignment = assignment  # set current student assignment score
            obj.total = obj.get_score(assignment=assignment)
            obj.grade = obj.get_marked_grade(total=obj.total)
            obj.point = obj.get_point(grade=obj.grade)
            obj.comment = obj.get_comment(grade=obj.grade)
            obj.save()
            try:
                a = Result.objects.get(student=student.student, trimester=current_trimester, session=current_session, level=student.student.level)
                a.score = obj.total
                a.comment = obj.comment
                a.save()
            except:
                Result.objects.get_or_create(student=student.student, comment=obj.comment, trimester=current_trimester,
                                             session=current_session, level=student.student.level)

        messages.success(request, 'Score Updated. ')
        return HttpResponseRedirect(reverse_lazy('lecturer_confirm_score', kwargs={'id': id}))
    return HttpResponseRedirect(reverse_lazy('lecturer_confirm_score', kwargs={'id': id}))

@login_required
@student_required
def provisional_result(request):
    student = Student.objects.get(student__pk=request.user.id)
    assess_courses = UsersCourses.objects.filter(student__student__pk=request.user.id).filter(course__level=student.level)
    assess_results = Result.objects.filter(student__student__pk=request.user.id)

    result_set = set()

    for result in assess_results:
        result_set.add(result.session)

    sorted_result = sorted(result_set)

    total_first_trimester_credit = 0
    total_sec_trimester_credit = 0
    for i in assess_courses:
        if i.course.trimester == "First":
            total_first_trimester_credit += int(i.course.credit)
        if i.course.trimester == "Second":
            total_sec_trimester_credit += int(i.course.credit)

    past_gp = 0
    for i in assess_results:
        past_level = i.level
        try:
            a = Result.objects.get(student__student__pk=request.user.id, level=past_level, trimester="Second")
            past_gp = a.cgpa
            break
        except:
            past_gp = 0

    context = {
        "courses": assess_courses,
        "results": assess_results,
        "sorted_result": sorted_result,
        "student": student,
        'total_first_trimester_credit': total_first_trimester_credit,
        'total_sec_trimester_credit': total_sec_trimester_credit,
        'total_first_and_second_trimester_credit': total_first_trimester_credit + total_sec_trimester_credit,
        "previousCGPA": past_gp,
    }

    return render(request, 'scores/provisional_result.html', context)

@login_required
@student_required
def com_result(request):
    student = Student.objects.get(student__pk=request.user.id)
    assess_courses = UsersCourses.objects.filter(student__student__pk=request.user.id, course__level=student.level)
    assess_result = Result.objects.filter(student__student__pk=request.user.id)

    context = {
        "courses": assess_courses,
        "scores": assess_result,
        "student": student,
    }

    return render(request, 'scores/com_result.html', context)


import matplotlib.pyplot as plt
import cv2 as cv
structure = cv.imread('WeChat Image_20210320120051.png')
plt.imshow(structure)
plt.show()
# 在OpenCV中，我们要获取一个视频，需要创建一个VideoCapture对象
# 创建读取视频的对象
# cap = cv.VideoCapture()

# 获取视频的某些属性 retval = cap.get(propId)

# 修改视频的属性信息 cap.set(propId, value)

# 判断图像是否读取成功 isornot = cap.isOpened()

# 获取视频的一帧图像 ret, frame = cap.read() ret判断获取是否成功，成功为True frame为获取到的某一帧的图像
# 调用cv.imshow()显示图像，在显示图像时使用cv.waitKey()设置适当的持续时间，如果太低视频会播放的非常快，如果太高会非常慢，
# 通常情况设定为25ms即可
# 最后用cap.release()将视频释放掉

cap = cv.VideoCapture('Golden_Gate_Bridge__SaveYouTube_com_.mp4')
retval = cap.get(propId=3)
print(retval)
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        cv.imshow('frame', frame)
    if cv.waitKey(25) & 0xFF == ord('q'):
        break
cap.release()
cv.destroyAllWindows()

# 视频保存
# out = cv2.VideoWriter(filename,fourcc, fps, frameSize)
# filename：视频保存的位置
# fourcc：指定视频编解码器的4字节代码
# fps：帧率
# frameSize：帧大小
# 其中，fourcc是需要设置的，设置视频的编解码 retval = cv2.VideoWriter_fourcc( c1, c2, c3, c4 )
# c1,c2,c3,c4: 是视频编解码器的4字节代码，在fourcc.org中找到可用代码列表，与平台紧密相关，常用的有：
# In windows DIVX(.avi) In OS MJPG(.mp4), X264(.mkv) DIVX(.avi)
# 利用cap.read()获取每一帧，然后out.write()将某一帧图像写入视频中
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

out = cv.VideoWriter('Out.avi', cv.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10, (frame_width, frame_height))
while(True):
    ret, frame = cap.read()
    if ret == True:
        out.write(frame)
    else:
        break
cap.release()
out.release()
cv.destroyAllWindows()

# 读取视频：
#
#     读取视频：cap = cv.VideoCapture()
#     判断读取成功：cap.isOpened()
#     读取每一帧图像：ret,frame = cap.read()
#     获取属性：cap.get(proid)
#     设置属性：cap.set(proid,value)
#     资源释放：cap.release()
# 保存视频
#     保存视频： out = cv.VideoWrite()
#     视频写入：out.write()
#     资源释放：out.release()


import unittest
import neural_logic_machines.instance as instance
import neural_logic_machines.problem as problem
import jax.numpy as jnp

class TestInstance(unittest.TestCase):

    facts = ['female(alice).',
             'male(bob).',
             'female(carol).',
             'male(dave).',
             'sibling(bob, carol).',
             'sibling(alice, dave).']
    max_predicates = [1, 2, 2]
    predicate_names = [['family'],
                       ['male', 'female'],
                       ['sibling', 'brother']]
    knowledge_base = []
    problem = problem.Problem(max_predicates,
                              predicate_names,
                              knowledge_base)
    sut = instance.Instance(problem, facts)

    def test_init(self):
        self.assertEqual(self.sut.max_predicates, [1, 2, 2])
        self.assertEqual(self.sut.predicate_names, [['family'],
                                                    ['male', 'female'],
                                                    ['sibling', 'brother']])
        self.assertEqual(self.sut.objects, ['alice', 'bob', 'carol', 'dave'])

    def test_get_objects(self):
        # When
        result = self.sut.objects

        # Then
        self.assertEqual(result, ['alice', 'bob', 'carol', 'dave'])

    def test_text_to_tensor(self):
        # Given
        text = ['female(alice).',
                'male(bob).',
                'female(carol).',
                'male(dave).',
                'sibling(bob, carol).',
                'sibling(alice, dave).']

        # When
        result = self.sut.text_to_tensor(text)

        # Then
        self.assertTrue(result[0] == jnp.array([0]))
        self.assertTrue(
            (result[1] == jnp.array([[0, 1, 0, 1],
                                     [1, 0, 1, 0]])).all())
        self.assertTrue(
            (result[2] == jnp.array([[[0, 0, 0, 0],
                                      [0, 0, 0, 0],
                                      [0, 1, 0, 0],
                                      [1, 0, 0, 0]],
                                     [[0, 0, 0, 0],
                                      [0, 0, 0, 0],
                                      [0, 0, 0, 0],
                                      [0, 0, 0, 0]]])).all())

    def test_tensor_to_text(self):
        # Given
        tensor =[jnp.array([0]),
                 jnp.array([[0, 1, 0, 1],
                            [1, 0, 1, 0]]),
                 jnp.array([[[0, 0, 0, 0],
                             [0, 0, 0, 0],
                             [0, 1, 0, 0],
                             [1, 0, 0, 0]],
                            [[0, 0, 0, 0],
                             [0, 0, 0, 0],
                             [0, 0, 0, 0],
                             [0, 0, 0, 0]]])]

        # When
        result = self.sut.tensor_to_text(tensor)

        # Then
        self.assertEqual(result, ['male(bob).',
                                  'male(dave).',
                                  'female(alice).',
                                  'female(carol).',
                                  'sibling(bob, carol).',
                                  'sibling(alice, dave).'])

    def test_arguments_binary(self):
        # Given
        fact = 'sibling(alice, dave).'

        # When
        result = self.sut.get_arguments(fact)

        # Then
        self.assertListEqual(result, [0, 3])

    def test_get_arguments_nullary(self):
        # Given
        fact = 'family.'

        # When
        result = self.sut.get_arguments(fact)

        # Then
        self.assertEqual(result, [])

    def test_get_head_binary(self):
        # Given
        fact = 'brother(dave, alice).'
        arity = 2

        # When
        result = self.sut.get_head(fact, arity)

        # Then
        self.assertEqual(result, 1)

    def test_get_head_nullary(self):
        # Given
        fact = 'family.'
        arity = 0

        # When
        result = self.sut.get_head(fact, arity)

        # Then
        self.assertEqual(result, 0)

    def test_get_head_error(self):
        # Given
        fact = 'sister(alice, dave).'
        arity = 2

        # Then
        with self.assertRaises(RuntimeError):
            # When
            self.sut.get_head(fact, arity)

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


# coding=utf-8
from __future__ import unicode_literals
from collections import OrderedDict

from faker.providers.date_time import Provider as DateTimeProvider
from .. import BaseProvider
import redis

localized = True

class DebitCard(object):

    def __init__(self, name, prefixes, length=19):
        self.name = name
        self.prefixes = prefixes
        self.length = length

class Provider(BaseProvider):

    # 大陆信用卡
    prefix_cmbc = ["472067", "427570", "421393", "621692", "623683", "622620", "622622", "900003", "622615", "622619"]
    prefix_cmb = ["410062", "690755", "512425", "622580", "622598", "95555", "468203", "623262", "402658", "623126"]
    prefix_cib = ["438589", "90592", "622909"]
    prefix_ceb = ["620518", "622664", "622668", "622667", "623157", "622670", "623155", "621490", "621492", "620535"]
    prefix_citic = ["622698", "620082", "621770", "622696", "622690", "968809", "433670", "622691", "622999", "621768"]
    prefix_hxb = ["623022", "622633", "621222", "999999", "623021", "622630"]
    prefix_spdb = ["84373", "84390", "87040", "621791", "622518", "621792", "623250", "984303", "87000", "87010"]
    prefix_gdb = ["623259", "623506", "6858009", "9111"]
    prefix_pingan = ["622535", "412962", "412963", "415752", "998800", "622538", "622536", "415753"]
    prefix_egb = ["622384"]
    prefix_czb = ["621019", "622309"]
    prefix_cbhb = ["622884", "621453", "621268"]

    debit_card_types = OrderedDict((
        (u'民生银行',   DebitCard(u'民生银行',     prefix_cmbc, 16)),
        (u'招商银行',    DebitCard(u'招商银行',    prefix_cmb, 16)),
        (u'兴业银行',    DebitCard(u'兴业银行', prefix_cib, 18)),
        (u'光大银行',    DebitCard(u'光大银行',   prefix_ceb, 16)),
        (u'中信银行',    DebitCard(u'中信银行',    prefix_citic, 16)),
        (u'华夏银行',    DebitCard(u'华夏银行',  prefix_hxb, 16)),
        (u'浦发银行',    DebitCard(u'浦发银行', prefix_spdb, 16)),
        (u'广发银行',    DebitCard(u'广发银行', prefix_gdb, 16)),
        (u'平安银行',    DebitCard(u'平安银行',   prefix_pingan, 16)),
        (u'恒丰银行',    DebitCard(u'恒丰银行',   prefix_egb, 16)),
        (u'浙商银行',    DebitCard('浙商银行',   prefix_czb, 19)),
        (u'渤海银行',    DebitCard(u'渤海银行',   prefix_cbhb, 16))
    ))

    # prefix_dic = {"华夏银行": 621222, "招商银行": 690755, "光大银行": 622662, "民生银行": 622615, "中信银行": 433670,
    #           "兴业银行": 622909, "浦发银行": 622516, "广发银行": 623259, "平安银行": 412963, "恒丰银行": 622384,
    #           "浙商银行": 621019, "渤海银行": 621268}

    luhn_lookup = {'0': 0, '1': 2, '2': 4, '3': 6, '4': 8,
                   '5': 1, '6': 3, '7': 5, '8': 7, '9': 9}

    # @classmethod
    # def all_debit_cards(cls):
    #     ret = {}
    #     for key in cls.prefix_dic.keys():
    #         number = cls._bank_card_number(str(cls.prefix_dic[key]))
    #         ret[key] = number
    #         print key+':'+number
    #     return ret

    @classmethod
    def debit_card_provider(cls, card_type=None):
        """ Returns the provider's name of the debit card. """
        if card_type is None:
            card_type = cls.random_element(cls.debit_card_types.keys())
        return cls._debit_card_type(card_type).name

    @classmethod
    def debit_card_number(cls, card_type=None):
        """ Returns a valid debit card number. """
        card = cls._debit_card_type(card_type)
        prefix = cls.random_element(card.prefixes)
        number = cls._generate_number(prefix, card.length)
        return number

    # @classmethod
    # def bank_card_info(cls):
    #     """ Returns a dict that contains bank card info.        """
    #     prefix = cls.random_element(cls.card_prefix)
    #     bank_card_number = cls._bank_card_number()
    #     r = redis.StrictRedis(host='10.12.9.14', port=6379, db=0)
    #     info = r.get(prefix+"CORE_CARD_BIN")
    #     if info is not None:
    #         names = ['bank_name', 'bank_code', 'card_name', 'card_bin', 'card_type']
    #         values = info.decode('utf-8').split('|')
    #         card_info = dict(zip(names, values))
    #         card_info['card_number'] = bank_card_number
    #     else:
    #         print "Redis中没有找到该卡的属性:%s" % prefix
    #         raise Exception
    #     return  card_info

    @classmethod
    def debit_card_expire(cls, start='now', end='+10y', date_format='%m/%y'):
        expire_date = DateTimeProvider.date_time_between(start, end)
        return expire_date.strftime(date_format)

    def debit_card_full(self, card_type=None):
        card = self._debit_card_type(card_type)

        tpl = ('{provider}\n'
               '{owner}\n'
               '{number} {expire_date}\n')

        tpl = tpl.format(provider = card.name,
                         owner = self.generator.parse("{{first_name}} {{last_name}}"),
                         number = self.debit_card_number(card),
                         expire_date = self.debit_card_expire(),
                         )

        return self.generator.parse(tpl)

    @classmethod
    def debit_card_security_code(cls, card_type=None):
        """ Returns a security code string. """
        sec_len = cls._debit_card_type(card_type).security_code_length
        return cls.numerify('#' * sec_len)

    @classmethod
    def _debit_card_type(cls, card_type=None):
        """ Returns a random debit card type instance. """
        if card_type is None:
            card_type = cls.random_element(cls.debit_card_types.keys())
        elif isinstance(card_type, DebitCard):
            return card_type
        return cls.debit_card_types[card_type]

    @classmethod
    def _generate_number(cls, prefix, length):
        """
        'prefix' is the start of the CC number as a string, any number of digits.
        'length' is the length of the CC number to generate. Typically 13 or 16
        """
        number = prefix
        # Generate random char digits
        number += '#' * (length - len(prefix) - 1)
        number = cls.numerify(number)
        reverse = number[::-1]
        # Calculate sum
        tot = 0
        pos = 0
        while pos < length - 1:
            tot += Provider.luhn_lookup[reverse[pos]]
            if pos != (length - 2):
                tot += int(reverse[pos + 1])
            pos += 2
        # Calculate check digit
        check_digit = (10 - (tot % 10)) % 10
        number += str(check_digit)
        return number