问:
JSTree not populating properly from JSON Array. If I return a single String it works but not from my Array. Where am I going wrong?
I have been trying to get this working for days but failing. If I return a single string using this format from C#:

```<code>"{ \"id\": \"" + libraryName + "\", \"parent\": \"#\", \"text\": \"" + libraryName + "\", \"type\": \"FDR\", \"value\": \"0\" }"
</code>```

It will work but obviously a Tree is no use with a single item! As soon as I add the items to a List or Array (which JSTree needs) then it seems to interpret each String as only a String and doesn't read in any values.

I have set an alert before it builds the tree to double check and it looks to be presenting the data correctly:

```<code>{ "id": "New Lib", "parent": "#", "text": "New Lib", "type": "FDR", "value": "0" }, { "id": "40", "parent": "New Lib", "text": "Text TXT", "type": "TXT", "value": "1" }, { "id": "39", "parent": "New Lib", "text": "new 5", "type": "IMG", "value": "2" }, { "id": "34", "parent": "New Lib", "text": "Hi", "type": "FDR", "value": "3" }, { "id": "41", "parent": "34", "text": "Test URL Facebook", "type": "URL", "value": "4" }, { "id": "37", "parent": "34", "text": "Hi 2", "type": "FDR", "value": "5" }
</code>```

but I get this instead:

Result

what am I doing wrong??

```<code>[WebMethod]
public static Array getChildren(string libraryID)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    con.Open();

    //Build root
    string[] documentArray = null;
    List<string> documentList = new List<string>();

    string getUserInfo = "select LibraryName from Document_Library_Names where Id =" + libraryID;
    SqlCommand getUserInfocmd = new SqlCommand(getUserInfo, con);
    string libraryName = Convert.ToString(getUserInfocmd.ExecuteScalar()).Trim();

    documentList.Add("{ \"id\": \"" + libraryName + "\", \"parent\": \"#\", \"text\": \"" + libraryName + "\", \"type\": \"FDR\", \"value\": \"0\" }");

    //Getting documents
    string strGetDocuments = "Select * from Documents where LID =" + libraryID + "  order by DisplayOrder ASC";
    SqlCommand getDocumentsCMD = new SqlCommand(strGetDocuments, con);
    getDocumentsCMD.ExecuteNonQuery();

    DataTable dt = new DataTable();
    SqlDataReader sqlDR = getDocumentsCMD.ExecuteReader();
    dt.Load(sqlDR);
    sqlDR.Close();

    if (dt != null)
    {
        if (dt.Rows.Count > 0)
        {
            //Build the string
            foreach (DataRow row in dt.Rows)
            {
                //Getting the data
                string ID = row[0].ToString().Trim();
                string type = row[2].ToString().Trim();
                string name = row[3].ToString().Trim();
                string parentFolder = row[4].ToString().Trim();
                string displayOrder = row[5].ToString().Trim();
                string extension = row[8].ToString().Trim();

                //Get parentFolder ID
                string parentFolderID = "0";
                if (parentFolder != "")
                {
                    string strParentFolderID = "Select ID from Documents where Name=@Name and Type=0";
                    SqlCommand strParentFolderIDcmd = new SqlCommand(strParentFolderID, con);
                    strParentFolderIDcmd.Parameters.AddWithValue("@Name", parentFolder);
                    parentFolderID = Convert.ToString(strParentFolderIDcmd.ExecuteScalar());
                }
                else
                {
                    parentFolderID = libraryName;
                }
                documentList.Add(" { \"id\": \"" + ID + "\", \"parent\": \"" + parentFolderID + "\", \"text\": \"" + name + "\", \"type\": \"" + extension + "\", \"value\": \"" + displayOrder + "\" }");
                documentArray = documentList.ToArray();
            }
            con.Close();
            //documentList = documentList + "]";
            return documentArray;
        }
        else
        {
            con.Close();
            return documentArray;
        }
    }
    else
    {
        con.Close();
        return documentArray;
    }
}
</code>```

Javascript:

```<code><script src="Scripts/jquery-3.6.1.js"></script>
<script src="Scripts/jstree.js"></script>
<link href="Scripts/themes/default/style.css" rel="stylesheet" />
    <div id="libraryTreeview">

    </div>

    <script type="text/javascript">

        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        const libraryID = urlParams.get('ID');

        $('#libraryTreeview').jstree({
            "core": {
                "data": {
                        type: "POST",
                        url: "LibraryFiles.aspx/getChildren",
                        data: '{"libraryID":"' + libraryID + '"}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (results) {
                            results.d;
                            alert(results.d);
                        },
                },
                "themes": {
                    dots: false,
                    "variant": "large",
                    "responsive": true
                },
        });
    </script>
</code>```

I originally tried with 1 big long string but JSTree didn't like anything after the first folders ending "}" so I had to move to an Array.

Result from Google Inspect:

```<code><div id="libraryTreeview" class="jstree jstree-1 jstree-default jstree-default-responsive jstree-default-large" role="tree" aria-multiselectable="true" tabindex="0" aria-activedescendant="j1_2" aria-busy="false"><ul class="jstree-container-ul jstree-children jstree-no-dots" role="group"><li role="none" id="j1_1" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor" href="#" tabindex="-1" role="treeitem" aria-selected="false" aria-level="1" id="j1_1_anchor"><i class="jstree-icon jstree-themeicon" role="presentation"></i>{ "id": "New Lib", "parent": "#", "text": "New Lib", "type": "FDR", "value": "0" }</a></li><li role="none" id="j1_2" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor" href="#" tabindex="-1" role="treeitem" aria-selected="false" aria-level="1" id="j1_2_anchor"><i class="jstree-icon jstree-themeicon" role="presentation"></i> { "id": "40", "parent": "New Lib", "text": "Text TXT", "type": "TXT", "value": "1" }</a></li><li role="none" id="j1_3" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor" href="#" tabindex="-1" role="treeitem" aria-selected="false" aria-level="1" id="j1_3_anchor"><i class="jstree-icon jstree-themeicon" role="presentation"></i> { "id": "39", "parent": "New Lib", "text": "new 5", "type": "IMG", "value": "2" }</a></li><li role="none" id="j1_4" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor" href="#" tabindex="-1" role="treeitem" aria-selected="false" aria-level="1" id="j1_4_anchor"><i class="jstree-icon jstree-themeicon" role="presentation"></i> { "id": "34", "parent": "New Lib", "text": "Hi", "type": "FDR", "value": "3" }</a></li><li role="none" id="j1_5" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor" href="#" tabindex="-1" role="treeitem" aria-selected="false" aria-level="1" id="j1_5_anchor"><i class="jstree-icon jstree-themeicon" role="presentation"></i> { "id": "41", "parent": "34", "text": "Test URL Facebook", "type": "URL", "value": "4" }</a></li><li role="none" id="j1_6" class="jstree-node  jstree-leaf jstree-last"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor" href="#" tabindex="-1" role="treeitem" aria-selected="false" aria-level="1" id="j1_6_anchor"><i class="jstree-icon jstree-themeicon" role="presentation"></i> { "id": "37", "parent": "34", "text": "Hi 2", "type": "FDR", "value": "5" }</a></li></ul></div>
</code>```

Body:
I have been trying to get this working for days but failing. If I return a single string using this format from C#:

"{ \"id\": \"" + libraryName + "\", \"parent\": \"#\", \"text\": \"" + libraryName + "\", \"type\": \"FDR\", \"value\": \"0\" }"

It will work but obviously a Tree is no use with a single item! As soon as I add the items to a List or Array (which JSTree needs) then it seems to interpret each String as only a String and doesn't read in any values.

I have set an alert before it builds the tree to double check and it looks to be presenting the data correctly:

{ "id": "New Lib", "parent": "#", "text": "New Lib", "type": "FDR", "value": "0" }, { "id": "40", "parent": "New Lib", "text": "Text TXT", "type": "TXT", "value": "1" }, { "id": "39", "parent": "New Lib", "text": "new 5", "type": "IMG", "value": "2" }, { "id": "34", "parent": "New Lib", "text": "Hi", "type": "FDR", "value": "3" }, { "id": "41", "parent": "34", "text": "Test URL Facebook", "type": "URL", "value": "4" }, { "id": "37", "parent": "34", "text": "Hi 2", "type": "FDR", "value": "5" }

but I get this instead:

Result

what am I doing wrong??

[WebMethod]
public static Array getChildren(string libraryID)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    con.Open();

    //Build root
    string[] documentArray = null;
    List<string> documentList = new List<string>();

    string getUserInfo = "select LibraryName from Document_Library_Names where Id =" + libraryID;
    SqlCommand getUserInfocmd = new SqlCommand(getUserInfo, con);
    string libraryName = Convert.ToString(getUserInfocmd.ExecuteScalar()).Trim();

    documentList.Add("{ \"id\": \"" + libraryName + "\", \"parent\": \"#\", \"text\": \"" + libraryName + "\", \"type\": \"FDR\", \"value\": \"0\" }");

    //Getting documents
    string strGetDocuments = "Select * from Documents where LID =" + libraryID + "  order by DisplayOrder ASC";
    SqlCommand getDocumentsCMD = new SqlCommand(strGetDocuments, con);
    getDocumentsCMD.ExecuteNonQuery();

    DataTable dt = new DataTable();
    SqlDataReader sqlDR = getDocumentsCMD.ExecuteReader();
    dt.Load(sqlDR);
    sqlDR.Close();

    if (dt != null)
    {
        if (dt.Rows.Count > 0)
        {
            //Build the string
            foreach (DataRow row in dt.Rows)
            {
                //Getting the data
                string ID = row[0].ToString().Trim();
                string type = row[2].ToString().Trim();
                string name = row[3].ToString().Trim();
                string parentFolder = row[4].ToString().Trim();
                string displayOrder = row[5].ToString().Trim();
                string extension = row[8].ToString().Trim();

                //Get parentFolder ID
                string parentFolderID = "0";
                if (parentFolder != "")
                {
                    string strParentFolderID = "Select ID from Documents where Name=@Name and Type=0";
                    SqlCommand strParentFolderIDcmd = new SqlCommand(strParentFolderID, con);
                    strParentFolderIDcmd.Parameters.AddWithValue("@Name", parentFolder);
                    parentFolderID = Convert.ToString(strParentFolderIDcmd.ExecuteScalar());
                }
                else
                {
                    parentFolderID = libraryName;
                }
                documentList.Add(" { \"id\": \"" + ID + "\", \"parent\": \"" + parentFolderID + "\", \"text\": \"" + name + "\", \"type\": \"" + extension + "\", \"value\": \"" + displayOrder + "\" }");
                documentArray = documentList.ToArray();
            }
            con.Close();
            //documentList = documentList + "]";
            return documentArray;
        }
        else
        {
            con.Close();
            return documentArray;
        }
    }
    else
    {
        con.Close();
        return documentArray;
    }
}

Javascript:

<link href="Scripts/themes/default/style.css" rel="stylesheet" />

I originally tried with 1 big long string but JSTree didn't like anything after the first folders ending "}" so I had to move to an Array.

Result from Google Inspect:

{ "id": "New Lib", "parent": "#", "text": "New Lib", "type": "FDR", "value": "0" }

 { "id": "40", "parent": "New Lib", "text": "Text TXT", "type": "TXT", "value": "1" }

 { "id": "39", "parent": "New Lib", "text": "new 5", "type": "IMG", "value": "2" }

 { "id": "34", "parent": "New Lib", "text": "Hi", "type": "FDR", "value": "3" }

 { "id": "41", "parent": "34", "text": "Test URL Facebook", "type": "URL", "value": "4" }

 { "id": "37", "parent": "34", "text": "Hi 2", "type": "FDR", "value": "5" }


来源: stackexchange

问:
In Excel, how can a filled map have multiple data elements?
I have a filled map sheet that takes totals of different categories, and fills the ZIP codes. My chart only uses the first total in the list where, many times, there are 2-4 totals for different categories.

I want it to show each category on a separate line, rather than just the first, then stop.

I believe that my problem is with the data range selected.

ContentLicense: CC BY-SA 4.0


问:
Python 2D engine without GUI for server side
I wanted to make a simple 2D network game completely in python, the game client will most likely be on pygame, the connection between the client and the server will be established via sockets, the problem is that I don’t know which library I should use for the game itself on the server side, then  Is there a way and where I can calculate the flight paths of projectiles, catch the events of a projectile collision with a player, so I'm looking for a 2D engine that will allow me to do all this on the server side without calling the graphical interface.</p>


问:
Appending on a copied python list
Why does instantly appending on a copied python list not work?

I have the following code:

```<code>mylist = [1]
mylist2 = mylist.copy()
mylist2.append(2)
</code>```

This gives me the expected mylist2 = [1,2].
Why does the following code lead to a None?

```<code>mylist = [1]
mylist2 = mylist.copy().append(2)
</code>```

Title: Appending on a copied python list

Body:
Why does instantly appending on a copied python list not work?

I have the following code:

mylist = [1]
mylist2 = mylist.copy()
mylist2.append(2)

This gives me the expected mylist2 = [1,2].
Why does the following code lead to a None?

mylist = [1]
mylist2 = mylist.copy().append(2)


问:
I want to call a JS api and use that to filter my product page by category and brand for ecommcerce website
I want to call a JS api and use that to filter my  product page by category and brand for ecommcerce website. I want it to work on an html drop down button, but I just don't know how to filter them because I do not know what to do to bring the apis into an html file.
Here is my filterapi code:

```<code>const express = require('express');
const router = express.Router();
const dbConn = require('../../dbconnection.js');

router.get('/categories', async (req, res, next) => {
    let Category = req.params.Category;
    dbConn.query('SELECT DISTINCT Category FROM Product', Category, (err, result) => {
        if (err) {
            console.log('Error while fetching Category', err);
            res.status(500);
            res.json({ "error": { "message": "Internal Server Error", "code": "500" } });
        } else {
            console.log(JSON.stringify(result));
            res.json(result);
        }
    });
}
);

router.get('/subcategories', async (req, res, next) => {
    let Category = req.params.Category;
    dbConn.query('SELECT DISTINCT SubCategory FROM Product', Category, (err, result) => {
        if (err) {
            console.log('Error while fetching SubCategory', err);
            res.status(500);
            res.json({ "error": { "message": "Internal Server Error", "code": "500" } });
        } else {
            console.log(JSON.stringify(result));
            res.json(result);
        }
    });
}
);

router.get('/brands', async (req, res, next) => {
    let Category = req.params.Category;
    dbConn.query('SELECT DISTINCT Brand FROM Product', Category, (err, result) => {
        if (err) {
            console.log('Error while fetching Brand', err);
            res.status(500);
            res.json({ "error": { "message": "Internal Server Error", "code": "500" } });
        } else {
            console.log(JSON.stringify(result));
            res.json(result);
        }
    });
}
);

module.exports = router;

</code>```

I tried to create an html file and then write a script in there to filter by category and brand manually but I just couldn't figure it out

Body:
I want to call a JS api and use that to filter my  product page by category and brand for ecommcerce website. I want it to work on an html drop down button, but I just don't know how to filter them because I do not know what to do to bring the apis into an html file.
Here is my filterapi code:

const express = require('express');
const router = express.Router();
const dbConn = require('../../dbconnection.js');

router.get('/categories', async (req, res, next) => {
    let Category = req.params.Category;
    dbConn.query('SELECT DISTINCT Category FROM Product', Category, (err, result) => {
        if (err) {
            console.log('Error while fetching Category', err);
            res.status(500);
            res.json({ "error": { "message": "Internal Server Error", "code": "500" } });
        } else {
            console.log(JSON.stringify(result));
            res.json(result);
        }
    });
}
);

router.get('/subcategories', async (req, res, next) => {
    let Category = req.params.Category;
    dbConn.query('SELECT DISTINCT SubCategory FROM Product', Category, (err, result) => {
        if (err) {
            console.log('Error while fetching SubCategory', err);
            res.status(500);
            res.json({ "error": { "message": "Internal Server Error", "code": "500" } });
        } else {
            console.log(JSON.stringify(result));
            res.json(result);
        }
    });
}
);

router.get('/brands', async (req, res, next) => {
    let Category = req.params.Category;
    dbConn.query('SELECT DISTINCT Brand FROM Product', Category, (err, result) => {
        if (err) {
            console.log('Error while fetching Brand', err);
            res.status(500);
            res.json({ "error": { "message": "Internal Server Error", "code": "500" } });
        } else {
            console.log(JSON.stringify(result));
            res.json(result);
        }
    });
}
);

module.exports = router;

I tried to create an html file and then write a script in there to filter by category and brand manually but I just couldn't figure it out


问:
Stop the redirected output containing the `for in` clause on the GitHub Codespaces environment

Background

I want to redirect the result of a one-liner shell script to a file on a terminal in the GitHub Codespaces environment.

For example, when I executed the following one-liner in the Terminal view of VSCode:

$ for i in 1 2 3; do echo $i; done
```
<p>I got the following result:</p>
<p><img src="https://i.stack.imgur.com/p6vTI.png" alt="for i in 1 2 3; do echo $i; done123$" /></p>
<h2>Problem</h2>
<p>When I redirected the result of the same one-liner:</p>
<pre class="lang-bash prettyprint-override"><code>$ for i in 1 2 3; do echo $i; done > foo.txt
</code>```

I got the foo.txt like this. It contains escape sequences and the for ... in clause of the one-liner:

```<code>]633;C]633;E;for\x20i\x20in\x201\x202\x2031
2
3
</code>```

When I ran the same one-liner in my WSL2 environment, the result didn't contain these headings.

Question

How can I stop the redirected output containing the for in clause on the GitHub Codespaces environment?

Body:
Background

I want to redirect the result of a one-liner shell script to a file on a terminal in the GitHub Codespaces environment.

For example, when I executed the following one-liner in the Terminal view of VSCode:

$ for i in 1 2 3; do echo $i; done

I got the following result:

Problem

When I redirected the result of the same one-liner:

$ for i in 1 2 3; do echo $i; done > foo.txt

I got the foo.txt like this. It contains escape sequences and the for ... in clause of the one-liner:

]633;C]633;E;for\x20i\x20in\x201\x202\x2031
2
3

When I ran the same one-liner in my WSL2 environment, the result didn't contain these headings.

Question

How can I stop the redirected output containing the for in clause on the GitHub Codespaces environment?


问:
Terraform oauth2: cannot fetch token: 400 Bad Request │ Response: {"error":"invalid_grant","error_description":"Invalid JWT Signature."}
this is my file main.tf

```<code>data "google_compute_image" "my-image" {
  name    = "my-image-bk"
  project = "my-proyect"
}

resource "google_compute_instance" "my-instance" {
  name = "instance-live"
  #machine_type = "e2-custom-2-2096"
  machine_type   = "e2-small"
  zone           = var.zone
  can_ip_forward = false
  description    = ""

  boot_disk {
    initialize_params {
      image = data.google_compute_image.my-image.self_link
      type  = "pd-ssd"
      size  = "100"
    }
  }

  network_interface {
    #network = google_compute_network.my-network.id
    #subnetwork = google_compute_subnetwork.subnet-my.id
    network    = "default"
    network_ip = "10.150.0.10"
    access_config {
    }
  }

  service_account {
    scopes = ["userinfo-email", "compute-ro", "storage-ro"]
  }
}
</code>```

When exec terraform plan..... terraform launch this error:

Error: error retrieving image information: Get
"https://compute.googleapis.com/compute/v1/projects/my-project/global/images/my-image?alt=json&prettyPrint=false":
oauth2: cannot fetch token: 400 Bad Request Response:
{"error":"invalid_grant","error_description":"Invalid JWT Signature."}

of course, the image "my-image" exists in the project my-project, i check this with the command :

```<code>gcloud compute images list --project my-project
</code>```

any idea?

My Platform:
OS: windows 11, Terraform: 0.13 and 1.3.6... same error, provider: GCP

Body:
this is my file main.tf

data "google_compute_image" "my-image" {
  name    = "my-image-bk"
  project = "my-proyect"
}

resource "google_compute_instance" "my-instance" {
  name = "instance-live"
  #machine_type = "e2-custom-2-2096"
  machine_type   = "e2-small"
  zone           = var.zone
  can_ip_forward = false
  description    = ""

  boot_disk {
    initialize_params {
      image = data.google_compute_image.my-image.self_link
      type  = "pd-ssd"
      size  = "100"
    }
  }

  network_interface {
    #network = google_compute_network.my-network.id
    #subnetwork = google_compute_subnetwork.subnet-my.id
    network    = "default"
    network_ip = "10.150.0.10"
    access_config {
    }
  }

  service_account {
    scopes = ["userinfo-email", "compute-ro", "storage-ro"]
  }
}

When exec terraform plan..... terraform launch this error:

Error: error retrieving image information: Get
"https://compute.googleapis.com/compute/v1/projects/my-project/global/images/my-image?alt=json&prettyPrint=false":
oauth2: cannot fetch token: 400 Bad Request Response:
{"error":"invalid_grant","error_description":"Invalid JWT Signature."}

of course, the image "my-image" exists in the project my-project, i check this with the command :

gcloud compute images list --project my-project

any idea?

My Platform:
OS: windows 11, Terraform: 0.13 and 1.3.6... same error, provider: GCP


Title: Reading and printing the data between two positions in file with using file.read().find()

Body:
I am trying to read and print data between two positions that I found with file.read().find . How can I print them ?

This is the code that I use for found the start and end positions of the data.

name = "FEMMeshGmsh.inp"
file = open(name, "r")
text = file.read()
startPosition = text.find("Face9")
print(startPosition)
endPosition = text.find("*",startPosition)
print(endPosition)

outputs :

72365
73071

This is the data that I am trying to print in file :

** node loads on shape: Connect:Face9
10,1,0.0000000000000E+00
11,1,0.0000000000000E+00
26,1,0.0000000000000E+00
27,1,0.0000000000000E+00
80,1,6.2500000000000E+01
152,1,0.0000000000000E+00
153,1,0.0000000000000E+00
154,1,0.0000000000000E+00
155,1,6.2500000000000E+01
156,1,6.2500000000000E+01
157,1,6.2500000000000E+01
158,1,6.2500000000000E+01
159,1,0.0000000000000E+00
160,1,0.0000000000000E+00
161,1,0.0000000000000E+00
162,1,6.2500000000000E+01
163,1,6.2500000000000E+01
164,1,6.2500000000000E+01
165,1,6.2500000000000E+01
166,1,6.2500000000000E+01
424,1,1.2500000000000E+02
425,1,1.2500000000000E+02
426,1,1.2500000000000E+02
427,1,1.2500000000000E+02
428,1,1.2500000000000E+02
429,1,1.2500000000000E+02
430,1,1.2500000000000E+02

***********************************************************

I used file.read().find() for taking the positions. And I assigned them into variable. Start and end. I should use "Face9" and "*" parameters to reach the data


问:
Gtk app on Windows, how to disable the Control-Win-Left/Right/Up/Down keybindings?
Windows 10/11 defines the following key bindings for all applications by default:

Win+Left/Right : split view mode (i.e. dock window against left or right side of screen);

Ctrl+Win+Left/Right : scroll to previous/next workspace.

Gtk 3.x also by default associates Ctrl+Win+Left/Right with split view actions. Thus pressing Ctrl+Win+Left/Right with a Gtk 3.x application in focus on Windows 10 causes both the application window to go into split view mode and a workspace switch. This is confusing. By comparison, non-Gtk apps ignore the Ctrl+Win+arrow combinations.

I tried hooking a signal handler to intercept key press events in my application window, that I would then use to block the unwanted key combinations, i.e. (C++):

```<code>         add_events( Gdk::EventMask::ALL_EVENTS_MASK );
         signal_event().connect(
            [&] ( GdkEvent* pEvent ) -> bool
            {
               // Return 'true' if match, do not propagate the event further:
               if( pEvent->type == Gdk::KEY_PRESS && pEvent->key.keyval == GDK_KEY_Left )
               {
                  return true;
               }
               else
               {
                  return false;
               }
            } );
</code>```

This does block the Left arrow key (with any combination of modifier keys)... but the particular Win+anything combinations are handled at a lower lever and never reach the handler.

Then I did find the documentation on GtkBindingSet and added definitions in my gtk.css file to unbind Ctrl+Win+Left/Right in the application, but it also had no effect. I know that the binding set is loaded in the app because I can define other keybindings that do work (i.e. I successfully changed the behavior of the Left/Right keys in GtkEntry widgets).

This is the CSS that I added which does not work. The syntax appears correct since other definitions in the same file do take effect, just not my binding set:

```<code> @binding-set ms-keys {
    unbind "<Control><Super>Left";
    unbind "<Control><Super>Right";
    unbind "<Control><Super>Up";
    unbind "<Control><Super>Down"; }

 Window { -gtk-key-bindings: ms-keys; }
</code>```

I'm not a CSS expert, perhaps I'm doing something wrong? I've run out of ideas to try, any help appreciated.

Body:
Windows 10/11 defines the following key bindings for all applications by default:

Win+Left/Right : split view mode (i.e. dock window against left or right side of screen);

Ctrl+Win+Left/Right : scroll to previous/next workspace.

Gtk 3.x also by default associates Ctrl+Win+Left/Right with split view actions. Thus pressing Ctrl+Win+Left/Right with a Gtk 3.x application in focus on Windows 10 causes both the application window to go into split view mode and a workspace switch. This is confusing. By comparison, non-Gtk apps ignore the Ctrl+Win+arrow combinations.

I tried hooking a signal handler to intercept key press events in my application window, that I would then use to block the unwanted key combinations, i.e. (C++):

         add_events( Gdk::EventMask::ALL_EVENTS_MASK );
         signal_event().connect(
            [&] ( GdkEvent* pEvent ) -> bool
            {
               // Return 'true' if match, do not propagate the event further:
               if( pEvent->type == Gdk::KEY_PRESS && pEvent->key.keyval == GDK_KEY_Left )
               {
                  return true;
               }
               else
               {
                  return false;
               }
            } );

This does block the Left arrow key (with any combination of modifier keys)... but the particular Win+anything combinations are handled at a lower lever and never reach the handler.

Then I did find the documentation on GtkBindingSet and added definitions in my gtk.css file to unbind Ctrl+Win+Left/Right in the application, but it also had no effect. I know that the binding set is loaded in the app because I can define other keybindings that do work (i.e. I successfully changed the behavior of the Left/Right keys in GtkEntry widgets).

This is the CSS that I added which does not work. The syntax appears correct since other definitions in the same file do take effect, just not my binding set:

 @binding-set ms-keys {
    unbind "<Control><Super>Left";
    unbind "<Control><Super>Right";
    unbind "<Control><Super>Up";
    unbind "<Control><Super>Down"; }

 Window { -gtk-key-bindings: ms-keys; }

I'm not a CSS expert, perhaps I'm doing something wrong? I've run out of ideas to try, any help appreciated.


问:
Forge - Integration with AutoDesk COST...When I look through AutoDesk site at the PO
Forge - Integration with AutoDesk COST...When I look through AutoDesk site at the PO, then view the schedule of values full page, it shows a “/SOVS” at the end of the URL, tried to add an include=sovs in my link instead of include=budgets, but it is, ignored.

I am trying to get the schedule of values for a PO.  I do a “GET”  (https://developer.api.autodesk.com/cost/v1/containers/9bb64cd6-26a4-4e45-88f8-d98f9643d8b9/contracts/3df929a1-5c9b-4085-beb0-a58d25fcf2c3?include=budgets), but this doesn’t give me the line items.  I can’t find anything in docs saying what the call would be.  When I look through AutoDesk site at the PO, then view the schedule of values full page, it shows a “/SOVS” at the end of the URL,

I tried to add an include=sovs in my link instead of include=budgets, but it is, ignored.


问:
Why is the Mach exception `EXC_CRASH` only catchable by an out-of-process handler?
EXC_CRASH can only be caught by an out-of-process exception handler. I'm curious about why the handler has to be out-of-process.</p>


问:
How to traverse an unknown-length path in SurrealDB?
I want to recursively follow related records in SurrealDB, and I can't find the syntax to express it.

The simplest explanation of my goal is Neo4j/Cypher's variable length pattern matches. More generally, I want to start at a record and follow particular relations until I stop (either by number of steps or some other condition), where I don't know how many relation steps are needed between start and end.

The closest I can find is discussed here, in the section on 'No JOINs'. This doesn't fill my need, because the query specifies the number of steps between start and end. I'm imagining something like SELECT {->parent->person REPEATED 1..5} FROM person:tobie, which would find all of tobie's ancestors for 5 generations (person:tobie->parent->person, person:tobie->parent->person->parent->person, etc).

If this isn't part of SurrealQL's features, can you give me hints on other ways to get the same result? I've considered using the scripting functions, which seems powerful but off the beaten path.


问:
How can I create an offcanvas with Bootstrap using a custom animated button that rotates?
I would like to create a top offcanvas with Boostrap using my custom button that rotates (not icons) but I cannot do this because the rotation disappears and I would like it to be visibile while opening the offcanvas.
When I click on the button it remains fixed without rotating and the same happens in the offcanvas.
How could I do that?
This is my code

`

```<code> <nav class="navbar sticky-top navbar-expand-lg" aria-label=" offcanvas navbar" role="navigation">
            <div class="container-fluid gx-5">
            <a class="navbar-brand" href="/">
                <img src="./assets/img/logo.svg" alt="name of site - Home" width="43" class="d-inline-block align-text-top"
                    title="Homepage">
            </a>
                <button class="navbar-toggler collapsed d-flex d-lg-none flex-column justify-content-around" type="button" data-bs-toggle="offcanvas"
                    data-bs-target="#offcanvasNavbarLight" aria-controls="offcanvasNavbarLight" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="toggler-icon top-bar"></span>
                    <span class="toggler-icon middle-bar"></span>
                    <span class="toggler-icon bottom-bar"></span>
                </button>
                <div class="offcanvas offcanvas-top vh-100" tabindex="-1" id="offcanvasNavbarLight"
                    aria-labelledby="offcanvasNavbarLightLabel">
                    <div class="offcanvas-header">
                        <button type="button" class="navbar-toggler ms-auto" data-bs-dismiss="offcanvas" aria-label="Close">
                            <span class="toggler-icon top-bar"></span>
                            <span class="toggler-icon middle-bar"></span>
                            <span class="toggler-icon bottom-bar"></span>
                        </button>
                    </div>
                    <div class="offcanvas-body">
                        <ul class="navbar-nav justify-content-end flex-grow-1 pe-3">
                            <li class="nav-item">
                                <a class="nav-link" href="index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="skills.html">Skills</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" aria-current="page" href="projects.html">Projects</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="contact.html">Contact</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </nav>
</code>```

`

`

```<code>.navbar-toggler {
  width: 27px;
  height: 30px;
  position: relative;
  transition: 0.5s ease-in-out;
}

.toggler-icon {
  display: block;
  position: absolute;
  height: 2px;
  width: 100%;
  background: #2E2E2F;
  border-radius: 10px;
  opacity: 1;
  left: 0;
  transform: rotate(0deg);
  transition: 0.25s ease-in-out;
}

.middle-bar {
  margin-top: 0em;
}

/* When navigation is clicked */
span.toggler-icon.top-bar {
  margin-top: 0em;
  transform: rotate(45deg);
}

span.toggler-icon.middle-bar {
  opacity: 0;
  filter: alpha(opacity=0);
}

span.toggler-icon.bottom-bar {
  margin-top: 0px;
  transform: rotate(-45deg);
}

/* State when the navbar is collapsed */
.navbar-toggler.collapsed .top-bar {
  margin-top: -16px;
  transform: rotate(0deg);
}

.navbar-toggler.collapsed .middle-bar {
  opacity: 1;
  filter: alpha(opacity=100);
}

.navbar-toggler.collapsed .bottom-bar {
  margin-top: 16px;
  transform: rotate(0deg);
}
</code>```

`

Body:
I would like to create a top offcanvas with Boostrap using my custom button that rotates (not icons) but I cannot do this because the rotation disappears and I would like it to be visibile while opening the offcanvas.
When I click on the button it remains fixed without rotating and the same happens in the offcanvas.
How could I do that?
This is my code

`

                <button class="navbar-toggler collapsed d-flex d-lg-none flex-column justify-content-around" type="button" data-bs-toggle="offcanvas"
                    data-bs-target="#offcanvasNavbarLight" aria-controls="offcanvasNavbarLight" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                        <button type="button" class="navbar-toggler ms-auto" data-bs-dismiss="offcanvas" aria-label="Close">

                        </button>

                                Home

                                Skills

                                Projects

                                Contact

`

`

.navbar-toggler {
  width: 27px;
  height: 30px;
  position: relative;
  transition: 0.5s ease-in-out;
}

.toggler-icon {
  display: block;
  position: absolute;
  height: 2px;
  width: 100%;
  background: #2E2E2F;
  border-radius: 10px;
  opacity: 1;
  left: 0;
  transform: rotate(0deg);
  transition: 0.25s ease-in-out;
}

.middle-bar {
  margin-top: 0em;
}

/* When navigation is clicked */
span.toggler-icon.top-bar {
  margin-top: 0em;
  transform: rotate(45deg);
}

span.toggler-icon.middle-bar {
  opacity: 0;
  filter: alpha(opacity=0);
}

span.toggler-icon.bottom-bar {
  margin-top: 0px;
  transform: rotate(-45deg);
}

/* State when the navbar is collapsed */
.navbar-toggler.collapsed .top-bar {
  margin-top: -16px;
  transform: rotate(0deg);
}

.navbar-toggler.collapsed .middle-bar {
  opacity: 1;
  filter: alpha(opacity=100);
}

.navbar-toggler.collapsed .bottom-bar {
  margin-top: 16px;
  transform: rotate(0deg);
}

`


问:
Is it possible to have dynamic margin with Nivo line chart?
I have a React project where I use @nivo/line to build a line chart.
I see that I could specify the margin of the chart using props of the nivo component.
But if I set the margin to 0 I can't see the ticks and legends.

I wonder if there's a way to have dynamic margins according to ticks and legends.

My code :

```<code><ResponsiveLine
      areaOpacity={0.1}
      axisBottom={{
        orient: 'bottom',
        tickSize: 8,
        tickPadding: 8,
        tickRotation: 0,
        tickValues: 'every month',
      }}
      axisLeft={{
        orient: 'left',
        tickSize: 8,
        tickPadding: 8,
        tickRotation: 0,
      }}
      axisRight={null}
      axisTop={null}
      curve="monotoneX"
      data={data}
      enableArea
      enableGridX={false}
      enablePoints={false}
      lineWidth={2}
      margin={{ top: 32, right: 56, bottom: 32, left: 56 }} // TODO: check if possible to have dynamic margins
      motionConfig="default"
      useMesh
      xFormat={`time:${iso8601Format}`}
      xScale={{ type: 'time', format: iso8601Format }}
      yScale={{
        type: 'linear',
        min: 0,
        max: 'auto',
        stacked: true,
        reverse: false,
      }}
    />
</code>```

I tried to set the margin to "auto" but it didn't work (the chart went blank).

Body:
I have a React project where I use @nivo/line to build a line chart.
I see that I could specify the margin of the chart using props of the nivo component.
But if I set the margin to 0 I can't see the ticks and legends.

I wonder if there's a way to have dynamic margins according to ticks and legends.

My code :

<ResponsiveLine
      areaOpacity={0.1}
      axisBottom={{
        orient: 'bottom',
        tickSize: 8,
        tickPadding: 8,
        tickRotation: 0,
        tickValues: 'every month',
      }}
      axisLeft={{
        orient: 'left',
        tickSize: 8,
        tickPadding: 8,
        tickRotation: 0,
      }}
      axisRight={null}
      axisTop={null}
      curve="monotoneX"
      data={data}
      enableArea
      enableGridX={false}
      enablePoints={false}
      lineWidth={2}
      margin={{ top: 32, right: 56, bottom: 32, left: 56 }} // TODO: check if possible to have dynamic margins
      motionConfig="default"
      useMesh
      xFormat={`time:${iso8601Format}`}
      xScale={{ type: 'time', format: iso8601Format }}
      yScale={{
        type: 'linear',
        min: 0,
        max: 'auto',
        stacked: true,
        reverse: false,
      }}
    />

I tried to set the margin to "auto" but it didn't work (the chart went blank).


问:
Google App Engine instance being restarted
I have a java app deployed to GCP App Engine with a jar. I tested with a load testing framework to generate steady state 100 QPS of traffic. I have also set the maximum instance count to 1. I am following the automatic scaling.

When I go to "instances" page, it says "This instance is being restarted" all the time. But all requests are succeeding.

Why is the instance being restarted while serving requests?

How do I know the cause for this restart?


问:
Why having Issues when calling Model data into Controller to view?
I'm a beginner at Codigniter4. I'm just wondering "Am I missing something or my Code has some kind of problem?" Please check my code below, if anybody can help me to solve this issues I will be so glad full. I'm having the warning "Whoops! We seem to have hit a snag. Please try again later...".

Router.php

```<code>$routes->get('/country', 'CountryController::index');
</code>```

CountryController.php

```<code>namespace App\Controllers;
use App\Models\CountryModel;
class CountryController extends BaseController{

public function index()
{
$country = new CountryModel();
    $data['country'] = $country->findAll();
    return view('country/index.php', $data);
}}
</code>```

CountryModel.php

```<code>namespace App\Models;
use CodeIgniter\Model;
class CountryModel extends Model{

protected $table = 'country';
protected $primaryKey = 'id';
protected $allowedFields= [
    'countryName',
    'countryFlag'
];}
</code>```

index.php

```<code>print_r($country);
</code>```

Body:
I'm a beginner at Codigniter4. I'm just wondering "Am I missing something or my Code has some kind of problem?" Please check my code below, if anybody can help me to solve this issues I will be so glad full. I'm having the warning "Whoops! We seem to have hit a snag. Please try again later...".

Router.php

$routes->get('/country', 'CountryController::index');

CountryController.php

namespace App\Controllers;
use App\Models\CountryModel;
class CountryController extends BaseController{

public function index()
{
$country = new CountryModel();
    $data['country'] = $country->findAll();
    return view('country/index.php', $data);
}}

CountryModel.php

namespace App\Models;
use CodeIgniter\Model;
class CountryModel extends Model{

protected $table = 'country';
protected $primaryKey = 'id';
protected $allowedFields= [
    'countryName',
    'countryFlag'
];}

index.php

print_r($country);


问:
What is the best practice to wrap up VNRecognizeTextRequest usage?

Problem

I have a simple yet weird function that returns errors through completion and throw.

func recognize(text: String,
                      in imageURL: URL,
                      completion: @escaping (Result<[VNRecognizedTextObservation], Error>) -> Void) throws {
    guard let image = NSImage(contentsOf: imageURL),
    let cgImage = image.cgImage else {
        throw PTError.general("无法处理图片 " + imageURL.path)
    }

    let imageRequestHandler = VNImageRequestHandler(cgImage: cgImage, orientation: .up)
    let size = CGSize(width: cgImage.width, height: cgImage.height)

    let request = VNRecognizeTextRequest { request, error in
        if let e = error {
            completion(.failure(e))
        }
        else if let results = request.results as? [VNRecognizedTextObservation] {
            completion(.success(results))
        }
        else {
            completion(.failure(PTError.general("ImageRecognition 未知错误")))
        }
    }

    request.recognitionLevel = .accurate
    request.recognitionLanguages = ["zh-Hans"]

    try imageRequestHandler.perform([request])
}
```
<p>Why?</p>
<p>Because VNRecognizeTextRequest.init is declared like this</p>
<pre class="lang-swift prettyprint-override"><code>typealias VNRequestCompletionHandler = (VNRequest, Error?) -> Void
init(completionHandler: VNRequestCompletionHandler?)
</code>```

So I cant throw inside its completionHandler. And then I have to

try imageRequestHandler.perform([request])
```
<p>So I need to add "throws" to my function declaration.</p>
<p><em><strong>Is it normal in Swift or am I missing something?</strong></em></p>
<h3>Possible Solution</h3>
<p>The only way I could think about is to replace all</p>
<pre class="lang-swift prettyprint-override"><code>throw PTError.general("errorMessage")
</code>```

with

completion(.failure(PTError.general("errorMessage")))
```
<p>And catch errors asap</p>
<pre class="lang-swift prettyprint-override"><code>do {
    try imageRequestHandler.perform([request])
}
catch let error {
    completion(.failure(error))
}
</code>```

The function now becomes

func recognize(text: String,
               in imageURL: URL,
               completion: @escaping (Result<[VNRecognizedTextObservation], Error>) -> Void) {
    guard let image = NSImage(contentsOf: imageURL),
          let cgImage = image.cgImage else {
        completion(.failure(PTError.general("无法处理图片 " + imageURL.path)))
        return
    }

    let imageRequestHandler = VNImageRequestHandler(cgImage: cgImage, orientation: .up)
    let size = CGSize(width: cgImage.width, height: cgImage.height)

    let request = VNRecognizeTextRequest { request, error in
        if let e = error {
            completion(.failure(e))
        }
        else if let results = request.results as? [VNRecognizedTextObservation] {
            completion(.success(results))
        }
        else {
            completion(.failure(PTError.general("ImageRecognition 未知错误")))
        }
    }

    request.recognitionLevel = .accurate
    request.recognitionLanguages = ["zh-Hans"]

    do {
        try imageRequestHandler.perform([request])
    }
    catch let error {
        completion(.failure(error))
    }
}
```

Still tedious.

Body:
Problem

I have a simple yet weird function that returns errors through completion and throw.

func recognize(text: String,
                      in imageURL: URL,
                      completion: @escaping (Result<[VNRecognizedTextObservation], Error>) -> Void) throws {
    guard let image = NSImage(contentsOf: imageURL),
    let cgImage = image.cgImage else {
        throw PTError.general("无法处理图片 " + imageURL.path)
    }

    let imageRequestHandler = VNImageRequestHandler(cgImage: cgImage, orientation: .up)
    let size = CGSize(width: cgImage.width, height: cgImage.height)

    let request = VNRecognizeTextRequest { request, error in
        if let e = error {
            completion(.failure(e))
        }
        else if let results = request.results as? [VNRecognizedTextObservation] {
            completion(.success(results))
        }
        else {
            completion(.failure(PTError.general("ImageRecognition 未知错误")))
        }
    }

    request.recognitionLevel = .accurate
    request.recognitionLanguages = ["zh-Hans"]

    try imageRequestHandler.perform([request])
}

Why?

Because VNRecognizeTextRequest.init is declared like this

typealias VNRequestCompletionHandler = (VNRequest, Error?) -> Void
init(completionHandler: VNRequestCompletionHandler?)

So I cant throw inside its completionHandler. And then I have to

try imageRequestHandler.perform([request])

So I need to add "throws" to my function declaration.

Is it normal in Swift or am I missing something?

Possible Solution

The only way I could think about is to replace all

throw PTError.general("errorMessage")

with

completion(.failure(PTError.general("errorMessage")))

And catch errors asap

do {
    try imageRequestHandler.perform([request])
}
catch let error {
    completion(.failure(error))
}

The function now becomes

func recognize(text: String,
               in imageURL: URL,
               completion: @escaping (Result<[VNRecognizedTextObservation], Error>) -> Void) {
    guard let image = NSImage(contentsOf: imageURL),
          let cgImage = image.cgImage else {
        completion(.failure(PTError.general("无法处理图片 " + imageURL.path)))
        return
    }

    let imageRequestHandler = VNImageRequestHandler(cgImage: cgImage, orientation: .up)
    let size = CGSize(width: cgImage.width, height: cgImage.height)

    let request = VNRecognizeTextRequest { request, error in
        if let e = error {
            completion(.failure(e))
        }
        else if let results = request.results as? [VNRecognizedTextObservation] {
            completion(.success(results))
        }
        else {
            completion(.failure(PTError.general("ImageRecognition 未知错误")))
        }
    }

    request.recognitionLevel = .accurate
    request.recognitionLanguages = ["zh-Hans"]

    do {
        try imageRequestHandler.perform([request])
    }
    catch let error {
        completion(.failure(error))
    }
}

Still tedious.


问:
MySQL SELECT MIN and MAX RIGHT JOIN numeric value of the last 30 days
I need a query to return the initial and final numeric value of the number of listeners of some artists of the last 30 days ordered from the highest increase of listeners to the lowest.

To better understand what I mean, here are the tables involved.

artist table saves the information of a Spotify artist.

id
name
Spotify_id

1
Shakira
0EmeFodog0BfCgMzAIvKQp

2
Bizarrap
716NhGYqD1jl2wI1Qkgq36

platform_information table save the information that I want to get from the artists and on which platform.

id
platform
information

1
spotify
monthly_listeners

2
spotify
followers

platform_information_artist table stores information for each artist on a platform and information on a specific date.

id
platform_information_id
artist_id
date
value

1
1
1
2022-11-01
100000

2
1
1
2022-11-15
101000

3
1
1
2022-11-30
102000

4
1
2
2022-11-02
85000

5
1
2
2022-11-06
90000

6
1
2
2022-11-26
100000

Right now have this query:

```<code>
SELECT (SELECT value
        FROM platform_information_artist
        WHERE artist_id = 1
          AND platform_information_id =
              (SELECT id from platform_information WHERE platform = 'spotify' AND information = 'monthly_listeners')
          AND DATE(date) >= DATE(NOW()) - INTERVAL 30 DAY
        ORDER BY date ASC
        LIMIT 1)                        as month_start,
       (SELECT value
        FROM platform_information_artist
        WHERE artist_id = 1
          AND platform_information_id =
              (SELECT id from platform_information WHERE platform = 'spotify' AND information = 'monthly_listeners')
          AND DATE(date) >= DATE(NOW()) - INTERVAL 30 DAY
        ORDER BY date DESC
        LIMIT 1)                        as month_end,
       (SELECT month_end - month_start) as diference
ORDER BY month_start;
</code>```

Which returns the following:

month_start
month_end
difference

100000
102000
2000

The problem is that this query only returns the artist I specify.

And I need the information like this:

artist_id
name
platform_information_id
month_start_value
month_end_value
difference

2
Bizarrap
1
85000
100000
15000

1
Shakira
1
100000
102000
2000

The query should return the 5 artists that have grown the most in number of monthly listeners over the last 30 days, along with the starting value 30 days ago, and the current value.

Thanks for the help.

Body:
I need a query to return the initial and final numeric value of the number of listeners of some artists of the last 30 days ordered from the highest increase of listeners to the lowest.

To better understand what I mean, here are the tables involved.

artist table saves the information of a Spotify artist.

id
name
Spotify_id

1
Shakira
0EmeFodog0BfCgMzAIvKQp

2
Bizarrap
716NhGYqD1jl2wI1Qkgq36

platform_information table save the information that I want to get from the artists and on which platform.

id
platform
information

1
spotify
monthly_listeners

2
spotify
followers

platform_information_artist table stores information for each artist on a platform and information on a specific date.

id
platform_information_id
artist_id
date
value

1
1
1
2022-11-01
100000

2
1
1
2022-11-15
101000

3
1
1
2022-11-30
102000

4
1
2
2022-11-02
85000

5
1
2
2022-11-06
90000

6
1
2
2022-11-26
100000

Right now have this query:

SELECT (SELECT value
        FROM platform_information_artist
        WHERE artist_id = 1
          AND platform_information_id =
              (SELECT id from platform_information WHERE platform = 'spotify' AND information = 'monthly_listeners')
          AND DATE(date) >= DATE(NOW()) - INTERVAL 30 DAY
        ORDER BY date ASC
        LIMIT 1)                        as month_start,
       (SELECT value
        FROM platform_information_artist
        WHERE artist_id = 1
          AND platform_information_id =
              (SELECT id from platform_information WHERE platform = 'spotify' AND information = 'monthly_listeners')
          AND DATE(date) >= DATE(NOW()) - INTERVAL 30 DAY
        ORDER BY date DESC
        LIMIT 1)                        as month_end,
       (SELECT month_end - month_start) as diference
ORDER BY month_start;

Which returns the following:

month_start
month_end
difference

100000
102000
2000

The problem is that this query only returns the artist I specify.

And I need the information like this:

artist_id
name
platform_information_id
month_start_value
month_end_value
difference

2
Bizarrap
1
85000
100000
15000

1
Shakira
1
100000
102000
2000

The query should return the 5 artists that have grown the most in number of monthly listeners over the last 30 days, along with the starting value 30 days ago, and the current value.

Thanks for the help.


问:
Generated .wasm file contains an "import" that prohibits it from being used in Worker's thread
I've created a Rust lib with wasm-bindgen, compiled it to WASM using wasm-pack, and am trying to import it inside an AudioWorkletProcessor's thread.

On my main thread, I fetch the file and pass the resulting buffer to the Worker:

const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("./my-custom-audio-processor.js");
const my-custom-audio-processorHandle = new AudioWorkletNode(
    audioContext,
    "my-custom-audio-processor"
);

WebAssembly.compileStreaming(fetch('./my-wasm-lib_bg.wasm')).then(async compiledModule => {
    my-custom-audio-processorHandle.port.postMessage({
        compiledModule,
    });
});
```
<p>Inside the Worker's thread, we have this:</p>
<pre class="lang-js prettyprint-override"><code>this.port.onmessage = async event => {
    const instance = await WebAssembly.instantiate(event.data.compiledModule, /* here's the problem */);
}
</code>```

The problem is that the WASM file specifies an import, which is one of the.js file that got generated along with it:

```<code>(import "./my-wasm-lib_bg.js" "__wbindgen_throw" (func (;0;) (type 0)))
</code>```

This is the object it expects me to pass as the .instantiate() method's second argument:

let imports = {};
imports['./my-wasm-lib_bg.js'] = require('my-wasm-lib/my-wasm-lib_bg.js');
```

However, this only works if I run .instantiate() from the main thread. If I try these last lines above inside the Worker's thread, I get that "require is not defined".
Passing the instance to the Worker's thread doesn't work either, nor does passing the require function.

Is there any configuration I can use to avoid that line from going into my WASM lib? Or is there any way to call "require" from within the Worker's thread?

Body:
I've created a Rust lib with wasm-bindgen, compiled it to WASM using wasm-pack, and am trying to import it inside an AudioWorkletProcessor's thread.

On my main thread, I fetch the file and pass the resulting buffer to the Worker:

const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("./my-custom-audio-processor.js");
const my-custom-audio-processorHandle = new AudioWorkletNode(
    audioContext,
    "my-custom-audio-processor"
);

WebAssembly.compileStreaming(fetch('./my-wasm-lib_bg.wasm')).then(async compiledModule => {
    my-custom-audio-processorHandle.port.postMessage({
        compiledModule,
    });
});

Inside the Worker's thread, we have this:

this.port.onmessage = async event => {
    const instance = await WebAssembly.instantiate(event.data.compiledModule, /* here's the problem */);
}

The problem is that the WASM file specifies an import, which is one of the.js file that got generated along with it:

(import "./my-wasm-lib_bg.js" "__wbindgen_throw" (func (;0;) (type 0)))

This is the object it expects me to pass as the .instantiate() method's second argument:

let imports = {};
imports['./my-wasm-lib_bg.js'] = require('my-wasm-lib/my-wasm-lib_bg.js');

However, this only works if I run .instantiate() from the main thread. If I try these last lines above inside the Worker's thread, I get that "require is not defined".
Passing the instance to the Worker's thread doesn't work either, nor does passing the require function.

Is there any configuration I can use to avoid that line from going into my WASM lib? Or is there any way to call "require" from within the Worker's thread?


问:
Identify Graph nodes belonging to a clique (Max clique problem with Python constraints api)
I am trying to solve the max clique problem using Python's constraints api and I am planning to use the MIP-model, where there is a boolean for each n[i] node indicating if the node belongs (1 / true), or not (0 / false), to a clique.
The constraint I will add is that for each not connected nodes pair i + j, n[i] + n[j] <=1, because these could only be set to 1 if they were connected.
Then to indentify the clique's size, I will calculate the sum of all the node variables, and maximize this measure.

What I am not sure about is this:
How do I identify if a node belongs to a clique or not? If I don't know this, then how can I even begin to use the logic above?


问:
How to import selected fields from matlab struct into Simulink?
I have a .mat file containing a struct with a bunch of data (about 80 fields, each thousands of rows long). I also have a simulink model to process some of the data. Is there a way to import only some of the fields of the struct into simulink? (That is, the data from a specific field would go into an inport or something that allows me to process it as a signal). I only need about 8 of the fields, not all 80 of them.

I thought about using a timetable but then I read that that requires there to be a single column of data so that wouldn't work as I would have multiple columns, each representing a different signal/variable.


问:
How do I use the break after the item is added?
If the items in the itemsSold array in the customer's product are null, I want to add the 'car' element and exit the loop with break.

let customer = [{
    active: true,
    product: {
      itemSold: [null, null],
      purchasedItems: []
    },
  },
  {
    active: true,
    product: {
      itemSold: [null, null],
      purchasedItems: []
    },
  },
];

let itemSold = ["car", "home"];
let purchasedItems = ["phone", "computer"];

for (let i = 0; i < customer.length; i++) {
  //What should i write?
  if (customer[i].product["itemSold"] === null) {
    break;
  }
}```


问:
How can i handle JWT Tokens in my application
I'm a full time systems engineering student and i have a project that i've hit a bumped on the road, i'm handling right now all the users state with sessions and i would like to implement the JWT token for more "security", the application is a 2 part app (Api's = backend in one solution, Frontend in another solution)

Have to mention, I'm using C# in VS 2022 with asp.net .Net framework 4.7.2

The code architechture is MVC.

Here is my code

This is in the Users Model:

```<code>public string GetToken(Guid Id)
    {
        try
        {
            var key = ConfigurationManager.AppSettings["JwtKey"];

            var issuer = ConfigurationManager.AppSettings["JwtIssuer"];

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            //Create a List of Claims, Keep claims name short
            var permClaims = new List<Claim>();
            permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            permClaims.Add(new Claim("userid", "Id"));

            //Create Security Token object by giving required parameters
            var token = new JwtSecurityToken(issuer, //Issure
                            issuer,  //Audience
                            permClaims,
                            expires: DateTime.Now.AddDays(1),
                            signingCredentials: credentials);
            var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);
            return jwt_token;
        }
        catch(Exception ex)
        {
            return string.Empty;
        }

    }
</code>```

Once i get this token i include it in the Users object response and i'm able to see it in the front end response, i'm able to see the information being returned succesfully, I'm storing this data in a session variable.

this is my LogIn Controller:

```<code>[HttpPost]
        public ActionResult ValidateUser(Users User)
        {

            if (User.noHashPass != null && User.Username != null)
            {
                var datos = model.ValidateUser(User);

                var tok = datos.User;

                if (datos != null)
                {

                    Session["User"] = new Users();
                    Session["User"] = datos.User;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    return ViewBag.Msj = "¡ERROR! El usuario o la contraseña son incorrectos. Por favor intente de nuevo."; ;
                }
            }
            else
            {
                ViewBag.Msj = "¡ERROR! El usuario o la contraseña son incorrectos. Por favor intente de nuevo.";

            }
            return View();

        }
</code>```

i was trying to do this to extract just the token piece in the users model:

```<code>public Respuesta ViewUserById(Guid Id)
        {

            using (var client = new HttpClient())
            {
                try
                {
                    object sesion = new Users();
                    sesion = HttpContext.Current.Session["User"];

                    string api = "Users/ViewUserById?Id=" + Id;
                    string route = Url + api;

                    HttpResponseMessage response = client.GetAsync(route).Result;

                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        var responseBody = response.Content.ReadAsAsync<Respuesta>().Result; //serializacion del obj JSON a un objeto
                        return responseBody;
                    }
                    else
                    {
                        throw new Exception("No se encontro un usuario existente bajo el Id:" + " " + Id);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
        }
</code>```

But the sesion variable only gives me a ToString() function, i can see the sesion variable filling up and getting all the data but i cannot handle it for example, sesion.Token to get the Token inside the session variable.

Any suggestions are appreciated.

How can i handle the session variable in order to get the data within?

Body:
I'm a full time systems engineering student and i have a project that i've hit a bumped on the road, i'm handling right now all the users state with sessions and i would like to implement the JWT token for more "security", the application is a 2 part app (Api's = backend in one solution, Frontend in another solution)

Have to mention, I'm using C# in VS 2022 with asp.net .Net framework 4.7.2

The code architechture is MVC.

Here is my code

This is in the Users Model:

public string GetToken(Guid Id)
    {
        try
        {
            var key = ConfigurationManager.AppSettings["JwtKey"];

            var issuer = ConfigurationManager.AppSettings["JwtIssuer"];

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            //Create a List of Claims, Keep claims name short
            var permClaims = new List<Claim>();
            permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            permClaims.Add(new Claim("userid", "Id"));

            //Create Security Token object by giving required parameters
            var token = new JwtSecurityToken(issuer, //Issure
                            issuer,  //Audience
                            permClaims,
                            expires: DateTime.Now.AddDays(1),
                            signingCredentials: credentials);
            var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);
            return jwt_token;
        }
        catch(Exception ex)
        {
            return string.Empty;
        }

    }

Once i get this token i include it in the Users object response and i'm able to see it in the front end response, i'm able to see the information being returned succesfully, I'm storing this data in a session variable.

this is my LogIn Controller:

[HttpPost]
        public ActionResult ValidateUser(Users User)
        {

            if (User.noHashPass != null && User.Username != null)
            {
                var datos = model.ValidateUser(User);

                var tok = datos.User;

                if (datos != null)
                {

                    Session["User"] = new Users();
                    Session["User"] = datos.User;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    return ViewBag.Msj = "¡ERROR! El usuario o la contraseña son incorrectos. Por favor intente de nuevo."; ;
                }
            }
            else
            {
                ViewBag.Msj = "¡ERROR! El usuario o la contraseña son incorrectos. Por favor intente de nuevo.";

            }
            return View();

        }

i was trying to do this to extract just the token piece in the users model:

public Respuesta ViewUserById(Guid Id)
        {

            using (var client = new HttpClient())
            {
                try
                {
                    object sesion = new Users();
                    sesion = HttpContext.Current.Session["User"];

                    string api = "Users/ViewUserById?Id=" + Id;
                    string route = Url + api;

                    HttpResponseMessage response = client.GetAsync(route).Result;

                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        var responseBody = response.Content.ReadAsAsync<Respuesta>().Result; //serializacion del obj JSON a un objeto
                        return responseBody;
                    }
                    else
                    {
                        throw new Exception("No se encontro un usuario existente bajo el Id:" + " " + Id);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
        }

But the sesion variable only gives me a ToString() function, i can see the sesion variable filling up and getting all the data but i cannot handle it for example, sesion.Token to get the Token inside the session variable.

Any suggestions are appreciated.

How can i handle the session variable in order to get the data within?


问:
Cannot visualize the points around one of the selected points in point cloud. Not sure what I am missing
I used this code. What it does is just takes a pointcloud and convert it into polydata and visualize it. After visualizing the pointcloud, I use mouse to select one point and calculate points around that particular point in a given radius. I am able to calculate those points but not able to visualize those. Also moving further I select 1000 random points in data and calculate their clusters too, calculate Hausdorff  distances of each with original cluster and visualize the minimum distance cluster. In all this I am not able to visualize any cluster.`

```<code>import vtk
import numpy as np
import open3d as o3d
import math
from numpy import random
from scipy.spatial.distance import directed_hausdorff

import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkIdTypeArray
from vtkmodules.vtkCommonDataModel import (
    vtkSelection,
    vtkSelectionNode,
    vtkUnstructuredGrid
)
from vtkmodules.vtkFiltersCore import vtkTriangleFilter
from vtkmodules.vtkFiltersExtraction import vtkExtractSelection
from vtkmodules.vtkFiltersSources import vtkPlaneSource
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera
from vtkmodules.vtkRenderingCore import (
    vtkActor,
    vtkCellPicker,
    vtkDataSetMapper,
    vtkPolyDataMapper,
    vtkRenderWindow,
    vtkRenderWindowInteractor,
    vtkRenderer
)

class VtkPointCloud:

    def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=2e6):
        # c = vtkNamedColors()
        self.maxNumPoints = maxNumPoints
        self.vtkPolyData = vtk.vtkPolyData()
        self.clearPoints()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.vtkPolyData)
        mapper.SetColorModeToDefault()
        mapper.SetScalarRange(zMin, zMax)
        mapper.SetScalarVisibility(1)
        self.vtkActor = vtk.vtkActor()
        # self.vtkActor.GetProperty().SetColor(1,1,1)
        # self.vtkActor.GetProperty().SetColor(c.GetColor3d('Yellow'))
        self.vtkActor.SetMapper(mapper)

    def addPoint(self, point):
        if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
            pointId = self.vtkPoints.InsertNextPoint(point[:])
            self.vtkDepth.InsertNextValue(point[2])
            self.vtkCells.InsertNextCell(1)
            self.vtkCells.InsertCellPoint(pointId)
        else:
            r = random.randint(0, self.maxNumPoints)
            self.vtkPoints.SetPoint(r, point[:])
        self.vtkCells.Modified()
        self.vtkPoints.Modified()
        self.vtkDepth.Modified()

    def clearPoints(self):
        self.vtkPoints = vtk.vtkPoints()
        self.vtkCells = vtk.vtkCellArray()
        self.vtkDepth = vtk.vtkDoubleArray()
        self.vtkDepth.SetName('DepthArray')
        self.vtkPolyData.SetPoints(self.vtkPoints)
        self.vtkPolyData.SetVerts(self.vtkCells)
        self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
        self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray')

# Catch mouse events
class MouseInteractorStyle(vtkInteractorStyleTrackballCamera):
    def __init__(self, data):
        self.AddObserver('LeftButtonPressEvent', self.left_button_press_event)
        self.AddObserver('RightButtonPressEvent', self.right_button_press_event)
        self.data = data
        self.selected_mapper = vtkDataSetMapper()
        self.selected_actor = vtkActor()

        self.selected_mapper2 = vtkDataSetMapper()
        self.selected_actor2 = vtkActor()

        self.vtk_list = vtk.vtkIdList()
        self.locator = vtk.vtkPointLocator()
        self.locator.SetDataSet(self.data)
        self.locator.BuildLocator()

        self.colors = vtkNamedColors()
    def left_button_press_event(self, obj, event):

        pos = self.GetInteractor().GetEventPosition()

        picker = vtkCellPicker()
        picker.SetTolerance(0.001)

        # Pick from this location.
        picker.Pick(pos[0], pos[1], 0, self.GetDefaultRenderer())

        world_position = picker.GetPickPosition()
        print(f'Cell id is: {picker.GetCellId()}')

        # print(world_position)

        self.locator.FindPointsWithinRadius(0.02,world_position, self.vtk_list)
        print(self.vtk_list)

        if picker.GetCellId() != -1:
            print(f'Pick position is: ({world_position[0]:.6g}, {world_position[1]:.6g}, {world_position[2]:.6g})')

            ids = vtkIdTypeArray()
            ids.SetNumberOfComponents(1)
            ids.InsertNextValue(picker.GetCellId())
            # print(ids,'\n')

            selection_node = vtkSelectionNode()
            selection_node.SetFieldType(vtkSelectionNode.CELL)
            selection_node.SetContentType(vtkSelectionNode.INDICES)
            selection_node.SetSelectionList(ids)

            selection = vtkSelection()
            selection.AddNode(selection_node)

            extract_selection = vtkExtractSelection()
            extract_selection.SetInputData(0, self.data)
            extract_selection.SetInputData(1, selection)
            extract_selection.Update()

            # In selection
            selected = vtkUnstructuredGrid()
            selected.ShallowCopy(extract_selection.GetOutput())

            print(f'Number of points in the selection: {selected.GetNumberOfPoints()}')
            # print(f'Number of cells in the selection : {selected.GetNumberOfCells()}\n')

            print('########################\n')

            self.selected_mapper.SetInputData(selected)
            self.selected_actor.SetMapper(self.selected_mapper)
            # self.selected_actor.GetProperty().EdgeVisibilityOn()
            self.selected_actor.GetProperty().SetColor(self.colors.GetColor3d('Black'))
            self.selected_actor.GetProperty().SetPointSize(10)
            self.selected_actor.GetProperty().SetLineWidth(3)
            # print(self.selected_actor)

            self.GetInteractor().GetRenderWindow().GetRenderers().GetFirstRenderer().AddActor(self.selected_actor)

        # Forward events
        self.OnLeftButtonDown()

    def right_button_press_event(self, obj, event):

        if self.vtk_list.GetNumberOfIds() == 0:
            return
        else:
            ids2 = vtkIdTypeArray()
            ids2.SetNumberOfComponents(1)
            for i in range(self.vtk_list.GetNumberOfIds()):
                # print(i)
                ids2.InsertNextValue(i)
            # print(ids2)
            selection_node2 = vtkSelectionNode()
            selection_node2.SetFieldType(vtkSelectionNode.CELL)
            selection_node2.SetContentType(vtkSelectionNode.INDICES)
            selection_node2.SetSelectionList(ids2)

            selection2 = vtkSelection()
            selection2.AddNode(selection_node2)

            extract_selection2 = vtkExtractSelection()
            extract_selection2.SetInputData(0, self.data)
            extract_selection2.SetInputData(1, selection2)
            extract_selection2.Update()

    #         # In selection

            selected2 = vtkUnstructuredGrid()
            selected2.ShallowCopy(extract_selection2.GetOutput())

            print(f'Number of neighboring points: {selected2.GetNumberOfPoints()}')
    #         # print(f'Number of neighboring cells: {selected2.GetNumberOfCells()}\n')
            print('########################\n')

            self.selected_mapper2.SetInputData(selected2)
            self.selected_actor2.SetMapper(self.selected_mapper2)
            # self.selected_actor.GetProperty().EdgeVisibilityOn()
            self.selected_actor2.GetProperty().SetColor(self.colors.GetColor3d("tan"))
            self.selected_actor2.GetProperty().SetPointSize(10)
            self.selected_actor2.GetProperty().SetLineWidth(3)
            # print(self.selected_actor2)

            self.GetInteractor().GetRenderWindow().GetRenderers().GetFirstRenderer().AddActor(self.selected_actor2)

            print('Randomly Selecting 1000 points in the data........')
            point_indices = []
            cluster_points = np.zeros((self.vtk_list.GetNumberOfIds(),3))
            # print(cluster_points)
            print('Calculating the clusters around the centers ......')
            for i in range(self.vtk_list.GetNumberOfIds()):

                point_indices.append(self.vtk_list.GetId(i))

                cluster_points[i]=pointCloud.vtkPolyData.GetPoint(self.vtk_list.GetId(i))

            point_indices = np.asarray(point_indices)

            new_points= np.delete(points,point_indices, axis=0)

            random_array = np.random.randint(0,new_points.shape[0],(1000))

            min_haus = 1000000000.0
            for i in range(random_array.shape[0]):
                new_list=vtk.vtkIdList()
                new_center = new_points[random_array[i]]
            #     print('new center to find cluster:',new_center)
                self.locator.FindPointsWithinRadius(0.02,new_center, new_list)
                new_cluster_points = np.zeros((new_list.GetNumberOfIds(),3))
                for x in range(new_list.GetNumberOfIds()):
                    new_cluster_points[x]=pointCloud.vtkPolyData.GetPoint(new_list.GetId(x))
                    haus = directed_hausdorff(cluster_points,new_cluster_points)[0]
                    if haus<min_haus:
                        min_haus = haus
                        idx = random_array[i]
                        min_center = new_points[random_array[i]]

                # print('haus:',haus)
            print('min haus:',min_haus)
            print('idx of min haus:',idx)
            print('center of the min haus cluster:',min_center)

            min_list = vtk.vtkIdList()
            self.locator.FindPointsWithinRadius(0.02,min_center, min_list)
            print('Min list for min center', min_list)

    #     # Forward events
        self.OnRightButtonDown()

# Initialize point clouds
pointCloud = VtkPointCloud()

pointCloud2 = VtkPointCloud()
# print(type(pointCloud))

# Loading Point cloud using open3d
pt_cloud = o3d.io.read_point_cloud('fused_cloud_normal.ply')
points = np.asarray(pt_cloud.points)

pt_cloud2 = o3d.io.read_point_cloud('all_projected_pts.ply')
points2 = np.asarray(pt_cloud2.points)

# Adding the points into polydata
for row in points:
    pointCloud.addPoint(row)

for row in points2:
    pointCloud2.addPoint(row)

# Intialize actor
c = vtkNamedColors()
actor = pointCloud.vtkActor
actor.GetProperty().SetPointSize(10)
actor.GetProperty().SetColor(c.GetColor3d('Yellow'))

# actor.GetProperty().SetColor(0,0,0)
# Renderer
renderer = vtk.vtkRenderer()
renderer.AddActor(actor)
# renderer.AddActor(pointCloud2.vtkActor)
renderer.SetBackground(.1, .1, .4)
renderer.ResetCamera()

# Render Window
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)

style = MouseInteractorStyle(pointCloud.vtkPolyData)
style.SetDefaultRenderer(renderer)

# Interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderWindowInteractor.SetInteractorStyle(style)

# Begin Interaction
renderWindow.Render()
renderWindowInteractor.Start()
</code>```

`

Body:
I used this code. What it does is just takes a pointcloud and convert it into polydata and visualize it. After visualizing the pointcloud, I use mouse to select one point and calculate points around that particular point in a given radius. I am able to calculate those points but not able to visualize those. Also moving further I select 1000 random points in data and calculate their clusters too, calculate Hausdorff  distances of each with original cluster and visualize the minimum distance cluster. In all this I am not able to visualize any cluster.`

import vtk
import numpy as np
import open3d as o3d
import math
from numpy import random
from scipy.spatial.distance import directed_hausdorff

import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkIdTypeArray
from vtkmodules.vtkCommonDataModel import (
    vtkSelection,
    vtkSelectionNode,
    vtkUnstructuredGrid
)
from vtkmodules.vtkFiltersCore import vtkTriangleFilter
from vtkmodules.vtkFiltersExtraction import vtkExtractSelection
from vtkmodules.vtkFiltersSources import vtkPlaneSource
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera
from vtkmodules.vtkRenderingCore import (
    vtkActor,
    vtkCellPicker,
    vtkDataSetMapper,
    vtkPolyDataMapper,
    vtkRenderWindow,
    vtkRenderWindowInteractor,
    vtkRenderer
)

class VtkPointCloud:

    def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=2e6):
        # c = vtkNamedColors()
        self.maxNumPoints = maxNumPoints
        self.vtkPolyData = vtk.vtkPolyData()
        self.clearPoints()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.vtkPolyData)
        mapper.SetColorModeToDefault()
        mapper.SetScalarRange(zMin, zMax)
        mapper.SetScalarVisibility(1)
        self.vtkActor = vtk.vtkActor()
        # self.vtkActor.GetProperty().SetColor(1,1,1)
        # self.vtkActor.GetProperty().SetColor(c.GetColor3d('Yellow'))
        self.vtkActor.SetMapper(mapper)

    def addPoint(self, point):
        if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
            pointId = self.vtkPoints.InsertNextPoint(point[:])
            self.vtkDepth.InsertNextValue(point[2])
            self.vtkCells.InsertNextCell(1)
            self.vtkCells.InsertCellPoint(pointId)
        else:
            r = random.randint(0, self.maxNumPoints)
            self.vtkPoints.SetPoint(r, point[:])
        self.vtkCells.Modified()
        self.vtkPoints.Modified()
        self.vtkDepth.Modified()

    def clearPoints(self):
        self.vtkPoints = vtk.vtkPoints()
        self.vtkCells = vtk.vtkCellArray()
        self.vtkDepth = vtk.vtkDoubleArray()
        self.vtkDepth.SetName('DepthArray')
        self.vtkPolyData.SetPoints(self.vtkPoints)
        self.vtkPolyData.SetVerts(self.vtkCells)
        self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
        self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray')

# Catch mouse events
class MouseInteractorStyle(vtkInteractorStyleTrackballCamera):
    def __init__(self, data):
        self.AddObserver('LeftButtonPressEvent', self.left_button_press_event)
        self.AddObserver('RightButtonPressEvent', self.right_button_press_event)
        self.data = data
        self.selected_mapper = vtkDataSetMapper()
        self.selected_actor = vtkActor()

        self.selected_mapper2 = vtkDataSetMapper()
        self.selected_actor2 = vtkActor()

        self.vtk_list = vtk.vtkIdList()
        self.locator = vtk.vtkPointLocator()
        self.locator.SetDataSet(self.data)
        self.locator.BuildLocator()

        self.colors = vtkNamedColors()
    def left_button_press_event(self, obj, event):

        pos = self.GetInteractor().GetEventPosition()

        picker = vtkCellPicker()
        picker.SetTolerance(0.001)

        # Pick from this location.
        picker.Pick(pos[0], pos[1], 0, self.GetDefaultRenderer())

        world_position = picker.GetPickPosition()
        print(f'Cell id is: {picker.GetCellId()}')

        # print(world_position)

        self.locator.FindPointsWithinRadius(0.02,world_position, self.vtk_list)
        print(self.vtk_list)

        if picker.GetCellId() != -1:
            print(f'Pick position is: ({world_position[0]:.6g}, {world_position[1]:.6g}, {world_position[2]:.6g})')

            ids = vtkIdTypeArray()
            ids.SetNumberOfComponents(1)
            ids.InsertNextValue(picker.GetCellId())
            # print(ids,'\n')

            selection_node = vtkSelectionNode()
            selection_node.SetFieldType(vtkSelectionNode.CELL)
            selection_node.SetContentType(vtkSelectionNode.INDICES)
            selection_node.SetSelectionList(ids)

            selection = vtkSelection()
            selection.AddNode(selection_node)

            extract_selection = vtkExtractSelection()
            extract_selection.SetInputData(0, self.data)
            extract_selection.SetInputData(1, selection)
            extract_selection.Update()

            # In selection
            selected = vtkUnstructuredGrid()
            selected.ShallowCopy(extract_selection.GetOutput())

            print(f'Number of points in the selection: {selected.GetNumberOfPoints()}')
            # print(f'Number of cells in the selection : {selected.GetNumberOfCells()}\n')

            print('########################\n')

            self.selected_mapper.SetInputData(selected)
            self.selected_actor.SetMapper(self.selected_mapper)
            # self.selected_actor.GetProperty().EdgeVisibilityOn()
            self.selected_actor.GetProperty().SetColor(self.colors.GetColor3d('Black'))
            self.selected_actor.GetProperty().SetPointSize(10)
            self.selected_actor.GetProperty().SetLineWidth(3)
            # print(self.selected_actor)

            self.GetInteractor().GetRenderWindow().GetRenderers().GetFirstRenderer().AddActor(self.selected_actor)

        # Forward events
        self.OnLeftButtonDown()

    def right_button_press_event(self, obj, event):

        if self.vtk_list.GetNumberOfIds() == 0:
            return
        else:
            ids2 = vtkIdTypeArray()
            ids2.SetNumberOfComponents(1)
            for i in range(self.vtk_list.GetNumberOfIds()):
                # print(i)
                ids2.InsertNextValue(i)
            # print(ids2)
            selection_node2 = vtkSelectionNode()
            selection_node2.SetFieldType(vtkSelectionNode.CELL)
            selection_node2.SetContentType(vtkSelectionNode.INDICES)
            selection_node2.SetSelectionList(ids2)

            selection2 = vtkSelection()
            selection2.AddNode(selection_node2)

            extract_selection2 = vtkExtractSelection()
            extract_selection2.SetInputData(0, self.data)
            extract_selection2.SetInputData(1, selection2)
            extract_selection2.Update()

    #         # In selection

            selected2 = vtkUnstructuredGrid()
            selected2.ShallowCopy(extract_selection2.GetOutput())

            print(f'Number of neighboring points: {selected2.GetNumberOfPoints()}')
    #         # print(f'Number of neighboring cells: {selected2.GetNumberOfCells()}\n')
            print('########################\n')

            self.selected_mapper2.SetInputData(selected2)
            self.selected_actor2.SetMapper(self.selected_mapper2)
            # self.selected_actor.GetProperty().EdgeVisibilityOn()
            self.selected_actor2.GetProperty().SetColor(self.colors.GetColor3d("tan"))
            self.selected_actor2.GetProperty().SetPointSize(10)
            self.selected_actor2.GetProperty().SetLineWidth(3)
            # print(self.selected_actor2)

            self.GetInteractor().GetRenderWindow().GetRenderers().GetFirstRenderer().AddActor(self.selected_actor2)

            print('Randomly Selecting 1000 points in the data........')
            point_indices = []
            cluster_points = np.zeros((self.vtk_list.GetNumberOfIds(),3))
            # print(cluster_points)
            print('Calculating the clusters around the centers ......')
            for i in range(self.vtk_list.GetNumberOfIds()):

                point_indices.append(self.vtk_list.GetId(i))

                cluster_points[i]=pointCloud.vtkPolyData.GetPoint(self.vtk_list.GetId(i))

            point_indices = np.asarray(point_indices)

            new_points= np.delete(points,point_indices, axis=0)

            random_array = np.random.randint(0,new_points.shape[0],(1000))

            min_haus = 1000000000.0
            for i in range(random_array.shape[0]):
                new_list=vtk.vtkIdList()
                new_center = new_points[random_array[i]]
            #     print('new center to find cluster:',new_center)
                self.locator.FindPointsWithinRadius(0.02,new_center, new_list)
                new_cluster_points = np.zeros((new_list.GetNumberOfIds(),3))
                for x in range(new_list.GetNumberOfIds()):
                    new_cluster_points[x]=pointCloud.vtkPolyData.GetPoint(new_list.GetId(x))
                    haus = directed_hausdorff(cluster_points,new_cluster_points)[0]
                    if haus<min_haus:
                        min_haus = haus
                        idx = random_array[i]
                        min_center = new_points[random_array[i]]

                # print('haus:',haus)
            print('min haus:',min_haus)
            print('idx of min haus:',idx)
            print('center of the min haus cluster:',min_center)

            min_list = vtk.vtkIdList()
            self.locator.FindPointsWithinRadius(0.02,min_center, min_list)
            print('Min list for min center', min_list)

    #     # Forward events
        self.OnRightButtonDown()

# Initialize point clouds
pointCloud = VtkPointCloud()

pointCloud2 = VtkPointCloud()
# print(type(pointCloud))

# Loading Point cloud using open3d
pt_cloud = o3d.io.read_point_cloud('fused_cloud_normal.ply')
points = np.asarray(pt_cloud.points)

pt_cloud2 = o3d.io.read_point_cloud('all_projected_pts.ply')
points2 = np.asarray(pt_cloud2.points)

# Adding the points into polydata
for row in points:
    pointCloud.addPoint(row)

for row in points2:
    pointCloud2.addPoint(row)

# Intialize actor
c = vtkNamedColors()
actor = pointCloud.vtkActor
actor.GetProperty().SetPointSize(10)
actor.GetProperty().SetColor(c.GetColor3d('Yellow'))

# actor.GetProperty().SetColor(0,0,0)
# Renderer
renderer = vtk.vtkRenderer()
renderer.AddActor(actor)
# renderer.AddActor(pointCloud2.vtkActor)
renderer.SetBackground(.1, .1, .4)
renderer.ResetCamera()

# Render Window
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)

style = MouseInteractorStyle(pointCloud.vtkPolyData)
style.SetDefaultRenderer(renderer)

# Interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderWindowInteractor.SetInteractorStyle(style)

# Begin Interaction
renderWindow.Render()
renderWindowInteractor.Start()

`