import math
import numpy as np
from grooming.Algorithm.NodeStructure import Nodestructureservices
from pydantic import BaseModel
from grooming.schemas import LowRateGrooming, GroomingLightPath, GroomingOutput, RemaningServices, GroomOutType, RoutingType, NodeStructure
from pulp import LpProblem, LpMinimize, LpVariable, lpSum, LpStatus, PULP_CBC_CMD
from pydantic import BaseModel

def MP2X(Services_lower10):
    """
        This function packs the MP2X input services to 10G service.

        Advantages:
            - Optimum packing by means of ILP

        :param <Services_lower10>: <input>
        :type <list>: <each memeber of list is a tuple included service id and the capacity of service>

        :param <prob>: <LP problem>
        :type <class>: <ILP is solved by means of this class>

        :param <max_number_device>: <maximum number of device>
        :type <integer>: <>

        :param <NO_service_lower10>: <number of services in input parameter>
        :type <integer>: <length of Services_lower10>

        :param <Output>: <maximum number of device>
        :type <list>: <list of list which is included  tuples with  service id and the capacity of service>

    """
    prob = LpProblem("grooming", LpMinimize )
    B=10                    #u
    max_port=16
    y=[]
    min_number_of_service=3

        #Services_lower10=[0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 2.5, 2.5, 0.62, 0.62, 0.62, 0.62, 0.62]
        #Services_lower10=[2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,0.62]

    NO_service_lower10 = len(Services_lower10)
    #print(sum([pair[1] for pair in Services_lower10]))
    #print(math.ceil(sum([pair[1] for pair in Services_lower10])/20))
    NO_Lineport_MP2x=max(math.ceil(NO_service_lower10/8),math.ceil(sum([pair[1] for pair in Services_lower10])/10))    #number of line ports
    max_number_device=math.ceil(NO_Lineport_MP2x/2)
    max_number_device=max_number_device*2
    #    max_number_device=NO_Lineport_MP2x
    #    if NO_service_lower10 ==81:
    #        print("max=",max_number_device)
    #        print("**",max_number_device)
    for i in range(1,max_number_device+1):
        #y[i]=LpVariable(name='y[i]', cat='Binary')
        y.append(LpVariable(name='y%s'%i, cat='Binary'))

    x = {}
    for j in range(1,max_number_device+1):
        for i in range(1,NO_service_lower10+1):
           #x ={ (i, j): LpVariable("x",  cat='Binary')}
           x[(i,j)] = LpVariable("x%s_%s"%(i,j),  cat='Binary')

    #    prob += lpSum([x[(i,j)] for j in range(1,NO_service_lower10+1) for i in range(1,max_number_device+1)])
    prob += lpSum([y[i-1] for i in range(1,max_number_device+1)])
    #    prob += lpSum([y[i-1] for i in range(1,max_number_device+1)])
    #     for j in range(1,max_number_device+1):
    #        prob +=lpSum(Services_lower10[i-1][1]*x[(i,j)] for i in range(1,NO_service_lower10+1))

    for i in range(1,NO_service_lower10+1):
        prob +=lpSum(x[(i,j)] for j in range(1,max_number_device+1) ) ==1,""

    for j in range(1,max_number_device+1):
        prob +=lpSum(Services_lower10[i-1][1]*x[(i,j)] for i in range(1,NO_service_lower10+1)) <= B*y[j-1],""

    for j in range(1,max_number_device+1):
        for  i in range(1,NO_service_lower10+1):
            prob +=lpSum(x[(i,j)]) <= y[j-1],""

    for j in range(1,max_number_device+1):
        prob +=lpSum(x[(i,j)] for i in range(1,NO_service_lower10+1) ) <=max_port,""

    #prob.writeLP("grooming.lp")
    prob.solve(PULP_CBC_CMD(msg=False))

    #print("Status:", LpStatus[prob.status])

    #for j in range(1,max_number_device+1):

    '''for v in prob.variables():
        print (v.name, "=", v.varValue)'''
    '''for j in range(1,max_number_device+1):
        print("******   ",y[j-1],"=",y[j-1].value(),"     *********    ")
        for i in range(1,NO_service_lower10+1):
            print(x[(i,j)],"=",x.get(i,j))'''
    ans = prob.variables()
    Result = {}
    for j in range(max_number_device):
        Result[ans[-1 - j].name] = {}
    #    yy={}
    for i in range( len(ans) - max_number_device ):
        itemName = ans[i].name
        itemValue = ans[i].varValue

        find_underscore = itemName.index("_")
        ServiceNum = itemName[1:find_underscore]
        PanelNum = itemName[(find_underscore+1):]

        key_panel = 'y' + PanelNum
        if itemValue:
            namee=Services_lower10[int(ServiceNum) - 1][0]
        else:
            namee=0
        Result[key_panel][itemName] = (namee ,itemValue * Services_lower10[int(ServiceNum) - 1][1])
    #print(Result)

    #for j in range(1,max_number_device+1):
    #    if y[j-1].value()==1:
    #        h=0
    #        for i in range(1,NO_service_lower10+1):
    ##            print('**',x[(i,j)].value())
    #            if x[(i,j)].value()==1:
    #                h=h+1
    ##                print('h=',h)
    #        if h>= min_number_of_service:
    #            print(j,y[j-1])                        #????

    Output=[]

    for key, value in Result.items():
        y=[]
        for inner_key,inner_value in value.items():
            if inner_value[1] != 0:
                y.append(( inner_value[0],inner_value[1]))
        if y:
            Output.append(y)
    #    dele=[]
    #    for i in range(0, len(Output)):
    #        if (len(Output[i])==0):
    #            dele.append(i)
    #
    #    print('dsdsss')
    #    print(Output)
    #    print('dsdsss')
    return Output

def PS6X(Services_lower10_i):
    """
        This function packs the PS6X input services to 10G service.

        Advantages:
            - Optimum packing by means of ILP

        :param <Services_lower10>: <input>
        :type <list>: <each memeber of list is a tuple included service id and the capacity of service>

        :param <prob>: <LP problem>
        :type <class>: <ILP is solved by means of this class>

        :param <max_number_device>: <maximum number of device>
        :type <integer>: <>

        :param <NO_service_lower10>: <number of services in input parameter>
        :type <integer>: <length of Services_lower10>

        :param <Output>: <maximum number of device>
        :type <list>: <list of list which is included  tuples with  service id and the capacity of service>

    """
    prob = LpProblem("grooming", LpMinimize )
    B=10                    #u
    max_port=16
    y=[]
    min_number_of_service=3
    Services_lower10=[]
    no_fe=0

        #Services_lower10=[0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 2.5, 2.5, 0.62, 0.62, 0.62, 0.62, 0.62]
        #Services_lower10=[2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,0.62]

    for i in range(0,len(Services_lower10_i)):
        if(Services_lower10_i[i][1]==0.1):
            Services_lower10.append(Services_lower10_i[i])
            no_fe=no_fe+1
    for i in range(0,len(Services_lower10_i)):
        if(Services_lower10_i[i][1]==1):
            Services_lower10.append(Services_lower10_i[i])
    NO_service_lower10 = len(Services_lower10)
    #print(sum([pair[1] for pair in Services_lower10]))
    #print(math.ceil(sum([pair[1] for pair in Services_lower10])/20))
    NO_Lineport=max(math.ceil(NO_service_lower10/10),math.ceil(sum([pair[1] for pair in Services_lower10])/10))    #number of line ports
    max_number_device=math.ceil(NO_Lineport/2)
    max_number_device=max_number_device*2
    #    max_number_device=NO_Lineport_MP2x
    #    if NO_service_lower10 ==81:
    #        print("max=",max_number_device)
    #        print("**",max_number_device)`
    for i in range(1,max_number_device+1):
        #y[i]=LpVariable(name='y[i]', cat='Binary')
        y.append(LpVariable(name='y%s'%i, cat='Binary'))

    x = {}
    for j in range(1,max_number_device+1):
        for i in range(1,NO_service_lower10+1):
           #x ={ (i, j): LpVariable("x",  cat='Binary')}
           x[(i,j)] = LpVariable("x%s_%s"%(i,j),  cat='Binary')

    #    prob += lpSum([x[(i,j)] for j in range(1,NO_service_lower10+1) for i in range(1,max_number_device+1)])
    prob += lpSum([y[i-1] for i in range(1,max_number_device+1)])
    #    prob += lpSum([y[i-1] for i in range(1,max_number_device+1)])
    #     for j in range(1,max_number_device+1):
    #        prob +=lpSum(Services_lower10[i-1][1]*x[(i,j)] for i in range(1,NO_service_lower10+1))

    for i in range(1,NO_service_lower10+1):
        prob +=lpSum(x[(i,j)] for j in range(1,max_number_device+1) ) ==1,""

    for j in range(1,max_number_device+1):
        prob +=lpSum(Services_lower10[i-1][1]*x[(i,j)] for i in range(1,NO_service_lower10+1)) <= B*y[j-1],""

    for j in range(1,max_number_device+1):
        for  i in range(1,NO_service_lower10+1):
            prob +=lpSum(x[(i,j)]) <= y[j-1],""

    for j in range(1,max_number_device+1):
        prob +=lpSum(x[(i,j)] for i in range(1,no_fe+1) ) <=14,""

    for j in range(1,max_number_device+1):
        prob +=lpSum(x[(i,j)] for i in range(1,NO_service_lower10+1) ) <=16,""
    #    for j in range(1,max_number_device+1):
    #        prob +=lpSum((x[(i,j)] for i in range(no_fe+1,NO_service_lower10+1)) + (x[(k,j)] for k in range(1,no_fe+1)) ) <=16,""

    #prob.writeLP("grooming.lp")
    prob.solve()

    #print("Status:", LpStatus[prob.status])

    #for j in range(1,max_number_device+1):

    '''for v in prob.variables():
        print (v.name, "=", v.varValue)
    for j in range(1,max_number_device+1):
        print("******   ",y[j-1],"=",y[j-1].value(),"     *********    ")
        for i in range(1,NO_service_lower10+1):
            print(x[(i,j)],"=",x.get(i,j))'''
    ans = prob.variables()
    #    print(ans)
    Result = {}
    for j in range(max_number_device):
        Result[ans[-1 - j].name] = {}
    #    yy={}
    for i in range( len(ans) - max_number_device ):
        itemName = ans[i].name
        itemValue = ans[i].varValue

        find_underscore = itemName.index("_")
        ServiceNum = itemName[1:find_underscore]
        PanelNum = itemName[(find_underscore+1):]

        key_panel = 'y' + PanelNum
        Result[key_panel][itemName] = (itemValue * Services_lower10[int(ServiceNum) - 1][0],itemValue * Services_lower10[int(ServiceNum) - 1][1])
    #print(Result)

    #for j in range(1,max_number_device+1):
    #    if y[j-1].value()==1:
    #        h=0
    #        for i in range(1,NO_service_lower10+1):
    ##            print('**',x[(i,j)].value())
    #            if x[(i,j)].value()==1:
    #                h=h+1
    ##                print('h=',h)
    #        if h>= min_number_of_service:
    #            print(j,y[j-1])                        #????

    Output=[]

    for key, value in Result.items():
        y=[]
        for inner_key,inner_value in value.items():
            if inner_value[1] != 0:
                y.append((int (inner_value[0]),inner_value[1]))
        if y:
            Output.append(y)
    #    dele=[]
    #    for i in range(0, len(Output)):
    #        if (len(Output[i])==0):
    #            dele.append(i)
    #
    #    print('dsdsss')
    #    print(Output)
    #    print('dsdsss')
    #    print(Output)
    #    print(Services_lower10)
    return Output

    #def PS6X(Services_lower10):
    #    prob = LpProblem("grooming", LpMinimize )
    #    B=10                    #u
    #    max_port=16
    #    y=[]
    #    min_number_of_service=3
    #
    #
    #        #Services_lower10=[0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 2.5, 2.5, 0.62, 0.62, 0.62, 0.62, 0.62]
    #        #Services_lower10=[2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,2.5,0.62]
    #
    #    NO_service_lower10 = len(Services_lower10)
    #    NO_service_lower10_fe=[]
    #    NO_service_lower10_ge=[]
    #    for i in range(0,len(NO_service_lower10)):
    #        if(NO_service_lower10[i][1]==0.1):
    #            NO_service_lower10_fe.append(NO_service_lower10[i])
    #        elif(NO_service_lower10[i][1]==1):
    #            NO_service_lower10_ge.append(NO_service_lower10[i])
    #    NO_service_fe=len(NO_service_lower10_fe)
    #    NO_service_ge=len(NO_service_lower10_ge)
    #    #print(sum([pair[1] for pair in Services_lower10]))
    #    #print(math.ceil(sum([pair[1] for pair in Services_lower10])/20))
    #    NO_Lineport=max(math.ceil(NO_service_lower10/10),math.ceil(sum([pair[1] for pair in Services_lower10])/10))    #number of line ports
    #    max_number_device=math.ceil(NO_Lineport/2)
    #    max_number_device=max_number_device*2
    ##    max_number_device=NO_Lineport_MP2x
    ##    if NO_service_lower10 ==81:
    ##        print("max=",max_number_device)
    ##        print("**",max_number_device)
    #    for i in range(1,max_number_device+1):
    #        #y[i]=LpVariable(name='y[i]', cat='Binary')
    #        y.append(LpVariable(name='y%s'%i, cat='Binary'))
    #
    #    x = {}
    #    for j in range(1,max_number_device+1):
    #        for i in range(1,NO_service_fe+1):
    #            for k in range(1,NO_service_ge+1):
    #           #x ={ (i, j): LpVariable("x",  cat='Binary')}
    #               x[(i,k,j)] = LpVariable("x%s_%s"%(i,k,j),  cat='Binary')
    #
    #
    #
    ##    prob += lpSum([x[(i,j)] for j in range(1,NO_service_lower10+1) for i in range(1,max_number_device+1)])
    #    prob += lpSum([y[i-1] for i in range(1,max_number_device+1)])
    ##    prob += lpSum([y[i-1] for i in range(1,max_number_device+1)])
    ##     for j in range(1,max_number_device+1):
    ##        prob +=lpSum(Services_lower10[i-1][1]*x[(i,j)] for i in range(1,NO_service_lower10+1))
    #
    #
    #    for i in range(1,NO_service_fe+1):
    #        prob +=lpSum(x[(i,k,j)] for j in range(1,max_number_device+1) ) ==1,""
    #
    #    for k in range(1,NO_service_ge+1):
    #        prob +=lpSum(x[(i,k,j)] for j in range(1,max_number_device+1) ) ==1,""
    #
    #
    #    for j in range(1,max_number_device+1):
    #        prob +=lpSum(Services_lower10[i-1][1]*x[(i,j)] for i in range(1,NO_service_lower10+1)) <= B*y[j-1],""
    #
    #
    #    for j in range(1,max_number_device+1):
    #        for  i in range(1,NO_service_lower10+1):
    #            prob +=lpSum(x[(i,k,j)]) <= y[j-1],""
    #
    #    for j in range(1,max_number_device+1):
    #        prob +=lpSum(x[(i,j)] for i in range(1,NO_service_lower10+1) ) <=max_port,""
    #
    #
    #
    #
    #    #prob.writeLP("grooming.lp")
    #    prob.solve()
    #
    #    #print("Status:", LpStatus[prob.status])
    #
    #    #for j in range(1,max_number_device+1):
    #
    #    '''for v in prob.variables():
    #        print (v.name, "=", v.varValue)'''
    #    '''for j in range(1,max_number_device+1):
    #        print("******   ",y[j-1],"=",y[j-1].value(),"     *********    ")
    #        for i in range(1,NO_service_lower10+1):
    #            print(x[(i,j)],"=",x.get(i,j))'''
    #    ans = prob.variables()
    #    Result = {}
    #    for j in range(max_number_device):
    #        Result[ans[-1 - j].name] = {}
    #    #    yy={}
    #    for i in range( len(ans) - max_number_device ):
    #        itemName = ans[i].name
    #        itemValue = ans[i].varValue
    #
    #        find_underscore = itemName.index("_")
    #        ServiceNum = itemName[1:find_underscore]
    #        PanelNum = itemName[(find_underscore+1):]
    #
    #        key_panel = 'y' + PanelNum
    #        Result[key_panel][itemName] = (itemValue * Services_lower10[int(ServiceNum) - 1][0],itemValue * Services_lower10[int(ServiceNum) - 1][1])
    #    #print(Result)
    #
    #    #for j in range(1,max_number_device+1):
    #    #    if y[j-1].value()==1:
    #    #        h=0
    #    #        for i in range(1,NO_service_lower10+1):
    #    ##            print('**',x[(i,j)].value())
    #    #            if x[(i,j)].value()==1:
    #    #                h=h+1
    #    ##                print('h=',h)
    #    #        if h>= min_number_of_service:
    #    #            print(j,y[j-1])                        #????
    #
    #    Output=[]
    #
    #    for key, value in Result.items():
    #        y=[]
    #        for inner_key,inner_value in value.items():
    #            if inner_value[1] != 0:
    #                y.append((int (inner_value[0]),inner_value[1]))
    #        if y:
    #            Output.append(y)
    ##    dele=[]
    ##    for i in range(0, len(Output)):
    ##        if (len(Output[i])==0):
    ##            dele.append(i)
    ##
    ##    print('dsdsss')
    ##    print(Output)
    ##    print('dsdsss')
    #    return Output

        #  remain_lower100            (the services which are not assigned to lightpath)  (DemandId,[ServiceId])
        #  MP2x_list                  (MP2X with 2 output)                               (DemandId,[ServiceId(groomout10),ServiceId(groomout10)])
        #  remaining_service_lower10  (MP2X with 1 output)                               (DemandId,ServiceId(groomout10))

def grooming_fun( TM, MP1H_Threshold,  tmId, percentage, uuid, MP2X_Threshold = None, state=None):
        """
            This function grooms the services and produces lightpaths, groomouts, devices and remaining services.

            :param <service_lower10_SDH>: <list of SDH services>
            :type <list>: <each memeber of list is a tuple included demand is and a list of tuples included service id and the capacity of service>

            :param <service_lower10_E>: <list of Ethernet services>
            :type <list>: <each memeber of list is a tuple included demand is and a list of tuples included service id and the capacity of service>

            :param <service_lower100>: <list of services that capacity of them is lower than 100>
            :type <List>: <each memeber of list is a tuple included demand is and a list of tuples included service id and the capacity of service >

            :param <remaining_service_lower10>: <list of remaining services that capacity of them is lower than 10>
            :type <List>: <each memeber of list is a tuple included demand is and a list of tuples included service id and the capacity of service >

            :param <device_dict>: <list of devices>
            :type <dictionary>: <keys are the nodes names and values are dictionary which keys of them are device name and values are the list of dedicated devices>

            :param <remaining_service_lower10_dict>: <list of remaining services that capacity of them is lower than 10>
            :type <dictionary>: <keys are the demands id and values are list of tuples included service ids and capacity of them>

            :param <groom_out10_list>: <list of grooming of services that capacity of them is lower than 10>
            :type <List>: <each memeber of list is a tuple included demand is and a list of tuples included groomout10 (output of MP2X) id and the capacity of that >

            :param <Groomout10>: <list of grooming of services that capacity of them is lower than 10>
            :type <dictionary>: <keys are the id of demands and values are the demand Specifications and the list of groomouts>

            :param <FinalLightPath>: <list of 100G Lightpaths>
            :type <dictionary>: <keys are lightpath id and values are the lightpaths>

            :param <groomingresult>: <output>
            :type <dictionary>: <keys are lightpath, low_rate_grooming_result, and remaining_services and values are the dictionary of that corresponding keys that mentioned previously>

            :param <percentage>: <input>
            :type <integer>: < initiate value of progress percentage>

            :param <state>: <input>
            :type <object>: <working object >

            :param <TM>: <input>
            :type <dictionary>: <traffic matrix >

            :param <tmId>: <input>
            :type <string>: <traffic matrix id>

            :param <uuid>: <input>
            :type <function>: <generate a unique id>

            :param <MP1H_Threshold>: <input>
            :type <integer>: <capacity threshold of generating lightpath>

            :param <MP2X_Threshold>: <input>
            :type <integer>: <capacity threshold of generating groom out>

        """
        service_lower10_SDH=[]
        service_lower10_E=[]
        service_lower100=[]
        remain_lower100_2=[]
        remaining_service_lower10=[]
        MP2x_list=[]
        MP2x_Dict={}                                 #(DemandId,Service)
        output_100=[]
        remain_lower100_dict={}
        remaining_service_lower10_dict={}
        groom_out10_list=[]
        remain_lower100=[]
        GRO10Id=0
        Groomout10={"demands":{}}
        remaningnservices={"demands":{}}
        FinalLightPath={}
        FinalLightPath.update({'LightPaths':{}})
        FinalLightPath.update({"id":uuid()})
        remaining_services= {"demands":{}}
        remaining_groomouts= {"demands":{}}
        def addlightpath(source,destination,capacity,service_id_list,demand_id,Routing_type,groomout10_id_list, protection_type, restoration_type, sdict):
            """
            This function create a lightpath and add it to FinalLightPath dictionary .

            :param <lst>: <list of services and type of them>
            :type <list>: <for groomout 10 value of type is "groomout" and for 10G services the value of type is "normal">

            :param <lightpathId>: <dedicated unique id for each lightpath>
            :type <string>: <id is generate by the uuid() function>
            """

            lst=[]
            for u in service_id_list:
                lst.append({"id":u,
                            "type":"normal",
                            "normal_service_type": sdict[str (demand_id)][u]})
            if groomout10_id_list != "None":
                for u in groomout10_id_list:
                    lst.append({"id":u,
                                "type":"groomout",
                                "normal_service_type": None,
                                "mp2x_panel_address": {"source":{   "rack_id": "None",
                                                                    "shelf_id": "None",
                                                                    "slot_id_list":["None"]},
                                                        "destination":{ "rack_id": "None",
                                                                        "shelf_id": "None",
                                                                        "slot_id_list":["None"]}}})
            lightpathId = uuid()
            lp1={

                "id": lightpathId,
                "source": source,
                "destination": destination,
                "service_id_list": lst,
                "routing_type":  Routing_type,
                "demand_id": str (demand_id),
                "protection_type":  protection_type,
                "restoration_type":  restoration_type,
                "capacity": capacity
            }
            FinalLightPath['LightPaths'].update({lightpathId:lp1})
            return lightpathId
        MP2x_dict={}
        TP1H_dict={}
        MP1H_dict={}
        device_dict={}
        lightpathId=1
        nume=1
        sdict={}
        for i in TM['demands'].keys():
            sdict.update({i:{}})
            remaining_groomouts["demands"].update({i:[]})
            remaining_services["demands"].update({i:{   "E1": { "count":  0,
                                                                "service_id_list": [],
                                                                "type": "E1"},
                                                        "stm1_e":{ "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "STM1 Electrical"} ,
                                                        "stm1_o": { "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "STM1 Optical"} ,
                                                        "stm4": {   "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "STM4"} ,
                                                        "stm16": {    "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "STM16"} ,
                                                        "stm64": {    "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "STM64"},
                                                        "FE": {    "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "STM64"},
                                                        "GE1": {    "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "GE"},
                                                        "GE10": {    "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "10GE"},
                                                        "GE100": {    "count":  0,
                                                                    "service_id_list": [],
                                                                    "type": "100GE"}}})
            per = math.ceil(percentage[0] + (nume/len(TM['demands'].keys())) * (percentage[1] - percentage[0]))

            if state is not None:
                state.update_state(state='PROGRESS', meta={'current': per, 'total': 100, 'status': 'Starting Grooming Algorithm!'})

            nume = nume + 1
            if TM['demands'][i]["source"] not in device_dict.keys():
                        device_dict.update({TM['demands'][i]["source"]:{
                                    "TP1H": [],
                                    "MP1H": [],
                                    "MP2X": []
                                    }})
            if TM['demands'][i]["destination"] not in device_dict.keys():
                device_dict.update({TM['demands'][i]["destination"]:{
                                    "TP1H": [],
                                    "MP1H": [],
                                    "MP2X": []
                                    }})
            y=[]
            z=[]
            x=[]
            output_10=[]
            for j in range(0,len(TM["demands"][i]["services"])):
                if TM["demands"][i]["services"][j]["type"] == "100GE":
                    for k in TM["demands"][i]["services"][j]["service_id_list"]:
                        sdict[i].update({k:TM["demands"][i]["services"][j]["type"]})
                        LPId=addlightpath(source=TM["demands"][i]["source"],
                        destination=TM["demands"][i]["destination"],
                        capacity=100,
                        service_id_list=[k],
                        groomout10_id_list="None",
                        demand_id=TM["demands"][i]["id"],
                        Routing_type=RoutingType.GE100,
                        protection_type=TM["demands"][i]["protection_type"],
                        restoration_type=TM["demands"][i]["restoration_type"],
                        sdict=sdict
                        )
                        if i in TP1H_dict.keys():
                            TP1H_dict[i].append((LPId,k))
                            device_dict[TM['demands'][i]["source"]]["TP1H"].append(
                                        {
                                            "panel" : "TP1H",
                                            "sub_tm_id": tmId,
                                            "lightpath_id": LPId,
                                            "id": uuid() })
                            device_dict[TM['demands'][i]["destination"]]["TP1H"].append(
                                        {
                                            "panel" : "TP1H",
                                            "sub_tm_id": tmId,
                                            "lightpath_id": LPId,
                                            "id": uuid()}
                            )
                        else:
                            TP1H_dict.update({TM["demands"][i]["id"]:[(LPId,k)]})
                            device_dict[TM['demands'][i]["source"]]["TP1H"].append(
                                        {
                                            "panel" : "TP1H",
                                            "sub_tm_id": tmId,
                                            "lightpath_id": LPId,
                                            "id": uuid()
                                    })
                            device_dict[TM['demands'][i]["destination"]]["TP1H"].append(
                                        {
                                            "panel" : "TP1H",
                                            "sub_tm_id": tmId,
                                            "lightpath_id": LPId,
                                            "id": uuid()}
                            )
                elif ((TM["demands"][i]["services"][j]["type"] == "STM64") or (TM["demands"][i]["services"][j]["type"] == "10GE")):
                    for k in TM["demands"][i]["services"][j]["service_id_list"]:
                        z.append((k,10))
                        sdict[i].update({k:TM["demands"][i]["services"][j]["type"]})
                elif TM["demands"][i]["services"][j]["type"] == "GE":
                    for k in TM["demands"][i]["services"][j]["service_id_list"]:
                        y.append((k,1.25))
                        sdict[i].update({k:TM["demands"][i]["services"][j]["type"]})
                elif TM["demands"][i]["services"][j]["type"] == "FE":
                    for k in TM["demands"][i]["services"][j]["service_id_list"]:
                        y.append((k,0.1))
                        sdict[i].update({k:TM["demands"][i]["services"][j]["type"]})
                elif TM["demands"][i]["services"][j]["type"] == "STM16":
                    for k in TM["demands"][i]["services"][j]["service_id_list"]:
                        y.append((k,2.5))
                        sdict[i].update({k:TM["demands"][i]["services"][j]["type"]})
                elif TM["demands"][i]["services"][j]["type"] in ["STM1 Optical", "STM1 Electrical"]:
                    for k in TM["demands"][i]["services"][j]["service_id_list"]:
                        y.append((k,0.15552))
                        sdict[i].update({k:TM["demands"][i]["services"][j]["type"]})
            if y:
                service_lower10_SDH.append((i,y))
                if len(y)>100:
                    yy=[]
                    res10=[]
                    for iii in range(0,math.ceil(len(y)/50)):
                        yy.append(y[iii*50:(iii+1)*50])
                    for y2 in yy:
                        res10.append(MP2X(y2))
                    finalres10=[]
                    for y2 in res10:
                        for y3 in y2:
                           finalres10.append(y3)
                    output_10.append((i,finalres10))
                else:
                    output_10.append((i,MP2X(y)))
                listofs=[]
                cap=0
                hhhh=[]
                service_id_list_of_gro10=[]
                Groomout10["demands"].update({i:{
                    "source":TM["demands"][i]["source"],
                    "destination":TM["demands"][i]["destination"],
                    "id":TM["demands"][i]["id"],
                    "protection_type" : TM["demands"][i]["protection_type"],
                    "RestorationType":TM["demands"][i]["protection_type"],
                    "groomouts":{}}})
                for num in range(0,len(output_10[0][1])):
                    listofs=[]
                    cap=0
                    for nu in range(0,len(output_10[0][1][num])):
                        listofs.append({    "id":str (output_10[0][1][num][nu][0]),
                                            "type":sdict[i][str (output_10[0][1][num][nu][0])]})
                        cap = cap + output_10[0][1][num][nu][1]
                    GroomOutId = uuid()
                    LastId = GroomOutId
                    Groomout10["demands"][i]["groomouts"].update({ GroomOutId:
                    {"quantity": 1,
                    "id": GroomOutId,
                    "service_id_list": listofs,
                    "type": GroomOutType.mp2x,
                    "sla":"None",
                    "capacity":cap}})
                    ffff=[(LastId,10)]
                    hhhh.append((LastId,cap,len(listofs),listofs))
                    z.append((LastId,cap))
                 #                    service_lower100.append((i,ffff))
                groom_out10_list.append((i,hhhh))
            if x:
                service_lower10_E.append((i,x))

            if z:
                service_lower100.append((i,z))

        for i in range(0,len(groom_out10_list)):
            nooo=[]
            for j in range(0,len(groom_out10_list[i][1])):
                for k in range(0,len(groom_out10_list[i][1])):
                    if ((k not in nooo) and (j not in nooo) and (j!=k) and (groom_out10_list[i][1][j][2] + groom_out10_list[i][1][k][2]) <=16):
                        MP2x_list.append((groom_out10_list[i][0],(groom_out10_list[i][1][j][0],groom_out10_list[i][1][k][0])))
                        if groom_out10_list[i][0] in MP2x_Dict.keys():
                            MP2x_Dict[groom_out10_list[i][0]].append((groom_out10_list[i][1][j][0],groom_out10_list[i][1][k][0]))
                        else:
                            MP2x_Dict.update({groom_out10_list[i][0]:[(groom_out10_list[i][1][j][0],groom_out10_list[i][1][k][0])]})
                        device_dict[TM['demands'][groom_out10_list[i][0]]["source"]]["MP2X"].append({
                                        "line1":{
                                                "demand_id": groom_out10_list[i][0],
                                                "groomout_id": groom_out10_list[i][1][k][0]
                                                    },
                                        "line2":{
                                                "demand_id": groom_out10_list[i][0],
                                                "groomout_id": groom_out10_list[i][1][j][0]
                                                    },
                                        "panel" : "MP2X",
                                        "sub_tm_id": tmId,
                                        "id": uuid()
                            })

                        device_dict[TM['demands'][groom_out10_list[i][0]]["destination"]]["MP2X"].append({
                                        "line1":{
                                                "demand_id": groom_out10_list[i][0],
                                                "groomout_id": groom_out10_list[i][1][k][0]
                                                    },
                                        "line2":{
                                                "demand_id": groom_out10_list[i][0],
                                                "groomout_id": groom_out10_list[i][1][j][0]
                                                    },
                                        "panel" : "MP2X",
                                        "sub_tm_id": tmId,
                                        "id": uuid()

                            }

                            )

                        nooo.append(j)
                        nooo.append(k)
            for m in range(0,len(groom_out10_list[i][1])):
                if m not in nooo:
                    remaining_service_lower10.append((groom_out10_list[i][0],groom_out10_list[i][1][m][0]))
                    if groom_out10_list[i][0] in remaining_service_lower10_dict.keys():
                        remaining_service_lower10_dict[groom_out10_list[i][0]].append(groom_out10_list[i][1][m][0])
                    else:
                        remaining_service_lower10_dict.update({groom_out10_list[i][0]:[groom_out10_list[i][1][m][0]]})
                    device_dict[TM['demands'][groom_out10_list[i][0]]["source"]]["MP2X"].append({
                                    "line1":{
                                            "demand_id": groom_out10_list[i][0],
                                            "groomout_id": groom_out10_list[i][1][m][0]
                                                },
                                    "panel" : "MP2X",
                                    "sub_tm_id": tmId,
                                    "id": uuid()
                        })

                    device_dict[TM['demands'][groom_out10_list[i][0]]["destination"]]["MP2X"].append({
                                    "line1":{
                                            "demand_id": groom_out10_list[i][0],
                                            "groomout_id": groom_out10_list[i][1][m][0]
                                            },
                                    "panel" : "MP2X",
                                    "sub_tm_id": tmId,
                                    "id": uuid()
                        }

                        )

        for i in range(0,len(service_lower100)):
            NO_LP= math.ceil(len(service_lower100[i][1])/10)
            orsr=TM["demands"][service_lower100[i][0]]["source"]
            ords=TM["demands"][service_lower100[i][0]]["destination"]
            for j in range(0,NO_LP):
                list_of_service=[]
                list_of_service2=[]
                cap=0
                for k in range(j*10,(j+1)*10):
                    if (k < len(service_lower100[i][1])):
                        list_of_service.append(service_lower100[i][1][k][0])
                        list_of_service2.append((service_lower100[i][1][k][0],service_lower100[i][1][k][1]))
                        cap=cap+service_lower100[i][1][k][1]
                if cap >= MP1H_Threshold:
                    typee="100GE"
                else:
                    typee="NonCoherent"

                if cap < MP1H_Threshold:
                    remain_lower100.append((service_lower100[i][0],list_of_service))
                    remain_lower100_2.append((service_lower100[i][0],list_of_service2))
                    remain_lower100_dict.update({service_lower100[i][0]:list_of_service})
                    for idd in list_of_service:
                        if idd in sdict[service_lower100[i][0]]:
                            fg="none"
                            if sdict[service_lower100[i][0]][idd] == "10GE":
                                fg="GE10"
                            else:
                                fg="stm64"
                            remaining_services["demands"][service_lower100[i][0]][fg]["count"] = remaining_services["demands"][service_lower100[i][0]][fg]["count"] + 1
                            remaining_services["demands"][service_lower100[i][0]][fg]["service_id_list"].append(idd)
                        else:
                            remaining_groomouts["demands"][service_lower100[i][0]].append(idd)
                    if service_lower100[i][0] in remaningnservices['demands'].keys():
                        remaningnservices['demands'][service_lower100[i][0]].append(list_of_service)
                    else:
                        remaningnservices['demands'].update({service_lower100[i][0]:list_of_service})
                else:
                    los1=[]
                    los2=[]
                    for ii in list_of_service:
                        if (service_lower100[i][0] in Groomout10["demands"]) and (ii in  Groomout10["demands"][service_lower100[i][0]]["groomouts"]):
                            los2.append(ii)
                        else:
                            los1.append(ii)
                    LPId=addlightpath(
                        source=TM["demands"][service_lower100[i][0]]["source"],
                        destination=TM["demands"][service_lower100[i][0]]["destination"],
                        capacity=cap,
                        service_id_list=los1,
                        groomout10_id_list= los2,
                        demand_id=TM["demands"][service_lower100[i][0]]["id"],
                        Routing_type=RoutingType.GE100,
                        protection_type=TM["demands"][service_lower100[i][0]]["protection_type"],
                        restoration_type=TM["demands"][service_lower100[i][0]]["restoration_type"],
                        sdict=sdict
                        )
                    device_dict[TM['demands'][service_lower100[i][0]]["source"]]["MP1H"].append({
                                    "panel" : "MP1H",
                                    "sub_tm_id": tmId,
                                    "lightpath_id": LPId,
                                    "id": uuid()
                    })
                    device_dict[TM['demands'][service_lower100[i][0]]["destination"]]["MP1H"].append({
                                    "panel" : "MP1H",
                                    "sub_tm_id": tmId,
                                    "lightpath_id": LPId,
                                    "id": uuid()
                    })

        devicedict={}
        groomingresult={}
        groomingresult.update({'low_rate_grooming_result':Groomout10})
        groomingresult.update({'lightpaths':FinalLightPath['LightPaths']})
        groomingresult.update({'remaining_services':remaining_services})
        groomingresult.update({'remaining_groomouts':remaining_groomouts})
        # groomingresult.update({'cluster_id':TM1[0]['id']})
        # devicedict.update({'service_devices': Nodestructureservices(device_dict)})
        return groomingresult,device_dict


from discord.ext.commands import Context
from discord.ext import commands
import discord

from bot import Waifu

from inspect import Parameter
from datetime import datetime
import asyncio

class Tag(commands.Cog):

    def __init__(self, bot: Waifu):
        self.bot = bot

    @commands.group(invoke_without_command=True)
    async def tag(self, ctx: Context, *, name: lambda inp: inp.lower()):
        """Get a tag"""
        query = "SELECT * FROM tags WHERE guild_id = $1 AND title = $2"
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        if tag is None:
            await ctx.message.delete(delay=10.0)
            message = await ctx.send('Could not find a tag with that name.')
            return await message.delete(delay=10.0)

        await ctx.send(tag['text'])
        await self.bot.con.execute("UPDATE tags SET uses = uses + 1 WHERE guild_id = $1 AND title = $2",
                                   ctx.guild.id, name)

    @tag.command()
    async def create(self, ctx: Context, name: lambda inp: inp.lower(), *, text: str = None):
        """Create a tag by providing a name and the content."""

        name = await commands.clean_content().convert(ctx=ctx, argument=name)
        query = "SELECT * FROM tags WHERE guild_id = $1 AND title = $2"
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        if tag is not None:
            return await ctx.send('A tag with that name already exists.')

        if not text and not ctx.message.attachments:
            raise commands.MissingRequiredArgument(Parameter("text", Parameter.POSITIONAL_OR_KEYWORD))
        if not text:
            text = "\n".join([i.url for i in ctx.message.attachments])
        else:
            text = await commands.clean_content().convert(ctx=ctx, argument=text)

        insert_query = """INSERT INTO tags(guild_id, author_id, title, text, uses, created_at)
                          VALUES($1, $2, $3, $4, $5, $6)"""
        await self.bot.con.execute(insert_query, ctx.guild.id, ctx.author.id, name, text, 0, datetime.utcnow())
        await ctx.send('You have successfully created your tag.')

    @tag.command()
    async def info(self, ctx: Context, *, name: lambda inp: inp.lower()):
        """Get information regarding the specified tag."""
        query = """SELECT * FROM tags WHERE guild_id = $1 AND title = $2"""
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        if tag is None:
            await ctx.message.delete(delay=10.0)
            return await ctx.send('Could not find a tag with that name.', delete_after=10)

        author = self.bot.get_user(tag['author_id'])
        author = str(author) if isinstance(author, discord.User) else f"(ID: {tag['author_id']})"

        info = discord.Embed(title=f"🏷 Tag: {tag['title']}", color=discord.Color.gold())
        info.add_field(name='Creator', value=author)
        info.add_field(name='Uses', value=tag['uses'])

        await ctx.send(embed=info)

    @tag.command()
    async def list(self, ctx: Context, *, member: discord.Member = None):
        """List your existing tags"""
        member = member or ctx.author
        query = """SELECT title FROM tags WHERE guild_id = $1 AND author_id = $2 ORDER BY title"""
        result = await self.bot.con.fetch(query, ctx.guild.id, member.id)

        if not result:
            return await ctx.send('No tags found.')

        await ctx.send(
            f"**{len(result)} tag{'s' * (len(result) > 1)} by {'you' if member == ctx.author else str(member)} found on this server.**"
        )

        pager = commands.Paginator()

        for record in result:
            pager.add_line(line=record["title"])

        for page in pager.pages:
            await ctx.send(page)

    @tag.command()
    async def delete(self, ctx: Context, *, name: lambda inp: inp.lower()):
        """Delete a tag."""
        query = """DELETE FROM tags WHERE guild_id = $1 AND title = $2"""
        await self.bot.con.execute(query, str(ctx.guild.id), name)
        await ctx.send("You have successfully deleted your tag.")

    @tag.command()
    async def all(self, ctx):
        """List all existing tags alphabetically ordered and sends them in DMs."""
        result = await self.bot.con.fetch(
            """SELECT title FROM tags WHERE guild_id = $1 ORDER BY title""",
            ctx.guild.id
        )
        if not result:
            return await ctx.send("This server doesn't have any tags.", delete_after=10)

        try:
            await ctx.author.send(f"***{len(result)} tag{'s' * (len(result) > 1)} found on this server.***")
        except discord.Forbidden:
            ctx.command.reset_cooldown(ctx)
            return await ctx.send("Could not dm you...", delete_after=10)

        pager = commands.Paginator()

        for record in result:
            pager.add_line(line=record["title"])

        for page in pager.pages:
            await asyncio.sleep(1)
            await ctx.author.send(page)

        await ctx.send("Tags sent in DMs.")

    @tag.command()
    async def edit(self, ctx: Context, name: lambda inp: inp.lower(), *, text: str):
        """Edit a tag"""
        text = await commands.clean_content().convert(ctx=ctx, argument=text)
        query = """SELECT * FROM tags WHERE guild_id = $1 AND title = $2"""
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        if tag is None:
            await ctx.message.delete(delay=10.0)
            return await ctx.send('Could not find a tag with that name.', delete_after=10)

        if tag['author_id'] != ctx.author.id:
            owner = await self.bot.is_owner(ctx.author)
            if not owner:
                return await ctx.send("You don't have permission to do that.")

        update = "UPDATE tags SET text = $1 WHERE guild_id = $2 AND title = $3"
        await self.bot.con.execute(update, text, ctx.guild.id, name)
        await ctx.send('You have successfully edited your tag.')

    @tag.command()
    async def rename(self, ctx: Context, name: lambda inp: inp.lower(), *, new_name: lambda inp: inp.lower()):
        """Rename a tag."""

        new_name = await commands.clean_content().convert(ctx=ctx, argument=new_name)

        query = "SELECT * FROM tags WHERE guild_id = $1 AND title = $2"
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        new_tag = await self.bot.con.fetchrow(query, ctx.guild.id, new_name)

        if new_tag is not None:
            return await ctx.send("A tag with that name already exists.")

        if tag is None:
            await ctx.message.delete(delay=10.0)
            return await ctx.send('Could not find a tag with that name.', delete_after=10)

        if tag['author_id'] != ctx.author.id:
            owner = await self.bot.is_owner(ctx.author)
            if not owner:
                return await ctx.send("You don't have permission to do that.")

        update = "UPDATE tags SET title = $1 WHERE guild_id = $2 AND title = $3"
        await self.bot.con.execute(update, new_name, ctx.guild.id, name)
        await ctx.send('You have successfully renamed your tag.')

    @tag.command()
    async def search(self, ctx: Context, *, term: str):
        """Search for a tag given a search term. PostgreSQL syntax must be used for the search."""
        query = """SELECT title FROM tags WHERE guild_id = $1 AND title LIKE $2 LIMIT 10"""
        result = await self.bot.con.fetch(query, ctx.guild.id, term)

        if not result:
            return await ctx.send("No tags found that has the term in it's name", delete_after=10)
        count = "Maximum of 10" if len(result) == 10 else len(result)
        tags = "\n".join(record["title"] for record in result)

        await ctx.send(
            f"**{count} tag{'s' * (len(result) > 1)} found with search term on this server.**```\n{tags}\n```"
        )

def setup(bot: Waifu):
    bot.add_cog(Tag(bot))


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

'''使用本机ubantu中配置的python2.7环境'''
__author__ = 'huanglingling'
'''update'''
__date__='2018.06.21'
#用户轨迹点映射到网格
#所有数据映射到主城区的网格，不在主城区的轨迹点网格映射为0

import csv as csv
import numpy as np
import pandas as pd
import math
import varGlobal
from pandas import *
from numpy import *
import os

class Record(object):
    def __init__(self, lng,lat):
        #self.lng = lng
        #self.lat = lat
        self.lng = float(lng)
        self.lat = float(lat)

class Grid(object):
    def __init__(self, uid,stime,etime,lat,lng,stated, gid):

        self.uid = uid
        self.stime = stime
        self.etime = etime
        self.lat=lat
        self.lng=lng
        self.stated = stated
        self.gid = gid

def grid2dict(obj):
    return {
        'uid': obj.uid,
        'stime': obj.stime,
        'etime': obj.etime,
        'stated': obj.stated,
        'gid': obj.gid,
    }

#读取文件数据
def readIn(path):
    #path = '/media/hll/amuse/gy/0511/lnglat0905_0.csv'
    with open(path,'r') as f:
        l=f.readlines()
        data = list(map(lambda x: Record(*x.strip().split(',')), l))
    return data
'''
# lng lat 均小于最小经纬度时映射到1 号网格
# lng lat 均大于最小经纬度时映射到 最大（4836） 号网格
def getGIDBylnglat(lng,lat):
    lng = float(lng)
    lat = float(lat)
    if lat > varGlobal.MAXLAT:
        x = varGlobal.COUNTLAT - 1
    elif lat < varGlobal.MINLAT:
        x = 0
    else:
        x = int((lat - varGlobal.MINLAT) / varGlobal.SIZELAT)
    if lng > varGlobal.MAXLNG:
        y = varGlobal.COUNTLNG - 1
    elif lng < varGlobal.MINLNG:
        y = 0
    else:
        y = int((lng - varGlobal.MINLNG) / varGlobal.SIZELNG)
    return x * varGlobal.COUNTLNG + y + 1
'''
def getGIDBylnglat(lng,lat):
    lng = float(lng)
    lat = float(lat)
    if (varGlobal.MINLAT < lat < varGlobal.MAXLAT) and (varGlobal.MINLNG < lng < varGlobal.MAXLNG):
        x = int((lat - varGlobal.MINLAT) / varGlobal.SIZELAT)
        y = int((lng - varGlobal.MINLNG) / varGlobal.SIZELNG)
        return x * varGlobal.COUNTLNG + y + 1
    else:
        return 0

def writetocsv(data):
    points=[(r.lng,r.lat) for r in data]
    #print(points)
    #grid= [getGIDBylnglat(float(x[0]), float(x[1])) for x in  points]
    grid = [getGIDBylnglat(x[0], x[1]) for x in points]
    print(grid[:5])
    return grid

def test():
    '''
    data = readIn()
    gid=writetocsv(data)
    datagid={'grid':gid}
    gidframe=pd.DataFrame(datagid,columns=['grid'])
'''
    path='/media/hll/doc/0511/0905/0905_6.csv'
    #path='/home/hll/PycharmProjects/gridMapHLL/testdata2.csv'
    #path = '/home/hll/PycharmProjects/gridMapHLL/testdata.csv'
    #dt = pd.read_csv(path,header=None)
    dt = pd.read_csv(path)
    print(dt.head())
    dt.columns = ['stime', 'uid','etime','lat','lng','stated']
    #dt.columns = ['uid', 'stime','etime', 'lat', 'lng', 'stated']
    print(dt.shape)
    print(dt.head())
    #print(dt[['lng','lat']].head())
    lnglat=dt[['lng','lat']]
    lnglat.to_csv('/media/hll/doc/0511/0905/lnglattestdata.csv',index=False,header=None)
    #/media/hll/doc/0511/0905/lnglattestdata.csv
    data = readIn('/media/hll/doc/0511/0905/lnglattestdata.csv')
    grid=writetocsv(data)
    datagrid = {'grid': grid}
    gridframe = pd.DataFrame(datagrid, columns=['grid'])
    print(gridframe.shape)
    #print(gridframe.head())
    #合并两个dataframe并写入csv

    frames=[dt,gridframe]
    results=pd.concat(frames,axis=1)
    print(results.head())
    #不将索引写入文件中
    results.to_csv('/media/hll/doc/0511/0905/0905gridUrban_6.csv',index=False)

if __name__=="__main__" : test()


from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import wikipedia as wiki
from PyQt5.uic import loadUiType

ui,_=loadUiType('wisdom.ui')

class MainApp(QMainWindow,ui):
    def __init__(self):
        QMainWindow.__init__(self)
        self.title = 'Wisdom by t0xic0der'
        self.setupUi(self)
        self.handle_buttons()

    def handle_buttons(self):
        self.box_smry.setReadOnly(True)
        self.box_sgst.setReadOnly(True)
        self.box_cont.setReadOnly(True)
        self.btn_find.clicked.connect(self.fetch_data)
        self.btn_relt.clicked.connect(self.fetch_relt)
        self.btn_imgs.clicked.connect(self.fetch_imgs)
        self.btn_rfer.clicked.connect(self.fetch_rfer)
        self.btn_loca.clicked.connect(self.dsply_lang)
        self.btn_docs.clicked.connect(self.fetch_docs)
        self.btn_dnat.clicked.connect(self.fetch_dnat)

    def fetch_rfer(self):
        prdct = self.box_sear.text()
        try:
            self.tex_name.setText("References")
            srch_rslt=wiki.search(prdct)
            paej = wiki.page(srch_rslt[0])
            relt = self.formt_rfer(paej.references)
            self.box_cont.setPlainText(relt)
            self.head_cont.setText("References for '"+str(prdct)+"'")
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("A references page has no URL")
        except Exception as e:
            print(e)
            self.tex_name.setText("References")
            self.tex_name.setText("References - Failed to display content")
            self.tex_wiki.setText("  Your keywords were either modified or deleted")
            self.head_cont.setText("Failed to display the list of references")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_relt(self):
        prdct = self.box_sear.text()
        try:
            self.tex_name.setText("Related articles")
            srch_rslt=wiki.search(prdct)
            paej = wiki.page(srch_rslt[0])
            relt = self.formt_relt(paej.links)
            self.box_cont.setPlainText(relt)
            self.head_cont.setText("Related links for '"+str(prdct)+"'")
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An related articles page has no URL")
        except Exception as e:
            print(e)
            self.tex_name.setText("Related articles")
            self.tex_name.setText("Related links - Failed to display content")
            self.tex_wiki.setText("  Your keywords were either modified or deleted")
            self.head_cont.setText("Failed to display the list of related links")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_imgs(self):
        prdct = self.box_sear.text()
        try:
            self.tex_name.setText("Image sources")
            srch_rslt=wiki.search(prdct)
            paej = wiki.page(srch_rslt[0])
            imgs = self.formt_imgs(paej.images)
            self.box_cont.setPlainText(imgs)
            self.head_cont.setText("Image sources for '"+str(prdct)+"'")
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An image sources page has no URL")
        except Exception as e:
            print(e)
            self.tex_name.setText("Image sources")
            self.tex_name.setText("Image sources - Failed to display content")
            self.tex_wiki.setText("  Your keywords were either modified or deleted")
            self.head_cont.setText("Failed to display the list of image sources")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_dnat(self):
        try:
            self.tex_name.setText("Donate to Wikipedia")
            dnat="Wikipedia is one of the most visited websites in the world.\n\nCommerce is fine. Advertising is not evil. But it doesn't belong here. Not in Wikipedia.\n\nWikipedia is something special. It is like a library or a public park. It is like a temple for the mind. It is a place we can all go to think, to learn, to share our knowledge with others.\n\nWhen I founded Wikipedia, I could have made it into a for-profit company with advertising banners, but I decided to do something different. We’ve worked hard over the years to keep it lean and tight. We fulfill our mission efficiently.\n\nIf everyone reading this donated, our fundraiser would be done within an hour. But not everyone can or will donate. And that's fine. Each year just enough people decide to give.\n\nThis year, please consider making a donation of or whatever you can to protect and sustain Wikipedia.\n\nThanks,\n\nJimmy Wales\nWikipedia Founder "
            self.box_cont.setPlainText(dnat)
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.head_cont.setText("From Wikipedia founder Jimmy Wales")
            self.art_url_disp.setText("A donation page has no URL")
            wiki.donate()
        except Exception as e:
            self.tex_name.setText("Donate to Wikipedia")
            self.head_cont.setText("Failed to retrieve the donation link")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def dsply_lang(self):
        try:
            self.tex_name.setText("Supported languages")
            content="Wikipedia provides content in the following languages\n"
            list_of_languages=wiki.languages().values()
            for lenguiz in list_of_languages:
                content+=str(str(lenguiz)+"\n")
            self.box_cont.setPlainText(content)
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.head_cont.setText("Wisdom currently supports only English language")
            self.art_url_disp.setText("An language page has no URL")
        except Exception as e:
            self.tex_name.setText("Supported languages")
            self.head_cont.setText("Failed to retrieve the list of supported languages")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_docs(self):
        try:
            self.tex_name.setText("Documentation")
            docs="Documentation of the API used here can be found in the links provided below\n\nDocumentation\nhttps://wikipedia.readthedocs.io/en/latest/code.html#api\n\nQuickstart\nhttps://wikipedia.readthedocs.io/en/latest/quickstart.html#quickstart"
            self.box_cont.setPlainText(docs)
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.head_cont.setText("API Documentation")
            self.art_url_disp.setText("A documentation page has no URL")
        except Exception as e:
            self.tex_name.setText("Documentation")
            self.head_cont.setText("Failed to retrieve the documentation")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_abut(self):
        pass

    def dsply_back(self):
        pass

    def formt_sgst(self, array):
        sgst_strg="People also search for \n"
        for i in range(len(array)):
            sgst_strg+=str(array[i])
            if i!=(len(array)-1):
                sgst_strg+="\n"
        return sgst_strg

    def formt_relt(self, array):
        list_of_related="These are the links related \n"
        for i in range(len(array)):
            list_of_related+=str(array[i])
            if i!=(len(array)-1):
                list_of_related+="\n"
        return list_of_related

    def formt_rfer(self, array):
        list_of_references="These are the references used \n"
        for i in range(len(array)):
            list_of_references+=str(array[i])
            if i!=(len(array)-1):
                list_of_references+="\n"
        return list_of_references

    def formt_imgs(self, array):
        list_of_images="These are the image sources used \n"
        for i in range(len(array)):
            list_of_images+=str(array[i])
            if i!=(len(array)-1):
                list_of_images+="\n"
        return list_of_images

    def fetch_data(self):
        prdct = self.box_sear.text()
        try:
            srch_rslt=wiki.search(prdct)
            suggest=self.formt_sgst(srch_rslt)                              # Format list of suggestion using function
            summery=wiki.summary(srch_rslt[0])                              # Fetches summary of the given title
            self.box_smry.setPlainText(summery)                             # Sets summary on the box provided
            self.box_sgst.setPlainText(suggest)                             # Sets suggestion on the box provided
            paej=wiki.page(srch_rslt[0])                                    # Fetches the page data for the given title
            self.box_cont.setPlainText(paej.content)                        # Sets content from the fetched page on the box provided
            self.tex_name.setText(srch_rslt[0])                             # Sets title from the fetched page on the box provided
            self.head_cont.setText(srch_rslt[0])                            # Sets title from the fetched page on the box provided
            self.val_paid.setText(str(paej.parent_id))                      # Sets parent ID from the fetched page on the box provided
            self.val_reid.setText(str(paej.revision_id))                    # Sets revision ID from the fetched page on the box provided
            self.art_url_disp.setText("Visit "+paej.url+" for more")        # Sets URL from the fetched page on the box provided
            self.tex_wiki.setText("  From Wikipedia, the free encyclopedia")
        except wiki.PageError as e:
            print(e)
            self.tex_name.setText("Page Not Found - Keywords do not match any article")
            self.tex_wiki.setText("  Try refining your search string to match results")
            self.head_cont.setText("Keywords do not match any article")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")
        except wiki.DisambiguationError as e:
            print(e)
            self.tex_name.setText("Disambiguation - Too many results to choose from")
            self.tex_wiki.setText("  Try refining your search keyword to fetch particular results")
            self.head_cont.setText("There are way too many results!")
            self.box_cont.setPlainText("Seems like your search query was too generalised that it fetched multiple results. Do not fret for it happens with the best of us. Just pick any one from the suggestions provided on the right side to move forward or be a bit more specific about what you are looking for")
            self.box_smry.clear()
            self.box_sgst.clear()
            self.box_sgst.setPlainText(str(e))
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")
        except wiki.HTTPTimeoutError as e:
            print(e)
            self.tex_name.setText("HTTP Timeout - Taking too long to fetch results")
            self.tex_wiki.setText("  Please wait for sometime before trying again")
            self.head_cont.setText("Taking too long to fetch results")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")
        except wiki.WikipediaException as e:
            print(e)
            self.tex_name.setText("Aww snap! - It's not you, It is me")
            self.tex_wiki.setText("  We are experiencing problems at our end")
            self.head_cont.setText("It's not you, It is me")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")
        except:
            self.tex_name.setText("Processing Error - Unable to fetch results")
            self.tex_wiki.setText("  Check the keywords and your internet connection once")
            self.head_cont.setText("Unable to fetch results")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

def main():
    app=QApplication(sys.argv)
    QFontDatabase.addApplicationFont("AkzidenzGroteskLight.ttf")
    window=MainApp()
    window.show()
    app.exec_()

if __name__ == '__main__':
    main()


import torch
import torchvision

from .custom_torch_transforms import TensorFlatten
import os
import numpy as np
def mnist_dataloader(data_path: str, batch_size: int, train:bool=True):
    """
    Load mnist image data from specified, convert to grayscaled (then binarised) tensors, flatten, return dataloader

    :param data_path: full path to data directory
    :param batch_size: batch size for dataloader
    :param train: whether to load train or test data
    :return dataloader: pytorch dataloader for mnist training dataset
    """
    # transforms to add to data
    transform = torchvision.transforms.Compose([
                                                torchvision.transforms.Grayscale(),
                                                torchvision.transforms.ToTensor(),
                                                lambda x: x>=0.5,
                                                lambda x: x.float(),
                                                TensorFlatten()
                                                ])

    mnist_data = torchvision.datasets.MNIST(data_path, transform=transform, train=train)
    dataloader = torch.utils.data.DataLoader(mnist_data, batch_size=batch_size, shuffle=True)

    return dataloader

def binarised_mnist_dataloader(data_path: str, batch_size: int, train=True, balanced=False):
    """
    Load binarised mnist image data from specified, convert to  tensors, flatten, return dataloader

    :param data_path: full path to data directory
    :param batch_size: batch size for dataloader
    :param train: whether to load train or test data
    :param balanced: whether to load balanced training data (if |train| is True).
    :return dataloader: pytorch dataloader for mnist training dataset
    """
    def read_file_to_numpy(file_name):
        mynumbers = []
        with open(file_name) as f:
            for line in f:
                mynumbers.append(np.array([float(n) for n in line.strip().split()]))
        return mynumbers

    train_file, valid_file, test_file, local_file = [os.path.join(data_path, 'binarizedMNIST/binarized_mnist_' + ds + '.amat') for ds in ['train', 'valid', 'test', 'local']]

    if train:
        if balanced:
            local_ar = read_file_to_numpy(local_file)
            tensorData = torch.Tensor(local_ar)
        else:
            train_ar, valid_ar = [read_file_to_numpy(f) for f in [train_file, valid_file]]
            train_ar = np.concatenate((train_ar, valid_ar), axis=0) # merge train and val into larger train set
            tensorData = torch.Tensor(train_ar)
    else:
        test_ar = read_file_to_numpy(test_file)
        tensorData = torch.Tensor(test_ar)

    # Do not shuffle the balanced training dataset.
    shuffle = not (train and balanced)

    targets = torch.Tensor([-1 for _ in range(len(tensorData))]).view(len(tensorData), -1) # these are dummy targets to match API

    tensorDataset = torch.utils.data.TensorDataset(tensorData, targets)
    dataloader = torch.utils.data.DataLoader(tensorDataset, batch_size=batch_size, shuffle=shuffle)

    return dataloader

def fashion_mnist_dataloader(data_path: str, batch_size: int, train:bool=True):
    """
        Load fashion_mnist image data from specified location, convert to tensors, binarise, flatten, and return dataloader
        Note: fashion_mnist already grayscaled in each channel.
        :param data_path: full path to data directory
        :param batch_size: batch size for dataloader
        :param train: whether to load train or test data
        :return dataloader: pytorch dataloader for mnist training dataset
        """
    # transforms to add to data
    transform = torchvision.transforms.Compose([
                                                torchvision.transforms.ToTensor(),
                                                lambda x: x>=0.5,
                                                lambda x: x.float(),
                                                TensorFlatten()
                                                ])

    fashion_mnist_data = torchvision.datasets.FashionMNIST(data_path, transform=transform, train=train)
    dataloader = torch.utils.data.DataLoader(fashion_mnist_data, batch_size=batch_size, shuffle=True)

    return dataloader

def cifar_dataloader(data_path: str, batch_size: int, train:bool=True, balanced=False):
    """
        Load CIFAR image data from specified location, convert to  tensors, binarise, and return dataloader
        Note: CIFAR already grayscaled in each channel.

        :param data_path: full path to data directory
        :param batch_size: batch size for dataloader
        :param train: whether to load train or test data
        :param balanced: whether to load balanced training data (if |train| is True).
        :return dataloader: pytorch dataloader for CIFAR training dataset
        """
    # transforms to add to data
    transform = torchvision.transforms.Compose([
                                                torchvision.transforms.ToTensor(),
                                                lambda x: x>=0.5,
                                                lambda x: x.float(),
                                                ])

    CIFAR10_data = torchvision.datasets.CIFAR10(data_path, transform=transform, train=train)

    if train and balanced:
        label_indices = [[] for i in range(10)]
        index = 0
        # Find at least 10 indices corresponding to each label.
        while any(len(indices) < 10 for indices in label_indices):
            _, label = CIFAR10_data[index]
            label_indices[label].append(index)
            index += 1
        # Extract the first 10 indices of each label.
        balanced_indices = [index for indices in label_indices for index in indices[:10]]
        # Form a balanced (unshuffled) datset from the extracted indices.
        CIFAR10_subset = torch.utils.data.Subset(CIFAR10_data, balanced_indices)
        dataloader = torch.utils.data.DataLoader(CIFAR10_subset, batch_size=batch_size, shuffle=False)
    else:
        dataloader = torch.utils.data.DataLoader(CIFAR10_data, batch_size=batch_size, shuffle=True)

    return dataloader


from flask import Flask, redirect,render_template,request
from cs50 import SQL

app= Flask(__name__)
TEMPLATES_AUTO_RELOAD = True

# This is class of cs50 which is from sql alchemy for sqltie
db=SQL('sqlite:///stroing_info.db')

@app.route("/")
def padf():
    return render_template('index.html')

@app.route("/register",methods=["POST"])
def registered():
    # TO get data from user which submits by form
    req=request.form.get('nam')
    db.execute('INSERT INTO first (name) VALUES (?)',req)
    return redirect('/sub')

@app.route('/sub')
def showdata():
    showin=db.execute('SELECT * FROM first')
    return render_template('show.html',registered=showin)


# -*- coding: utf-8 -*-
# CDICALC: calculator for coherent X-ray diffraction imaging experiments
#       authors:
#         Jerome Carnis, carnis_jerome@yahoo.fr

"""Model to handle the calculations in the secondary source tab."""

import logging

from cdicalc.models.model import Model
from cdicalc.resources.constants import EMPTY_MSG, ERROR_MSG
from cdicalc.utils.snippets_quantities import (
    CallbackParams,
    to_quantity,
)

logger = logging.getLogger(__name__)

class ModelCoherence(Model):
    """
    Specific class gathering methods for the calculations in the secondary source tab.
    """

    def update_horizontal_divergence(self, params: CallbackParams) -> None:
        """
        Update the horizontal divergence widget.

        :param params: an instance of CallbackParams
        """
        logger.debug("  -> update_angular_sampling")
        if not isinstance(params, CallbackParams):
            logger.exception(
                "params should be an instance of type Callback_params, "
                f"got {type(params)}"
            )
            return
        widget = params.ui.horizontal_divergence
        primary_source_distance = to_quantity(
            params.ui.primary_source_distance.text(),
            field_name=params.ui.primary_source_distance.objectName(),
        )
        horizontal_source_size = to_quantity(
            params.ui.horizontal_source_size.text(),
            field_name=params.ui.horizontal_source_size.objectName(),
        )

        if primary_source_distance is None or horizontal_source_size is None:
            # not beautiful but mypy does not understand any()
            widget.setText(EMPTY_MSG)
        elif primary_source_distance == 0:
            widget.setText(ERROR_MSG)
        else:
            horizontal_divergence = (
                horizontal_source_size / primary_source_distance
            ).to("radian")
            self.update_text(
                CallbackParams(
                    value=horizontal_divergence,
                    target_widgets=widget,
                    ui=params.ui,
                )
            )
        self.update_transverse_coherence(params)

    def update_vertical_divergence(self, params: CallbackParams) -> None:
        """
        Update the vertical divergence widget.

        :param params: an instance of CallbackParams
        """
        logger.debug("  -> update_angular_sampling")
        if not isinstance(params, CallbackParams):
            logger.exception(
                "params should be an instance of type Callback_params, "
                f"got {type(params)}"
            )
            return
        widget = params.ui.vertical_divergence
        primary_source_distance = to_quantity(
            params.ui.primary_source_distance.text(),
            field_name=params.ui.primary_source_distance.objectName(),
        )
        vertical_source_size = to_quantity(
            params.ui.vertical_source_size.text(),
            field_name=params.ui.vertical_source_size.objectName(),
        )

        if primary_source_distance is None or vertical_source_size is None:
            # not beautiful but mypy does not understand any()
            widget.setText(EMPTY_MSG)
        elif primary_source_distance == 0:
            widget.setText(ERROR_MSG)
        else:
            vertical_divergence = (vertical_source_size / primary_source_distance).to(
                "radian"
            )
            self.update_text(
                CallbackParams(
                    value=vertical_divergence,
                    target_widgets=widget,
                    ui=params.ui,
                )
            )
        self.update_transverse_coherence(params)

    def update_transverse_coherence(self, params: CallbackParams) -> None:
        """
        Update the horizontal and vertical coherence length widget.

        :param params: an instance of CallbackParams
        """
        logger.debug("  -> update_d2theta")
        if not isinstance(params, CallbackParams):
            logger.exception(
                "params should be an instance of type Callback_params, "
                f"got {type(params)}"
            )
            return

        wavelength = to_quantity(
            params.ui.xray_wavelength.text(),
            field_name=params.ui.xray_wavelength.objectName(),
        )
        if wavelength is None:
            params.target_widgets = [
                params.ui.horizontal_coherence_length,
                params.ui.vertical_coherence_length,
            ]
            self.clear_widget(params)
            return

        target_widget = params.ui.horizontal_coherence_length
        horizontal_divergence = to_quantity(
            params.ui.horizontal_divergence.text(),
            field_name=params.ui.horizontal_divergence.objectName(),
        )
        if horizontal_divergence is None:
            target_widget.setText(EMPTY_MSG)
        elif horizontal_divergence == 0:
            target_widget.setText(ERROR_MSG)
        else:
            horizontal_coherence = wavelength / horizontal_divergence
            self.update_text(
                CallbackParams(
                    value=horizontal_coherence,
                    target_widgets=target_widget,
                    ui=params.ui,
                )
            )

        target_widget = params.ui.vertical_coherence_length
        vertical_divergence = to_quantity(
            params.ui.vertical_divergence.text(),
            field_name=params.ui.vertical_divergence.objectName(),
        )
        if vertical_divergence is None:
            target_widget.setText(EMPTY_MSG)
        elif vertical_divergence == 0:
            target_widget.setText(ERROR_MSG)
        else:
            vertical_coherence = wavelength / vertical_divergence
            self.update_text(
                CallbackParams(
                    value=vertical_coherence,
                    target_widgets=target_widget,
                    ui=params.ui,
                )
            )


import numpy as np
from triqs.lattice.tight_binding import TightBinding, BravaisLattice

number_of_orbitals = 4

bl = BravaisLattice(
    units = [(1,0,0),(0,1,0)],
    orbital_positions = [(0,0,0)]*number_of_orbitals)

# Hopping matrix with wrong size!!!!
hopping = { (0, 0): np.eye(2) }

got_dimension_error = False

try:
    tb = TightBinding(bl, hopping)
except:
    got_dimension_error = True

assert( got_dimension_error )


from sqlalchemy import select
from db_models import CustomerTable, PersonTable
from linking_tables import CustomerPeopleLinking
from person import Person as p
from main import session

class Customers:
    @staticmethod
    def create_customer(person_id, is_guest):
        customer = CustomerTable(person_id=person_id, is_guest=is_guest)
        session.add_all([customer])
        session.commit()

    @staticmethod
    def update_is_guest_by_id(c_id, is_guest):
        customer_to_update = session.query(CustomerTable).filter(CustomerTable.customer_id == c_id).first()
        customer_to_update.is_guest = is_guest
        session.commit()

    @staticmethod
    def create_list_of_customers():
        results = session.query(CustomerTable).join(PersonTable, CustomerTable.person_id == PersonTable.person_id).all()
        return results

    @staticmethod
    def create_list_of_current_guests():
        statement = select(CustomerTable).join(PersonTable, CustomerTable.person_id == PersonTable.person_id) \
            .filter(CustomerTable.is_guest == 1)
        results = session.scalars(statement)
        return results

    @staticmethod
    def create_list_of_non_current_guests():
        statement = select(CustomerTable).join(PersonTable, CustomerTable.person_id == PersonTable.person_id) \
            .filter(CustomerTable.is_guest == 0)
        results = session.scalars(statement)
        return results

    @staticmethod
    def delete_customer_by_id(c_id):
        statement = select(CustomerTable).filter(CustomerTable.customer_id == c_id)
        results = session.scalars(statement)
        print('CUSTOMER: ', statement)
        for result in results:
            session.delete(result)
            print('<<<<<<<<<DELETED OBJECT>>>>>>>>>>')
        # session.commit()

        # statement = select(PersonTable).where(PersonTable.person_id == CustomerTable.person_id) \
        #     .filter(CustomerTable.customer_id == c_id)
        #
        # results = session.scalars(statement)
        # for result in results:
        #     print(f'<<<< PRINT RESULTS.FIRST: {result} >>>>>')

        # customer_id = statement.person_id

        # for customer in results:
        # p.check_if_valid(c_id)
        statement = select(CustomerTable.customer_id).where(PersonTable.person_id == CustomerTable.customer_id)
        results = session.scalars(statement)
        for result in results:
            print (result)

        # if not CustomerTable.is_guest:
        #     # first delete customer from customer table
        #     customer = session.query(CustomerTable).filter_by(customer_id=c_id).first()
        #     session.delete(customer)
        #     session.commit()
        #     # next delete customer from person table
        #
        #     session.delete(results)
        #     session.commit()
        #     # p.delete_person_by_id(CreatePerson).first()
        #
        # else:
        #     print(f'<<<< Cannot delete PERSON ID: {statement.person_id}  '
        #           f'Name: {results.first_name, results.last_name} they are currently a guest. >>>>')
        # print('PRINT RESULTS: ', results)
        # # results = Customer.create_list_of_customers()
        # # for customer in results:
        # #     print('customer: ', customer)

def test():
    # statement = select(Customer).join(CreatePerson, Customer.person_id == CreatePerson.person_id)\
    #     .filter(Customer.is_guest == 0)

    # Customers.create_customer(person_id=1, is_guest=0)
    # Customers.create_customer(person_id=2, is_guest=1)
    # Customers.create_customer(person_id=4, is_guest=1)
    # Customers.create_customer(person_id=5, is_guest=0)
    #
    # CustomerPeopleLinking.create_link(1,1)
    # CustomerPeopleLinking.create_link(2, 2)
    # CustomerPeopleLinking.create_link(3, 3)
    # CustomerPeopleLinking.create_link(4, 4)

    # results = Customers.create_list_of_non_current_guests()
    # print("<<<< Customer that are not Guests >>>>>")
    # for customer in results:
    #     print('Customer ID:', customer.customer_id, customer.person)
    #
    # results = Customers.create_list_of_current_guests()
    # print("<<<< Customer that are Guests >>>>>")
    # for customer in results:
    #     print('Customer ID:', customer.customer_id, customer.person)

    # Customer.delete_customer_by_id(2)
    # Customer.delete_customer_by_id(1)
    Customers.delete_customer_by_id(1)

    # results = p.create_list_of_all_people()
    # print('<<<< list of all people >>>>')
    # for customer in results:
    #     print('Customer ID:', customer.person_id, customer)

if __name__ == '__main__':
    test()


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

graphene = sisl.geom.graphene(orthogonal=True)

elec = graphene.tile(25, axis=0)
H = sisl.Hamiltonian(elec)
H.construct(([0.1, 1.43], [0., -2.7]))
H.write('ELEC.nc')

device = elec.tile(15, axis=1)
device = device.remove(
    device.close(
        device.center(what='cell'), R=10.)
)

# Each carbon atom in graphene has 3 nn, whichever atom has lt 3 is a dangling bond
dangling = [ia for ia in device.close(device.center(what='cell'), R=14.)
            if len(device.close(ia, R=1.43)) < 3]
# plt.gca().set_aspect('equal', adjustable='box')
# sisl.plot(device, s=1); plt.show()
device = device.remove(dangling)
# plt.gca().set_aspect('equal', adjustable='box')
# sisl.plot(device, s=1); plt.show()
edge = []
for ia in device.close(device.center(what='cell'), R=14.):
    if len(device.close(ia, R=1.43)) < 4:
        edge.append(ia)
edge = np.array(edge)

# Pretty-print the list of atoms (for use in sdata)
# Note we add 1 to get fortran indices
print(sisl.utils.list2str(edge + 1))

Hdev = sisl.Hamiltonian(device)
Hdev.construct(([0.1, 1.43], [0, -2.7]))
Hdev.geometry.write('device.xyz')
Hdev.write('DEVICE.nc')


from desafio115.lib.interface import * # * importa tudo
from desafio115.lib.arquivo import *
from time import sleep

arq = 'cursoemvideo.txt'
if not arquivoExiste(arq):
    criarArquivo(arq)

while True:
    n = menu(['Ver pessoas cadastradas', 'Cadastrar nova pessoa', 'Sair do sistema'])
    if n == 1:
        lerArquivo(arq)
    elif n == 2:
        cabeçalho('Cadastro de pessoas')
        nome = str(input('Nome:'))
        idade = leiaInt('Idade: ')
        cadastrar(arq, nome, idade)
    elif n == 3:
        cabeçalho('Saindo do sistema... Até logo')
        break
    else:
        print('ERRO! Digite uma opção cadastrada')
    sleep(2)


import sys, os
import argparse

parser = argparse.ArgumentParser(
    description='Train a new network on a data set')

# Compulsory command: python train.py data_directory
parser.add_argument('data_directory', action="store",type = str,help="Set a data directory to train the model on")

# Option 1 : Set directwersory to save checkpoints: python train.py data_dir --save_dir save_directory
parser.add_argument('--save_dir', action="store", type = str, dest = "save_dir", help="Set a directory to save the checkpoint")

# Option 2: Choose architecture: python train.py data_dir --arch "vgg13"
parser.add_argument('--arch', action="store", default = "models.vgg13", type = str, dest="model", help="Choose an architecture for the model like models.vgg16")

# Option 3: Set hyperparameters: python train.py data_dir --learning_rate 0.01 --hidden_units 512 --epochs 20
parser.add_argument('--learning_rate', action="store", default = 0.001, type = int, dest = "learning_rate", help="Choose a learning rate")
parser.add_argument('--hidden_units', action="store", default = 2000, type = int, dest="num_hidden_layers",help="Choose the number of hidden units")
parser.add_argument('--epochs', action="store", default = 1, type = int, dest="epochs_number", help="Choose the number of epochs")

# Option 4: Use GPU for training: python train.py data_dir --gpu
parser.add_argument('--gpu', action="store", default = "cuda", type = str, dest="device", help="Choose the device cuda or cpu")

results = parser.parse_args()
#print(parser.parse_args(['-a', '-bval', '-c', '3']))

print('checkpoint_dir= {!r}'.format(results.save_dir))
print('architecture_model= {!r}'.format(results.model))
print('learning_rate        = {!r}'.format(results.learning_rate))
print('hidden_units      = {!r}'.format(results.num_hidden_layers))
print('epochs = {!r}'.format(results.epochs_number))
print('gpu = {!r}'.format(results.device))

os.system("python3 model.py "+str(results.device)+" "+str(results.model)+" "+str(results.learning_rate)+" "+str(results.num_hidden_layers)+" "+str(results.epochs_number)+" "+str(sys.argv[1]))
# Print : Prints out training loss, validation loss, and validation accuracy as the network trains


import scrapy
from scrapy.spiders.crawl import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
class ArticleSpider(scrapy.Spider):
    name="article"
    allowed_domains = ["en.wikipedia.org"]
    start_urls = ["http://en.wikipedia.org/wiki/Python_%28programming_language%29"]
    rules = [Rule(SgmlLinkExtractor(allow=('(/wiki/)((?!:).)*$'),),
                                   callback="parse_item", follow=True)]
    def parse_item(self, response):
        item = Article()
        title = response.xpath('//h1/text()')[0].extract()
        print("Title is: "+title)
        item['title'] = title
        return item


R1 = open("file1.txt")
lst_1 = []
for c in R1:
  lst_1.append([int(n) for n in c.split()])
list_1 = [x[0] for x in lst_1]

R2 = open("file2.txt")
lst_2 = []
for b in R2:
  lst_2.append([int(y) for y in b.split()])
list_2 = [y[0] for y in lst_2]

result = [n for n in list_1 if n in list_2]
print(list_2)
print(list_1)
# Write your code above ðŸ‘†

print(result)

# or we can use the following to convert the data read to a list

with open("file1.txt") as file1:
    file_1_data = file1.readlines()

with open("file2.txt") as file2:
    file_2_data = file2.readlines()
results = [int(n) for n in file_1_data if n in file_2_data]


#!/usr/bin/python2

import time
import pygame
from random import randrange

import sys, signal

print("Init")
pygame.display.init()

print("Size")
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print(size)

print("Screen")
screen = pygame.display.set_mode((640, 480))
#screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
exit(0)
print("Mouse")
pygame.mouse.set_visible(False)

while True:
  print("Fill")
  screen.fill((randrange(255),randrange(255),randrange(233)))
  print("Update")
  pygame.display.update()
  print("Sleep")
  time.sleep(5)


def solution(couple):
    if len(couple[0]) > len(couple[1]):
        l_name = couple[0]
        s_name = couple[1]
    elif len(couple[0]) == len(couple[1]):
        if couple[0] == couple[1]:
            ans = 'YES'
        else:
            ans = 'NO'

        return ans
    else:
        l_name = couple[1]
        s_name = couple[0]

    s, l = 0, 0
    while s < len(s_name) and l < len(l_name):
        if s_name[s] == l_name[l]:
            s += 1
            l += 1
        else:
            l += 1

    if s == len(s_name):
        ans = 'YES'
    else:
        ans = 'NO'

    return ans

T = int(input())
A = []

for i in range(T):
    A.append(input().split(" "))

for x in A:
    print(solution(x))


# Imports
import os
import pandas as pd
import logging
from bs4 import BeautifulSoup

# Init
logging.basicConfig(level=logging.INFO,
                    filename=snakemake.log[0],
                    format='%(message)s')

logging.getLogger().addHandler(logging.StreamHandler())

# Load run-specific data
scopID = snakemake.params[0]
comID_list = snakemake.params[1].split(',')
userID = snakemake.params[2]

# Functions
def unpackInfo(fname):
    tmp = open(path_tmp + fname, 'r').read().rstrip('\n')
    return(tmp)

# Directory vars
path_share = f'/projects/{userID}/COMUNEQAID/outs/{scopID}'
path_bcls  = f'{path_share}/scRNAseq/01_BCL'
path_fastq = f'{path_share}/scRNAseq/02_FASTQ'

for comID in comID_list:
    uniqueID = f'{scopID}_{comID}'
    path_tmp = f'/projects/{userID}/COMUNEQAID/manage-dir/tmp-data/{uniqueID}'
    path_sample_sheets = f'{path_tmp}/sample-sheets'

    # Run vars
    workflow    = unpackInfo('/tmp_workflow.txt')
    versionRNA    = unpackInfo('/tmp_versionRNA.txt')

    bcl_dict_path = open(f'{path_tmp}/pin-data-10x.pkl', 'rb')
    pinDict_10x = pickle.load(bcl_dict_path)
    bcl_dict_path.close()

    if (workflow == '10x + HTO'):
        bcl_dict_path = open(f'{path_tmp}/pin-data-hto.pkl', 'rb')
        pinDict_hto = pickle.load(bcl_dict_path)
        bcl_dict_path.close()

    ################################################################################
    ################################################################################
    ################################################################################

    print('#'*80)
    print('#####                                                                      #####')
    print('#####                      Demultiplexing FASTQ files                      #####')
    print('#####                                                       ** / *****     #####')
    print('#'*80)
    print('#####\n##')
    print('##\tDemultiplexing libraries:')

    for pin, (indices,seq_name) in pinDict_10x.items():

        print(f'##\t-\t{seq_name}')

        flowID = seq_name.split('_')[3][1:]

        dir_bcl = f'{path_bcls}/{seq_name}'
        sample_sheet = f'{path_sample_sheets}/samplesheet_{pin}.csv'
        dir_out = f'{path_fastq}/{seq_name}'

        if os.path.isfile(f'{dir_out}/interop_path/IndexMetricsOut.bin'):
            print('##\t-\tpipestance exists - skipping')

        else:
            with open(f'{dir_bcl}/RunParameters.xml', 'r') as f:
                tmp_xml = f.read()
                tmp_bea = BeautifulSoup(tmp_xml, "xml")

                tmp_R1 = tmp_bea.find('Read1NumberOfCycles').text
                tmp_R2 = tmp_bea.find('Read2NumberOfCycles').text
                tmp_I1 = tmp_bea.find('IndexRead1NumberOfCycles').text
                tmp_I2 = tmp_bea.find('IndexRead2NumberOfCycles').text

            os.system(f'mkdir -p {dir_out}')
            os.chdir(dir_out)

            if (versionRNA == 'RNA v3.0'):
                os.system(f'bcl2fastq --use-bases-mask=Y{tmp_R1},I{tmp_I1},Y{tmp_R2} \
                --create-fastq-for-index-reads \
                --minimum-trimmed-read-length=8 \
                --mask-short-adapter-reads=8 \
                --ignore-missing-positions \
                --ignore-missing-controls \
                --ignore-missing-filter \
                --ignore-missing-bcls \
                -r {snakemake.threads} -p {snakemake.threads} -w {snakemake.threads} -R {dir_bcl} \
                --output-dir=fastq-path \
                --interop-dir=interop_path \
                --sample-sheet={sample_sheet} \
                --barcode-mismatches=1 \
                --no-lane-splitting 2>&1 | tee logs/bcl2fastq.log -a')

            if (versionRNA == 'RNA v3.1'):
                os.system(f'bcl2fastq --use-bases-mask=Y{tmp_R1},I{tmp_I1},I{tmp_I2},Y{tmp_R2} \
                --create-fastq-for-index-reads \
                --minimum-trimmed-read-length=10 \
                --mask-short-adapter-reads=10 \
                --ignore-missing-positions \
                --ignore-missing-controls \
                --ignore-missing-filter \
                --ignore-missing-bcls \
                -r {snakemake.threads} -p {snakemake.threads} -w {snakemake.threads} -R {dir_bcl} \
                --output-dir=fastq-path \
                --interop-dir=interop_path \
                --sample-sheet={sample_sheet} \
                --barcode-mismatches=1 \
                --no-lane-splitting 2>&1 | tee logs/bcl2fastq.log -a')

    os.chdir(f'/projects/{userID}/COMUNEQAID/manage-dir')

    print('##\n###')
    print('#'*80)

os.system(f'touch {snakemake.output[0]}')


from Lien_DB import CreationDB
from tkinter import Tk,Button,Frame
import Fenetre_Login
from Fenetre_Affichage_Soin import Fenetre_Affichage_Soin
from tkinter.font import Font

class Fenetre_TypesSoins():

    def __init__(self):
        #initialisation de la fenetre
        self.fenetre = Tk()
        self.fenetre.title("Fenetre d'inscription")
        self.fenetre.iconbitmap("Classes\\IHM\\logo.ico")
        self.fenetre.title("Les Soins Disponibles : ")
        self.fenetre.resizable(width=False, height=False)
        self.cadre = Frame(self.fenetre)
        self.cadre.pack()

        font = Font(weight='bold',size=14)
        color = '#006666'
        i=1
        j=1
        indice = 0
        self.listButton = list()
        # Ce code permet de recupere tous les soins de la base de donnees
        # et l'afficher sous forme des boutons
        for soin in CreationDB.collectionSoin.find({},{'Nom':1}):

            nom = soin['Nom']
            # on a utiliser lambda nom = nom : fonction d'affichage parceque en premier lieu pour passer un argument a la methode
            # et pour changer le parametre nom dans lambda puisque il change a chaque iteration on doit l'affecter
            self.listButton.append(Button(self.cadre, text=nom,width=20,height=8,bg=color,fg='white',font=font,bd=3,command=lambda nom=nom: self.afficher_info_soin(nom)))

            if j == 5 :

               i = i+1
               j=1
               self.listButton[indice].grid(row=i,column=j)

            else:

              self.listButton[indice].grid(row=i,column=j)

            j = j +1
            indice = indice +1

    def  afficher_info_soin(self,nom):
        f = Fenetre_Affichage_Soin(nom)
        f.fenetre.mainloop()

if __name__ == '__main__':

    f = Fenetre_TypesSoins()
    f.fenetre.mainloop()