问:
Publishing Web Application to IIS and Get Error on Page that Holds Database Info
I have recently published my first app to an internal web server using IIS. The web application opens fine and I can view the Home and About pages just fine. However, when I click on the Children page (which contains a list from a database table), I get this error:

I do have the ASPNETCORE_ENVIRONMENT set to Production under the Solution properties, so I'm not quite sure why it is saying "Development Mode". Is there somewhere else that I need to change a setting?

I did try: Swapping to the Development environment displays detailed information about the error that occurred. I still received the same exact error!

Any assistance would be greatly appreciated. Please phrase your answer so that an extreme novice can understand it. In other words, don't just say change X w/o explaining where X is and what to change X to. Thanks!!

EDITED TO ADD: Here is a snip from program.cs

```<code>// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.//
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
</code>```

Body:
I have recently published my first app to an internal web server using IIS. The web application opens fine and I can view the Home and About pages just fine. However, when I click on the Children page (which contains a list from a database table), I get this error:

I do have the ASPNETCORE_ENVIRONMENT set to Production under the Solution properties, so I'm not quite sure why it is saying "Development Mode". Is there somewhere else that I need to change a setting?

I did try: Swapping to the Development environment displays detailed information about the error that occurred. I still received the same exact error!

Any assistance would be greatly appreciated. Please phrase your answer so that an extreme novice can understand it. In other words, don't just say change X w/o explaining where X is and what to change X to. Thanks!!

EDITED TO ADD: Here is a snip from program.cs

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.//
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();


来源: stackexchange

问:
AsyncIO when to create a custom Transport Vs Protocol
I have a simple protocol which acts like tcp but works above udp, lets call it supa.

I want to use asyncIO's create_connection to create a reader/writer.

I'm struggling to understand the different roles of transport and protocol.

I'm also not sure why Protocol is the one that receives but doesn't sends: In DatagramProtocol we have datagram_received but no matching send method.

I was able to create my own dumbed down version of  reader/writer and protocol(which inherited from
DatagramProtocol). So if this is create_connection:

```<code>async def open_connection(host=None, port=None, *,
                          limit=_DEFAULT_LIMIT, **kwds):
    loop = events.get_running_loop()
    reader = StreamReader(limit=limit, loop=loop)
    protocol = StreamReaderProtocol(reader, loop=loop)
    transport, _ = await loop.create_connection(
        lambda: protocol, host, port, **kwds)
    writer = StreamWriter(transport, protocol, reader, loop)
    return reader, writer
</code>```

I created something like:

```<code>async def open_connection(host=None, port=None, *,
                          limit=_DEFAULT_LIMIT, **kwds):
    loop = events.get_running_loop()
    reader = SupaReader(limit=limit, loop=loop)
    protocol = SupaProtocol(reader, loop=loop)
    transport, _ = await loop.create_connection(
        lambda: protocol, host, port, **kwds)
    writer = SupaWriter(transport, protocol, reader, loop)
    return reader, writer
</code>```

But doing that means that I have to implement StreamReader and StreamWriter again.
I can't use the current StreamWriter because StreamWriter writes straight to the transport bypassing the protocol, as we see here:

```<code>class StreamWriter:

    ...
    @property
    def transport(self):
        return self._transport

    def write(self, data):
        self._transport.write(data)
    ...
</code>```

Which means I can't control the data that is sent to the udp socket (meaning I can't run supa's code).
I thought maybe I should create my own transport layer as well but the docs warn against doing that.

To clear up the question: When and how should one create a custom transport layer?

Thank you!

ContentLicense: CC BY-SA 4.0

Body:
I have a simple protocol which acts like tcp but works above udp, lets call it supa.

I want to use asyncIO's create_connection to create a reader/writer.

I'm struggling to understand the different roles of transport and protocol.

I'm also not sure why Protocol is the one that receives but doesn't sends: In DatagramProtocol we have datagram_received but no matching send method.

I was able to create my own dumbed down version of  reader/writer and protocol(which inherited from
DatagramProtocol). So if this is create_connection:

async def open_connection(host=None, port=None, *,
                          limit=_DEFAULT_LIMIT, **kwds):
    loop = events.get_running_loop()
    reader = StreamReader(limit=limit, loop=loop)
    protocol = StreamReaderProtocol(reader, loop=loop)
    transport, _ = await loop.create_connection(
        lambda: protocol, host, port, **kwds)
    writer = StreamWriter(transport, protocol, reader, loop)
    return reader, writer

I created something like:

async def open_connection(host=None, port=None, *,
                          limit=_DEFAULT_LIMIT, **kwds):
    loop = events.get_running_loop()
    reader = SupaReader(limit=limit, loop=loop)
    protocol = SupaProtocol(reader, loop=loop)
    transport, _ = await loop.create_connection(
        lambda: protocol, host, port, **kwds)
    writer = SupaWriter(transport, protocol, reader, loop)
    return reader, writer

But doing that means that I have to implement StreamReader and StreamWriter again.
I can't use the current StreamWriter because StreamWriter writes straight to the transport bypassing the protocol, as we see here:

class StreamWriter:

    ...
    @property
    def transport(self):
        return self._transport

    def write(self, data):
        self._transport.write(data)
    ...

Which means I can't control the data that is sent to the udp socket (meaning I can't run supa's code).
I thought maybe I should create my own transport layer as well but the docs warn against doing that.

To clear up the question: When and how should one create a custom transport layer?

Thank you!


问:
Creating the class graph in python to then implement a quadrtee on graphs
Hello i have a project in class witch consists in representing a city as an undirected graph a street is symbolized as an edge between two vertexes .A street will be lightened if one of the Vertexes on an edge is illuminated.The idea is to sybolize the tree as its quadtree and then find the optimal illumination patern like that .I have implemented the class graph and i'm trying to create a function that will take an adjacency matrix as an input and then create the object graph and i dont know why my function isnt working
{

```<code>class Sommet:  #on definis la classe sommet on lui donne un nom et un tableau qui contiendra ses voisins
    def __init__(self, sommet):
        self.name = sommet
        self.voisins = []

    def aj_voisin(self, voisin): #on définis la méthode qui va rajouter les voisins d'un sommet elle prend le sommet considéré en paramètre et un voisin rencontré
        if isinstance(voisin, Sommet): #is instance teste si les voisin rencontré est un sommet
            if voisin.name not in self.voisins: #si le voisin n'est pas dans la liste de voisins
                self.voisins.append(voisin.name) #on rajoute le nom du  voisin à la liste des noms du voisin d'un sommet.
                voisin.voisins.append(self.name) #on rajoute le sommet a la liste de voisins du voisin
                self.voisins = sorted(self.voisins) #trie la liste de voisins du sommet considéré
                voisin.voisins = sorted(voisin.voisins) #trie la liste du voisin considéré
        else:
            return False #retourne false si il n'y a pas de voisins

    def aj_voisins(self, voisins):#on rajoute plusieurs voisins à un sommet
        for voisin in voisins:
            if isinstance(voisin, Sommet):
                if voisin.name not in self.voisins:
                    self.voisins.append(voisin.name)
                    voisin.voisins.append(self.name)
                    self.voisins = sorted(self.voisins)
                    voisin.voisins = sorted(voisin.voisins)
            else:
                return False

    def __voirv__(self): #Renvoie la liste des voisins d'un sommet
        return str(self.voisins)

########################################################################################################
class Graph: #on définis une classe graph on lui attribue un dictionnaire qui contiendra ses sommets
    def __init__(self):
        self.sommets = {}

    def add_sommet(self, sommet): #rajoute un somet à l'objet graph
        if isinstance(sommet, Sommet):
            self.sommets[sommet.name] = sommet.voisins

    def add_sommets(self, sommets): #rajoute plusieurs sommets au graphe
        for sommet in sommets:
            if isinstance(sommet, Sommet):
                self.sommets[sommet.name] = sommet.voisins

    def add_arrete(self, sommet_from , sommet_to): #rajoute une arrete entre deux sommets
        if isinstance(sommet_from, Sommet) and isinstance(sommet_to, Sommet):
            sommet_from.aj_voisin(sommet_to)
            if isinstance(sommet_from, Sommet) and isinstance(sommet_to, Sommet):
                self.sommets[sommet_from.name] = sommet_from.voisins
                self.sommets[sommet_to.name] = sommet_to.voisins

    def add_arretes(self, arretes):#rajoute plusieurs arretes au graphe
        for arrete in arretes:
            self.add_arrete(arrete[0],arrete[1])

    def MatriceAdjacence(self): #matrice d'adjacence
        if len(self.sommets) >= 1:
            self.sommet_names = sorted(g.sommets.keys())
            self.sommet_indices = dict(zip(self.sommet_names, range(len(self.sommet_names))))
            import numpy as np
            self.adjacency_matrix = np.zeros(shape=(len(self.sommets),len(self.sommets)))
            for i in range(len(self.sommet_names)):
                for j in range(i, len(self.sommets)):
                    for el in g.sommets[self.sommet_names[i]]:
                        j = g.sommet_indices[el]
                        self.adjacency_matrix[i,j] = 1
            return self.adjacency_matrix
        else:
            return dict()

    def ListeAdjacence(self): #liste d'adjacence
        if len(self.sommets) >= 1:
                return [str(key) + ":" + str(self.sommets[key]) for key in self.sommets.keys()]
        else:
            return dict()

    def graph(g): #imprime la matrice d'adjacence et le graphe comme une liste de sommets , leur voisins et les arretes correspondantes
        return str(g.ListeAdjacence()) + '\n' + '\n' + str(g.MatriceAdjacence())
#########################################################################################################Methodes qui créent un graphe en fonction d'une matrice d'adjacence

def créergraphe(M): #Créer une liste de sommets a partir d'une matrice d'adjacence (petit problèmme ici)
        g=Graph()
        for i in range (len(M)):
            user_input = input("Quel est le nom du sommet ? : \n")
            globals()[user_input] = Sommet([user_input])
            g.sommets.append(globals()[user_input]
        return g

def grapheDuneMatrice(M): #créer un graphe en fonction d'une matrice d'adjacence
        h=créergraphe(M)
        for i in range(len(M)):
            for j in range(len(M)):
                if (M[i][j]==1):
                    h.add_arrete(h.sommets[i],h.sommets[j])
        return h
#############################################################################################################Dessin d'un graphe

##############################################################################################################"Implémentation d'un quadtree"

</code>```

}
Also i need some help here how can i efficiently draw my graph in order to apply the quadtree on it?i need some optimal way to represent the graph

i tried to do a function that would take an adjacency matrix as a parameter and then create the object graph associated in it .I believe it's not working because i have a syntax issue.And i dont know how to draw graphs optimally.The function trying to create the graph doesnt ask me the names of the Vertexes.The function in question is créergraphe

Body:
Hello i have a project in class witch consists in representing a city as an undirected graph a street is symbolized as an edge between two vertexes .A street will be lightened if one of the Vertexes on an edge is illuminated.The idea is to sybolize the tree as its quadtree and then find the optimal illumination patern like that .I have implemented the class graph and i'm trying to create a function that will take an adjacency matrix as an input and then create the object graph and i dont know why my function isnt working
{

class Sommet:  #on definis la classe sommet on lui donne un nom et un tableau qui contiendra ses voisins
    def __init__(self, sommet):
        self.name = sommet
        self.voisins = []

    def aj_voisin(self, voisin): #on définis la méthode qui va rajouter les voisins d'un sommet elle prend le sommet considéré en paramètre et un voisin rencontré
        if isinstance(voisin, Sommet): #is instance teste si les voisin rencontré est un sommet
            if voisin.name not in self.voisins: #si le voisin n'est pas dans la liste de voisins
                self.voisins.append(voisin.name) #on rajoute le nom du  voisin à la liste des noms du voisin d'un sommet.
                voisin.voisins.append(self.name) #on rajoute le sommet a la liste de voisins du voisin
                self.voisins = sorted(self.voisins) #trie la liste de voisins du sommet considéré
                voisin.voisins = sorted(voisin.voisins) #trie la liste du voisin considéré
        else:
            return False #retourne false si il n'y a pas de voisins

    def aj_voisins(self, voisins):#on rajoute plusieurs voisins à un sommet
        for voisin in voisins:
            if isinstance(voisin, Sommet):
                if voisin.name not in self.voisins:
                    self.voisins.append(voisin.name)
                    voisin.voisins.append(self.name)
                    self.voisins = sorted(self.voisins)
                    voisin.voisins = sorted(voisin.voisins)
            else:
                return False

    def __voirv__(self): #Renvoie la liste des voisins d'un sommet
        return str(self.voisins)

########################################################################################################
class Graph: #on définis une classe graph on lui attribue un dictionnaire qui contiendra ses sommets
    def __init__(self):
        self.sommets = {}

    def add_sommet(self, sommet): #rajoute un somet à l'objet graph
        if isinstance(sommet, Sommet):
            self.sommets[sommet.name] = sommet.voisins

    def add_sommets(self, sommets): #rajoute plusieurs sommets au graphe
        for sommet in sommets:
            if isinstance(sommet, Sommet):
                self.sommets[sommet.name] = sommet.voisins

    def add_arrete(self, sommet_from , sommet_to): #rajoute une arrete entre deux sommets
        if isinstance(sommet_from, Sommet) and isinstance(sommet_to, Sommet):
            sommet_from.aj_voisin(sommet_to)
            if isinstance(sommet_from, Sommet) and isinstance(sommet_to, Sommet):
                self.sommets[sommet_from.name] = sommet_from.voisins
                self.sommets[sommet_to.name] = sommet_to.voisins

    def add_arretes(self, arretes):#rajoute plusieurs arretes au graphe
        for arrete in arretes:
            self.add_arrete(arrete[0],arrete[1])

    def MatriceAdjacence(self): #matrice d'adjacence
        if len(self.sommets) >= 1:
            self.sommet_names = sorted(g.sommets.keys())
            self.sommet_indices = dict(zip(self.sommet_names, range(len(self.sommet_names))))
            import numpy as np
            self.adjacency_matrix = np.zeros(shape=(len(self.sommets),len(self.sommets)))
            for i in range(len(self.sommet_names)):
                for j in range(i, len(self.sommets)):
                    for el in g.sommets[self.sommet_names[i]]:
                        j = g.sommet_indices[el]
                        self.adjacency_matrix[i,j] = 1
            return self.adjacency_matrix
        else:
            return dict()

    def ListeAdjacence(self): #liste d'adjacence
        if len(self.sommets) >= 1:
                return [str(key) + ":" + str(self.sommets[key]) for key in self.sommets.keys()]
        else:
            return dict()

    def graph(g): #imprime la matrice d'adjacence et le graphe comme une liste de sommets , leur voisins et les arretes correspondantes
        return str(g.ListeAdjacence()) + '\n' + '\n' + str(g.MatriceAdjacence())
#########################################################################################################Methodes qui créent un graphe en fonction d'une matrice d'adjacence

def créergraphe(M): #Créer une liste de sommets a partir d'une matrice d'adjacence (petit problèmme ici)
        g=Graph()
        for i in range (len(M)):
            user_input = input("Quel est le nom du sommet ? : \n")
            globals()[user_input] = Sommet([user_input])
            g.sommets.append(globals()[user_input]
        return g

def grapheDuneMatrice(M): #créer un graphe en fonction d'une matrice d'adjacence
        h=créergraphe(M)
        for i in range(len(M)):
            for j in range(len(M)):
                if (M[i][j]==1):
                    h.add_arrete(h.sommets[i],h.sommets[j])
        return h
#############################################################################################################Dessin d'un graphe

##############################################################################################################"Implémentation d'un quadtree"

}
Also i need some help here how can i efficiently draw my graph in order to apply the quadtree on it?i need some optimal way to represent the graph

i tried to do a function that would take an adjacency matrix as a parameter and then create the object graph associated in it .I believe it's not working because i have a syntax issue.And i dont know how to draw graphs optimally.The function trying to create the graph doesnt ask me the names of the Vertexes.The function in question is créergraphe


Title: OpenRouteService:Unable to compute a distance/duration matrix

Body:
Trying to calculate distance matrix with ors service, but it occurs some mistakes in unexpectable ways. Using standalone openrouteservice api in docker, already created theme on  ors forum: https://ask.openrouteservice.org/t/matrix-api-server-different-response/4383, but there is no answers. Problem is in Request to v2/matrix/foot-walking. Body:

{
    "locations": [
        ["49.20929961078032", "55.25079065207174"],
        ["49.00354426424202", "55.52838054232154"],
        ["48.83267189756864", "54.94429477743261"],
        ["48.83294182389862", "54.94821584094245"],
        ["48.83294449200721", "54.94845893042766"],
        ["48.83294671888989", "54.94855894252475"],
        ["48.83295288031679", "54.9488356599419"],
        ["48.83297220394691", "54.94970350842952"]
    ],
    "metrics": ["distance"],
    "sources": [0],
    "units": "m"
}

Response:

{
    "distances": [
        [
            0.0,
            47366.25,
            54492.89,
            54229.96,
            54202.76,
            54191.64,
            54160.86,
            54064.36
        ]
    ],
    "destinations": [
        {
            "location": [
                49.2093,
                55.250791
            ]
        },
        {
            "location": [
                49.003544,
                55.52838
            ],
            "snapped_distance": 0.01
        },
        {
            "location": [
                48.832659,
                54.944297
            ],
            "snapped_distance": 0.87
        },
        {
            "location": [
                48.832942,
                54.948216
            ],
            "snapped_distance": 0.01
        },
        {
            "location": [
                48.832944,
                54.948459
            ],
            "snapped_distance": 0.01
        },
        {
            "location": [
                48.832947,
                54.948559
            ],
            "snapped_distance": 0.01
        },
        {
            "location": [
                48.832953,
                54.948836
            ],
            "snapped_distance": 0.01
        },
        {
            "location": [
                48.832972,
                54.949704
            ],
            "snapped_distance": 0.01
        }
    ],
    "sources": [
        {
            "location": [
                49.2093,
                55.250791
            ]
        }
    ],
    "metadata": {
        "attribution": "openrouteservice.org, OpenStreetMap contributors",
        "service": "matrix",
        "timestamp": 1670420158472,
        "query": {
            "locations": [
                [
                    49.20929961078032,
                    55.25079065207174
                ],
                [
                    49.00354426424202,
                    55.52838054232154
                ],
                [
                    48.83267189756864,
                    54.94429477743261
                ],
                [
                    48.83294182389862,
                    54.94821584094245
                ],
                [
                    48.83294449200721,
                    54.94845893042766
                ],
                [
                    48.83294671888989,
                    54.94855894252475
                ],
                [
                    48.83295288031679,
                    54.9488356599419
                ],
                [
                    48.83297220394691,
                    54.94970350842952
                ]
            ],
            "profile": "foot-walking",
            "responseType": "json",
            "metricsStrings": [
                "DISTANCE"
            ],
            "sources": [
                "0"
            ],
            "metrics": [
                "distance"
            ],
            "units": "m"
        },
        "engine": {
            "version": "6.7.0",
            "build_date": "2022-12-02T21:59:11Z",
            "graph_date": null
        }
    }
}

remove one coord from body Request:

{
    "locations": [
        ["49.00354426424202", "55.52838054232154"],
        ["48.83267189756864", "54.94429477743261"],
        ["48.83294182389862", "54.94821584094245"],
        ["48.83294449200721", "54.94845893042766"],
        ["48.83294671888989", "54.94855894252475"],
        ["48.83295288031679", "54.9488356599419"],
        ["48.83297220394691", "54.94970350842952"]
    ],
    "metrics": ["distance"],
    "sources": [0],
    "units": "m"
}

Response:

{
    "error": {
        "code": 6099,
        "message": "Unable to compute a distance/duration matrix."
    },
    "info": {
        "engine": {
            "version": "6.7.0",
            "build_date": "2022-12-02T21:59:11Z"
        },
        "timestamp": 1670420357029
    }
}


问:
how to finetune gpt-2 in hugging-face's pytorch transformer library
I want to finetune gpt-2 by this link https://www.modeldifferently.com/en/2021/12/generaci%C3%B3n-de-fake-news-con-gpt-2/
it works correctly in google colab. but when i run it on my lab gpu, i encounter the following error:

x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight)
RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)
i am so confused. please help.
thanks.


问:
how can i compare 2 variables without using ==
I need to write a c++ Projekt and the conditions are, i can only use the < to compare 2 variables. I cant use <=, >=, >, ==, !=. But now i need to compare 2 variables. How can i compare them, if they are the same without using ==.

Example:

```<code> if {
A == B; // can´t use this but need to scan if they are the same
}
</code>```

i have 0 idea how to do that so i hope any of you can help me.
I tried to do it like

A < B && B < A but i think i cant get to the solution.

Body:
I need to write a c++ Projekt and the conditions are, i can only use the < to compare 2 variables. I cant use <=, >=, >, ==, !=. But now i need to compare 2 variables. How can i compare them, if they are the same without using ==.

Example:

 if {
A == B; // can´t use this but need to scan if they are the same
}

i have 0 idea how to do that so i hope any of you can help me.
I tried to do it like

A < B && B < A but i think i cant get to the solution.


问:
RreactJS-How to refactor product option code logic?
Hi? I am a beginner in front-end development.
I Made product options with react.But I don't like my code.So I'm fixing it, but I'm still making logic with the same flow of thought.

I get the feeling that my code is declaring unnecessary state and executing a function with repetitive behavior.

Please let me know what's wrong with my code and ask a question on stackoverflow in hopes of finding a solution.

Optional features have the following requirements.

If the preceding option is not selected, the next option cannot be selected.

The value of the next option changes according to the value selected in the preceding option.Depending on the color, the item on the wire is different.

If the value of the previous option is changed, all options after that must be initialized.

// Base data structure to create option selectors
// I am creating an option selector with the array data below.
[
    {
      name: 'ivory',
      option: [
        {
          name: 'black 2M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
                {
                  name: 'TEST Whiz Color LED 8W',
                  productCode: 'P1236',
                  price: 162800,
                  monthPrice: 12900,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
        {
          name: 'white 3M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
                {
                  name: 'TEST Whiz Color LED 8W',
                  productCode: 'P1236',
                  price: 162800,
                  monthPrice: 12900,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
      ],
    },
    {
      name: 'sand white',
      option: [
        {
          name: 'black 2M',
          option: [
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
        {
          name: 'white 3M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
                {
                  name: 'TEST Whiz Color LED 8W',
                  productCode: 'P1236',
                  price: 162800,
                  monthPrice: 12900,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
      ],
    },
    {
      name: 'warm gray',
      option: [
        {
          name: 'black 2M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
              ],
            },
          ],
        },
        {
          name: 'white 3M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST Whiz Color LED 8W',
                  productCode: 'P1236',
                  price: 162800,
                  monthPrice: 12900,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
      ],
    },
  ]
```
<pre class="lang-js prettyprint-override"><code>  export default function OptionSelector({
    optionGroups = [],
    products = [],
    sellPrice,
  }: IOptionSelector) {
    // original option data
    const [originOptionItemData, setOriginOptionItemData] = useState<IOptionItems[] | undefined>([])
    // array state to create the next option selector
    const [targetOptionItemData, setTargetOptionItemData] = useState<IOptionItems[] | undefined>([])
    // A two-dimensional array containing the currently active options
    const [optionItemNames, setOptionItemNames] = useState<IOptionNameLabel[][]>([[]])
    // Additional amount per option
    const [addPrices, setAddPrices] = useState<number[]>([])
    // array of selected options
    const [selectedOptionsNames, setSelectedOptionsNames] = useRecoilState<ISelectedOptionInfo[]>(
      currentSelectedOptionNamesAtom
    )

    /**
     * After selecting all options, convert the data to display
     * If you select all options, later Color: Ivory/ Wire: Black 2M/ Lamp: Bracket type (basic) Displayed like this
     * @param {*} optionGroupIndex : option group select index
     * @param {*} selectedOptionName : Selected Option Name
     * @param {*} index :
     * @returns
     */
    const makeSelectedOptionInfoObj = (
      optionGroupIndex: number,
      selectedOptionName: string,
      index: string
    ) => {
      return {
        optionGroupName: optionGroups[optionGroupIndex].name,
        optionName: selectedOptionName,
        index,
      }
    }

    /**
     * Returns an array of options if there is next option data, otherwise returns an object with the final amount and product code
     * @param {*} targetDatas : data with next option data
     * @param {*} prevSelectOptionName : Previously selected option name
     * @returns
     */
    const findNextOption = (
      targetDatas: IOptionItems[] | undefined,
      prevSelectOptionName: string
    ): IOptionItems | ISelectedProduct => {
      const nextOptions = targetDatas?.find((targetData) => targetData.name === prevSelectOptionName)
      if (nextOptions?.option) {
        return nextOptions as IOptionItems
      } else {
        return nextOptions as ISelectedProduct
      }
    }

    /**
     * Logic to create options
     * @param {*} selectedOptionIndex : index of the selected option
     * @param {*} clickedOptionGroupIndex :index of option select boxes
     */
    const setOptionData = (
      selectedOptionIndex: string,
      clickedOptionGroupIndex: number
    ) => {
      const selectedOptionName =
        optionItemNames[clickedOptionGroupIndex][parseInt(selectedOptionIndex)].name
      const additionalPrice =
        optionItemNames[clickedOptionGroupIndex][parseInt(selectedOptionIndex)].addPrice
      const numberAdditionalPrice = isNaN(parseInt(additionalPrice)) ? 0 : parseInt(additionalPrice)

      const newSelectedOptionObj = makeSelectedOptionInfoObj(
        clickedOptionGroupIndex,
        selectedOptionName,
        selectedOptionIndex
      )
      const spliceSeletedOptionNames = [...selectedOptionsNames]
      spliceSeletedOptionNames.splice(clickedOptionGroupIndex)
      spliceSeletedOptionNames.push(newSelectedOptionObj)

      const spliceOptionNames = optionItemNames
      spliceOptionNames?.splice(clickedOptionGroupIndex + 1)

      const spliceAddPrices = [...addPrices]
      spliceAddPrices.splice(clickedOptionGroupIndex)
      spliceAddPrices.push(numberAdditionalPrice)

      let _nextOptionItemDatas = originOptionItemData
      for (let i = 0; i < spliceSeletedOptionNames.length; i++) {
        const hasNextOption = findNextOption(
          _nextOptionItemDatas,
          spliceSeletedOptionNames[i].optionName
        )
        if ('option' in hasNextOption) {
          _nextOptionItemDatas = hasNextOption.option
        } else {
          _nextOptionItemDatas = undefined
        }
      }

      setSelectedOptionsNames([...spliceSeletedOptionNames])
      if (spliceOptionNames) {
        if (_nextOptionItemDatas && sellPrice) {
          const optionNames = pickOptionName(_nextOptionItemDatas, sellPrice, spliceAddPrices)
          if (optionNames) setOptionItemNames([...spliceOptionNames, optionNames])
          setTargetOptionItemData(_nextOptionItemDatas)
          setAddPrices(spliceAddPrices)
        } else {
          const nextOption = findNextOption(
            targetOptionItemData,
            selectedOptionName
          ) as ISelectedProduct
          setSelectedProduct(nextOption)
        }
      }
      resetItemCount()
    }

    // selectBox onChange event
    const changeOption = (
      optionGroupIndex: number,
      e: React.ChangeEvent<HTMLSelectElement>
    ): void => {
      const {
        target: { value: selectedOptionIndex },
      } = e
      setOptionData(selectedOptionIndex, optionGroupIndex)
    }

    useEffect(() => {
      if (optionGroups.length > 0 && sellPrice) {
        const originOptions = buildOptions(optionGroups, products)
        if (originOptions) {
          const optionNames = pickOptionName(originOptions, sellPrice, addPrices)

          setOptionItemNames([optionNames || []])
          setOriginOptionItemData(originOptions)
          setTargetOptionItemData(originOptions)
        }
      }

      return () => {
        resetSelectedOptionNames()
      }
    }, [])

    return (
      <Style.OptionSelectorSection>
        <Style.OptionWrap>
          {optionGroups?.map((option, index) => {
            const isValued = selectedOptionsNames[index]?.index
            return (
              <Style.OptionSelectBox
                key={option.id}
                onChange={(e) => changeOption(index, e)}
                value={isValued ? isValued : ''}
              >
                <OptionItem
                  name={option.name}
                  optionItems={optionItemNames && optionItemNames[index]}
                />
              </Style.OptionSelectBox>
            )
          })}
        </Style.OptionWrap>
      </Style.OptionSelectorSection>
    )
  }

</code>```

This is the completed option initial ui.

Since the first option is not selected, the second option has no items to select.

Body:
Hi? I am a beginner in front-end development.
I Made product options with react.But I don't like my code.So I'm fixing it, but I'm still making logic with the same flow of thought.

I get the feeling that my code is declaring unnecessary state and executing a function with repetitive behavior.

Please let me know what's wrong with my code and ask a question on stackoverflow in hopes of finding a solution.

Optional features have the following requirements.

If the preceding option is not selected, the next option cannot be selected.

The value of the next option changes according to the value selected in the preceding option.Depending on the color, the item on the wire is different.

If the value of the previous option is changed, all options after that must be initialized.

// Base data structure to create option selectors
// I am creating an option selector with the array data below.
[
    {
      name: 'ivory',
      option: [
        {
          name: 'black 2M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
                {
                  name: 'TEST Whiz Color LED 8W',
                  productCode: 'P1236',
                  price: 162800,
                  monthPrice: 12900,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
        {
          name: 'white 3M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
                {
                  name: 'TEST Whiz Color LED 8W',
                  productCode: 'P1236',
                  price: 162800,
                  monthPrice: 12900,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
      ],
    },
    {
      name: 'sand white',
      option: [
        {
          name: 'black 2M',
          option: [
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
        {
          name: 'white 3M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
                {
                  name: 'TEST Whiz Color LED 8W',
                  productCode: 'P1236',
                  price: 162800,
                  monthPrice: 12900,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
      ],
    },
    {
      name: 'warm gray',
      option: [
        {
          name: 'black 2M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (white light)',
                  productCode: 'P1234',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: true,
                },
              ],
            },
          ],
        },
        {
          name: 'white 3M',
          option: [
            {
              name: 'Bracket type (basic)',
              option: [
                {
                  name: 'TEST Whiz Color LED 8W',
                  productCode: 'P1236',
                  price: 162800,
                  monthPrice: 12900,
                },
              ],
            },
            {
              name: 'Rail plug type (white)',
              option: [
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
            {
              name: 'Rail plug type (black)',
              option: [
                {
                  name: 'TEST LED 8W (yellow light)',
                  productCode: 'P1235',
                  price: 143000,
                  monthPrice: 11000,
                  isSoldOut: false,
                },
              ],
            },
          ],
        },
      ],
    },
  ]

  export default function OptionSelector({
    optionGroups = [],
    products = [],
    sellPrice,
  }: IOptionSelector) {
    // original option data
    const [originOptionItemData, setOriginOptionItemData] = useState<IOptionItems[] | undefined>([])
    // array state to create the next option selector
    const [targetOptionItemData, setTargetOptionItemData] = useState<IOptionItems[] | undefined>([])
    // A two-dimensional array containing the currently active options
    const [optionItemNames, setOptionItemNames] = useState<IOptionNameLabel[][]>([[]])
    // Additional amount per option
    const [addPrices, setAddPrices] = useState<number[]>([])
    // array of selected options
    const [selectedOptionsNames, setSelectedOptionsNames] = useRecoilState<ISelectedOptionInfo[]>(
      currentSelectedOptionNamesAtom
    )

    /**
     * After selecting all options, convert the data to display
     * If you select all options, later Color: Ivory/ Wire: Black 2M/ Lamp: Bracket type (basic) Displayed like this
     * @param {*} optionGroupIndex : option group select index
     * @param {*} selectedOptionName : Selected Option Name
     * @param {*} index :
     * @returns
     */
    const makeSelectedOptionInfoObj = (
      optionGroupIndex: number,
      selectedOptionName: string,
      index: string
    ) => {
      return {
        optionGroupName: optionGroups[optionGroupIndex].name,
        optionName: selectedOptionName,
        index,
      }
    }

    /**
     * Returns an array of options if there is next option data, otherwise returns an object with the final amount and product code
     * @param {*} targetDatas : data with next option data
     * @param {*} prevSelectOptionName : Previously selected option name
     * @returns
     */
    const findNextOption = (
      targetDatas: IOptionItems[] | undefined,
      prevSelectOptionName: string
    ): IOptionItems | ISelectedProduct => {
      const nextOptions = targetDatas?.find((targetData) => targetData.name === prevSelectOptionName)
      if (nextOptions?.option) {
        return nextOptions as IOptionItems
      } else {
        return nextOptions as ISelectedProduct
      }
    }

    /**
     * Logic to create options
     * @param {*} selectedOptionIndex : index of the selected option
     * @param {*} clickedOptionGroupIndex :index of option select boxes
     */
    const setOptionData = (
      selectedOptionIndex: string,
      clickedOptionGroupIndex: number
    ) => {
      const selectedOptionName =
        optionItemNames[clickedOptionGroupIndex][parseInt(selectedOptionIndex)].name
      const additionalPrice =
        optionItemNames[clickedOptionGroupIndex][parseInt(selectedOptionIndex)].addPrice
      const numberAdditionalPrice = isNaN(parseInt(additionalPrice)) ? 0 : parseInt(additionalPrice)

      const newSelectedOptionObj = makeSelectedOptionInfoObj(
        clickedOptionGroupIndex,
        selectedOptionName,
        selectedOptionIndex
      )
      const spliceSeletedOptionNames = [...selectedOptionsNames]
      spliceSeletedOptionNames.splice(clickedOptionGroupIndex)
      spliceSeletedOptionNames.push(newSelectedOptionObj)

      const spliceOptionNames = optionItemNames
      spliceOptionNames?.splice(clickedOptionGroupIndex + 1)

      const spliceAddPrices = [...addPrices]
      spliceAddPrices.splice(clickedOptionGroupIndex)
      spliceAddPrices.push(numberAdditionalPrice)

      let _nextOptionItemDatas = originOptionItemData
      for (let i = 0; i < spliceSeletedOptionNames.length; i++) {
        const hasNextOption = findNextOption(
          _nextOptionItemDatas,
          spliceSeletedOptionNames[i].optionName
        )
        if ('option' in hasNextOption) {
          _nextOptionItemDatas = hasNextOption.option
        } else {
          _nextOptionItemDatas = undefined
        }
      }

      setSelectedOptionsNames([...spliceSeletedOptionNames])
      if (spliceOptionNames) {
        if (_nextOptionItemDatas && sellPrice) {
          const optionNames = pickOptionName(_nextOptionItemDatas, sellPrice, spliceAddPrices)
          if (optionNames) setOptionItemNames([...spliceOptionNames, optionNames])
          setTargetOptionItemData(_nextOptionItemDatas)
          setAddPrices(spliceAddPrices)
        } else {
          const nextOption = findNextOption(
            targetOptionItemData,
            selectedOptionName
          ) as ISelectedProduct
          setSelectedProduct(nextOption)
        }
      }
      resetItemCount()
    }

    // selectBox onChange event
    const changeOption = (
      optionGroupIndex: number,
      e: React.ChangeEvent<HTMLSelectElement>
    ): void => {
      const {
        target: { value: selectedOptionIndex },
      } = e
      setOptionData(selectedOptionIndex, optionGroupIndex)
    }

    useEffect(() => {
      if (optionGroups.length > 0 && sellPrice) {
        const originOptions = buildOptions(optionGroups, products)
        if (originOptions) {
          const optionNames = pickOptionName(originOptions, sellPrice, addPrices)

          setOptionItemNames([optionNames || []])
          setOriginOptionItemData(originOptions)
          setTargetOptionItemData(originOptions)
        }
      }

      return () => {
        resetSelectedOptionNames()
      }
    }, [])

    return (

            )
          })}
        </Style.OptionWrap>
      </Style.OptionSelectorSection>
    )
  }

This is the completed option initial ui.

Since the first option is not selected, the second option has no items to select.


问:
I accidentally deleted .htaccess file on Cpanel and my site is not opening
Can someone help me, what is the content of .htaccess or how can I retrieve the default .htaccess

I've tried searching and making a new htaccess but my site displays

This site can’t be reachedCheck if there is a typo in estudylib.com.
If spelling is correct, try running Windows Network Diagnostics.
DNS_PROBE_FINISHED_NXDOMAIN


问:
Check an array of data by other array of data using includes on react
I have a problem to auto checked the checkbox depending on the permission sync on the role when editing the data. then I found a way to solve this using a checked attribute, which needs to give a boolean value to decide the permissions synched to the role or not, based on data from database.

Lets say I have an array of the permissions list like this:

```<code>props.permissions.name stored this array ['read','create','update','delete']; // this needed to show all the permission as a checkbox list to the screen
</code>```

then i have the array data of permissions which is synched to the role

```<code>data.permissions stored this array ['read','create'] //these permissions need to be checked on the checkbox when the user visits the edit page
</code>```

my progress is

```<code>export default function EditPermission (props){
const {role} = usePage().props
const { data, setData, put, processing, errors, reset } = useForm({
    name: role.name || '',
    permissions: role.permissions.map((permission,i)=>{
        return(
            permission['name']
        )
    }),//array of synched permission on role
    editedPermissions:[] //store the checked permissions
})

const handleChecked = (e) => {
    let value = e.target.name;
    if (e.target.checked) {
        setData("editedPermissions", [...data.editedPermissions, value]);
    } else {
        setData(
            "editedPermissions",
            data.editedPermissions.filter((item) => {
                return item !== value;
            })
        );
    }
};

const submit = (e) => {
    e.preventDefault();
    put(route('role.update',permission.id));
};

return (
    <AuthenticatedLayout auth={props.auth} errors={props.errors}>
    <div className="w-full lg:max-w-6xl mt-6 px-6 py-4 bg-white shadow-md overflow-hidden sm:rounded-lg">

        <form onSubmit={submit}>
            <div>

                <div class="grid grid-cols-5 gap-4">
                    //loop the permissions list array
                    {props.permissions && props.permissions.length > 0 ? props.permissions.map((permissions, i) => {
                        return(

                            <div>
                                <Checkbox
                                checked={props.permissions[i].name.includes(data.permissions['name'])} //im stuck here to check the list array includes the synched array , if include return true
                                name={permissions.name}
                                value={permissions.name}
                                handleChange={handleChecked} />

                                {permissions.name}
                            </div>
                        )

                        }):<p>not yet</p>
                    }
                </div>

                <InputError message={errors.permissions} className="mt-2" />

                <PrimaryButton className="ml-4" processing={processing}>
                    Update
                </PrimaryButton>
            </div>

        </form>
    </div>

    </AuthenticatedLayout>

)
}
</code>```

i hope somebody help me to solve this problem , or give me some hint or best practice to solve this
Thank you in advance

Body:
I have a problem to auto checked the checkbox depending on the permission sync on the role when editing the data. then I found a way to solve this using a checked attribute, which needs to give a boolean value to decide the permissions synched to the role or not, based on data from database.

Lets say I have an array of the permissions list like this:

props.permissions.name stored this array ['read','create','update','delete']; // this needed to show all the permission as a checkbox list to the screen

then i have the array data of permissions which is synched to the role

data.permissions stored this array ['read','create'] //these permissions need to be checked on the checkbox when the user visits the edit page

my progress is

export default function EditPermission (props){
const {role} = usePage().props
const { data, setData, put, processing, errors, reset } = useForm({
    name: role.name || '',
    permissions: role.permissions.map((permission,i)=>{
        return(
            permission['name']
        )
    }),//array of synched permission on role
    editedPermissions:[] //store the checked permissions
})

const handleChecked = (e) => {
    let value = e.target.name;
    if (e.target.checked) {
        setData("editedPermissions", [...data.editedPermissions, value]);
    } else {
        setData(
            "editedPermissions",
            data.editedPermissions.filter((item) => {
                return item !== value;
            })
        );
    }
};

const submit = (e) => {
    e.preventDefault();
    put(route('role.update',permission.id));
};

return (
    <AuthenticatedLayout auth={props.auth} errors={props.errors}>

        <form onSubmit={submit}>

                    //loop the permissions list array
                    {props.permissions && props.permissions.length > 0 ? props.permissions.map((permissions, i) => {
                        return(

                                <Checkbox
                                checked={props.permissions[i].name.includes(data.permissions['name'])} //im stuck here to check the list array includes the synched array , if include return true
                                name={permissions.name}
                                value={permissions.name}
                                handleChange={handleChecked} />

                                {permissions.name}

                        )

                        }):
not yet

                    }

                <InputError message={errors.permissions} className="mt-2" />

                <PrimaryButton className="ml-4" processing={processing}>
                    Update
                </PrimaryButton>

        </form>

    </AuthenticatedLayout>

)
}

i hope somebody help me to solve this problem , or give me some hint or best practice to solve this
Thank you in advance


问:
Alternative to Numpy's @ multiplication in DOK-matrix
I have a sparse DOK-matrix called occurrences and a Numpy matrix occurrences_np, which both count the occurrences of words in documents. Now, I want to get the cooccurrences and want to obtain this by multiplying occurence's transpose with occurrences.

With occurrences_np, I have done this as follows:

np.transpose(occurrences_np) @ occurrences_np

However, when I try:

```<code>occurrences.multiply(occurrences.transpose())
</code>```

I get the following error:

```<code>  File "<ipython-input-160-5bd1761dd328>", line 185, in create_cooccurrences
    cooccurrences = self.occurrences.multiply(self.occurrences.transpose())

  File "C:\Users\20200016\Anaconda3\lib\site-packages\scipy\sparse\base.py", line 336, in multiply
    return self.tocsr().multiply(other)

  File "C:\Users\20200016\Anaconda3\lib\site-packages\scipy\sparse\compressed.py", line 406, in multiply
    raise ValueError("inconsistent shapes")
</code>```

How can I do matrix multiplications with DOK-matrices?

Body:
I have a sparse DOK-matrix called occurrences and a Numpy matrix occurrences_np, which both count the occurrences of words in documents. Now, I want to get the cooccurrences and want to obtain this by multiplying occurence's transpose with occurrences.

With occurrences_np, I have done this as follows:

np.transpose(occurrences_np) @ occurrences_np

However, when I try:

occurrences.multiply(occurrences.transpose())

I get the following error:

  File "<ipython-input-160-5bd1761dd328>", line 185, in create_cooccurrences
    cooccurrences = self.occurrences.multiply(self.occurrences.transpose())

  File "C:\Users\20200016\Anaconda3\lib\site-packages\scipy\sparse\base.py", line 336, in multiply
    return self.tocsr().multiply(other)

  File "C:\Users\20200016\Anaconda3\lib\site-packages\scipy\sparse\compressed.py", line 406, in multiply
    raise ValueError("inconsistent shapes")

How can I do matrix multiplications with DOK-matrices?


问:
How can you get journey time volatility info from Google Maps Platform APIs?
In the google maps user-facing client, you can get ranges on a route's time (e.g. a planned route from London to Edinburgh  shows "typically 6 hr 50 min to 8 hr 50 min, Arrive at about 10:30 PM"). How can you pull that prediction info out of the Google Maps Platform APIs? I'm guessing either the DistanceMatrix or the new Routes APIs would be the ones, but neither look like they expose this, just giving a single value for the predicted journey time.</p>


问:
Amdocs Billing Clarification
Does any one knows how to prepare Amdocs Ensemble. Do you have any material or any study link about this Ensemble.

What is the difference between Amdocs ensemble and Kenen Billing?

Regards,
Moorthy

Title: Amdocs Billing Clarification


问:
Flutter synfucion calendar event can not add sql data
I am trying to do appointment calendar. My function fetch data from SQL database, because of that I must start 'appointments.add' function in my for loop. For loop is working perfect but 'appointments.add' function is not. Where is my fault?
I tried so many way to fix this but it doesn't work.
thanks for help.</p>
```<code>class _TakvimSayfasiState extends State<TakvimSayfasi> {

  final List<CalendarView> _allowedViews = <CalendarView>[
    CalendarView.day,
    CalendarView.week,
    CalendarView.workWeek,
    CalendarView.month,
    CalendarView.schedule,
    CalendarView.timelineDay,
    CalendarView.timelineWeek,
    CalendarView.timelineWorkWeek,
    CalendarView.timelineMonth,
  ];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SfCalendar(
        allowedViews: _allowedViews,
        backgroundColor: Colors.white,
        cellBorderColor: Colors.black,
        view: CalendarView.week,
        firstDayOfWeek: 6,
        dataSource: _getDataSource(setState),
      ),
    );
  }
}

MeetingDataSource _getDataSource(setState) {
  var db =  baglanti();
  List items = [];
  List<Appointment> appointments = <Appointment>[];
  final DateTime today = DateTime.now();
  final DateTime startTime = DateTime(today.year, today.month, today.day, 9, 0, 0);
  final DateTime endTime = startTime.add(const Duration(days: 2));

  db.getConnection().then((conn) async{
    var result = await conn.query(
        "SELECT yn.baslangic_tarihi FROM db.yn_notlar yn limit 3"
         );

    setState(() {
      items = result.toList();

      for(var row in items){

        ------------- THIS PART HAVE A PROBLEM--------------

          Appointment exceptionAppointment = Appointment(
            startTime: startTime,
            endTime: endTime,
            subject: '${row['baslangic_tarihi']}',
            color: Colors.blue,
            isAllDay: true);

          appointments.add(exceptionAppointment);
        }
    });
  });

  return MeetingDataSource(appointments);

}

class MeetingDataSource extends CalendarDataSource {
  MeetingDataSource(List<Appointment> source) {
    appointments = source;
  }
}
</code>```

Body:
I am trying to do appointment calendar. My function fetch data from SQL database, because of that I must start 'appointments.add' function in my for loop. For loop is working perfect but 'appointments.add' function is not. Where is my fault?
I tried so many way to fix this but it doesn't work.
thanks for help.

class _TakvimSayfasiState extends State<TakvimSayfasi> {

  final List<CalendarView> _allowedViews = <CalendarView>[
    CalendarView.day,
    CalendarView.week,
    CalendarView.workWeek,
    CalendarView.month,
    CalendarView.schedule,
    CalendarView.timelineDay,
    CalendarView.timelineWeek,
    CalendarView.timelineWorkWeek,
    CalendarView.timelineMonth,
  ];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SfCalendar(
        allowedViews: _allowedViews,
        backgroundColor: Colors.white,
        cellBorderColor: Colors.black,
        view: CalendarView.week,
        firstDayOfWeek: 6,
        dataSource: _getDataSource(setState),
      ),
    );
  }
}

MeetingDataSource _getDataSource(setState) {
  var db =  baglanti();
  List items = [];
  List<Appointment> appointments = <Appointment>[];
  final DateTime today = DateTime.now();
  final DateTime startTime = DateTime(today.year, today.month, today.day, 9, 0, 0);
  final DateTime endTime = startTime.add(const Duration(days: 2));

  db.getConnection().then((conn) async{
    var result = await conn.query(
        "SELECT yn.baslangic_tarihi FROM db.yn_notlar yn limit 3"
         );

    setState(() {
      items = result.toList();

      for(var row in items){

        ------------- THIS PART HAVE A PROBLEM--------------

          Appointment exceptionAppointment = Appointment(
            startTime: startTime,
            endTime: endTime,
            subject: '${row['baslangic_tarihi']}',
            color: Colors.blue,
            isAllDay: true);

          appointments.add(exceptionAppointment);
        }
    });
  });

  return MeetingDataSource(appointments);

}

class MeetingDataSource extends CalendarDataSource {
  MeetingDataSource(List<Appointment> source) {
    appointments = source;
  }
}


问:
Accessing production angular 10 app through chrome bookmarks loads old version and ignores cache meta tags
When i access my angular app through the chrome bookmarks right after a new production deploy, i get the old version of my app.

I'm expecting the new version since i'm using cache busting and all that.

Additionally i tried:

If i press f5 i get the new version.

If i close the tab and use the bookmark i get the old version again.

If i type the url manually i get the new version.

Only after a while (probably when cache is expired) i get the new version through the chrome bookmarks

It seems chrome bookmarks are completely ignoring cache busting.
I even added the following meta tag to prevent caching of the index.html but nothing changed

```<code><meta http-equiv="cache-control" content="no-cache, no-store" />
</code>```

I'm using angular 10 and building my production app using --prod and the output-hashing flag set to "all".

Any help would be appreciated. Thanks!

Body:
When i access my angular app through the chrome bookmarks right after a new production deploy, i get the old version of my app.

I'm expecting the new version since i'm using cache busting and all that.

Additionally i tried:

If i press f5 i get the new version.

If i close the tab and use the bookmark i get the old version again.

If i type the url manually i get the new version.

Only after a while (probably when cache is expired) i get the new version through the chrome bookmarks

It seems chrome bookmarks are completely ignoring cache busting.
I even added the following meta tag to prevent caching of the index.html but nothing changed

<meta http-equiv="cache-control" content="no-cache, no-store" />

I'm using angular 10 and building my production app using --prod and the output-hashing flag set to "all".

Any help would be appreciated. Thanks!


问:
openpyxl to write a single xlsx files over 6306456 rows with multi-sheets
```<code>import openpyxl

def read_excel():
    # Create a new workbook and add a worksheet
    workbook = openpyxl.Workbook()
    worksheet = workbook.create_sheet('Sheet1')

    # Use a while loop to generate and write the rows one at a time
    row = 1
    n = 1
    while row <= 6306456:  # 1048576*6+15000
        # If the row number is greater than 1,048,576, create a new worksheet
        # and reset the row number to 1

        c = row

        # if row > 1048576:
        if c > (1048576 * n):
            worksheet = workbook.create_sheet(f'Sheet{row // 1048576 + 1}')
            c = c - (1048576 * n)
            n = (row // 1048576) + 1

        # Write the row number to the first column of the worksheet
        worksheet.cell(row=c, column=1).value = row
        row += 1

        # Print the progress of the operation
        print(f'{row} of 6306456 rows written')

    # Save the workbook
    workbook.save('row_file.xlsx')

if __name__ == '__main__':
    # Call the read_excel function
    read_excel()
</code>```

Above is the script,but it doesn't work,and it showed row is over 1048576.

I have 1048576*6+15000=6306456 rows of data to write in a single .xlsx file.

Could someome please help to fix the script when using openpyxl to create another new worksheets when a sheet reached 1048576 rows.

Therefore,the result is a .xlsx file with 7 worksheets to store more than 6306456 rows.

Thanks a lot.

Body:
import openpyxl

def read_excel():
    # Create a new workbook and add a worksheet
    workbook = openpyxl.Workbook()
    worksheet = workbook.create_sheet('Sheet1')

    # Use a while loop to generate and write the rows one at a time
    row = 1
    n = 1
    while row <= 6306456:  # 1048576*6+15000
        # If the row number is greater than 1,048,576, create a new worksheet
        # and reset the row number to 1

        c = row

        # if row > 1048576:
        if c > (1048576 * n):
            worksheet = workbook.create_sheet(f'Sheet{row // 1048576 + 1}')
            c = c - (1048576 * n)
            n = (row // 1048576) + 1

        # Write the row number to the first column of the worksheet
        worksheet.cell(row=c, column=1).value = row
        row += 1

        # Print the progress of the operation
        print(f'{row} of 6306456 rows written')

    # Save the workbook
    workbook.save('row_file.xlsx')

if __name__ == '__main__':
    # Call the read_excel function
    read_excel()

Above is the script,but it doesn't work,and it showed row is over 1048576.

I have 1048576*6+15000=6306456 rows of data to write in a single .xlsx file.

Could someome please help to fix the script when using openpyxl to create another new worksheets when a sheet reached 1048576 rows.

Therefore,the result is a .xlsx file with 7 worksheets to store more than 6306456 rows.

Thanks a lot.


问:
Running pyautogui or pynput in selenium's headless mode
I am scraping data of the web and I want to toggle device toolbar to emulate a mobile view.I've tried pressing ctrl+shift+i and ctrl+shift+m using selenium's action chains and also by sending keys and holding keys but it doesn't work.Doing it with the pyautogui or library worked, whenever I had the tab open.Although if I was tabbing out it would not work. I am guessing that it would also not work if I am running selenium on headless mode but there is no way for me to tell, any clarification would be helpful. (I've also heard of pynput, I haven't tried it, but if it works on selenium's headless mode I can give it a shot.)</p>