问:
Load XML containing multiple lists to multiple DataTables
I have an XML that has the below structure:

```<code><?xml version="1.0" encoding="utf-8"?>
<n0:Response xmlns:n0="urn:sap-com:document:sap:rfc:functions">
    <Cars>
        <item>
            <ID>1</ID>
            <TYPE>SUV</TYPE>
            <YEAR>2022</YEAR>
        </item>
        <item>
            <ID>2</ID>
            <TYPE>Convertible</TYPE>
            <YEAR>2021</YEAR>
        </item>
    </Cars>
    <Employees>
        <item>
            <ID>1</ID>
            <NAME>John</NAME>
            <STATUS>1</STATUS>
            <PHONE>000000000</PHONE>
        </item>
        <item>
            <ID>2</ID>
            <NAME>Sam</NAME>
            <STATUS>2</STATUS>
            <PHONE>000000000</PHONE>
        </item>
        <item>
            <ID>3</ID>
            <NAME>Jane</NAME>
            <STATUS>1</STATUS>
            <PHONE>000000000</PHONE>
        </item>
    </Employees>
</n0:Response>
</code>```

(this is just a sample, the final file will have more than 10k items per row)

I need to load that file to two DataTables, each having the correct values.

I do this by creating DataSet, loading XML, and filtering the data table.

My DataSet has 3 tables:

but when I try to access the correct data table I get all the items instead of the correct ones (I get items from the entire XML):

```<code>var rel = ds.Relations.OfType<DataRelation>()
            .FirstOrDefault(x => x.ParentTable.TableName == "Cars")?.ChildTable;
</code>```

this is the result:

I managed to filter the data by adding a Select statement like below:

```<code>var ds = new DataSet();
using Stream stream = new FileStream("Sample.xml", FileMode.Open, FileAccess.Read);
ds.ReadXml(stream);
var table1 = ds.Relations.OfType<DataRelation>()
               .FirstOrDefault(x => x.ParentTable.TableName == "Cars")?
               .ChildTable.Select("Cars_Id = 0").CopyToDataTable();
var table2 = ds.Relations.OfType<DataRelation>()
                .FirstOrDefault(x => x.ParentTable.TableName == "Employees")?
                .ChildTable.Select("Employees_Id = 0").CopyToDataTable();
</code>```

but this isn't generic and I'd like to be able to access the correct DataTable only by name (the node name from XML).

My question is similar to How to get multiple tables in Dataset from XML, but the provided answer didn't solve the issue.

Body:
I have an XML that has the below structure:

<?xml version="1.0" encoding="utf-8"?>
<n0:Response xmlns:n0="urn:sap-com:document:sap:rfc:functions">
    <Cars>
        <item>
            <ID>1</ID>
            <TYPE>SUV</TYPE>
            <YEAR>2022</YEAR>
        </item>
        <item>
            <ID>2</ID>
            <TYPE>Convertible</TYPE>
            <YEAR>2021</YEAR>
        </item>
    </Cars>
    <Employees>
        <item>
            <ID>1</ID>
            <NAME>John</NAME>
            <STATUS>1</STATUS>
            <PHONE>000000000</PHONE>
        </item>
        <item>
            <ID>2</ID>
            <NAME>Sam</NAME>
            <STATUS>2</STATUS>
            <PHONE>000000000</PHONE>
        </item>
        <item>
            <ID>3</ID>
            <NAME>Jane</NAME>
            <STATUS>1</STATUS>
            <PHONE>000000000</PHONE>
        </item>
    </Employees>
</n0:Response>

(this is just a sample, the final file will have more than 10k items per row)

I need to load that file to two DataTables, each having the correct values.

I do this by creating DataSet, loading XML, and filtering the data table.

My DataSet has 3 tables:

but when I try to access the correct data table I get all the items instead of the correct ones (I get items from the entire XML):

var rel = ds.Relations.OfType<DataRelation>()
            .FirstOrDefault(x => x.ParentTable.TableName == "Cars")?.ChildTable;

this is the result:

I managed to filter the data by adding a Select statement like below:

var ds = new DataSet();
using Stream stream = new FileStream("Sample.xml", FileMode.Open, FileAccess.Read);
ds.ReadXml(stream);
var table1 = ds.Relations.OfType<DataRelation>()
               .FirstOrDefault(x => x.ParentTable.TableName == "Cars")?
               .ChildTable.Select("Cars_Id = 0").CopyToDataTable();
var table2 = ds.Relations.OfType<DataRelation>()
                .FirstOrDefault(x => x.ParentTable.TableName == "Employees")?
                .ChildTable.Select("Employees_Id = 0").CopyToDataTable();

but this isn't generic and I'd like to be able to access the correct DataTable only by name (the node name from XML).

My question is similar to How to get multiple tables in Dataset from XML, but the provided answer didn't solve the issue.


来源: stackexchange

问:
I am having an issue successfully fulfilling criteria in a while loop
I am working on a service bot but i am having issues getting back to the start of the loop and getting my new variable to go through the same parameters

```<code>issue = input(str("BOT: Hello i am service bot,and i will be helping you today,What is your issue:\nUSER: "))
issue = issue.lower()
individual = issue.split()
print()

**#This is the point i want to restart at **
while issue_fixed==False and space < len(individual):
    if individual[space]==("sound"):
        issue_fixed=True
        print("Please specify from the issues below")
        c.execute("""SELECT issue FROM sound""")
        problem=c.fetchall()
        conn.commit()
        print(problem)
        sound_issue=True
        response=input("Or press anything else to talk to an adviser: ")

    elif individual[space]==("screen"):
        issue_fixed=True
        print("BOT: Please specify from the issues below")
        c.execute("""SELECT issue FROM screen""")
        problem=c.fetchall()
        conn.commit()
        print(problem)
        response=input("Or press anything else to talk to an adviser: ")
    else:
        space=space+1
while issue_fixed==False and space >= len(individual):
        print("BOT: Sorry i was not able to recognise your issue")
        cs=input("BOT: Would you like to talk to a technical specialist to try and fix your issue, If you would please enter 'Y' if not press anything else:\nUSER:")
        cs=cs.upper()
        if cs=="Y":

                 print("BOT: Connecting you now")
                 issue_fixed=True
        else:
            retype=input("BOT: Please re-type your issue: ")
            retype=retype.lower()
            individ = retype.split()
            print(individ)
            space=0
            individ=individual
            issue_fixed=False
**#I am trying to make individ variable go through the parameters**
</code>```

What i expected to happen was i wanted 'individ' to be compared and ran through so that when i input "sound" it will execute the SQL code

ContentLicense: CC BY-SA 4.0

Body:
I am working on a service bot but i am having issues getting back to the start of the loop and getting my new variable to go through the same parameters

issue = input(str("BOT: Hello i am service bot,and i will be helping you today,What is your issue:\nUSER: "))
issue = issue.lower()
individual = issue.split()
print()

**#This is the point i want to restart at **
while issue_fixed==False and space < len(individual):
    if individual[space]==("sound"):
        issue_fixed=True
        print("Please specify from the issues below")
        c.execute("""SELECT issue FROM sound""")
        problem=c.fetchall()
        conn.commit()
        print(problem)
        sound_issue=True
        response=input("Or press anything else to talk to an adviser: ")

    elif individual[space]==("screen"):
        issue_fixed=True
        print("BOT: Please specify from the issues below")
        c.execute("""SELECT issue FROM screen""")
        problem=c.fetchall()
        conn.commit()
        print(problem)
        response=input("Or press anything else to talk to an adviser: ")
    else:
        space=space+1
while issue_fixed==False and space >= len(individual):
        print("BOT: Sorry i was not able to recognise your issue")
        cs=input("BOT: Would you like to talk to a technical specialist to try and fix your issue, If you would please enter 'Y' if not press anything else:\nUSER:")
        cs=cs.upper()
        if cs=="Y":

                 print("BOT: Connecting you now")
                 issue_fixed=True
        else:
            retype=input("BOT: Please re-type your issue: ")
            retype=retype.lower()
            individ = retype.split()
            print(individ)
            space=0
            individ=individual
            issue_fixed=False
**#I am trying to make individ variable go through the parameters**

What i expected to happen was i wanted 'individ' to be compared and ran through so that when i input "sound" it will execute the SQL code


问:
Python - Parse JSON file using ijson
I am having json file which around 600MB. The structure of the json file is,

```<code>[
    {
      "metadata":{
         "batchSize":100,
         "totalRecords":"1000",
         "batchIndex":1
      },
      "notificationData":[
            {
                "brandId":"A",
                "sourceUniqueId":"12345",
                "contentType":"PDF",
                "transactionId":"cABCD",
                "batchId":"ABC_1",
            }
      ]
    },
    {
      "metadata":{
         "batchSize":100,
         "totalRecords":"1000",
         "batchIndex":2
      },
      "notificationData":[
            {
                "brandId":"B",
                "sourceUniqueId":"789",
                "contentType":"PDF1",
                "transactionId":"XYZ",
                "batchId":"XYZ_1",
            }
      ]
    }
]
</code>```

Now, Output I want the notificationData array of provided batchIndex. I am able to find specific batchIndex But how to get notificationData of that batchIndex. BatchIndex is unique. And after getting notificationData stops the execution. No need to parse complete file.

```<code>f = open('batchIndex.json')
data = ijson.items(f,'item.metadata')
jsons = (o for o in data if o['batchIndex'] == input_batchIndex)
for j in jsons:
    print(j)
</code>```

Title: Python - Parse JSON file using ijson

Body:
I am having json file which around 600MB. The structure of the json file is,

[
    {
      "metadata":{
         "batchSize":100,
         "totalRecords":"1000",
         "batchIndex":1
      },
      "notificationData":[
            {
                "brandId":"A",
                "sourceUniqueId":"12345",
                "contentType":"PDF",
                "transactionId":"cABCD",
                "batchId":"ABC_1",
            }
      ]
    },
    {
      "metadata":{
         "batchSize":100,
         "totalRecords":"1000",
         "batchIndex":2
      },
      "notificationData":[
            {
                "brandId":"B",
                "sourceUniqueId":"789",
                "contentType":"PDF1",
                "transactionId":"XYZ",
                "batchId":"XYZ_1",
            }
      ]
    }
]

Now, Output I want the notificationData array of provided batchIndex. I am able to find specific batchIndex But how to get notificationData of that batchIndex. BatchIndex is unique. And after getting notificationData stops the execution. No need to parse complete file.

f = open('batchIndex.json')
data = ijson.items(f,'item.metadata')
jsons = (o for o in data if o['batchIndex'] == input_batchIndex)
for j in jsons:
    print(j)


问:
When copying code, U+00a0 (nbsp) characters creating problem with VS Code
In my Ubuntu machine recently i have installed vs code. But when i try to paste any code copied from php.net website all the spaces and tabs are replaced by "U+00a0 (nbsp) characters"
It looks like this

Currently i'm doing: using Regular Expression (.*) and search for the unicode character with regex [\xa0] and replace by space. Can anyone suggest me how to solve this problem.


问:
How to configure POM to resolve osgi.wiring.package missing requirements issues
Context: I'm building a PROTEGE plugin and I am having trouble with bundling the jar. When starting protege, this is the log that I am getting:

```<code>[FelixStartLevel] ERROR FrameworkSlf4jLogger    Error starting file:<someName>-1.0.jar
org.osgi.framework.BundleException: Unable to resolve <someName>[28](R 28.0): missing requirement [<someName>[28](R 28.0)] osgi.wiring.package; (osgi.wiring.package=org.neo4j.cypherdsl.core) Unresolved requirements: [[<someName>[28](R 28.0)] osgi.wiring.package; (osgi.wiring.package=org.neo4j.cypherdsl.core)]
    at org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:4111) ~[org.apache.felix.main.jar:na]
    at org.apache.felix.framework.Felix.startBundle(Felix.java:2117) ~[org.apache.felix.main.jar:na]
    at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1371) ~[org.apache.felix.main.jar:na]
    at org.apache.felix.framework.FrameworkStartLevelImpl.run(FrameworkStartLevelImpl.java:308) [org.apache.felix.main.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
</code>```

I have a dependency on the org.neo4j.cypherdsl.core package in my POM, but I am not sure how to correctly include it into the jar such that I won't get the error above. My current POM file (relevant bits):

    <dependencies>
        <dependency>
            <groupId>edu.stanford.protege</groupId>
            <artifactId>protege-editor-owl</artifactId>
            <version>5.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-cypher-dsl</artifactId>
            <version>2022.8.1</version>
        </dependency>
    </dependencies>
    <build>

        <resources>
            <resource>

                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>3.0.1</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-Activator>org.protege.editor.owl.ProtegeOWL</Bundle-Activator>
                        <Bundle-SymbolicName>${project.artifactId};singleton:=true</Bundle-SymbolicName>
                        <Bundle-Vendor>edu.stanford.protege.<someName></Bundle-Vendor>
                        <Bundle-ClassPath>.</Bundle-ClassPath>
                        <Export-Package>
                            edu.stanford.protege.<someName>.*
                        </Export-Package>
                        <Import-Package>
                            org.protege.editor.owl.*;version="5.0.0",
                            org.neo4j.cypherdsl.core,
                            *
                        </Import-Package>
                        <Include-Resource>{maven-resources}</Include-Resource>
                        <executions>
                            <execution>
                                <id>bundle-manifest</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>manifest</goal>
                                </goals>
                            </execution>
                        </executions>
                    </instructions>
                </configuration>
            </plugin>
```

My understanding was that if I include the package name in the <Import-Package> node, then it would work. However, I did not manage to solve the error.

Body:
Context: I'm building a PROTEGE plugin and I am having trouble with bundling the jar. When starting protege, this is the log that I am getting:

[FelixStartLevel] ERROR FrameworkSlf4jLogger    Error starting file:<someName>-1.0.jar
org.osgi.framework.BundleException: Unable to resolve <someName>[28](R 28.0): missing requirement [<someName>[28](R 28.0)] osgi.wiring.package; (osgi.wiring.package=org.neo4j.cypherdsl.core) Unresolved requirements: [[<someName>[28](R 28.0)] osgi.wiring.package; (osgi.wiring.package=org.neo4j.cypherdsl.core)]
    at org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:4111) ~[org.apache.felix.main.jar:na]
    at org.apache.felix.framework.Felix.startBundle(Felix.java:2117) ~[org.apache.felix.main.jar:na]
    at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1371) ~[org.apache.felix.main.jar:na]
    at org.apache.felix.framework.FrameworkStartLevelImpl.run(FrameworkStartLevelImpl.java:308) [org.apache.felix.main.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

I have a dependency on the org.neo4j.cypherdsl.core package in my POM, but I am not sure how to correctly include it into the jar such that I won't get the error above. My current POM file (relevant bits):

    <dependencies>
        <dependency>
            <groupId>edu.stanford.protege</groupId>
            <artifactId>protege-editor-owl</artifactId>
            <version>5.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-cypher-dsl</artifactId>
            <version>2022.8.1</version>
        </dependency>
    </dependencies>
    <build>

        <resources>
            <resource>

                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>3.0.1</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-Activator>org.protege.editor.owl.ProtegeOWL</Bundle-Activator>
                        <Bundle-SymbolicName>${project.artifactId};singleton:=true</Bundle-SymbolicName>
                        <Bundle-Vendor>edu.stanford.protege.<someName></Bundle-Vendor>
                        <Bundle-ClassPath>.</Bundle-ClassPath>
                        <Export-Package>
                            edu.stanford.protege.<someName>.*
                        </Export-Package>
                        <Import-Package>
                            org.protege.editor.owl.*;version="5.0.0",
                            org.neo4j.cypherdsl.core,
                            *
                        </Import-Package>
                        <Include-Resource>{maven-resources}</Include-Resource>
                        <executions>
                            <execution>
                                <id>bundle-manifest</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>manifest</goal>
                                </goals>
                            </execution>
                        </executions>
                    </instructions>
                </configuration>
            </plugin>

My understanding was that if I include the package name in the <Import-Package> node, then it would work. However, I did not manage to solve the error.


问:
How can i change the look of my surface plot? I want it to look like a grid an not like a solid surface
I'm trying to generate a 3d plot from a few datapoints. My goal is it, to compare two different datasets and show how good they match at different points. Right now I'm working on the first surface and my supervisor is unhappy with the visualization.

I use the following code at the moment:

```<code>import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d

# Create the figure and axes objects
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Define the data for the first surface
x1 = [25,35,40,45,50,55,60]
y1 = [1300,4000,5000,5400]
z1 = [8.06,5.81,5.10,4.55,4.1,3.01,2.51,6.46,4.93,4.4,4.03,3.15,2.83,2.4,5.95,4.6,3.87,3.19,2.91,2.7,2.36,5.69,4.29,3.63,3.1,2.85,2.65,2.33]

# Convert the z1 data to 2D arrays
x, y = np.meshgrid(x1, y1)
z1 = np.array(z1).reshape(x.shape)

# Plot the first surface
ax.plot_surface(x, y, z1)

# Show the plot
plt.show()

</code>```

And as a result the following plot is displayed:

enter image description here

My supervisor wants it to look something like this:

enter image description here

Note that this is a completly different diagram with a different dataset and also different axes.

I wonder if it is even possible to generate such a high resolution of a grid with so few datapoints.
Has is something to do with the way the points are connected in the diagram? In my diagram it looks like a linear interpolation. Is it possible to influence the interpolation?

I would be glad if anyone has an idea and is able to help me.

Thanks, and all the best!

Body:
I'm trying to generate a 3d plot from a few datapoints. My goal is it, to compare two different datasets and show how good they match at different points. Right now I'm working on the first surface and my supervisor is unhappy with the visualization.

I use the following code at the moment:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d

# Create the figure and axes objects
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Define the data for the first surface
x1 = [25,35,40,45,50,55,60]
y1 = [1300,4000,5000,5400]
z1 = [8.06,5.81,5.10,4.55,4.1,3.01,2.51,6.46,4.93,4.4,4.03,3.15,2.83,2.4,5.95,4.6,3.87,3.19,2.91,2.7,2.36,5.69,4.29,3.63,3.1,2.85,2.65,2.33]

# Convert the z1 data to 2D arrays
x, y = np.meshgrid(x1, y1)
z1 = np.array(z1).reshape(x.shape)

# Plot the first surface
ax.plot_surface(x, y, z1)

# Show the plot
plt.show()

And as a result the following plot is displayed:

enter image description here

My supervisor wants it to look something like this:

enter image description here

Note that this is a completly different diagram with a different dataset and also different axes.

I wonder if it is even possible to generate such a high resolution of a grid with so few datapoints.
Has is something to do with the way the points are connected in the diagram? In my diagram it looks like a linear interpolation. Is it possible to influence the interpolation?

I would be glad if anyone has an idea and is able to help me.

Thanks, and all the best!


问:
Cytoscape.js HTML links in label not clickable with expand-collapse expansion
I am trying to setup a cytoscape.js graph, which includes links in node labels and also expandable/collapsable parent nodes. After some research I decided to use the cytoscape-node-html-label extension in combination with the expand-collapse extension.

I played around with both extensions separately and they do what I want. However, when trying to combine them, HTML links are not clickable any more. It seems like the expand/collapse extension adds a layer, which does not propagate mouse events to the HTML extension.

```<code>{
        enablePointerEvents: true
    }
</code>```

is already set for the HTML label extension but does not solve the problem. Please find a minimum working example below.

I am happy to get your support on

how to propagate clicks to the HTML label or

how to move the HTML labels "on top" of the expand/collapse layer.

Thank you in advance :-)

code.js

```<code>document.addEventListener('DOMContentLoaded', function() {

    var cy = cytoscape({
        container: document.getElementById('cy'),
        layout: {
            name: 'fcose'
        },

        elements: {
            nodes: [
                { data: { id: 'node1', type: 2 } },
                { data: { id: 'node1.1', parent: 'node1' } },
                { data: { id: 'node2' } },
            ],
            edges: [
                { data: { source: 'node1', target: 'node2' } },
            ]
        },
    });

    cy.nodeHtmlLabel([{
        query: 'node[type=2]',
        valign: "top",
        valignBox: "top",
        tpl: function() {
            return '<p>Test label 1. <a href="https://stackoverflow.com">link</a></p>'
        }
    }], {
        enablePointerEvents: true
    });

    // If the following block is commented, the HTML link above works
    var api = cy.expandCollapse({
        layoutBy: {
            name: "fcose",
            animate: true,
            randomize: false,
            fit: true
        },
        fisheye: true,
        animate: true,
        undoable: false,
    });

});
</code>```

demo.html

```<code><!DOCTYPE>

<html>

<head>
    <title>cytoscape-expand-collapse.js demo</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="style.css">
    <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>

    <!-- for testing with local version of cytoscape.js -->
    <!--<script src="../cytoscape.js/build/cytoscape.js"></script>-->
    <script src="https://unpkg.com/layout-base/layout-base.js"></script>
    <script src="https://unpkg.com/cose-base/cose-base.js"></script>
    <script src="https://unpkg.com/cytoscape-fcose/cytoscape-fcose.js"></script>
    <script src="https://unpkg.com/cytoscape-expand-collapse/cytoscape-expand-collapse.js"></script>
    <script src="src/cytoscape-node-html-label.js"></script>

</head>

<body>
    <h1>cytoscape-expand-collapse demo</h1>
    <script src="code.js"></script>
    <div style="float: right; height: 95%; width: calc(80% - 4px);" id="cy"></div>

</body>

</html>
</code>```
```<code></code>```

Body:
I am trying to setup a cytoscape.js graph, which includes links in node labels and also expandable/collapsable parent nodes. After some research I decided to use the cytoscape-node-html-label extension in combination with the expand-collapse extension.

I played around with both extensions separately and they do what I want. However, when trying to combine them, HTML links are not clickable any more. It seems like the expand/collapse extension adds a layer, which does not propagate mouse events to the HTML extension.

{
        enablePointerEvents: true
    }

is already set for the HTML label extension but does not solve the problem. Please find a minimum working example below.

I am happy to get your support on

how to propagate clicks to the HTML label or

how to move the HTML labels "on top" of the expand/collapse layer.

Thank you in advance :-)

code.js

document.addEventListener('DOMContentLoaded', function() {

    var cy = cytoscape({
        container: document.getElementById('cy'),
        layout: {
            name: 'fcose'
        },

        elements: {
            nodes: [
                { data: { id: 'node1', type: 2 } },
                { data: { id: 'node1.1', parent: 'node1' } },
                { data: { id: 'node2' } },
            ],
            edges: [
                { data: { source: 'node1', target: 'node2' } },
            ]
        },
    });

    cy.nodeHtmlLabel([{
        query: 'node[type=2]',
        valign: "top",
        valignBox: "top",
        tpl: function() {
            return '
Test label 1. link
'
        }
    }], {
        enablePointerEvents: true
    });

    // If the following block is commented, the HTML link above works
    var api = cy.expandCollapse({
        layoutBy: {
            name: "fcose",
            animate: true,
            randomize: false,
            fit: true
        },
        fisheye: true,
        animate: true,
        undoable: false,
    });

});

demo.html

<!DOCTYPE>

    <title>cytoscape-expand-collapse.js demo</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="style.css">

cytoscape-expand-collapse demo


问:
My React website components overflow out of screen in landscape mode
enter image description here
i am using tailwind css and reactjs this code has a problem when i reduce viewport height hero section flowing of the screen overlapping the nav bar please help me.
i am using react router to navigate pages i got viewport height using this i tryed using 100vh but i didn't work nav bar height is 60px

```<code>  const [windowSize, setWindowSize] = useState(getWindowSize());
</code>```

my nav bar

```<code>import { useState, useEffect } from "react";
import { NavLink } from "react-router-dom";
import { motion } from "framer-motion";

function Nav() {
  const variants = {
    open: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.5,
      },
    },
    closed: {
      opacity: 0,
      y: "-100%",
      transition: {
        duration: 0.5,
      },
    },
  };
  const variants2 = {
    open: {
      opacity: 1,
      y: 0,
    },
    closed: {
      opacity: 1,
      y: 0,
    },
  };

  const [isOpen, setIsOpen] = useState(false);

  const [windowSize, setWindowSize] = useState(getWindowSize());

  useEffect(() => {
    function handleWindowResize() {
      setWindowSize(getWindowSize());
    }

    window.addEventListener("resize", handleWindowResize);

    return () => {
      window.removeEventListener("resize", handleWindowResize);
    };
  }, []);

  return (
    <nav
      style={navh}
      className="w-11/12 mx-auto flex flex-row justify-between items-center md:items-center"
    >
      <a href="/">my project</a>

      <motion.div
        style={t}
        animate={isOpen ? "open" : "closed"}
        variants={windowSize.innerWidth <= 768 ? variants : variants2}
        className="absolute md:relative md:top-auto top-0 right-0 md:bg-transparent bg-card md:h-auto h-screen md:w-auto w-1/2"
      >
        <ul className="md:flex mt-12 md:m-0 m-10">
          <li className="p-4 ">
            <NavLink to="/" end>
              Home
            </NavLink>
          </li>
          <li className="p-4">
            <NavLink to="/about">About</NavLink>
          </li>
          <li className="p-4">
            <NavLink to="/event">Event Galary</NavLink>
          </li>
          <li className="p-4">
            <NavLink to="/contact">Special Contact</NavLink>
          </li>
        </ul>
      </motion.div>
      <div
        className="md:hidden z-10"
        onClick={() => setIsOpen((isOpen) => !isOpen)}
      >
        <div style={isOpen ? close : toglech}></div>
        <div style={isOpen ? close2 : toglech}></div>
        <div style={isOpen ? close3 : toglech}></div>
      </div>
    </nav>
  );
}

export default Nav;
const navh = {
  height: "50px",
};
const toglech = {
  background: "#2e2e2e",
  height: "0.2rem",
  margin: "0.4rem 0.6rem",
  transition: ".3s ease-in",
  width: "2rem",
};
const close = {
  background: "#2e2e2e",
  height: "0.2rem",
  margin: "0.4rem 0.6rem",
  transition: ".3s ease-in",
  width: "2rem",
  transform: "rotate(-45deg) translate(-4px,5px)",
};
const close2 = {
  background: "#2e2e2e",
  height: "0.2rem",
  margin: "0.4rem 0.6rem",
  transition: ".3s ease-in",
  width: "2rem",
  opacity: "0",
};
const close3 = {
  background: "#2e2e2e",
  height: "0.2rem",
  margin: "0.6rem",
  transition: ".3s ease-in",
  width: "2rem",
  transform: "rotate(45deg) translate(-4px,-5px)",
};
function getWindowSize() {
  const { innerWidth, innerHeight } = window;
  return { innerWidth, innerHeight };
}

const t = {
  opacity: "0",
};
</code>```

My Hero section

```<code>const [height, setHeight] = useState(window.innerHeight);
  const updateDimensions = () => {
    setHeight(window.innerHeight);
  };
  useEffect(() => {
    window.addEventListener("resize", updateDimensions);
    return () => window.removeEventListener("resize", updateDimensions);
  }, []);

 const heightz = {
    height: `${height - 60}px`,
  };
  return (
    <div
      style={heightz}
      className="w-11/12 mx-auto flex items-center justify-center"
    >
      <section className="text-gray-600 body-font">
        <div className="container flex mx-auto items-center justify-center flex-col">
          <div className="flex items-center  flex-col">
            <motion.div className="flex items-center flex-col">
              <LazyLoadImage
                className="mt-4 object-cover object-center md:w-11/12 rounded-2xl lg:w-10/12 2xl:w-10/12"
                //class="lg:w-2/6 md:w-3/6 w-5/6 mb-10 object-cover object-center rounded"

                width={"auto"}
                height={"auto"}
                src={imgurl}
              ></LazyLoadImage>
            </motion.div>
            <div className="flex justify-center my-4 ">
              {data.map((n, index) => (
                <motion.div
                  whileHover={{ scale: 1.1 }}
                  whileTap={{ scale: 0.9 }}
                  key={"m_s" + n}
                  onClick={() => {
                    setcurrent(index);
                  }}
                >
                  <ImgMat
                    path={"/home/slider/"}
                    src={n}
                    width={100}
                    height={100}
                    pd={"pl-4"}
                  />
                </motion.div>
              ))}
            </div>
            {/* {<ImgLoad src={data["1"]} width={700} height={400} />} */}
          </div>

          {/* <img
            class="lg:w-2/6 md:w-3/6 w-5/6 mb-10 object-cover object-center rounded"
            alt="hero"
            src="https://dummyimage.com/720x600"
          /> */}
          <div className="text-center lg:w-2/3 w-full">
            <h1 className="title-font text-shadeBlack text-3xl sm:text-4xl md:text-5xl mb-4 font-medium lg:text-4xl">
              my project
            </h1>
            <p className="mb-8 leading-relaxed ">
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quaerat
              dolorum modi tempora doloremque veritatis quia, eveniet soluta sed
              minus. Deserunt, rerum voluptate. Illum rem, laboriosam error
              minus inventore modi, autem enim vitae debitis eligendi voluptas
              voluptatibus quisquam dolorem earum tempor
            </p>
            <div className="flex justify-center">
              <Button text={"Location's"} />
              <motion.button
                whileHover={{ scale: 1.1 }}
                whileTap={{ scale: 0.9 }}
                className="ml-4 inline-flex text-white bg-shadeBlack border-0 py-2 px-6 focus:outline-none hover:bg-hardred rounded text-lg hover:text-shadeBlack"
              >
                Event's
              </motion.button>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
</code>```

enter image description here

i want to prevent this main hero image box flowing off screen

Body:
enter image description here
i am using tailwind css and reactjs this code has a problem when i reduce viewport height hero section flowing of the screen overlapping the nav bar please help me.
i am using react router to navigate pages i got viewport height using this i tryed using 100vh but i didn't work nav bar height is 60px

  const [windowSize, setWindowSize] = useState(getWindowSize());

my nav bar

import { useState, useEffect } from "react";
import { NavLink } from "react-router-dom";
import { motion } from "framer-motion";

function Nav() {
  const variants = {
    open: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.5,
      },
    },
    closed: {
      opacity: 0,
      y: "-100%",
      transition: {
        duration: 0.5,
      },
    },
  };
  const variants2 = {
    open: {
      opacity: 1,
      y: 0,
    },
    closed: {
      opacity: 1,
      y: 0,
    },
  };

  const [isOpen, setIsOpen] = useState(false);

  const [windowSize, setWindowSize] = useState(getWindowSize());

  useEffect(() => {
    function handleWindowResize() {
      setWindowSize(getWindowSize());
    }

    window.addEventListener("resize", handleWindowResize);

    return () => {
      window.removeEventListener("resize", handleWindowResize);
    };
  }, []);

  return (

      my project

      <motion.div
        style={t}
        animate={isOpen ? "open" : "closed"}
        variants={windowSize.innerWidth <= 768 ? variants : variants2}
        className="absolute md:relative md:top-auto top-0 right-0 md:bg-transparent bg-card md:h-auto h-screen md:w-auto w-1/2"
      >

            <NavLink to="/" end>
              Home
            </NavLink>

            <NavLink to="/about">About</NavLink>

            <NavLink to="/event">Event Galary</NavLink>

            <NavLink to="/contact">Special Contact</NavLink>

      </motion.div>

 setIsOpen((isOpen) => !isOpen)}
      >

  );
}

export default Nav;
const navh = {
  height: "50px",
};
const toglech = {
  background: "#2e2e2e",
  height: "0.2rem",
  margin: "0.4rem 0.6rem",
  transition: ".3s ease-in",
  width: "2rem",
};
const close = {
  background: "#2e2e2e",
  height: "0.2rem",
  margin: "0.4rem 0.6rem",
  transition: ".3s ease-in",
  width: "2rem",
  transform: "rotate(-45deg) translate(-4px,5px)",
};
const close2 = {
  background: "#2e2e2e",
  height: "0.2rem",
  margin: "0.4rem 0.6rem",
  transition: ".3s ease-in",
  width: "2rem",
  opacity: "0",
};
const close3 = {
  background: "#2e2e2e",
  height: "0.2rem",
  margin: "0.6rem",
  transition: ".3s ease-in",
  width: "2rem",
  transform: "rotate(45deg) translate(-4px,-5px)",
};
function getWindowSize() {
  const { innerWidth, innerHeight } = window;
  return { innerWidth, innerHeight };
}

const t = {
  opacity: "0",
};

My Hero section

const [height, setHeight] = useState(window.innerHeight);
  const updateDimensions = () => {
    setHeight(window.innerHeight);
  };
  useEffect(() => {
    window.addEventListener("resize", updateDimensions);
    return () => window.removeEventListener("resize", updateDimensions);
  }, []);

 const heightz = {
    height: `${height - 60}px`,
  };
  return (

            <motion.div className="flex items-center flex-col">
              <LazyLoadImage
                className="mt-4 object-cover object-center md:w-11/12 rounded-2xl lg:w-10/12 2xl:w-10/12"
                //class="lg:w-2/6 md:w-3/6 w-5/6 mb-10 object-cover object-center rounded"

                width={"auto"}
                height={"auto"}
                src={imgurl}
              ></LazyLoadImage>
            </motion.div>

              {data.map((n, index) => (
                <motion.div
                  whileHover={{ scale: 1.1 }}
                  whileTap={{ scale: 0.9 }}
                  key={"m_s" + n}
                  onClick={() => {
                    setcurrent(index);
                  }}
                >
                  <ImgMat
                    path={"/home/slider/"}
                    src={n}
                    width={100}
                    height={100}
                    pd={"pl-4"}
                  />
                </motion.div>
              ))}

            {/* {<ImgLoad src={data["1"]} width={700} height={400} />} */}

          {/*  */}

              my project

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quaerat
              dolorum modi tempora doloremque veritatis quia, eveniet soluta sed
              minus. Deserunt, rerum voluptate. Illum rem, laboriosam error
              minus inventore modi, autem enim vitae debitis eligendi voluptas
              voluptatibus quisquam dolorem earum tempor

              <Button text={"Location's"} />
              <motion.button
                whileHover={{ scale: 1.1 }}
                whileTap={{ scale: 0.9 }}
                className="ml-4 inline-flex text-white bg-shadeBlack border-0 py-2 px-6 focus:outline-none hover:bg-hardred rounded text-lg hover:text-shadeBlack"
              >
                Event's
              </motion.button>

  );

enter image description here

i want to prevent this main hero image box flowing off screen


问:
Why mui grid iten is not justify horizontally in a Grid
```<code>  <Container maxWidth="lg">

      <AppBar position="static" color="inherit">
        <Typography variant="h2" align="center">
          Memories
        </Typography>
        <img src={memories} alt="memories" height="60" />
      </AppBar>

      <Grow in>
        <Container>
          <Grid
            container
            justifyContent="space-between"
            alignItems="stretch"
            spacing={3}
          >
            <Grid item xs={12} sm={7}>
              <Posts />
            </Grid>
            <Grid item xs={12} sm={7}>
              <Form />
            </Grid>
          </Grid>
        </Container>
      </Grow>
    </Container>
</code>```

I'm new to mui and following a tutorial.The problem is in tutorial the form
grid item is coming in row and here it is showing me vertically. I don't know what the issue is how can i align it horizontally

Body:
  <Container maxWidth="lg">

      <AppBar position="static" color="inherit">
        <Typography variant="h2" align="center">
          Memories
        </Typography>

      </AppBar>

      <Grow in>
        <Container>
          <Grid
            container
            justifyContent="space-between"
            alignItems="stretch"
            spacing={3}
          >
            <Grid item xs={12} sm={7}>
              <Posts />
            </Grid>
            <Grid item xs={12} sm={7}>
              <Form />
            </Grid>
          </Grid>
        </Container>
      </Grow>
    </Container>

I'm new to mui and following a tutorial.The problem is in tutorial the form
grid item is coming in row and here it is showing me vertically. I don't know what the issue is how can i align it horizontally


问:
How can I make sure route53 route traffic to two targets evenly?
I deployed two A records in host zone in route53.

One A record is an alias to AWS hosted application load balance which is located in Sydney region.

The other record is an A record points to an IP address hosted by load balance from GCP in Melbourne region.

And I am using Weighted routing policy that each has 200 weight. When I send requests from a laptop in Melbourne, all the traffic is routed to GCP load balance. It only route traffics to AWS when I bring down the application in GCP.

My question is how I can make sure route53 route traffic roughly evenly (not exact even) cross the two targets. Why does route53 route all traffic to GCP (Melbourne region)?


问:
Yii2 Typeahead + table
I am new to Yii2 and I am trying to figure out how it works.

Now my scenario is that I have a controller which queries a DB and outputs a $table, that I use for the Typeahead Widget:

```<code>Typehead::widget([
  $data_select_name =  ArrayHelper::getColumn($table, 'name');
  'dataset' => [ [ 'local' => $data_select_name, 'limit' => 10 ] ]
]);
</code>```

Now in the view I have a table which for each $item in $table outputs a row with the details.

How could I bind the Typeahead widget with the table, in order to inject these suggestions as the feed for the table generation? (I think with ajax, but let me know)

Thanks!

Title: Yii2 Typeahead + table

Body:
I am new to Yii2 and I am trying to figure out how it works.

Now my scenario is that I have a controller which queries a DB and outputs a $table, that I use for the Typeahead Widget:

Typehead::widget([
  $data_select_name =  ArrayHelper::getColumn($table, 'name');
  'dataset' => [ [ 'local' => $data_select_name, 'limit' => 10 ] ]
]);

Now in the view I have a table which for each $item in $table outputs a row with the details.

How could I bind the Typeahead widget with the table, in order to inject these suggestions as the feed for the table generation? (I think with ajax, but let me know)

Thanks!


问:
Getting 'Empty' screenshot while running 'Android Emulator' in 'headless' mode
I'm trying to run my Appium code in 'Android Emulator' in 'Headless' (-no-window) mode.
And I'm facing the issue that screenshots stop working properly and return empty images.
Although they work fine when running Emulator with UI (without the '-no-window' option).
I also tried to take a screenshot with 'adb' and that doesn't work either

Repro Rate: 4/5

To reproduce, just run launch Emulator with '-no-window' param:

```<code>emulator -avd <emulator_name> -no-window
</code>```

Then just keep capturing screenshot:

```<code>adb exec-out screencap -p > screen.png
</code>```

You will notice that sometimes it will provide a regular screenshot, but rarely, and usually it will be a blank screenshot.

The same behavior with 'Appium' code:

```<code>self.driver.screenshot_as_png
</code>```

Tried with different functions (with 'Selenium' functions as well), in different 'system-iamges' (Android Emulator API lvl), with different configs and nothing helps yet..

Anyone faced the same problem?
Haven't found a suitable solution for this yet.
Last but not least, I'm on macOS (13.0.1 (22A400))

Body:
I'm trying to run my Appium code in 'Android Emulator' in 'Headless' (-no-window) mode.
And I'm facing the issue that screenshots stop working properly and return empty images.
Although they work fine when running Emulator with UI (without the '-no-window' option).
I also tried to take a screenshot with 'adb' and that doesn't work either

Repro Rate: 4/5

To reproduce, just run launch Emulator with '-no-window' param:

emulator -avd <emulator_name> -no-window

Then just keep capturing screenshot:

adb exec-out screencap -p > screen.png

You will notice that sometimes it will provide a regular screenshot, but rarely, and usually it will be a blank screenshot.

The same behavior with 'Appium' code:

self.driver.screenshot_as_png

Tried with different functions (with 'Selenium' functions as well), in different 'system-iamges' (Android Emulator API lvl), with different configs and nothing helps yet..

Anyone faced the same problem?
Haven't found a suitable solution for this yet.
Last but not least, I'm on macOS (13.0.1 (22A400))


问:
Clear result of custom function in excel addin before or after closing file
I have created a custom function in excel addin which displays the response of any API. I want to clear the values of response after closing the file

Please suggest to me something how can I clear the values after closing the file, or is there any method that indicates file is about to close ?


问:
How to install github CLI inside jenkins pipeline
am trying to install github cli in the jenkins pipeline using this commands from github CLI docs :

```<code>type -p curl >/dev/null || sudo apt install curl -y
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
&& sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
&& sudo apt update \
&& sudo apt install gh -y
</code>```

But it gives me this error :

```<code>dd: can't open '/usr/share/keyrings/githubcli-archive-keyring.gpg': No such file or directory
curl: (23) Failure writing output to destination
</code>```

Body:
am trying to install github cli in the jenkins pipeline using this commands from github CLI docs :

type -p curl >/dev/null || sudo apt install curl -y
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
&& sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
&& sudo apt update \
&& sudo apt install gh -y

But it gives me this error :

dd: can't open '/usr/share/keyrings/githubcli-archive-keyring.gpg': No such file or directory
curl: (23) Failure writing output to destination


问:
Why does the 'mypy' module report an error when I implement a method in the class and assign a reference to a method in a class by a factory method
I encounter a problem when I use the mypy module to check my code. The problem is demonstrated in the code as below:

```<code>from typing import Callable
from abc import ABCMeta, abstractmethod

class A(metaclass = ABCMeta):

    def __init__(self):
        pass

    @abstractmethod
    def foo(self):
        raise NotImplementedError

class B(A):

    def __init__(self, shouldUseG: bool):
        super().__init__()
        self.foo: Callable = self._factory_to_generate_function(shouldUseG) # line 17

    def _factory_to_generate_function(self, shouldUseG: bool) -> Callable:

        read_data_function: Callable = {True:  self.g,
                                        False: self.h}[shouldUseG]
        return read_data_function

    def foo(self): # line 25
        pass

    def g(self):
        print('This is g.')

    def h(self):
        print('This is h.')
</code>```

Class B is a subclass of Class A. For Class B to inherit Class A, the method foo must be implemented in Class B. But the reference of foo depends on the value of the variable shouldUseG in Class B. So I create a method _factory_to_generate_function to determine the reference of the method foo. And I also declare the method foo in class B in line 25.

My question is when I run the mypy module to check this code, it will return the following error for line 17:

```<code>test.py:17: error: Cannot assign to a method  [assignment]
Found 1 error in 1 file (checked 1 source file)
</code>```

And I find that this error won't occur if I do not declare the method foo in line 25. I can't understand why this will cause the error. Could anyone kindly explain it to me? And does that mean that the abstract method can be implemented in a way like in line 17 so I do not have to declare the method again in a scenario like this? Thank you in advance.

Body:
I encounter a problem when I use the mypy module to check my code. The problem is demonstrated in the code as below:

from typing import Callable
from abc import ABCMeta, abstractmethod

class A(metaclass = ABCMeta):

    def __init__(self):
        pass

    @abstractmethod
    def foo(self):
        raise NotImplementedError

class B(A):

    def __init__(self, shouldUseG: bool):
        super().__init__()
        self.foo: Callable = self._factory_to_generate_function(shouldUseG) # line 17

    def _factory_to_generate_function(self, shouldUseG: bool) -> Callable:

        read_data_function: Callable = {True:  self.g,
                                        False: self.h}[shouldUseG]
        return read_data_function

    def foo(self): # line 25
        pass

    def g(self):
        print('This is g.')

    def h(self):
        print('This is h.')

Class B is a subclass of Class A. For Class B to inherit Class A, the method foo must be implemented in Class B. But the reference of foo depends on the value of the variable shouldUseG in Class B. So I create a method _factory_to_generate_function to determine the reference of the method foo. And I also declare the method foo in class B in line 25.

My question is when I run the mypy module to check this code, it will return the following error for line 17:

test.py:17: error: Cannot assign to a method  [assignment]
Found 1 error in 1 file (checked 1 source file)

And I find that this error won't occur if I do not declare the method foo in line 25. I can't understand why this will cause the error. Could anyone kindly explain it to me? And does that mean that the abstract method can be implemented in a way like in line 17 so I do not have to declare the method again in a scenario like this? Thank you in advance.


问:
Error while waiting for device: Illegal char <*> at index 0: *.lock
I am not able to run my android application on emulator. I am getting Error while waiting for device: Illegal char <*> at index 0: *.lock. For this I deleted hardware-qemu.ini.lock folder of avd, but after deleting this when I am running app this folder is coming again and not able to launch app.

Can someone help me to solve this issue?

I tried to remove hardware-qemu.ini.lock folder of avd.

I am expecting to solve this issue.


问:
How to set a default mat-option value on hover when a mat-autocomplete-panel is opened?
In Angular 14, I'm using the mat-autocomplete component from Material.

When an option has been selected, if the user click on the autocomplete input again, the drop-down list of all available options shows up again but the selected option is not on hover. Instead, the focus is back on the first entry of the list.

How can we force a specific mat-option to be on focus when the drop-down appears?

<mat-form-field>
  <input
    matInput
    type="text"
    [formControl]="this.formControl"
    [matAutocomplete]="autoComplete"
    [value]="this.value"
    (blur)="this.resetInput(this.value)"  // Set previous selected value back in input if user click away
    (focus)="this.emptyInput()"  // Clear the input if the user focuses it
  >

  <mat-autocomplete
    #autoComplete="matAutocomplete"
    [displayWith]="this.displayWithFn"
    (optionSelected)="this.doSomething($event)"
  >
    <mat-option
      *ngFor="let oneOption of options$ | async"
      [value]="oneOption"
    >
      {{ oneOption.title }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>
```


问:
How to fix unknown lines being created by svg transformation
I have a loading svg icon consisting of 3 circles that rotates clockwise. It works fine and designs are correct on chrome and firefox but, on safari, circles create a weird line at a certain point (SS below). Not sure what could be causing this issue.

The code for loader svg

```<code><div class="flex flex-row justify-center items-center w-full h-full fixed select-none z-50" style="left: 50%;top: 50%;transform: translateX(-50%) translateY(-50%);background: rgba(255,255,255,0.7);" x-show="isLoading" x-transition:enter="ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100" x-transition:leave="ease-in duration-200" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">

    <svg width="57" height="57" viewBox="0 0 57 57" xmlns="http://www.w3.org/2000/svg" stroke="#fff" class="stroke-current text-primary" style="/* stroke: salmon; */">
        <g fill="none" fill-rule="evenodd" style="fill: color();">
            <g transform="translate(1 1)" stroke-width="2" style="translate: (0,1);transform: translate();transform: translate(112341122121,5);">
                <circle cx="5" cy="50" r="5">
                    <animate attributeName="cy" begin="0s" dur="2.2s" values="50;5;50;50" calcMode="linear" repeatCount="indefinite"></animate>
                    <animate attributeName="cx" begin="0s" dur="2.2s" values="5;27;49;5" calcMode="linear" repeatCount="indefinite"></animate>
                </circle>
                <circle cx="27" cy="5" r="5">
                    <animate attributeName="cy" begin="0s" dur="2.2s" from="5" to="5" values="5;50;50;5" calcMode="linear" repeatCount="indefinite"></animate>
                    <animate attributeName="cx" begin="0s" dur="2.2s" from="27" to="27" values="27;49;5;27" calcMode="linear" repeatCount="indefinite"></animate>
                </circle>
                <circle cx="49" cy="50" r="5">
                    <animate attributeName="cy" begin="0s" dur="2.2s" values="50;50;5;50" calcMode="linear" repeatCount="indefinite"></animate>
                    <animate attributeName="cx" from="49" to="49" begin="0s" dur="2.2s" values="49;5;27;49" calcMode="linear" repeatCount="indefinite"></animate>
                </circle>
            </g>
        </g>
    </svg>
    <div class="ml-10 text-primary text-xl">
        Loading...    </div>
</div>
</code>```

How can I solve it? Cannot figure it out.

Body:
I have a loading svg icon consisting of 3 circles that rotates clockwise. It works fine and designs are correct on chrome and firefox but, on safari, circles create a weird line at a certain point (SS below). Not sure what could be causing this issue.

The code for loader svg

    <svg width="57" height="57" viewBox="0 0 57 57" xmlns="http://www.w3.org/2000/svg" stroke="#fff" class="stroke-current text-primary" style="/* stroke: salmon; */">
        <g fill="none" fill-rule="evenodd" style="fill: color();">
            <g transform="translate(1 1)" stroke-width="2" style="translate: (0,1);transform: translate();transform: translate(112341122121,5);">
                <circle cx="5" cy="50" r="5">
                    <animate attributeName="cy" begin="0s" dur="2.2s" values="50;5;50;50" calcMode="linear" repeatCount="indefinite"></animate>
                    <animate attributeName="cx" begin="0s" dur="2.2s" values="5;27;49;5" calcMode="linear" repeatCount="indefinite"></animate>
                </circle>
                <circle cx="27" cy="5" r="5">
                    <animate attributeName="cy" begin="0s" dur="2.2s" from="5" to="5" values="5;50;50;5" calcMode="linear" repeatCount="indefinite"></animate>
                    <animate attributeName="cx" begin="0s" dur="2.2s" from="27" to="27" values="27;49;5;27" calcMode="linear" repeatCount="indefinite"></animate>
                </circle>
                <circle cx="49" cy="50" r="5">
                    <animate attributeName="cy" begin="0s" dur="2.2s" values="50;50;5;50" calcMode="linear" repeatCount="indefinite"></animate>
                    <animate attributeName="cx" from="49" to="49" begin="0s" dur="2.2s" values="49;5;27;49" calcMode="linear" repeatCount="indefinite"></animate>
                </circle>
            </g>
        </g>
    </svg>

        Loading...

How can I solve it? Cannot figure it out.


问:
How Docker Compose And Rabbitmmq Config together?
I built two microservices and RabbitMQ and containerize them by docker...
when I run docker-compose. "yaml up"
i have this error in microservice container " Mass Transit[0] Connection Failed: rabbitmq://localhost/ RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable "
without containerizing them and run by IIssexpress I have no problem</p>


问:
vercel No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm trying to deploy backend with vercel, but I get "500: internal server error" after deploying like this
img 500 internal server error
and "No 'Access-Control-Allow-Origin' header is present on the requested resource." after i tried the API like this
cors error

i also implemented cors in index.js like this
index.js, but still got cors error

does anyone know how to solve it?


问:
Login Logout with different users whose credentials will come from an Excel file one after another using Selenium
I was trying to build a framework where credentials of various users will come from an excel file.
The user will login to the application and perform some actions and then logout. After that another user will do the same, that is login, perform some actions and logout.
I was able to do only onle time and not multipe time. Please can anyone solve this.

Regards
Below is my code

```<code>package testCases;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import utilities.Constants;
import utilities.ExcelUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class WebInteractions {

    //creating object of ExcelUtils class
    static ExcelUtils excelUtils = new ExcelUtils();

    //using the Constants class values for excel file path
    static String excelFilePath = Constants.Path_TestData + Constants.File_TestData;

    public static void main(String args[]) throws IOException {
        //set the Chrome Driver path
        System.setProperty("webdriver.chrome.driver", "C:\\Apps\\Eclipse\\Selenium\\chromedriver.exe");

        //Creating an object of ChromeDriver
        WebDriver driver = new ChromeDriver();

        //launching the specified URL
        driver.get("https://dev2-merchant-admin.canpaydebit.com/");

        //Identify the WebElements for the student registration form
        WebElement Username = driver.findElement(By.xpath("//input[@placeholder='Email']"));
        WebElement Password = driver.findElement(By.xpath("//input[@placeholder='Password']"));
        WebElement Login = driver.findElement(By.xpath("//button[@type='button']"));

        //calling the ExcelUtils class method to initialise the workbook and sheet
        excelUtils.setExcelFile(excelFilePath, "Sheet1");

        //iterate over all the row to print the data present in each cell.
            for (int i = 1; i <= excelUtils.getRowCountInSheet(); i++)
                {

                    //Enter the values read from Excel in Username, Password
                    Username.sendKeys(excelUtils.getCellData(i, 0));
                    Password.sendKeys(excelUtils.getCellData(i, 1));

                    //Click on submit button
                    Login.click();
                    driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);

                    //Clicking on Logout button
                    driver.findElement(By.xpath("//a[@class='d-block accordion-toggle collapsed']")).click();
                    driver.findElement(By.xpath("//p[normalize-space()='Logout']")).click();

                }

    }
}

</code>```

I tried the above code. I'm expecting that one user logs in, perform some action, then logs out, then another user logs in, perform some actions and then logout, and like these all others users. The email and password will be coming from the Excel file.

Body:
I was trying to build a framework where credentials of various users will come from an excel file.
The user will login to the application and perform some actions and then logout. After that another user will do the same, that is login, perform some actions and logout.
I was able to do only onle time and not multipe time. Please can anyone solve this.

Regards
Below is my code

package testCases;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import utilities.Constants;
import utilities.ExcelUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class WebInteractions {

    //creating object of ExcelUtils class
    static ExcelUtils excelUtils = new ExcelUtils();

    //using the Constants class values for excel file path
    static String excelFilePath = Constants.Path_TestData + Constants.File_TestData;

    public static void main(String args[]) throws IOException {
        //set the Chrome Driver path
        System.setProperty("webdriver.chrome.driver", "C:\\Apps\\Eclipse\\Selenium\\chromedriver.exe");

        //Creating an object of ChromeDriver
        WebDriver driver = new ChromeDriver();

        //launching the specified URL
        driver.get("https://dev2-merchant-admin.canpaydebit.com/");

        //Identify the WebElements for the student registration form
        WebElement Username = driver.findElement(By.xpath("//input[@placeholder='Email']"));
        WebElement Password = driver.findElement(By.xpath("//input[@placeholder='Password']"));
        WebElement Login = driver.findElement(By.xpath("//button[@type='button']"));

        //calling the ExcelUtils class method to initialise the workbook and sheet
        excelUtils.setExcelFile(excelFilePath, "Sheet1");

        //iterate over all the row to print the data present in each cell.
            for (int i = 1; i <= excelUtils.getRowCountInSheet(); i++)
                {

                    //Enter the values read from Excel in Username, Password
                    Username.sendKeys(excelUtils.getCellData(i, 0));
                    Password.sendKeys(excelUtils.getCellData(i, 1));

                    //Click on submit button
                    Login.click();
                    driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);

                    //Clicking on Logout button
                    driver.findElement(By.xpath("//a[@class='d-block accordion-toggle collapsed']")).click();
                    driver.findElement(By.xpath("//p[normalize-space()='Logout']")).click();

                }

    }
}

I tried the above code. I'm expecting that one user logs in, perform some action, then logs out, then another user logs in, perform some actions and then logout, and like these all others users. The email and password will be coming from the Excel file.


问:
Onepassword_item error terraform plan "status 401: Authentication: (Invalid token signature), Each header's KID must match the KID of the public key"
I have a kubernetes cluster running on google cloud. This cluster has a op_connect_server up and running and I am trying to use terraform to create the items on some specific vaults.
To be able to run it locally, I am port-forwarding the port 8080 to my kubernetes op_connect_server pod. (

```<code>kubectl get pods -A |grep onepassword-connect |grep -v operator |awk '{print $2}' 8080:8080 -n tools)
</code>```

My kubernetes cluster is a private one with a public address attached to it. To run it locally, I am accessing it's public address, and to run it on gitlab, I am accessing it's private address (Because my gitlab pipeline machine is running from inside kubernetes cluster and has access to it's private address. It works for other features)

When I run it locally, everything works well. The items are created on vault without any problems, and also during the terraform plan it can connect to the op_connect_server and check the items without any error.

On my terraform provider for one_password I am setting the token and the op_connect_server address.

When I run it on my pipeline (gitlab), I get the error: status 401: Authentication: (Invalid token signature), Each header's KID must match the KID of the public key.
This error happens during terraform plan, when checking for some onepassword_item. I tried to retrieve the same information using curl and I am able to do it, but for some reason, it fails on terraform.
I already checked/tried:

Check all variables like token, op_connect server address, vault id and they are the same on both (local and gitlab)

Tried using the same cluster endpoint (public one) when running locally and from gitlab

Delete the cluster and create/run everything from the gitlab pipeline.

The creation process works (op_connect_server, all items are created and so on) but when I run it again, it fails with the same error message.

This is my code for creating the items:

```<code>resource "onepassword_item" "credentials" {
vault = ""
title = "Redis Database cache"
category = "database"
type = "other"
username = ""

database = "Redis Database"
hostname = module.beta_redis.database_host_access_private
port = module.beta_redis.database_host_access_port
password = module.beta_redis.auth_string

section {
label = "TLS"
field {
label = "tls_cert"
value = module.beta_redis.tls_cert
type = "CONCEALED"
}
field {
label = "tls_transit_encryption_mode"
value = module.beta_redis.tls_transit_encryption_mode
type = "CONCEALED"
}
field {
label = "tls_sha1_fingerprint"
value = module.beta_redis.tls_sha1_fingerprint
type = "CONCEALED"
}
}
</code>```

My op_connect_server has these settings:

```<code>set {
name = "connect.credentials_base64"
value = data.local_file.input.content_base64
type = "string"
}

set {
name = "connect.serviceType"
value = "NodePort"
}

set {
name = "operator.create"
value = "true"
}

set {
name = "operator.autoRestart"
value = "true"
}

set {
name = "operator.clusterRole.create"
value = "true"
}

set {
name = "operator.roleBinding.create"
value = "true"
}

set {
name = "connect.api.name"
value = "beta-connect-api"
}

set {
name = "operator.token.value"
value = var.op_token_beta
}
</code>```

My one password version is:
1.1.4

Does someone have any clue why this could be happening, or how can I debug it?

Body:
I have a kubernetes cluster running on google cloud. This cluster has a op_connect_server up and running and I am trying to use terraform to create the items on some specific vaults.
To be able to run it locally, I am port-forwarding the port 8080 to my kubernetes op_connect_server pod. (

kubectl get pods -A |grep onepassword-connect |grep -v operator |awk '{print $2}' 8080:8080 -n tools)

My kubernetes cluster is a private one with a public address attached to it. To run it locally, I am accessing it's public address, and to run it on gitlab, I am accessing it's private address (Because my gitlab pipeline machine is running from inside kubernetes cluster and has access to it's private address. It works for other features)

When I run it locally, everything works well. The items are created on vault without any problems, and also during the terraform plan it can connect to the op_connect_server and check the items without any error.

On my terraform provider for one_password I am setting the token and the op_connect_server address.

When I run it on my pipeline (gitlab), I get the error: status 401: Authentication: (Invalid token signature), Each header's KID must match the KID of the public key.
This error happens during terraform plan, when checking for some onepassword_item. I tried to retrieve the same information using curl and I am able to do it, but for some reason, it fails on terraform.
I already checked/tried:

Check all variables like token, op_connect server address, vault id and they are the same on both (local and gitlab)

Tried using the same cluster endpoint (public one) when running locally and from gitlab

Delete the cluster and create/run everything from the gitlab pipeline.

The creation process works (op_connect_server, all items are created and so on) but when I run it again, it fails with the same error message.

This is my code for creating the items:

resource "onepassword_item" "credentials" {
vault = ""
title = "Redis Database cache"
category = "database"
type = "other"
username = ""

database = "Redis Database"
hostname = module.beta_redis.database_host_access_private
port = module.beta_redis.database_host_access_port
password = module.beta_redis.auth_string

section {
label = "TLS"
field {
label = "tls_cert"
value = module.beta_redis.tls_cert
type = "CONCEALED"
}
field {
label = "tls_transit_encryption_mode"
value = module.beta_redis.tls_transit_encryption_mode
type = "CONCEALED"
}
field {
label = "tls_sha1_fingerprint"
value = module.beta_redis.tls_sha1_fingerprint
type = "CONCEALED"
}
}

My op_connect_server has these settings:

set {
name = "connect.credentials_base64"
value = data.local_file.input.content_base64
type = "string"
}

set {
name = "connect.serviceType"
value = "NodePort"
}

set {
name = "operator.create"
value = "true"
}

set {
name = "operator.autoRestart"
value = "true"
}

set {
name = "operator.clusterRole.create"
value = "true"
}

set {
name = "operator.roleBinding.create"
value = "true"
}

set {
name = "connect.api.name"
value = "beta-connect-api"
}

set {
name = "operator.token.value"
value = var.op_token_beta
}

My one password version is:
1.1.4

Does someone have any clue why this could be happening, or how can I debug it?


问:
Finding OpenBLAS on Windows with CMake
I followed the instructions here:
https://github.com/xianyi/OpenBLAS/wiki/How-to-use-OpenBLAS-in-Microsoft-Visual-Studio
for building and installing OpenBLAS, specifically 1. "Native (MSVC) ABI".
And now all the includes and libraries and CMake files are in C:/opt like it wanted.

I then saw I could use FindBLAS in my project's CMakeFile so I added
FindBLAS(), but apparently it's not a command?
I saw everyone who mentioned FindBLAS instead wrote:

```<code>set(BLA_VENDOR OpenBLAS)
find_package(BLAS REQUIRED)
</code>```

so I'm actually pretty confused. What is FindBLAS? Why can't I find any examples of anyone using it?

But then I tried the set and find_package route I saw everywhere and got:

```<code>CMake Error at C:/Program Files/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
  Could NOT find BLAS (missing: BLAS_LIBRARIES)
Call Stack (most recent call first):
  C:/Program Files/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake:600 (_FPHSA_FAILURE_MESSAGE)
  C:/Program Files/CMake/share/cmake-3.25/Modules/FindBLAS.cmake:1346 (find_package_handle_standard_args)
</code>```

I tried setting the environment variables, resetting, everything I can think of. I'm not sure why CMake refuses to find the library and update ${BLAS_LIBRARIES}.

Title: Finding OpenBLAS on Windows with CMake

Body:
I followed the instructions here:
https://github.com/xianyi/OpenBLAS/wiki/How-to-use-OpenBLAS-in-Microsoft-Visual-Studio
for building and installing OpenBLAS, specifically 1. "Native (MSVC) ABI".
And now all the includes and libraries and CMake files are in C:/opt like it wanted.

I then saw I could use FindBLAS in my project's CMakeFile so I added
FindBLAS(), but apparently it's not a command?
I saw everyone who mentioned FindBLAS instead wrote:

set(BLA_VENDOR OpenBLAS)
find_package(BLAS REQUIRED)

so I'm actually pretty confused. What is FindBLAS? Why can't I find any examples of anyone using it?

But then I tried the set and find_package route I saw everywhere and got:

CMake Error at C:/Program Files/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
  Could NOT find BLAS (missing: BLAS_LIBRARIES)
Call Stack (most recent call first):
  C:/Program Files/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake:600 (_FPHSA_FAILURE_MESSAGE)
  C:/Program Files/CMake/share/cmake-3.25/Modules/FindBLAS.cmake:1346 (find_package_handle_standard_args)

I tried setting the environment variables, resetting, everything I can think of. I'm not sure why CMake refuses to find the library and update ${BLAS_LIBRARIES}.


问:
How to get children of terms in sharepoint
I have a few levels of terms in term store. I wanted to be able to create the whole tree of terms using a single query

The following request doesn't return terms with their children:

https://graph.microsoft.com/v1.0/sites/{siteId}/termStore/groups/{groupId}/sets/{setId}/terms?$expand=children

What is wrong with it?
I was able to get children for the single term by its id but not for the whole set of terms


问:
How to redirect user to dashboard after authentication in react js?
Im using react js with redux/toolkit to create user authentication.
I created a form with Formik. When the I submit the form it doesn't redirect me to the dashboard aand I'm unable to identify the issue.

I created a  default authentication service under src/services/AuthService.js, the service method works coresponded useAuth fuction.

AuthService.js

```<code>export async function apiSignIn (data) {
    return ApiService.fetchData({
        url: '/v1/auth/login',
        method: 'post',
        data
    })
}
</code>```

And then I created a store with to Slices:

1- sessionsSlice

2- userSlice:

The logic I implemented in : src/store/auth/sessionSlice.js

```<code>import { createSlice } from '@reduxjs/toolkit'

export const sessionSlice = createSlice({
    name: 'auth/session',
    initialState: {
        token: '',
        signedIn: false,
    },
    reducers: {
        onSignInSuccess: (state, action) => {
            state.signedIn = true
            state.token = action.payload
        },
        onSignOutSuccess: (state) => {
            state.signedIn = false
            state.token = ''
        },
        setToken: (state, action) =>  {
            state.token = action.payload
        }
    },
})

export const { onSignInSuccess, onSignOutSuccess, setToken } = sessionSlice.actions
export default sessionSlice.reducer
</code>```

The logic I implemented in : src/store/auth/userSlice .js

```<code>import { createSlice } from '@reduxjs/toolkit'

export const initialState = {
    avatar: '',
    userName: '',
    email: '',
    authority: []
}

export const userSlice = createSlice({
    name: 'auth/user',
    initialState,
    reducers: {
        setUser: (_, action) => action.payload,
        userLoggedOut: () => initialState,
    },
})

export const { setUser } = userSlice.actions
export default userSlice.reducer
</code>```

The signIn logic implementation in the useAuth looks this way:

```<code>import { useSelector, useDispatch } from 'react-redux'
import { setUser, initialState } from 'store/auth/userSlice'
import { apiSignIn, apiSignOut, apiSignUp } from 'services/AuthService'
import { onSignInSuccess, onSignOutSuccess } from 'store/auth/sessionSlice'
import { REDIRECT_URL_KEY } from 'constants/app.constant'
import { useNavigate } from 'react-router-dom'
import useQuery from './useQuery'

function useAuth() {

    const dispatch = useDispatch()
    const navigate = useNavigate()
    const query = useQuery()
    const { token, signedIn } = useSelector((state) => state.auth.session)
    const signIn = async (values) => {
        try {
            const resp = await apiSignIn(values)
            if (resp.data) {
                const { token } = resp.data
                dispatch(onSignInSuccess(token))
                if(resp.data) {
                    dispatch(setUser(resp.data || {
                        avatar: '',
                        userName: resp.data.userName,
                        authority: [resp.data.role],
                        email: resp.data.email
                    }))
                }
                const redirectUrl = query.get(REDIRECT_URL_KEY)

                navigate(redirectUrl ? redirectUrl : '/dashboard')
                return {
                    status: 'success',
                    message: ''
                }
            }
        } catch (errors) {
            return {
                status: 'failed',
                message: errors?.response?.data?.message || errors.toString()
            }
    }
    }

    const signUp = async (values) => {
        try {
        const resp = await apiSignUp(values)
            if (resp.data) {
                const { token } = resp.data
                dispatch(onSignInSuccess(token))
                if(resp.data.user) {
                    dispatch(setUser(resp.data.user || {
                        avatar: '',
                        userName: 'Anonymous',
                        authority: ['USER'],
                        email: ''
                    }))
                }
                const redirectUrl = query.get(REDIRECT_URL_KEY)
                navigate(redirectUrl ? redirectUrl : '/dashboard')
                return {
                    status: 'success',
                    message: ''
                }
            }
        } catch (errors) {
            return {
                status: 'failed',
                message: errors?.response?.data?.message || errors.toString()
            }
    }
    }

    const handleSignOut = ()  => {
        dispatch(onSignOutSuccess())
        dispatch(setUser(initialState))
        navigate('/dashboard')
    }

    const signOut = async () => {
        await apiSignOut()
        handleSignOut()
    }

    return {
        authenticated: token && signedIn,
        signIn,
        signUp,
        signOut
    }
}

export default useAuth
</code>```

And finally, My form looks this way:

```<code>import React from 'react'
import { Input, Button, Checkbox, FormItem, FormContainer, Alert } from 'components/ui'
import { PasswordInput, ActionLink } from 'components/shared'
import useTimeOutMessage from 'utils/hooks/useTimeOutMessage'
import { Field, Form, Formik } from 'formik'
import * as Yup from 'yup'
import useAuth from 'utils/hooks/useAuth'

const validationSchema = Yup.object().shape({
    userName: Yup.string().required('Please enter your username'),
    password: Yup.string().required('Please enter your password'),
    rememberMe: Yup.bool()
})

const SignInForm = props => {

    const {
        disableSubmit = false,
        className,
    } = props

    const [message, setMessage] = useTimeOutMessage()

    const { signIn } = useAuth()

    const onSignIn = async (values, setSubmitting) => {
        const { userName, password } = values
        setSubmitting(true)

        const result = await signIn({ userName, password })

        if (result.status === 'failed') {
            setMessage(result.message)
        }
        setSubmitting(false)
    }

    return (
        <div className={className}>
            {message && <Alert className="mb-4" type="danger" showIcon>{message}</Alert>}
            <Formik
                initialValues={{
                    userName: '',
                    password: '',
                    rememberMe: true
                }}
                validationSchema={validationSchema}
                onSubmit={(values, { setSubmitting }) => {
                    if(!disableSubmit) {
                        onSignIn(values, setSubmitting)
                    } else {
                        setSubmitting(false)
                    }
                }}
            >
                {({touched, errors, isSubmitting}) => (
                    <Form>
                        <FormContainer>
                            <FormItem
                                label="User Name"
                                invalid={errors.userName && touched.userName}
                                errorMessage={errors.userName}
                            >
                                <Field
                                    type="text"
                                    autoComplete="off"
                                    name="userName"
                                    placeholder="User Name"
                                    component={Input}
                                />
                            </FormItem>
                            <FormItem
                                label="Password"
                                invalid={errors.password && touched.password}
                                errorMessage={errors.password}
                            >
                                <Field
                                    autoComplete="off"
                                    name="password"
                                    placeholder="Password"
                                    component={PasswordInput}
                                />
                            </FormItem>
                            <div className="flex justify-between mb-6">
                                <Field className="mb-0" name="rememberMe" component={Checkbox} children="Remember Me" />
                            </div>
                            <Button block loading={isSubmitting} variant="solid" type="submit">
                                { isSubmitting ? 'Signing in...' : 'Sign In' }
                            </Button>
                        </FormContainer>
                    </Form>
                )}
            </Formik>
        </div>
    )
}

export default SignInForm
</code>```

Body:
Im using react js with redux/toolkit to create user authentication.
I created a form with Formik. When the I submit the form it doesn't redirect me to the dashboard aand I'm unable to identify the issue.

I created a  default authentication service under src/services/AuthService.js, the service method works coresponded useAuth fuction.

AuthService.js

export async function apiSignIn (data) {
    return ApiService.fetchData({
        url: '/v1/auth/login',
        method: 'post',
        data
    })
}

And then I created a store with to Slices:

1- sessionsSlice

2- userSlice:

The logic I implemented in : src/store/auth/sessionSlice.js

import { createSlice } from '@reduxjs/toolkit'

export const sessionSlice = createSlice({
    name: 'auth/session',
    initialState: {
        token: '',
        signedIn: false,
    },
    reducers: {
        onSignInSuccess: (state, action) => {
            state.signedIn = true
            state.token = action.payload
        },
        onSignOutSuccess: (state) => {
            state.signedIn = false
            state.token = ''
        },
        setToken: (state, action) =>  {
            state.token = action.payload
        }
    },
})

export const { onSignInSuccess, onSignOutSuccess, setToken } = sessionSlice.actions
export default sessionSlice.reducer

The logic I implemented in : src/store/auth/userSlice .js

import { createSlice } from '@reduxjs/toolkit'

export const initialState = {
    avatar: '',
    userName: '',
    email: '',
    authority: []
}

export const userSlice = createSlice({
    name: 'auth/user',
    initialState,
    reducers: {
        setUser: (_, action) => action.payload,
        userLoggedOut: () => initialState,
    },
})

export const { setUser } = userSlice.actions
export default userSlice.reducer

The signIn logic implementation in the useAuth looks this way:

import { useSelector, useDispatch } from 'react-redux'
import { setUser, initialState } from 'store/auth/userSlice'
import { apiSignIn, apiSignOut, apiSignUp } from 'services/AuthService'
import { onSignInSuccess, onSignOutSuccess } from 'store/auth/sessionSlice'
import { REDIRECT_URL_KEY } from 'constants/app.constant'
import { useNavigate } from 'react-router-dom'
import useQuery from './useQuery'

function useAuth() {

    const dispatch = useDispatch()
    const navigate = useNavigate()
    const query = useQuery()
    const { token, signedIn } = useSelector((state) => state.auth.session)
    const signIn = async (values) => {
        try {
            const resp = await apiSignIn(values)
            if (resp.data) {
                const { token } = resp.data
                dispatch(onSignInSuccess(token))
                if(resp.data) {
                    dispatch(setUser(resp.data || {
                        avatar: '',
                        userName: resp.data.userName,
                        authority: [resp.data.role],
                        email: resp.data.email
                    }))
                }
                const redirectUrl = query.get(REDIRECT_URL_KEY)

                navigate(redirectUrl ? redirectUrl : '/dashboard')
                return {
                    status: 'success',
                    message: ''
                }
            }
        } catch (errors) {
            return {
                status: 'failed',
                message: errors?.response?.data?.message || errors.toString()
            }
    }
    }

    const signUp = async (values) => {
        try {
        const resp = await apiSignUp(values)
            if (resp.data) {
                const { token } = resp.data
                dispatch(onSignInSuccess(token))
                if(resp.data.user) {
                    dispatch(setUser(resp.data.user || {
                        avatar: '',
                        userName: 'Anonymous',
                        authority: ['USER'],
                        email: ''
                    }))
                }
                const redirectUrl = query.get(REDIRECT_URL_KEY)
                navigate(redirectUrl ? redirectUrl : '/dashboard')
                return {
                    status: 'success',
                    message: ''
                }
            }
        } catch (errors) {
            return {
                status: 'failed',
                message: errors?.response?.data?.message || errors.toString()
            }
    }
    }

    const handleSignOut = ()  => {
        dispatch(onSignOutSuccess())
        dispatch(setUser(initialState))
        navigate('/dashboard')
    }

    const signOut = async () => {
        await apiSignOut()
        handleSignOut()
    }

    return {
        authenticated: token && signedIn,
        signIn,
        signUp,
        signOut
    }
}

export default useAuth

And finally, My form looks this way:

import React from 'react'
import { Input, Button, Checkbox, FormItem, FormContainer, Alert } from 'components/ui'
import { PasswordInput, ActionLink } from 'components/shared'
import useTimeOutMessage from 'utils/hooks/useTimeOutMessage'
import { Field, Form, Formik } from 'formik'
import * as Yup from 'yup'
import useAuth from 'utils/hooks/useAuth'

const validationSchema = Yup.object().shape({
    userName: Yup.string().required('Please enter your username'),
    password: Yup.string().required('Please enter your password'),
    rememberMe: Yup.bool()
})

const SignInForm = props => {

    const {
        disableSubmit = false,
        className,
    } = props

    const [message, setMessage] = useTimeOutMessage()

    const { signIn } = useAuth()

    const onSignIn = async (values, setSubmitting) => {
        const { userName, password } = values
        setSubmitting(true)

        const result = await signIn({ userName, password })

        if (result.status === 'failed') {
            setMessage(result.message)
        }
        setSubmitting(false)
    }

    return (

            {message && <Alert className="mb-4" type="danger" showIcon>{message}</Alert>}
            <Formik
                initialValues={{
                    userName: '',
                    password: '',
                    rememberMe: true
                }}
                validationSchema={validationSchema}
                onSubmit={(values, { setSubmitting }) => {
                    if(!disableSubmit) {
                        onSignIn(values, setSubmitting)
                    } else {
                        setSubmitting(false)
                    }
                }}
            >
                {({touched, errors, isSubmitting}) => (
                    <Form>
                        <FormContainer>
                            <FormItem
                                label="User Name"
                                invalid={errors.userName && touched.userName}
                                errorMessage={errors.userName}
                            >
                                <Field
                                    type="text"
                                    autoComplete="off"
                                    name="userName"
                                    placeholder="User Name"
                                    component={Input}
                                />
                            </FormItem>
                            <FormItem
                                label="Password"
                                invalid={errors.password && touched.password}
                                errorMessage={errors.password}
                            >
                                <Field
                                    autoComplete="off"
                                    name="password"
                                    placeholder="Password"
                                    component={PasswordInput}
                                />
                            </FormItem>

                                <Field className="mb-0" name="rememberMe" component={Checkbox} children="Remember Me" />

                            <Button block loading={isSubmitting} variant="solid" type="submit">
                                { isSubmitting ? 'Signing in...' : 'Sign In' }
                            </Button>
                        </FormContainer>
                    </Form>
                )}
            </Formik>

    )
}

export default SignInForm


问:
Unseen data manipulation for pretrained model with picke dumps
I have several logs that are manipulated by two different TfIdfVectorizer objects.
The first one reads and splits the log in ngrams

with open("my/log/path.txt", "r") as test:
    corpus = [test.read()]
    tf = TfidfVectorizer(ngram_range=ngr)
    corpus_transformed = tf.fit_transform(corpus)
infile.close()
```
<p>The resulting data is written in a Pandas dataframe that has 4 columns</p>
<p>(<em><strong>score</strong></em> [float], <em><strong>review</strong></em> [ngrams of text], <em><strong>isbad</strong></em> [0/1], <em><strong>kfold</strong></em> [int]).
Initial kfold value is -1.</p>
<p>where I have:</p>
<pre class="lang-py prettyprint-override"><code>my_df = pd.DataFrame(corpus_transformed.toarray(), index=['score'], columns=tf.get_feature_names()).transpose()
</code>```

For cross-validation I split the dataset in test and train with StratifiedKFolds by doing a simple:

ngr=(1,2)

for fold_ in range(5):
    # 'reviews' column has short sentences expressing an opinion
    train_df = df[df.kfold != fold_].reset_index(drop=True)
    test_df = df[df.kfold == fold_].reset_index(drop=True)

    new_tf = TfidfVectorizer(ngram_range=ngr)
    new_tf.fit(train_df.reviews)

    xtrain = new_tf.transform(train_df.reviews)
    xtest = new_tf.transform(test_df.reviews)
```
<p>And only after this double tfidf transformation I fit my SVC model with:</p>
<pre class="lang-py prettyprint-override"><code>model.fit(xtrain, train_df.isbad) # where 'isbad' column is 0 if negative and 1 if positive
preds = model.predict(xtest)
accuracy = metrics.accuracy_score(test_df.isbad, preds)
</code>```

So at the end of the day I have my model that classifies reviews in both classes (negative-0 or positive-1), I dump my model and both tfidf vectorizers (tf and new_tf) but when it comes to new data, even if I do:

with open("never/seen/data.txt", "r") as unseen: # load REAL SAMPLE data

    corpus = [unseen.read()]
    # to transform the unseen data I use one of the dumped tfidf's obj
    corpus_transformed = tf_dump.transform(corpus)

unseen.close()

my_unseen_df = pd.DataFrame(corpus_transformed.toarray(), index=['score'], columns=tf_dump.get_feature_names()).transpose()
my_unseen_df = my_unseen_df.sample(frac=1).reset_index(drop=True) # randomize rows

# to transform reviews' data that are going to be classified I use the new_tf dump, like before
X = new_tf_dump.transform(my_unseen_df.reviews)
# use the previously loaded model and make predictions
res = model_dump.predict(X)
#print(res)
```

I got ValueError: X has 604,969 features, but SVC is expecting 605,424 as input, but how is that possibile if I manipulate the data with the same objects? What am I doing wrong here?
I want to use my trained model as a classifier for new, unseen data. Isn't this the right way to go?

Thank you.

Body:
I have several logs that are manipulated by two different TfIdfVectorizer objects.
The first one reads and splits the log in ngrams

with open("my/log/path.txt", "r") as test:
    corpus = [test.read()]
    tf = TfidfVectorizer(ngram_range=ngr)
    corpus_transformed = tf.fit_transform(corpus)
infile.close()

The resulting data is written in a Pandas dataframe that has 4 columns

(score [float], review [ngrams of text], isbad [0/1], kfold [int]).
Initial kfold value is -1.

where I have:

my_df = pd.DataFrame(corpus_transformed.toarray(), index=['score'], columns=tf.get_feature_names()).transpose()

For cross-validation I split the dataset in test and train with StratifiedKFolds by doing a simple:

ngr=(1,2)

for fold_ in range(5):
    # 'reviews' column has short sentences expressing an opinion
    train_df = df[df.kfold != fold_].reset_index(drop=True)
    test_df = df[df.kfold == fold_].reset_index(drop=True)

    new_tf = TfidfVectorizer(ngram_range=ngr)
    new_tf.fit(train_df.reviews)

    xtrain = new_tf.transform(train_df.reviews)
    xtest = new_tf.transform(test_df.reviews)

And only after this double tfidf transformation I fit my SVC model with:

model.fit(xtrain, train_df.isbad) # where 'isbad' column is 0 if negative and 1 if positive
preds = model.predict(xtest)
accuracy = metrics.accuracy_score(test_df.isbad, preds)

So at the end of the day I have my model that classifies reviews in both classes (negative-0 or positive-1), I dump my model and both tfidf vectorizers (tf and new_tf) but when it comes to new data, even if I do:

with open("never/seen/data.txt", "r") as unseen: # load REAL SAMPLE data

    corpus = [unseen.read()]
    # to transform the unseen data I use one of the dumped tfidf's obj
    corpus_transformed = tf_dump.transform(corpus)

unseen.close()

my_unseen_df = pd.DataFrame(corpus_transformed.toarray(), index=['score'], columns=tf_dump.get_feature_names()).transpose()
my_unseen_df = my_unseen_df.sample(frac=1).reset_index(drop=True) # randomize rows

# to transform reviews' data that are going to be classified I use the new_tf dump, like before
X = new_tf_dump.transform(my_unseen_df.reviews)
# use the previously loaded model and make predictions
res = model_dump.predict(X)
#print(res)

I got ValueError: X has 604,969 features, but SVC is expecting 605,424 as input, but how is that possibile if I manipulate the data with the same objects? What am I doing wrong here?
I want to use my trained model as a classifier for new, unseen data. Isn't this the right way to go?

Thank you.