Title: SVG icon does not display on the homepage of my iPhone but it shows on all other pages and shows on iPad and desktops homepage

Body:
I'm hoping someone can help with this. I have a marquee banner on my website and for some odd reason it does not show up on the homepage of my website when viewing it from my iPhone. I shows up on desktops, and iPad homepage. I have added the code below.No modifications have been made to it by me.

<svg width="768" height="285" viewBox="0 0 768 285" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0)">
<path d="M19.53 227.27L26.19 281.53H259.36L251.73 219.39H143.01L142.06 211.69L242.19 141.72L235.5 87.3601H2.34998L9.97998 149.49H118.88L119.83 157.26L19.53 227.27Z" fill="black"/>
<path d="M262.59 87.3601L286.44 281.53H519.78L495.93 87.3601H262.59Z" fill="#AA8FFF"/>
<path d="M764.47 157.26C759.09 113.62 724.81 87.1701 678.21 87.3601H523L546.84 281.54H616.67L611.89 242.7H685.78C743.93 242.69 770.54 206.46 764.47 157.26ZM678.23 188.26L605.23 188.34L599.51 141.74L672.92 141.8C690.18 142.01 699.01 151.73 700.44 165.03C701.32 173.59 697.4 188.25 678.23 188.25V188.26Z" fill="black"/>
<path d="M332.303 61.5598C344.584 48.3762 342.443 26.4212 327.522 12.522C312.601 -1.37727 290.549 -1.95741 278.269 11.2262C265.988 24.4098 268.129 46.3647 283.05 60.264C297.971 74.1632 320.023 74.7434 332.303 61.5598Z" fill="black"/>
</g>
<defs>
<clipPath id="clip0">
<rect width="768" height="285" fill="white"/>
</clipPath>
</defs>
</svg>

I tried changing the width and height of the icon but it did not work. I even hired someone on Fiverr and he couldn't figure it out.


来源: stackexchange

问:
Creating a trigger on [msdb].[dbo].restorehistory
I have a requirement to update or change the values of some fields in specific tables when someone restores a Prod database to a Test environment. I just want to change for example 'PROD' characters to 'Test' characters in certain fields once a database have been restored from Prod to Test environment. I have just created a small DB with two tables only and a trigger on [msdb].[dbo].restorehistory table, backed up the sample DB to simulate the scenario. But whenever I try restore there is nothing happening on the trigger.

From the below this is what I tried but it seems not working. It looks like the trigger is not hit when there is an [INSERT] event to the table[restorehistory].

```<code>USE [msdb]
GO
/****** Object:  Trigger [dbo].[TriggerA]    Script Date: 12/24/2022 8:22:59 PM ******/

CREATE TRIGGER [dbo].[TriggerA]
ON [msdb].[dbo].[restorehistory]
FOR INSERT
AS

DECLARE @DatabaseName AS VARCHAR(100)

SELECT @DatabaseName = DESTINATION_DATABASE_NAME
FROM INSERTED

IF @DatabaseName='TestDB'

BEGIN
    UPDATE [TestDB].[dbo].<TABLE_X>
        SET FIELD_A     = REPLACE(FIELD_A,'_character_to_replace_','_replace_with_this_character_'),
            FIELD_B     = REPLACE(FIELD_B,'_character_to_replace_','_replace_with_this_character_')
        WHERE
            FIELD_A LIKE '%_character_to_replace_%'

END
</code>```

Please advise if there is something I'm doing wrong or if there is any better alternative.

ContentLicense: CC BY-SA 4.0

Body:
I have a requirement to update or change the values of some fields in specific tables when someone restores a Prod database to a Test environment. I just want to change for example 'PROD' characters to 'Test' characters in certain fields once a database have been restored from Prod to Test environment. I have just created a small DB with two tables only and a trigger on [msdb].[dbo].restorehistory table, backed up the sample DB to simulate the scenario. But whenever I try restore there is nothing happening on the trigger.

From the below this is what I tried but it seems not working. It looks like the trigger is not hit when there is an [INSERT] event to the table[restorehistory].

USE [msdb]
GO
/****** Object:  Trigger [dbo].[TriggerA]    Script Date: 12/24/2022 8:22:59 PM ******/

CREATE TRIGGER [dbo].[TriggerA]
ON [msdb].[dbo].[restorehistory]
FOR INSERT
AS

DECLARE @DatabaseName AS VARCHAR(100)

SELECT @DatabaseName = DESTINATION_DATABASE_NAME
FROM INSERTED

IF @DatabaseName='TestDB'

BEGIN
    UPDATE [TestDB].[dbo].<TABLE_X>
        SET FIELD_A     = REPLACE(FIELD_A,'_character_to_replace_','_replace_with_this_character_'),
            FIELD_B     = REPLACE(FIELD_B,'_character_to_replace_','_replace_with_this_character_')
        WHERE
            FIELD_A LIKE '%_character_to_replace_%'

END

Please advise if there is something I'm doing wrong or if there is any better alternative.


问:
Is it possible to rerun the same querySelector once DOM elements have changed?
I have a calendar that logs the event date, title and description of an event created through an event form. This data is stored within the cell of the day it was logged (the date as an ID and event title as a text node). When the button is pressed, a modal is presented with all of this information.

To fetch the information of each event previously logged, I'm using a querySelectAll method to fetch all the ID's and adding an event listener to them. This event listener converts the ID of each cell to Unix time, and if a button is present on the cell (created with the form), to display the modal described above.

While this works to each cell on the starting month, any navigation to a month forward or previous to it does not display any of this information inside the modal.

I suspect it is because my queryselector is only gathering the cells present when the page loads, but is not 'reloading' once new cells are presented on the page.

How could this be made to work? is there a way to rerun this same querySelector once my DOM elements have changed? and if not, is there a way to rerun a .js script once a navigation button is pressed?

Below is my block of code I would like to run each time a month navigation button is pressed:

```<code>  document.querySelectorAll("[id*='date']")
.forEach(e => e.addEventListener("click", function () {
    //fixing the time
    var time = e.id
    var timeFixed = time.replace(/\D/g, "")
    console.log(timeFixed)

    //getting and logging the event title
    var eventText = e.querySelector('#titleText')
    if (eventText != null) {
        console.log('first Child', eventText.textContent)
    }
    if (eventText == null) {
        return
    }

    //get the event title
    body = $('#modalHead').text('Title: ' + eventText.textContent)

    //header append to modal
    header = $('#modalDate').text('Date: ' + new Date(parseInt(timeFixed)).toLocaleDateString('en-US'));

    //description append to modal
    var descEvent = e.querySelector('#descText')
    if (descEvent.textContent != null) {
        desc = $('#modalDesc').text('Description: ' + descEvent.textContent)
        console.log('description', descEvent.textContent)
    }
    if (descEvent.textContent == null) {
        body = $('#modalHead').text('Title: ' + eventText.textContent)
    }
}))
</code>```

I have tried to implement this code block as a function that can be called once my button is pressed, however I ran into problems trying to make the event targets work. I also tried to fit this code block into a setinterval() every second, but scrapped the idea as I imagine this would be incredibly inefficient.

Body:
I have a calendar that logs the event date, title and description of an event created through an event form. This data is stored within the cell of the day it was logged (the date as an ID and event title as a text node). When the button is pressed, a modal is presented with all of this information.

To fetch the information of each event previously logged, I'm using a querySelectAll method to fetch all the ID's and adding an event listener to them. This event listener converts the ID of each cell to Unix time, and if a button is present on the cell (created with the form), to display the modal described above.

While this works to each cell on the starting month, any navigation to a month forward or previous to it does not display any of this information inside the modal.

I suspect it is because my queryselector is only gathering the cells present when the page loads, but is not 'reloading' once new cells are presented on the page.

How could this be made to work? is there a way to rerun this same querySelector once my DOM elements have changed? and if not, is there a way to rerun a .js script once a navigation button is pressed?

Below is my block of code I would like to run each time a month navigation button is pressed:

  document.querySelectorAll("[id*='date']")
.forEach(e => e.addEventListener("click", function () {
    //fixing the time
    var time = e.id
    var timeFixed = time.replace(/\D/g, "")
    console.log(timeFixed)

    //getting and logging the event title
    var eventText = e.querySelector('#titleText')
    if (eventText != null) {
        console.log('first Child', eventText.textContent)
    }
    if (eventText == null) {
        return
    }

    //get the event title
    body = $('#modalHead').text('Title: ' + eventText.textContent)

    //header append to modal
    header = $('#modalDate').text('Date: ' + new Date(parseInt(timeFixed)).toLocaleDateString('en-US'));

    //description append to modal
    var descEvent = e.querySelector('#descText')
    if (descEvent.textContent != null) {
        desc = $('#modalDesc').text('Description: ' + descEvent.textContent)
        console.log('description', descEvent.textContent)
    }
    if (descEvent.textContent == null) {
        body = $('#modalHead').text('Title: ' + eventText.textContent)
    }
}))

I have tried to implement this code block as a function that can be called once my button is pressed, however I ran into problems trying to make the event targets work. I also tried to fit this code block into a setinterval() every second, but scrapped the idea as I imagine this would be incredibly inefficient.


问:
Composing SwiftUI Views and Delegating the Delete Operation
I am creating a small sample app, where I display a list of items. I have composed the app with several different views as shown below:

```<code>   struct ItemCellView: View {

        let item: Item
        let onDelete: (Item) -> Void

        var body: some View {
            HStack {
                Text(item.name)
                Spacer()
                Image(systemName: "trash")
                    .onTapGesture {
                       onDelete(item)
                    }
            }
        }
    }

   struct ItemListView: View {

    let items: [Item]
    @EnvironmentObject private var model: Model

    var body: some View {
        List(items, id: \.id) { item in
            ItemCellView(item: item, onDelete: {
                model.deleteItem(id: $0.id)
            })
        }
    }
}

    struct ContentView: View {

        @EnvironmentObject private var model: Model

        var body: some View {
            ItemListView(items: model.items)
        }
    }
</code>```

The model is defined below:

```<code>struct Item {
    let id = UUID()
    let name: String
}

class Model: ObservableObject {

    @Published var items: [Item] = [Item(name: "A"), Item(name: "B"), Item(name: "C"), Item(name: "D")]

    func deleteItem(id: UUID) {
        items = items.filter { $0.id != id }
    }

}
</code>```

My question is that how can I make sure that my views ItemListView and ItemCellView are reusable. Currently, I am deleting the item in ItemListView which makes it less reusable. I can add another closure in ItemListView and then transfer the control to ContentView but that seems like a lot of work.

How would you accomplish the deletion task which this view hierarchy?

Body:
I am creating a small sample app, where I display a list of items. I have composed the app with several different views as shown below:

   struct ItemCellView: View {

        let item: Item
        let onDelete: (Item) -> Void

        var body: some View {
            HStack {
                Text(item.name)
                Spacer()
                Image(systemName: "trash")
                    .onTapGesture {
                       onDelete(item)
                    }
            }
        }
    }

   struct ItemListView: View {

    let items: [Item]
    @EnvironmentObject private var model: Model

    var body: some View {
        List(items, id: \.id) { item in
            ItemCellView(item: item, onDelete: {
                model.deleteItem(id: $0.id)
            })
        }
    }
}

    struct ContentView: View {

        @EnvironmentObject private var model: Model

        var body: some View {
            ItemListView(items: model.items)
        }
    }

The model is defined below:

struct Item {
    let id = UUID()
    let name: String
}

class Model: ObservableObject {

    @Published var items: [Item] = [Item(name: "A"), Item(name: "B"), Item(name: "C"), Item(name: "D")]

    func deleteItem(id: UUID) {
        items = items.filter { $0.id != id }
    }

}

My question is that how can I make sure that my views ItemListView and ItemCellView are reusable. Currently, I am deleting the item in ItemListView which makes it less reusable. I can add another closure in ItemListView and then transfer the control to ContentView but that seems like a lot of work.

How would you accomplish the deletion task which this view hierarchy?


问:
I want to install repast4py, how to install repast4py in windows 10?
I want to install repast4py in windows10, But when I enter 'pip install repast4py' in cmd, It displays the error "MPI compiler is not specified. Please specify the MPI compiler using the 'cc' environment variable"
Thanks for the Answer.
cmd picture

I install mpi4py with 'pip install mpi4py' in windows10, and it installed, but when in python, I recall MPI from mpi4py, It gives an error.
error for import MPI


问:
aws python cdk: how to solve constructs version conflict (trying to create httpapi)
Goal (quite simple, or at least I thought so):

Returning HTML-Content from a lambda for a web browser.

Defining it with python aws cdk

As far as I understand it, I've got to put my lambda into an HttpLambdaIntegration which I can use in a route added to my HttpApi

Here is the example:

```<code>from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration

# books_default_fn: lambda.Function

books_integration = HttpLambdaIntegration("BooksIntegration", books_default_fn)

http_api = apigwv2.HttpApi(self, "HttpApi")

http_api.add_routes(
    path="/books",
    methods=[apigwv2.HttpMethod.GET],
    integration=books_integration
)
</code>```

https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_apigatewayv2_integrations/README.html

So far I found:

HttpLambdaIntegration here: https://pypi.org/project/aws-cdk.aws-apigatewayv2-integrations/

HttpApi here: https://pypi.org/project/aws-cdk.aws-apigatewayv2-alpha/#defining-http-apis

But I can`t install both because of a version clash:

The conflict is caused by:

aws-cdk-lib 2.56.1 depends on constructs<11.0.0 and >=10.0.0

aws-cdk-aws-apigatewayv2-alpha 2.56.1a0 depends on constructs<11.0.0
and >=10.0.0

aws-cdk-aws-apigatewayv2-integrations 1.184.1 depends on
constructs<4.0.0 and >=3.3.69

Am I using the wrong packages? Or am I on the wrong track anyway? The version mash up is quite confusing in the whole...

UPDATE (A few days later)

Ok, good news: I got it running ... but I switched to Typescript, following this example: https://bobbyhadz.com/blog/aws-cdk-http-api-apigateway-v2-example

And I still had to install using npm with --force, which always makes me more or less unhappy, but at least I could and it works.

I've come now to the conclusion, that I can't really recommend the python aws cdk. This is at least the third time I tried, and at least the third time I ran into trouble ...  There are just a lot more typescript examples!

Body:
Goal (quite simple, or at least I thought so):

Returning HTML-Content from a lambda for a web browser.

Defining it with python aws cdk

As far as I understand it, I've got to put my lambda into an HttpLambdaIntegration which I can use in a route added to my HttpApi

Here is the example:

from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration

# books_default_fn: lambda.Function

books_integration = HttpLambdaIntegration("BooksIntegration", books_default_fn)

http_api = apigwv2.HttpApi(self, "HttpApi")

http_api.add_routes(
    path="/books",
    methods=[apigwv2.HttpMethod.GET],
    integration=books_integration
)

https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_apigatewayv2_integrations/README.html

So far I found:

HttpLambdaIntegration here: https://pypi.org/project/aws-cdk.aws-apigatewayv2-integrations/

HttpApi here: https://pypi.org/project/aws-cdk.aws-apigatewayv2-alpha/#defining-http-apis

But I can`t install both because of a version clash:

The conflict is caused by:

aws-cdk-lib 2.56.1 depends on constructs<11.0.0 and >=10.0.0

aws-cdk-aws-apigatewayv2-alpha 2.56.1a0 depends on constructs<11.0.0
and >=10.0.0

aws-cdk-aws-apigatewayv2-integrations 1.184.1 depends on
constructs<4.0.0 and >=3.3.69

Am I using the wrong packages? Or am I on the wrong track anyway? The version mash up is quite confusing in the whole...

UPDATE (A few days later)

Ok, good news: I got it running ... but I switched to Typescript, following this example: https://bobbyhadz.com/blog/aws-cdk-http-api-apigateway-v2-example

And I still had to install using npm with --force, which always makes me more or less unhappy, but at least I could and it works.

I've come now to the conclusion, that I can't really recommend the python aws cdk. This is at least the third time I tried, and at least the third time I ran into trouble ...  There are just a lot more typescript examples!


问:
Is there a way to change the URL from an iframe with Livewire?
So far, this is my solution, and it works, but I think its a bit dirty...

I have a select that uses symbol variable to show a chart on an iframe:

```<code>      <select
        wire:model="symbol"
        id="symbol"
        class="w-full px-2 py-1 rounded-md"
        onchange="changeSymbol()"
        >
</code>```

The chart URL is something as: /chart/SYMBOL_VALUE

So far, I haven't been able to alter the URL using Livewire (using the wire:model and a updatedSymbol() function), so I had to use that changeSymbol() javascript function, that goes like:

```<code><script>
  const changeSymbol = () => {
    const sym = document.getElementById("symbol").value
    const graf = document.getElementById("graf")
    graf.innerHTML = `<iframe
      src="/chart/${sym}"
      height="100%"
      width="100%"
      ></iframe>
    `
  }
</script>
</code>```

Yeah... sure, this works, but I don't like it, it looks to me as a patchy solution. Is there a way to change the URL of an iframe inside livewire, and make it to load the inner page you want?

Body:
So far, this is my solution, and it works, but I think its a bit dirty...

I have a select that uses symbol variable to show a chart on an iframe:

      <select
        wire:model="symbol"
        id="symbol"
        class="w-full px-2 py-1 rounded-md"
        onchange="changeSymbol()"
        >

The chart URL is something as: /chart/SYMBOL_VALUE

So far, I haven't been able to alter the URL using Livewire (using the wire:model and a updatedSymbol() function), so I had to use that changeSymbol() javascript function, that goes like:

Yeah... sure, this works, but I don't like it, it looks to me as a patchy solution. Is there a way to change the URL of an iframe inside livewire, and make it to load the inner page you want?


问:
NextAuth Provider + custom username - Initial relation in a database
I am using Nextjs, NextAuth, and Prisma.

What is the correct method for connecting a custom username to a user's initial nextAuth provider-sign-up in my database?

I am using the Email Provider which just requires a user to type in their email so they can receive a sign-in link in their email. The 'user' doesn't get created in the database until the link is clicked in the email inbox so I can't add a mutation to add a username to their userid in the database until AFTER the user creates their account.

Do I attach the username as a payload in the JWT? Does nextAuth allow for this?


问:
Running a shell script can print all the output on a hyper terminal while running the corresponding python script can’t on an Ubuntu host terminal
I used a Hyper terminal such as GTKTerm to run a shell script ./test.sh (whose shell commands act on a hardware board) and it displays ALL the desired outputs on GTKTerm screen, and then I converted ./test.sh to a python script and ran it on a host Ubuntu terminal via a UART port like below

```<code>ser = serial.Serial('/dev/ttyUSB0', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=5)

ser.write(b"./test.sh\n")
</code>```

My question is – when the size of ./test.sh becomes bigger and bigger, I can still observe the entire output on the GTKTerm terminal after running ./test.sh, but running the converted python script (such as running python3 test.py or  python3 test.py > test.txt), can’t see the same whole output as running ./test.sh on GTKTerm when the size of ./test.sh reaches to a threshold value.

I tried to fix this issue using such as python3 -u ..., print function with flush argument, various flush commands related to UART, .... Unfortunately, I didn't solve this issue. Could anyone kindly tell me the reasons? Thank you!!

Body:
I used a Hyper terminal such as GTKTerm to run a shell script ./test.sh (whose shell commands act on a hardware board) and it displays ALL the desired outputs on GTKTerm screen, and then I converted ./test.sh to a python script and ran it on a host Ubuntu terminal via a UART port like below

ser = serial.Serial('/dev/ttyUSB0', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=5)

ser.write(b"./test.sh\n")

My question is – when the size of ./test.sh becomes bigger and bigger, I can still observe the entire output on the GTKTerm terminal after running ./test.sh, but running the converted python script (such as running python3 test.py or  python3 test.py > test.txt), can’t see the same whole output as running ./test.sh on GTKTerm when the size of ./test.sh reaches to a threshold value.

I tried to fix this issue using such as python3 -u ..., print function with flush argument, various flush commands related to UART, .... Unfortunately, I didn't solve this issue. Could anyone kindly tell me the reasons? Thank you!!


问:
Im getting an error with my agora implementation after i updated my packages
Im getting an error with agora rtc engine, i updated my packages and since then ive had this error (The function 'SurfaceView' isn't defined. Try importing the library that defines 'SurfaceView', correcting the name to the name of an existing function, or defining a function named 'SurfaceView'.). Please anyone help.

this is how im calling the import statements:

```<code>import 'package:agora_rtc_engine/agora_rtc_engine.dart' as RtcLocalView;
import 'package:agora_rtc_engine/agora_rtc_engine.dart' as RtcRemoteView;
</code>```

and this is where im making use of it

```<code>Widget _getRenderViews() {
    if (widget.isBroadcaster!) {
      return RtcLocalView.SurfaceView(); // error with the surfaceview
    } else {
      return RtcRemoteView.SurfaceView( // error with the surfaceview
        uid: widget.mUser!.getUid!,
        channelId: widget.channelName!,
      );
    }
  }
</code>```

Body:
Im getting an error with agora rtc engine, i updated my packages and since then ive had this error (The function 'SurfaceView' isn't defined. Try importing the library that defines 'SurfaceView', correcting the name to the name of an existing function, or defining a function named 'SurfaceView'.). Please anyone help.

this is how im calling the import statements:

import 'package:agora_rtc_engine/agora_rtc_engine.dart' as RtcLocalView;
import 'package:agora_rtc_engine/agora_rtc_engine.dart' as RtcRemoteView;

and this is where im making use of it

Widget _getRenderViews() {
    if (widget.isBroadcaster!) {
      return RtcLocalView.SurfaceView(); // error with the surfaceview
    } else {
      return RtcRemoteView.SurfaceView( // error with the surfaceview
        uid: widget.mUser!.getUid!,
        channelId: widget.channelName!,
      );
    }
  }


问:
Best approach for storing elements in C# that have within epsilon definition of equality
The program uses vertices in R^2 as nodes and there are edges between nodes, and ultimately more is built from there. There are a high number of circuitous ways that a point (x,y) in R^2 might be reached that may rely on layer after layer of trig functions. So it makes sense to define one vertex as the canonical vertex for all points in a square with side length 2*epsilon centered at the point. So various calculations happen, out comes a point (x,y) where I wish to put a vertex, a vertex factory checks to see if there is already vertex deemed as canonical that should be used for this point, if so it returns that vertex, if not a new vertex is created with the coordinates of the point and that vertex is now deemed canonical. I know this can lead to ambiguities given the possibility for overlap of the squares but that is immaterial for the moment, epsilon can be set to make the probability of such a case vanishingly small.

Clearly a list of canonical vertices must be kept.

I have working implementations using List<Vertex> and HashSet<Vertex>, however the vertex creation process seems to scale poorly when the number of vertices grows to over over 100,000 and incredibly poorly if the number gets anywhere near 1,000,000.

I have no idea how to efficiently implement the VertexFactory. Right now Vertex has method IsEquivalentTo(Vertex v) and returns true if v is contained in the square around the instance vertex calling it, false otherwise.

So the the vertex creation process looks like this:

Some point (x,y) get calculated and requests a new vertex from the vertex manager.

VertexManager creates a temporary vertex temp then uses a foreach to iterate over every vertex in the container using IsEquivalentTo(temp) to find a match and return it, if no match is found then add temp to the container and return it. I should state that if a match is found obviously it breaks out of the foreach loop.

I may be way off but my first guess would be put an order on the vertices such as

v1 < v2 iff ( (v1.X < v2.X) || ( (v1.X == v2.X) && (v1.Y < v2.Y) ) )
```

and then store the vertices in a sorted container. But to be honest I do not know enough about about the various containers to know which is the most appropriate for the purpose, standard C# best practices, etc

Edit:

I cannot mark the comment as an answer so thanks to GSerg whose comment guided me to kd-trees. This is exactly what I was looking for.

Thanks

Body:
The program uses vertices in R^2 as nodes and there are edges between nodes, and ultimately more is built from there. There are a high number of circuitous ways that a point (x,y) in R^2 might be reached that may rely on layer after layer of trig functions. So it makes sense to define one vertex as the canonical vertex for all points in a square with side length 2*epsilon centered at the point. So various calculations happen, out comes a point (x,y) where I wish to put a vertex, a vertex factory checks to see if there is already vertex deemed as canonical that should be used for this point, if so it returns that vertex, if not a new vertex is created with the coordinates of the point and that vertex is now deemed canonical. I know this can lead to ambiguities given the possibility for overlap of the squares but that is immaterial for the moment, epsilon can be set to make the probability of such a case vanishingly small.

Clearly a list of canonical vertices must be kept.

I have working implementations using List<Vertex> and HashSet<Vertex>, however the vertex creation process seems to scale poorly when the number of vertices grows to over over 100,000 and incredibly poorly if the number gets anywhere near 1,000,000.

I have no idea how to efficiently implement the VertexFactory. Right now Vertex has method IsEquivalentTo(Vertex v) and returns true if v is contained in the square around the instance vertex calling it, false otherwise.

So the the vertex creation process looks like this:

Some point (x,y) get calculated and requests a new vertex from the vertex manager.

VertexManager creates a temporary vertex temp then uses a foreach to iterate over every vertex in the container using IsEquivalentTo(temp) to find a match and return it, if no match is found then add temp to the container and return it. I should state that if a match is found obviously it breaks out of the foreach loop.

I may be way off but my first guess would be put an order on the vertices such as

v1 < v2 iff ( (v1.X < v2.X) || ( (v1.X == v2.X) && (v1.Y < v2.Y) ) )

and then store the vertices in a sorted container. But to be honest I do not know enough about about the various containers to know which is the most appropriate for the purpose, standard C# best practices, etc

Edit:

I cannot mark the comment as an answer so thanks to GSerg whose comment guided me to kd-trees. This is exactly what I was looking for.

Thanks


问:
access localhost with smartphone and get no response from the server

website works via localhost on pc

access with smartphone to localhost via ip too (I receive html, css and js for client)

when I click the button, a "hi" is also added but function "search()" is not executed

but when I enter the url http://localhost:3000/users I get the "hi1"

What do i have to do to make this work?

Client Side

```<code>const button = document.querySelector("button");

button.addEventListener("click", () => {
    document.getElementById("imageDiv").innerHTML = "Hi";//this work
    search();//this not work
});

async function search(){
    await fetch("http://localhost:3000/users")
    .then(response => response.json())
    .then(response => {
        var image;
        image = JSON.parse(JSON.stringify(Object.assign({},response)));
        document.getElementById("imageDiv").innerHTML = response;
    })};
</code>```

Server Side

```<code>const express = require('express');
const bodyParser = require('body-parser');
const path = require("path"); // window or mac
const cors = require('cors');
const app = express();
const port = 3000;
//var word = "";
//const router = express.Router();

// configure CORS to avoid CORS errors
app.use(cors());

// configure body parser so we can read req.body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static('./client'));

app.get('/', (req, res) => {
    res.sendFile("./index.html");
});

app.get("/users", (req, res) => {
    datafiles = ["hi1"];
    res.json(datafiles);
    res.status(200);
});

app.listen(port, () => {
    console.log(`Server listening on http://localhost:${port}`);
});
</code>```

Body:
website works via localhost on pc

access with smartphone to localhost via ip too (I receive html, css and js for client)

when I click the button, a "hi" is also added but function "search()" is not executed

but when I enter the url http://localhost:3000/users I get the "hi1"

What do i have to do to make this work?

Client Side

const button = document.querySelector("button");

button.addEventListener("click", () => {
    document.getElementById("imageDiv").innerHTML = "Hi";//this work
    search();//this not work
});

async function search(){
    await fetch("http://localhost:3000/users")
    .then(response => response.json())
    .then(response => {
        var image;
        image = JSON.parse(JSON.stringify(Object.assign({},response)));
        document.getElementById("imageDiv").innerHTML = response;
    })};

Server Side

const express = require('express');
const bodyParser = require('body-parser');
const path = require("path"); // window or mac
const cors = require('cors');
const app = express();
const port = 3000;
//var word = "";
//const router = express.Router();

// configure CORS to avoid CORS errors
app.use(cors());

// configure body parser so we can read req.body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static('./client'));

app.get('/', (req, res) => {
    res.sendFile("./index.html");
});

app.get("/users", (req, res) => {
    datafiles = ["hi1"];
    res.json(datafiles);
    res.status(200);
});

app.listen(port, () => {
    console.log(`Server listening on http://localhost:${port}`);
});


问:
How to conditionally increment value depending on whether a subdocument exists in mongoose
I want to allow users to vote yes (+1) or no (-1) on a post document (field: voteCount). Their vote may only count once, however, they can change their vote from yes to no or no to yes.

To minimize database queries, I would like to write one query that looks to see whether the user has a vote record (field: voteRecord) and perform the following:

if false (no prior vote record by user), increment voteCount + or - 1 and add voteRecord

if true and the vote is the same as the most recent vote, no update to voteCount or voteRecord

if true and the vote is different from the most recent vote, update voteCount and add voteRecord

Here's the schemas:

```<code>const postSchema = new Schema({
    title: String,
    description: String,
    voteRecords: [voteCount],
    voteCount: { type: Number, default: 0 }
});

const voteRecords = new Schema({
    _partisan: { type: Schema.Types.ObjectId, ref: 'partisans' },
    _user: { type: Schema.Types.ObjectId, ref: 'users' },
    dateVoted: Date,
    value: String
});
</code>```

Here's how far I've got. The query updates the voteCount irregardless of whether a prior vote exists or not. I'm wondering if it is possible to add a condition on the $inc and $addToSet properties.

```<code>const vote = {
    _user: userId,
    voteValue,
    dateVoted: new Date()
}

Post.findByIdAndUpdate({
    _id: postId,
    vote: {
        $elemMatch: {
            _user: userId
        }
    }
},
{
    // increment yes or no by one
    $inc: { voteCount: voteValue },
    // add record of vote to subdoc
    $addToSet: { voteRecords }
},
{ upsert: true, new: true }
)
</code>```

Body:
I want to allow users to vote yes (+1) or no (-1) on a post document (field: voteCount). Their vote may only count once, however, they can change their vote from yes to no or no to yes.

To minimize database queries, I would like to write one query that looks to see whether the user has a vote record (field: voteRecord) and perform the following:

if false (no prior vote record by user), increment voteCount + or - 1 and add voteRecord

if true and the vote is the same as the most recent vote, no update to voteCount or voteRecord

if true and the vote is different from the most recent vote, update voteCount and add voteRecord

Here's the schemas:

const postSchema = new Schema({
    title: String,
    description: String,
    voteRecords: [voteCount],
    voteCount: { type: Number, default: 0 }
});

const voteRecords = new Schema({
    _partisan: { type: Schema.Types.ObjectId, ref: 'partisans' },
    _user: { type: Schema.Types.ObjectId, ref: 'users' },
    dateVoted: Date,
    value: String
});

Here's how far I've got. The query updates the voteCount irregardless of whether a prior vote exists or not. I'm wondering if it is possible to add a condition on the $inc and $addToSet properties.

const vote = {
    _user: userId,
    voteValue,
    dateVoted: new Date()
}

Post.findByIdAndUpdate({
    _id: postId,
    vote: {
        $elemMatch: {
            _user: userId
        }
    }
},
{
    // increment yes or no by one
    $inc: { voteCount: voteValue },
    // add record of vote to subdoc
    $addToSet: { voteRecords }
},
{ upsert: true, new: true }
)


问:
Bluetooth Low Energy with EXPO React-native
Expo Posted this https://expo.canny.io/feature-requests/p/bluetooth-1

Here is my code:https://github.com/kimmyyyyyyyyyyyyy/hello--world-

When I run react-native-ble-plx on my project, or even a Simple Hello World project, I get following error:

Unable to resolve module fs from /Users/user/Downloads/hello,-world!/node_modules/@config-plugins/react-native-ble-plx/node_modules/@expo/config-plugins/build/utils/XML.js: fs could not be found within the project or in these directories:

All I'm running on App.js is:

```<code>import {

BleError,

BleManager,

Characteristic,

Device,

} from '@config-plugins/react-native-ble-plx';

const bleManager = new BleManager();

console.log(bleManager);
</code>```

Any idea what this is and how to fix this?

I am trying to solve this error.

Body:
Expo Posted this https://expo.canny.io/feature-requests/p/bluetooth-1

Here is my code:https://github.com/kimmyyyyyyyyyyyyy/hello--world-

When I run react-native-ble-plx on my project, or even a Simple Hello World project, I get following error:

Unable to resolve module fs from /Users/user/Downloads/hello,-world!/node_modules/@config-plugins/react-native-ble-plx/node_modules/@expo/config-plugins/build/utils/XML.js: fs could not be found within the project or in these directories:

All I'm running on App.js is:

import {

BleError,

BleManager,

Characteristic,

Device,

} from '@config-plugins/react-native-ble-plx';

const bleManager = new BleManager();

console.log(bleManager);

Any idea what this is and how to fix this?

I am trying to solve this error.


问:
List online users and get total "talep" count each user
I have a table for Talepler and Yonetim. Now Each talepler has his own users. and each user is mapped to that talepler by a field called user id. So how i can print out online users with total count in Talepler table by Count(*) with Join query.

Here my code with helper function. But i want with join.

```<code> $this->db->select('yonetim.id, yonetim.user, yonetim.onoff');
 $this->db->from('yonetim');
 $this->db->where('yonetim.onoff',1);

 $query = $this->db->get();

 $datam = array();
 foreach ($query->result() as $data) {
     $count = checkIfuserMax($data->id);
     if($talepsay < 10 ) {
     $datam[] = array(
         'id' => $data->id,
         'user' => $data->user,
         'onoff' => $data->onoff,
         'toplamtalep' => $count
     );
     }
 }

 echo json_encode($datam);
</code>```

and here my helper function

```<code>function checkIfuserMax($id) {
     $ci =& get_instance();
     $ci->db->select('COUNT(*) as toplam');
     $ci->db->where(array( 'hangiadmin' => $id, 'onaylayan' => null));
     $ci->db->from('talepler');
     $query = $ci->db->get();
     $result = $query->result();
     return $result[0]->toplam;
}
</code>```

Finally here my json result

```<code>[
  {
    "id": "1",
    "user": "user1",
    "onoff": "1",
    "toplamtalep": "13"
  },
  {
    "id": "2",
    "user": "user2",
    "onoff": "1",
    "toplamtalep": "0"
  },
  {
    "id": "4",
    "user": "user3",
    "onoff": "1",
    "toplamtalep": "2"
  },
  {
    "id": "173",
    "user": "user4",
    "onoff": "1",
    "toplamtalep": "6"
  }
]
</code>```

This code working properly. But i want to make this same result with "JOIN" query. Could you please help me about this query?

Body:
I have a table for Talepler and Yonetim. Now Each talepler has his own users. and each user is mapped to that talepler by a field called user id. So how i can print out online users with total count in Talepler table by Count(*) with Join query.

Here my code with helper function. But i want with join.

 $this->db->select('yonetim.id, yonetim.user, yonetim.onoff');
 $this->db->from('yonetim');
 $this->db->where('yonetim.onoff',1);

 $query = $this->db->get();

 $datam = array();
 foreach ($query->result() as $data) {
     $count = checkIfuserMax($data->id);
     if($talepsay < 10 ) {
     $datam[] = array(
         'id' => $data->id,
         'user' => $data->user,
         'onoff' => $data->onoff,
         'toplamtalep' => $count
     );
     }
 }

 echo json_encode($datam);

and here my helper function

function checkIfuserMax($id) {
     $ci =& get_instance();
     $ci->db->select('COUNT(*) as toplam');
     $ci->db->where(array( 'hangiadmin' => $id, 'onaylayan' => null));
     $ci->db->from('talepler');
     $query = $ci->db->get();
     $result = $query->result();
     return $result[0]->toplam;
}

Finally here my json result

[
  {
    "id": "1",
    "user": "user1",
    "onoff": "1",
    "toplamtalep": "13"
  },
  {
    "id": "2",
    "user": "user2",
    "onoff": "1",
    "toplamtalep": "0"
  },
  {
    "id": "4",
    "user": "user3",
    "onoff": "1",
    "toplamtalep": "2"
  },
  {
    "id": "173",
    "user": "user4",
    "onoff": "1",
    "toplamtalep": "6"
  }
]

This code working properly. But i want to make this same result with "JOIN" query. Could you please help me about this query?


问:
is there a way to hide a menu behind a div when closed with z-index
i want to hide that drop down menu when clicking the button above it using position and z-index
i did a animation so the menu goes up and with z-index hide it under the nav bar

before clicking

https://i.stack.imgur.com/QYs3t.png

after clicking

https://i.stack.imgur.com/GVmjY.png

```<code>.navBar{
    padding-left: 20px;
    height: 80px;
    float: left;
    width: calc(100% - 15%) ;
    display: flex;
    align-items: center;
    background-color: rgb(197, 18, 18);
    position: relative;

    z-index: 1;
}

.profileDropDown{
    position: absolute;
    width: 186px;
    height: 140px;
    /* border-left: 1px solid rgb(190, 190, 190); */
    background-color: white;
    right: 0px;
    /* bottom: -140px; */
    transition: 0.5s;
    z-index: -2;
    border-bottom: 1px solid rgb(190, 190, 190);
    overflow: hidden;
}
</code>```

the z-index of the drop down is smaller than the nav so i think it should be under the nav

the closing animation i did this

```<code>const toggle = () => {
    if (height === '-140px') {
      setHeight('0px')
    } else if (height === '0px') {
      setHeight('-140px')
    }
  }
</code>```

then passing the state to the element like this

```<code><div className="profileDropDown" style={{ bottom : height}}>
</code>```
```<code></code>```

Body:
i want to hide that drop down menu when clicking the button above it using position and z-index
i did a animation so the menu goes up and with z-index hide it under the nav bar

before clicking

https://i.stack.imgur.com/QYs3t.png

after clicking

https://i.stack.imgur.com/GVmjY.png

.navBar{
    padding-left: 20px;
    height: 80px;
    float: left;
    width: calc(100% - 15%) ;
    display: flex;
    align-items: center;
    background-color: rgb(197, 18, 18);
    position: relative;

    z-index: 1;
}

.profileDropDown{
    position: absolute;
    width: 186px;
    height: 140px;
    /* border-left: 1px solid rgb(190, 190, 190); */
    background-color: white;
    right: 0px;
    /* bottom: -140px; */
    transition: 0.5s;
    z-index: -2;
    border-bottom: 1px solid rgb(190, 190, 190);
    overflow: hidden;
}

the z-index of the drop down is smaller than the nav so i think it should be under the nav

the closing animation i did this

const toggle = () => {
    if (height === '-140px') {
      setHeight('0px')
    } else if (height === '0px') {
      setHeight('-140px')
    }
  }

then passing the state to the element like this


问:
What is the simplest way to animate the following changes to the page in React?
Im building a Q&A site, and I want to have a smooth transition from reading an answer to the question, and writing an answer to the question. Right now, the homepage looks like this:
Reading the answer

And upon clicking the 'Write Answer' button, I de-render the answer and author cards, and render in a form and a new button to submit answer:
The page where you can type in an answer

This is the code from the 'Write Answer' button, which I think should/could be what manages the animation:

```<code>import React from "react";
import Button from '@mui/material/Button';

function AnswerButton({childToParent}){
    const [AnswerState, setAnswerState] = React.useState(false)

    function Click(){
        setAnswerState(!AnswerState)
        return childToParent(AnswerState)
    }

    return <Button className="Answerbtn" variant="contained" onClick={Click}>Answer Question</Button>
}

export default AnswerButton;
</code>```

So, what is the simplest way to implement a smooth simple animation? Like the answer sliding out to the left and the input text sliding in from the right?

Researched some React-transition libraries, but found them to be too complex for me at this time.

Body:
Im building a Q&A site, and I want to have a smooth transition from reading an answer to the question, and writing an answer to the question. Right now, the homepage looks like this:
Reading the answer

And upon clicking the 'Write Answer' button, I de-render the answer and author cards, and render in a form and a new button to submit answer:
The page where you can type in an answer

This is the code from the 'Write Answer' button, which I think should/could be what manages the animation:

import React from "react";
import Button from '@mui/material/Button';

function AnswerButton({childToParent}){
    const [AnswerState, setAnswerState] = React.useState(false)

    function Click(){
        setAnswerState(!AnswerState)
        return childToParent(AnswerState)
    }

    return <Button className="Answerbtn" variant="contained" onClick={Click}>Answer Question</Button>
}

export default AnswerButton;

So, what is the simplest way to implement a smooth simple animation? Like the answer sliding out to the left and the input text sliding in from the right?

Researched some React-transition libraries, but found them to be too complex for me at this time.


问:
Python modue Using csv2vcard, the generated vcard looks good, but windows 10 people app doesn't display street address
reference csv2vcard

I imported the vcf file to google contacts, and the contact was correctly.

The problem is illustrated in the author's test case:
{csv2vcard.test_csv2vcard()}

The output is:
{'filename': 'gump_forrest.vcf', 'output': 'BEGIN:VCARD\nVERSION:3.0\nN;CHARSET=UTF-8:Gump;Forrest;;;\nTITLE;CHARSET=UTF-8:Shrimp Man\nORG;CHARSET=UTF-8:Bubba Gump Shrimp Co.\nTEL;TYPE=WORK,VOICE:+49 170 5 25 25 25\nEMAIL;TYPE=WORK:forrestgump@example.com\nURL;TYPE=WORK:https://www.linkedin.com/in/forrestgump\nADR;TYPE=WORK;CHARSET=UTF-8:42 Plantation St.;Baytown;30314;United States of America\nEND:VCARD\n', 'name': 'ForrestGump'}
Created vCard 3.0 for ForrestGump.

Note that only the city and postal code are shown
in windows 10 people app:

I also tried the "windows contacts" app.  It showed the
city as street address and postal code as city


问:
How can I make multiple telebot handlers at once?
how can i make multiple handlers at once using the telebot library in go?
i want to make a dialog between a user and a bot
i was able to find something similar using python, but it didnt help me

i want the user to be able to perform authorization in the service in stages, that is:

```<code>Bot: Enter the username.
User: username
Bot: Enter the password.
User: password
Bot: Authorization completed
</code>```

how can i do this?

to communicate with the user, i use a Poller:

```<code>pref := tele.Settings{
   Token:   cfg.Telegram.TelegramToken,
   Poller:  &tele.LongPoller{Timeout: 10 * time.Second},
   OnError: a.OnBotError,
}
bot, err := tele.NewBot(pref)
</code>```

i have a handler for authorization in some service:

```<code>a.bot.Handle(&btnAuth, func(c tele.Context) error {
}
</code>```

Body:
how can i make multiple handlers at once using the telebot library in go?
i want to make a dialog between a user and a bot
i was able to find something similar using python, but it didnt help me

i want the user to be able to perform authorization in the service in stages, that is:

Bot: Enter the username.
User: username
Bot: Enter the password.
User: password
Bot: Authorization completed

how can i do this?

to communicate with the user, i use a Poller:

pref := tele.Settings{
   Token:   cfg.Telegram.TelegramToken,
   Poller:  &tele.LongPoller{Timeout: 10 * time.Second},
   OnError: a.OnBotError,
}
bot, err := tele.NewBot(pref)

i have a handler for authorization in some service:

a.bot.Handle(&btnAuth, func(c tele.Context) error {
}


问:
Missing Semicolon Error in node js webpack
I am getting semicolon error in one of my json files while building my project using webpack, my json files are formated and still giving me this error. I am using these
"@babel/cli": "^7.6.2",
"@babel/core": "^7.5.5",
"@babel/preset-env": "^7.20.2",
"babel-core": "^6.26.3",
"babel-eslint": "^10.1.0",
"babel-loader": "^9.1.0",
"eslint": "^7.0.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.18.2",
"nodemon": "^2.0.20",
"nodemon-webpack-plugin": "^4.3.1",
"terser-webpack-plugin": "5.3.6",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-node-externals": "^3.0.0"

here is the error:

```<code>ERROR in ./src/express/routes/channels/libs/etsy/etsy.config.json
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\src\express\routes\channels\libs\etsy\etsy.config.json: Missing semicolon. (2:7)

  1 | {
> 2 |   "env": "development",
    |        ^
  3 |   "shopId": "FabricAndSewing",
  4 |   "key": "65hgx4sow7ih76bb9sir78f7",
  5 |   "secret": "8eoy84mw8u",
    at instantiate (C:\Excersys\FASAPI3\node_modules\@babel\parser\lib\index.js:67:32)
    at constructor (C:\Excersys\FASAPI3\node_modules\@babel\parser\lib\index.js:364:12)
</code>```

webpackConfig.js

```<code>import * as path from "path";
import Dotenv from "dotenv-webpack";
import nodeExternals from "webpack-node-externals";
import NodemonPlugin from "nodemon-webpack-plugin";
const __dirname = path.resolve(path.dirname(""));

const config = (env, argv) => ({
  entry: {
    server: "./src/index.js",
  },
  output: {
    path: path.join(__dirname, "dist"),
    publicPath: "/",
    filename: "[name].js",
  },
  mode: argv.mode,
  target: "node",
  node: {
    __dirname: false,
    __filename: false,
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.m?js/,
        resolve: {
          fullySpecified: false,
        },
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
    parser: {
      javascript: {
        // ...
        commonjsMagicComments: true,
      },
    },
  },

  plugins: [new NodemonPlugin(), new Dotenv()],
  resolve: {
    extensions: [".js", ".json", ".wasm"],
  },
});

export default config;

</code>```

.eslintrc.js

```<code>module.exports = {
  env: {
    browser: true,
    node: true,
    es2022: true,
  },
  // extends: ['airbnb-base'],
  // globals: {
  //    Atomics: 'readonly',
  //    SharedArrayBuffer: 'readonly'
  //  },
  parserOptions: {
    ecmaVersion: "latest",
    sourceType: "module",
    ecmaFeatures: {
      jsx: true,
    },
  },
  rules: {
    semi: "off",
  },
};

</code>```

I tried different webpack and eslint configs but nothing worked

Body:
I am getting semicolon error in one of my json files while building my project using webpack, my json files are formated and still giving me this error. I am using these
"@babel/cli": "^7.6.2",
"@babel/core": "^7.5.5",
"@babel/preset-env": "^7.20.2",
"babel-core": "^6.26.3",
"babel-eslint": "^10.1.0",
"babel-loader": "^9.1.0",
"eslint": "^7.0.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.18.2",
"nodemon": "^2.0.20",
"nodemon-webpack-plugin": "^4.3.1",
"terser-webpack-plugin": "5.3.6",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-node-externals": "^3.0.0"

here is the error:

ERROR in ./src/express/routes/channels/libs/etsy/etsy.config.json
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\src\express\routes\channels\libs\etsy\etsy.config.json: Missing semicolon. (2:7)

  1 | {
> 2 |   "env": "development",
    |        ^
  3 |   "shopId": "FabricAndSewing",
  4 |   "key": "65hgx4sow7ih76bb9sir78f7",
  5 |   "secret": "8eoy84mw8u",
    at instantiate (C:\Excersys\FASAPI3\node_modules\@babel\parser\lib\index.js:67:32)
    at constructor (C:\Excersys\FASAPI3\node_modules\@babel\parser\lib\index.js:364:12)

webpackConfig.js

import * as path from "path";
import Dotenv from "dotenv-webpack";
import nodeExternals from "webpack-node-externals";
import NodemonPlugin from "nodemon-webpack-plugin";
const __dirname = path.resolve(path.dirname(""));

const config = (env, argv) => ({
  entry: {
    server: "./src/index.js",
  },
  output: {
    path: path.join(__dirname, "dist"),
    publicPath: "/",
    filename: "[name].js",
  },
  mode: argv.mode,
  target: "node",
  node: {
    __dirname: false,
    __filename: false,
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.m?js/,
        resolve: {
          fullySpecified: false,
        },
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
    parser: {
      javascript: {
        // ...
        commonjsMagicComments: true,
      },
    },
  },

  plugins: [new NodemonPlugin(), new Dotenv()],
  resolve: {
    extensions: [".js", ".json", ".wasm"],
  },
});

export default config;

.eslintrc.js

module.exports = {
  env: {
    browser: true,
    node: true,
    es2022: true,
  },
  // extends: ['airbnb-base'],
  // globals: {
  //    Atomics: 'readonly',
  //    SharedArrayBuffer: 'readonly'
  //  },
  parserOptions: {
    ecmaVersion: "latest",
    sourceType: "module",
    ecmaFeatures: {
      jsx: true,
    },
  },
  rules: {
    semi: "off",
  },
};

I tried different webpack and eslint configs but nothing worked


问:
play audio file in the background using a service
I tried playing the sound in the background service, but when I press the "play" button, the sound plays for a moment, and then the application terminates directly, this is my code :</p>
```<code>public class AudioService extends Service {
        private MediaPlayer mediaPlayer;

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // Start the foreground service
            startForegroundService();

            // Create the media player and set the audio file to play
            mediaPlayer = MediaPlayer.create(this, R.raw.song_1);
            mediaPlayer.setLooping(true);

            // Start playing the audio
            mediaPlayer.start();

            return START_STICKY;
        }

        private void startForegroundService() {
            // Create the notification for the foreground service
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
                    .setSmallIcon(R.drawable.ic_play_arrow)
                    .setContentTitle("Background Audio Service")
                    .setContentText("Playing audio in the background");

            // Start the foreground service with the notification
            startForeground(1, builder.build());
        }

        @Override
        public IBinder onBind(Intent intent) {
            // Return null because this service is not bound to any activity
            return null;
        }

        @Override
        public void onDestroy() {
            // Release the media player and stop the foreground service
            mediaPlayer.release();
            stopForeground(true);
        }
    }
</code>```

Body:
I tried playing the sound in the background service, but when I press the "play" button, the sound plays for a moment, and then the application terminates directly, this is my code :

public class AudioService extends Service {
        private MediaPlayer mediaPlayer;

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // Start the foreground service
            startForegroundService();

            // Create the media player and set the audio file to play
            mediaPlayer = MediaPlayer.create(this, R.raw.song_1);
            mediaPlayer.setLooping(true);

            // Start playing the audio
            mediaPlayer.start();

            return START_STICKY;
        }

        private void startForegroundService() {
            // Create the notification for the foreground service
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
                    .setSmallIcon(R.drawable.ic_play_arrow)
                    .setContentTitle("Background Audio Service")
                    .setContentText("Playing audio in the background");

            // Start the foreground service with the notification
            startForeground(1, builder.build());
        }

        @Override
        public IBinder onBind(Intent intent) {
            // Return null because this service is not bound to any activity
            return null;
        }

        @Override
        public void onDestroy() {
            // Release the media player and stop the foreground service
            mediaPlayer.release();
            stopForeground(true);
        }
    }


问:
Is there any way to use the concept of "live bindings" in commonjs without esm?
I have a configuration file with some properties that may change during a lazy loading.

Usually I just import props through the destructurization method to reduce code, but in the lazy case I should forget about it, because commonjs uses the transfer to local variables instead of the new ES behavior.

My example code:

configs.js

```<code>let someLazy = null;

module.exports = { someLazy };
</code>```

setLazy:

```<code>const configs = require("./configs");

setTimeout(() => {
   configs.someLazy = true;
}, 1000);
</code>```

module.js

```<code>require("./setLazy");
const { someLazy } = require("./configs");
const configs = require("./configs");

setInterval(() => {

    //I don't want to write like this:
    console.log(configs.someLazy);

    //Instead of writing as above I need to make the following work:
    console.log(someLazy);

}, 1000);
</code>```

Of course, I can import full configs object into both of the above files, but at the end I get an extra code. It's more obvious when I have long property names.

Even if there is no way, is it possible to hack webpack just for that?

Body:
I have a configuration file with some properties that may change during a lazy loading.

Usually I just import props through the destructurization method to reduce code, but in the lazy case I should forget about it, because commonjs uses the transfer to local variables instead of the new ES behavior.

My example code:

configs.js

let someLazy = null;

module.exports = { someLazy };

setLazy:

const configs = require("./configs");

setTimeout(() => {
   configs.someLazy = true;
}, 1000);

module.js

require("./setLazy");
const { someLazy } = require("./configs");
const configs = require("./configs");

setInterval(() => {

    //I don't want to write like this:
    console.log(configs.someLazy);

    //Instead of writing as above I need to make the following work:
    console.log(someLazy);

}, 1000);

Of course, I can import full configs object into both of the above files, but at the end I get an extra code. It's more obvious when I have long property names.

Even if there is no way, is it possible to hack webpack just for that?


问:
In Scala cats 2.x, how to create a generic zero functor (given its type class)?
I'm looking for a method to initialise a zero functor z: F[_], given the type class Functor[F[_]]. The zero functor should ensure that any other function compose with it yields a fixed point. I've tried the following code:

```<code>import cats.Functor
import cats.syntax.functor._
import cats.instances.option._
import cats.instances.list._

def zeroFunctor[F[_]: Functor]: F[Nothing] = {
  val functorInstance = implicitly[Functor[F]]
  functorInstance.map(functorInstance.empty)(_ => ??? : Nothing)
}

val optZero = zeroFunctor[Option]  // None
val listZero = zeroFunctor[List]  // Nil
</code>```

But it failed with the following information:

```<code>
[Error] /home/peng/git/spookystuff/parent/core/src/main/scala/com/tribbloids/spookystuff/utils/SpookyViews_Imp0.scala:45:41: value empty is not a member of cats.Functor[F]
</code>```

SO what is the proper way to create it?

Body:
I'm looking for a method to initialise a zero functor z: F[_], given the type class Functor[F[_]]. The zero functor should ensure that any other function compose with it yields a fixed point. I've tried the following code:

import cats.Functor
import cats.syntax.functor._
import cats.instances.option._
import cats.instances.list._

def zeroFunctor[F[_]: Functor]: F[Nothing] = {
  val functorInstance = implicitly[Functor[F]]
  functorInstance.map(functorInstance.empty)(_ => ??? : Nothing)
}

val optZero = zeroFunctor[Option]  // None
val listZero = zeroFunctor[List]  // Nil

But it failed with the following information:

[Error] /home/peng/git/spookystuff/parent/core/src/main/scala/com/tribbloids/spookystuff/utils/SpookyViews_Imp0.scala:45:41: value empty is not a member of cats.Functor[F]

SO what is the proper way to create it?


问:
webview html video tag don't render video's frame?
how to fix webeview video tag render frame when rotating?

I have LinearLayout contains webView, in the webView has a video tag
that loads src local file video mp4. play it then pause, it works fine. (render the frame, paused with a frame).

But when I rotate the device from portrait to landscape mode (still shows frame here), then rotate back from landscape to portrait
mode, the video tag show black/blank (no frame). it did not show a frame in the paused state before.

I try this code:

```<code>webView.invalidate();

webView.requestLayout();

webView.refreshDrawableState();
</code>```

in the method onConfigurationChanged

But it is not effective. how to fix it? thank you so much!

Body:
how to fix webeview video tag render frame when rotating?

I have LinearLayout contains webView, in the webView has a video tag
that loads src local file video mp4. play it then pause, it works fine. (render the frame, paused with a frame).

But when I rotate the device from portrait to landscape mode (still shows frame here), then rotate back from landscape to portrait
mode, the video tag show black/blank (no frame). it did not show a frame in the paused state before.

I try this code:

webView.invalidate();

webView.requestLayout();

webView.refreshDrawableState();

in the method onConfigurationChanged

But it is not effective. how to fix it? thank you so much!


问:
Parallelizing inferences for multiple trained neural network models on the CPU
I have trained three different neural network models using Pytorch and CUDA.
I ported the trained models to C++ using libtorch. Everything works as it should.
When I make the inference on the three neural network models using the GPU, I
obtain different running times.
The first model runs in 60 ms, the second in 40 ms and the third in 10 ms.
I tried to parallelize the inference for all three neural networks using pthreads
and OpenMP. I expected the parallel versions to run in a time equal to the time of
the largest model. However, after parallelization, I only get an increase of at
most 5 ms in comparison with the version where all models inference is run
sequentially. I have enough space on the GPU to run all models in parallel and
my computer has multiple cores. Can the inference of the three neural models be
run in parallel in order to obtain a better running time?
Below is a code snippet with a parallelization I made using OpenMP.
Am I doing something wrong when using OpenMP? I get the same result when I run
with pthreads. It is worth mentioning that the functions test_model1
and test_model2 also unpack the tensors to obtain the results, so it is not just the
forward pass through the network.</p>
```<code>#pragma omp parallel
  {
     #pragma omp sections
     {
      #pragma omp section
      {
         test_model1(img_1);
      }
     #pragma omp section
     {
          test_model2(img_1);
     }
     #pragma omp section
     {
        cvtColor(img_1, img_1, COLOR_BGR2RGB);

        torch::Tensor imgTensor = ToTensor(img_1);

        inputs.push_back(imgTensor);

        torch::Tensor output = model3.forward(inputs).toTensor();
        result = ToCVImage(output.argmax(1));
    }
 }
}
</code>```

Body:
I have trained three different neural network models using Pytorch and CUDA.
I ported the trained models to C++ using libtorch. Everything works as it should.
When I make the inference on the three neural network models using the GPU, I
obtain different running times.
The first model runs in 60 ms, the second in 40 ms and the third in 10 ms.
I tried to parallelize the inference for all three neural networks using pthreads
and OpenMP. I expected the parallel versions to run in a time equal to the time of
the largest model. However, after parallelization, I only get an increase of at
most 5 ms in comparison with the version where all models inference is run
sequentially. I have enough space on the GPU to run all models in parallel and
my computer has multiple cores. Can the inference of the three neural models be
run in parallel in order to obtain a better running time?
Below is a code snippet with a parallelization I made using OpenMP.
Am I doing something wrong when using OpenMP? I get the same result when I run
with pthreads. It is worth mentioning that the functions test_model1
and test_model2 also unpack the tensors to obtain the results, so it is not just the
forward pass through the network.

#pragma omp parallel
  {
     #pragma omp sections
     {
      #pragma omp section
      {
         test_model1(img_1);
      }
     #pragma omp section
     {
          test_model2(img_1);
     }
     #pragma omp section
     {
        cvtColor(img_1, img_1, COLOR_BGR2RGB);

        torch::Tensor imgTensor = ToTensor(img_1);

        inputs.push_back(imgTensor);

        torch::Tensor output = model3.forward(inputs).toTensor();
        result = ToCVImage(output.argmax(1));
    }
 }
}


问:
Get the contents of a widget in a layout in PyQt
I recently decided to create a small application that simply reads the files in a compressed file and renames them. I went through several UI modules and decided to use PyQt6.

To achieve this, I first created a QWidget that holds the widgets QPushButton and QLineEdit.

The user then types the new name into the QLineEdit widget and select the QPushButton if the file has to be excluded.

Now, this widget that was created will be added into a QVBoxLayout which is then set as the QScrollArea layout.

Here's my problem:
Once I was done creating the scroll area and the list, I wanted to retrieve the content of each widget. For this purpose, I use the findChild method. But it only returns the address of the object.

Is there any way to get the text stored in QLineEdit of each widget? Is it possible to retrieve the text just by knowing its address?

Here's what I tried:

```<code>for index in range(self.layout.count()):
    widget = self.layout.itemAt(index).widget()
    nameFromLineEdit = widget.findChild(QLineEdit).text()
print(nameFromLineEdit)
</code>```

Body:
I recently decided to create a small application that simply reads the files in a compressed file and renames them. I went through several UI modules and decided to use PyQt6.

To achieve this, I first created a QWidget that holds the widgets QPushButton and QLineEdit.

The user then types the new name into the QLineEdit widget and select the QPushButton if the file has to be excluded.

Now, this widget that was created will be added into a QVBoxLayout which is then set as the QScrollArea layout.

Here's my problem:
Once I was done creating the scroll area and the list, I wanted to retrieve the content of each widget. For this purpose, I use the findChild method. But it only returns the address of the object.

Is there any way to get the text stored in QLineEdit of each widget? Is it possible to retrieve the text just by knowing its address?

Here's what I tried:

for index in range(self.layout.count()):
    widget = self.layout.itemAt(index).widget()
    nameFromLineEdit = widget.findChild(QLineEdit).text()
print(nameFromLineEdit)


Title: MariaDb Query using JSON_EXTRACT on a json object containing a nested array returns different result using or not using WHERE

Body:
On MariaDb 10.10.2 if I run the following query:

select l.Id ,
       json_length(l.Response, '$.Response.Errors') as nErrors,
       json_extract(l.Response, '$.Response.Errors[*].Reason') as reasons
from logs l LIMIT 0, 5;

I get the following result:

+----+---------+-----------------------+
| Id | nErrors | reasons               |
+----+---------+-----------------------+
|  1 |       1 | ["UsernameEmpty"]     |
|  2 |       1 | "UserAlreadyLoggedIn" |
|  3 |       2 | "EmailEmpty"          |
|  4 |       2 | "EmailNotValid"       |
|  5 |       2 | "EmailNotValid"       |
+----+---------+-----------------------+

If I run the following query:

 select l.Id ,
        json_length(l.Response, '$.Response.Errors') as nErrors,
        json_extract(l.Response, '$.Response.Errors[*].Reason') as reasons
from    logs l
where   id = 3;

I get the following results:

+----+---------+-----------------------------------+
| Id | nErrors | reasons                           |
+----+---------+-----------------------------------+
|  3 |       2 | ["EmailEmpty", "EmailDoNotMatch"] |
+----+---------+-----------------------------------+

Can someone tell me why in the second query I obtain the real result in 'reasons' while the first query returns only one reason? As you can see the only thing that changed is the where clause...

Thank you in advance!

Update:

These are the first 5 rows in the db:

+----+---------------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+----------------------------+----------------------------+--------+
| Id | IpAddress     | ElapsedTime | Request                                                                                | Response                                                                                | IsArchived | Created                    | LastModified               | UserId |
+----+---------------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+----------------------------+----------------------------+--------+
|  1 | 192.168.230.3 |         280 | {"Body":"{\n  \u0022Email\u0022:            \u0022demo1234@test.com\u0022,\n  \u0022EmailConfirm\u0022:     \u0022demo1234@test.com\u0022,\n  \u0022Username\u0022:         \u0022\u0022,\n  \u0022Password\u0022:         \u0012345678\u0022,\n  \u0022PasswordConfirm\u0022:  \u0012345678\u0022\n}","ByteBody":null,"ContentType":"application/json","Cookies":{},"Headers":{"Accept":"*/*","Connection":"close","Host":"192.168.230.1:5001","User-Agent":"Thunder Client (https://www.thunderclient.com)","Accept-Encoding":"gzip, deflate, br","Content-Type":"application/json","Content-Length":"188"},"Method":"POST","Path":"/api/users","Query":"","Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false}                                                                                | {"Response":{"StatusCode":400,"ByteResponse":null,"ByteContentType":"","Errors":[{"Type":"Validation","Parameters":null,"Class":"","Function":"","Message":"","ProdMessage":"","Reason":"UsernameEmpty","StackTrace":"","UserId":-1,"Username":""}],"Debug":[],"ElapsedTime":0},"Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false}                                                                                |          0 | 2022-12-24 17:14:46.355917 | 2022-12-24 17:14:46.355917 |     -1 |
|  2 | 192.168.230.1 |          13 | {"Body":"{\r\n  \u0022$id\u0022: \u00221\u0022,\r\n  \u0022Email\u0022: \u0022demo0964657430@test.com\u0022,\r\n  \u0022EmailConfirm\u0022: \u0022demo0964657430@test.com\u0022,\r\n  \u0022Username\u0022: \u0022demo0964657430\u0022,\r\n  \u0022Password\u0022: \u0012345678\u0022,\r\n  \u0022PasswordConfirm\u0022: \u0012345678\u0022\r\n}","ByteBody":null,"ContentType":"text/plain; charset=utf-8","Cookies":{},"Headers":{"Host":"192.168.230.1:5001","Authorization":"Bearer tqdsAR2I/WDzj\u002BRUt7XHSDMz9WQ2Z4Ehekw2ey0QiB/06Z9\u002B0pujjpxn\u002BAG5i1EojpZWfLPaiR1Ybi59Xg\u002BLreCRpI80Uoc0mhxYXw7SpFCsA2x/VH5LByKfM/DUEC84tGpZmRlZk7eBBNLKsWv5/ymLQi95xA2w7p4XYJM72es=","Content-Type":"text/plain; charset=utf-8","Content-Length":"203"},"Method":"POST","Path":"/api/users","Query":"","Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false} | {"Response":{"StatusCode":400,"ByteResponse":null,"ByteContentType":"","Errors":[{"Type":"Validation","Parameters":null,"Class":"","Function":"","Message":"","ProdMessage":"","Reason":"UserAlreadyLoggedIn","StackTrace":"","UserId":-1,"Username":""}],"Debug":[],"ElapsedTime":0},"Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false}                                                                                |          0 | 2022-12-24 17:20:02.404424 | 2022-12-24 17:20:02.404424 |     -1 |
|  3 | 192.168.230.1 |         214 | {"Body":"{\r\n  \u0022$id\u0022: \u00221\u0022,\r\n  \u0022Email\u0022: \u0022\u0022,\r\n  \u0022EmailConfirm\u0022: \u0022demo1488578354@test.com\u0022,\r\n  \u0022Username\u0022: \u0022demo1488578354\u0022,\r\n  \u0022Password\u0022: \u0012345678\u0022,\r\n  \u0022PasswordConfirm\u0022: \u0012345678\u0022\r\n}","ByteBody":null,"ContentType":"text/plain; charset=utf-8","Cookies":{},"Headers":{"Host":"192.168.230.1:5001","Content-Type":"text/plain; charset=utf-8","Content-Length":"177"},"Method":"POST","Path":"/api/users","Query":"","Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false}                                                                                | {"Response":{"StatusCode":400,"ByteResponse":null,"ByteContentType":"","Errors":[{"Type":"Validation","Parameters":null,"Class":"","Function":"","Message":"","ProdMessage":"","Reason":"EmailEmpty","StackTrace":"","UserId":-1,"Username":""},{"Type":"Validation","Parameters":null,"Class":"","Function":"","Message":"","ProdMessage":"","Reason":"EmailDoNotMatch","StackTrace":"","UserId":-1,"Username":""}],"Debug":[],"ElapsedTime":0},"Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false}    |          0 | 2022-12-24 17:26:05.526448 | 2022-12-24 17:26:05.526448 |     -1 |
|  4 | 192.168.230.1 |          45 | {"Body":"{\r\n  \u0022$id\u0022: \u00221\u0022,\r\n  \u0022Email\u0022: \u0022aaa\u0022,\r\n  \u0022EmailConfirm\u0022: \u0022demo1488578354@test.com\u0022,\r\n  \u0022Username\u0022: \u0022demo1488578354\u0022,\r\n  \u0022Password\u0022: \u0012345678\u0022,\r\n  \u0022PasswordConfirm\u0022: \u0012345678\u0022\r\n}","ByteBody":null,"ContentType":"text/plain; charset=utf-8","Cookies":{},"Headers":{"Host":"192.168.230.1:5001","Content-Type":"text/plain; charset=utf-8","Content-Length":"180"},"Method":"POST","Path":"/api/users","Query":"","Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false}                                                                                | {"Response":{"StatusCode":400,"ByteResponse":null,"ByteContentType":"","Errors":[{"Type":"Validation","Parameters":null,"Class":"","Function":"","Message":"","ProdMessage":"","Reason":"EmailNotValid","StackTrace":"","UserId":-1,"Username":""},{"Type":"Validation","Parameters":null,"Class":"","Function":"","Message":"","ProdMessage":"","Reason":"EmailDoNotMatch","StackTrace":"","UserId":-1,"Username":""}],"Debug":[],"ElapsedTime":0},"Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false} |          0 | 2022-12-24 17:26:05.626461 | 2022-12-24 17:26:05.626461 |     -1 |
|  5 | 192.168.230.1 |           7 | {"Body":"{\r\n  \u0022$id\u0022: \u00221\u0022,\r\n  \u0022Email\u0022: \u0022aaa@\u0022,\r\n  \u0022EmailConfirm\u0022: \u0022demo1488578354@test.com\u0022,\r\n  \u0022Username\u0022: \u0022demo1488578354\u0022,\r\n  \u0022Password\u0022: \u0012345678\u0022,\r\n  \u0022PasswordConfirm\u0022: \u0012345678\u0022\r\n}","ByteBody":null,"ContentType":"text/plain; charset=utf-8","Cookies":{},"Headers":{"Host":"192.168.230.1:5001","Content-Type":"text/plain; charset=utf-8","Content-Length":"181"},"Method":"POST","Path":"/api/users","Query":"","Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false}                                                                                | {"Response":{"StatusCode":400,"ByteResponse":null,"ByteContentType":"","Errors":[{"Type":"Validation","Parameters":null,"Class":"","Function":"","Message":"","ProdMessage":"","Reason":"EmailNotValid","StackTrace":"","UserId":-1,"Username":""},{"Type":"Validation","Parameters":null,"Class":"","Function":"","Message":"","ProdMessage":"","Reason":"EmailDoNotMatch","StackTrace":"","UserId":-1,"Username":""}],"Debug":[],"ElapsedTime":0},"Id":0,"Created":"0001-01-01T00:00:00","LastModified":"0001-01-01T00:00:00","IsArchived":false} |          0 | 2022-12-24 17:26:05.642447 | 2022-12-24 17:26:05.642447 |     -1 |
+----+---------------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+----------------------------+----------------------------+--------+


问:
What XPath expression is able to fetch rows from a table regardless of presence of implicit tbody tag in DOM?
I do web-parsing with python using lxml and I have to use the browser to test xpath expressions. If some page code has missing tbody tag between table and tr any modern browser by following the HTML5 standard automatically adds the missing tag into the DOM. But lxml is more concerned about matching the DOM to the source code than HTML5 standard. It puts tr right inside table and puts no tbody in between. As a result, xpath //table[@class='target']/*/tr works in the browser but not in lxml, and xpath //table[@class='target']/tr works in lxml but not in the browser. However, if I try to use something like //table[@class='target']//tr, it works in both, but captures trs from all the inner tables, which is not my goal.

I'm looking for a uniform xpath expression that captures rows from a particular table but not from its subtables, is unaffected by the presence of the tbody tag, and works identically in lxml and the browser.

Example html that is represented by different DOM trees in the browser and in lxml:

```<code><table class="target">
    <tr>
        <td>
            <table>
                <tr>
                    <td></td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</code>```


问:
How can I refresh an EJS partial with updated data every few seconds?
I'm trying to update the content of an ejs partial every 5 seconds with new data obtained from a fetch request. I want to avoid rewriting each line of the partial and instead just update the content within it. However, I am not sure how to call setInterval to re-render the partial.

This is my get route:

```<code>app.get("/tracker", async (req, res) => {
  const response = await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h%2C24h%2C7d");
  const listings = await response.json();

  if (req.user) {
    req.session.user = req.user;
  } else {
    req.session.user = null;
  }
  const user = req.session.user;

  res.render("./index", { listings, user });
});
</code>```

And this is a section of the Index EJS file it renders:

```<code> <tbody id="listings">
      <!-- Create token/coin listing -->
      <%- include ('./partials/list', { listings }) %>
  </tbody>
</code>```

Then this is the partial that gets called:

```<code><% for (let item of listings) { %>
<form action="/<%=item.market_cap_rank%>/favorites?_method=PUT" method="POST">
  <tr>
    <td class="rank text-center pb-3"><%=item.market_cap_rank%></td>
    <td class="text-center pb-3 image-cell">
      <img src="<%=item.image%>" alt="" class="item-image" />
    </td>
    <td class="name text-center pb-3">
      <a href="https://www.coingecko.com/en/coins/<%=item.id%>" class="item-link"><%=item.name%> (<%=item.symbol%>)</a>
    </td>
    <td class="price text-center pb-3">
      <% if(item.current_price > 0.01) { %>
      <!-- If current price is more than .01, only display 2 decimal points -->
      $<%=item.current_price.toFixed(2)%> <% } else { %>
      <!-- Else display all the decimal points -->
      $<%=item.current_price%> <% } %>
    </td>
    <td class="change text-center pb-3 ps-5 pe-5"><%=item.price_change_percentage_24h_in_currency.toFixed(2)%> %</td>
  </tr>
</form>
<% } %>
</code>```

I started off trying this and found out setInterval cannot be used in EJS like this:

```<code><tbody>
  <% setInterval((listings) => { %>
  <!-- Create token/coin listing -->
  <%- include ('./partials/list', { listings }) %>
  <% }, 5000) %>
</tbody>
</code>```

I now currently have a separate file that clears the html of the table and appends the new data back to it. For some reason it only lists every odd item after 3 or 4 intervals though. I would also prefer to just re-render the partial instead of recreating the table each time.

```<code>async function updateList() {
  console.log("test");
  await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h%2C24h%2C7d")
    .then(async (response) => await response.json())
    .then(async (newListings) => {
      // Clear the existing rows from the table
      const imageTds = document.querySelectorAll(".image-cell");
      await imageTds.forEach((td) => {
        td.innerHTML = "";
      });

      const nameTds = document.querySelectorAll(".name");
      await nameTds.forEach((td) => {
        td.innerHTML = "";
      });

      const priceTds = document.querySelectorAll(".price");
      await priceTds.forEach((td) => {
        td.innerHTML = "";
      });

      const changeTds = document.querySelectorAll(".change");
      await changeTds.forEach((td) => {
        td.innerHTML = "";
      });

      console.log(newListings);

      await newListings.forEach((item, i) => {
        const tr = document.createElement("tr");

        const imageTd = document.createElement("td");
        imageTd.classList.add("text-center", "pb-3", "image-cell");
        const image = document.createElement("img");
        image.src = item.image;
        image.alt = "";
        image.classList.add("item-image");
        imageTd.appendChild(image);
        imageTds[i].append(imageTd);

        const nameTd = document.createElement("td");
        nameTd.classList.add("name", "text-center", "pb-3");
        const link = document.createElement("a");
        link.href = `https://www.coingecko.com/en/coins/${item.id}`;
        link.classList.add("item-link");
        link.textContent = `${item.name} (${item.symbol})`;
        nameTd.appendChild(link);
        nameTds[i].append(nameTd);

        const priceTd = document.createElement("td");
        priceTd.classList.add("price", "text-center", "pb-3");
        if (item.current_price > 0.01) {
          priceTd.textContent = `$${item.current_price.toFixed(2)}`;
        } else {
          priceTd.textContent = `$${item.current_price}`;
        }
        priceTds[i].append(priceTd);

        const changeTd = document.createElement("td");
        changeTd.classList.add("change", "text-center", "pb-3", "ps-5", "pe-5");
        changeTd.textContent = item.price_change_percentage_24h_in_currency.toFixed(2);
        changeTds[i].append(changeTd);

        tr.append(imageTds, nameTds, priceTds, changeTds);
      });
    });
}

module.exports = updateList;
</code>```

I also found an answer here using the meta tag, but that refreshes the entire page when I just want the data of the table to refresh.

```<code><meta http-equiv="refresh" content="5" />
</code>```

Body:
I'm trying to update the content of an ejs partial every 5 seconds with new data obtained from a fetch request. I want to avoid rewriting each line of the partial and instead just update the content within it. However, I am not sure how to call setInterval to re-render the partial.

This is my get route:

app.get("/tracker", async (req, res) => {
  const response = await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h%2C24h%2C7d");
  const listings = await response.json();

  if (req.user) {
    req.session.user = req.user;
  } else {
    req.session.user = null;
  }
  const user = req.session.user;

  res.render("./index", { listings, user });
});

And this is a section of the Index EJS file it renders:

      <%- include ('./partials/list', { listings }) %>

Then this is the partial that gets called:

<% for (let item of listings) { %>
<form action="/<%=item.market_cap_rank%>/favorites?_method=PUT" method="POST">

    <%=item.market_cap_rank%>

      <img src="<%=item.image%>" alt="" class="item-image" />

      <a href="https://www.coingecko.com/en/coins/<%=item.id%>" class="item-link"><%=item.name%> (<%=item.symbol%>)

      <% if(item.current_price > 0.01) { %>

      $<%=item.current_price.toFixed(2)%> <% } else { %>

      $<%=item.current_price%> <% } %>

    <%=item.price_change_percentage_24h_in_currency.toFixed(2)%> %

</form>
<% } %>

I started off trying this and found out setInterval cannot be used in EJS like this:

  <% setInterval((listings) => { %>

  <%- include ('./partials/list', { listings }) %>
  <% }, 5000) %>

I now currently have a separate file that clears the html of the table and appends the new data back to it. For some reason it only lists every odd item after 3 or 4 intervals though. I would also prefer to just re-render the partial instead of recreating the table each time.

async function updateList() {
  console.log("test");
  await fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h%2C24h%2C7d")
    .then(async (response) => await response.json())
    .then(async (newListings) => {
      // Clear the existing rows from the table
      const imageTds = document.querySelectorAll(".image-cell");
      await imageTds.forEach((td) => {
        td.innerHTML = "";
      });

      const nameTds = document.querySelectorAll(".name");
      await nameTds.forEach((td) => {
        td.innerHTML = "";
      });

      const priceTds = document.querySelectorAll(".price");
      await priceTds.forEach((td) => {
        td.innerHTML = "";
      });

      const changeTds = document.querySelectorAll(".change");
      await changeTds.forEach((td) => {
        td.innerHTML = "";
      });

      console.log(newListings);

      await newListings.forEach((item, i) => {
        const tr = document.createElement("tr");

        const imageTd = document.createElement("td");
        imageTd.classList.add("text-center", "pb-3", "image-cell");
        const image = document.createElement("img");
        image.src = item.image;
        image.alt = "";
        image.classList.add("item-image");
        imageTd.appendChild(image);
        imageTds[i].append(imageTd);

        const nameTd = document.createElement("td");
        nameTd.classList.add("name", "text-center", "pb-3");
        const link = document.createElement("a");
        link.href = `https://www.coingecko.com/en/coins/${item.id}`;
        link.classList.add("item-link");
        link.textContent = `${item.name} (${item.symbol})`;
        nameTd.appendChild(link);
        nameTds[i].append(nameTd);

        const priceTd = document.createElement("td");
        priceTd.classList.add("price", "text-center", "pb-3");
        if (item.current_price > 0.01) {
          priceTd.textContent = `$${item.current_price.toFixed(2)}`;
        } else {
          priceTd.textContent = `$${item.current_price}`;
        }
        priceTds[i].append(priceTd);

        const changeTd = document.createElement("td");
        changeTd.classList.add("change", "text-center", "pb-3", "ps-5", "pe-5");
        changeTd.textContent = item.price_change_percentage_24h_in_currency.toFixed(2);
        changeTds[i].append(changeTd);

        tr.append(imageTds, nameTds, priceTds, changeTds);
      });
    });
}

module.exports = updateList;

I also found an answer here using the meta tag, but that refreshes the entire page when I just want the data of the table to refresh.

<meta http-equiv="refresh" content="5" />


问:
Drawing sprite get mirrored?
In the following example I am trying to have a trailing glow by using sf::RenderTexture. Unfortunately, the texture seem to be mirrored. I don't understand why.

Main program

```<code>#include <SFML/Graphics.hpp>
#include <iostream>
#define WIDTH 800
int main() {
    sf::RenderWindow window(sf::VideoMode(WIDTH, WIDTH), "Test");
    sf::Shader buffer;
    buffer.loadFromFile("buffer.frag", sf::Shader::Fragment);
    sf::Texture texture;
    texture.create(WIDTH, WIDTH);
    sf::Sprite sprite(texture);
    sf::RenderTexture renderTexture;
    renderTexture.create(WIDTH, WIDTH);
    sf::Vector2f mousePos = sf::Vector2f(-1.f, -1.f);
    buffer.setUniform("iChannel0", texture);
    buffer.setUniform("iResolution", sf::Glsl::Vec2(WIDTH, WIDTH));
    auto time = sf::Clock();
    window.clear();
    while(window.isOpen()) {
        sf::Event currEvent;
        while(window.pollEvent(currEvent))
            if (currEvent.type == sf::Event::Closed) window.close();
        buffer.setUniform("iTime", (float)time.getElapsedTime().asSeconds());
        renderTexture.clear();
        renderTexture.draw(sprite, &buffer);
        renderTexture.display();
        texture.update(renderTexture.getTexture());

        window.clear();
        window.draw(sprite);
        window.display();
    }
}
</code>```

Fragment Shader

```<code>#version 140
out vec4 out_Colour;

uniform sampler2D iChannel0;
uniform vec2 iResolution;
uniform float iTime;

void main(void) {
    vec2 spot = vec2(sin(iTime*5)*200+400, cos(iTime*15.0)*70+150);
    vec3 color = vec3(sin(iTime*5), sin(iTime*1), sin(iTime*10)) * 0.5 + 0.5;
    vec2 uv = (gl_FragCoord.xy - spot.xy) / iResolution.xy;
    vec3 blob = 1.0 - vec3(smoothstep(length(uv), 0, .02));
    vec3 stack = texture(iChannel0, gl_FragCoord.xy / iResolution.xy).xyz;
    stack -= vec3(0.003);
    out_Colour = vec4(stack + color * blob* 0.1, 1.0);
}
</code>```

I get this weird result where half the screen is mirrored:

But if I render directly the buffer I don't get this result:

```<code>    window.clear();
    window.draw(sprite, &buffer);
    window.display();
    texture.update(window);
</code>```

Title: Drawing sprite get mirrored?

Body:
In the following example I am trying to have a trailing glow by using sf::RenderTexture. Unfortunately, the texture seem to be mirrored. I don't understand why.

Main program

#include <SFML/Graphics.hpp>
#include <iostream>
#define WIDTH 800
int main() {
    sf::RenderWindow window(sf::VideoMode(WIDTH, WIDTH), "Test");
    sf::Shader buffer;
    buffer.loadFromFile("buffer.frag", sf::Shader::Fragment);
    sf::Texture texture;
    texture.create(WIDTH, WIDTH);
    sf::Sprite sprite(texture);
    sf::RenderTexture renderTexture;
    renderTexture.create(WIDTH, WIDTH);
    sf::Vector2f mousePos = sf::Vector2f(-1.f, -1.f);
    buffer.setUniform("iChannel0", texture);
    buffer.setUniform("iResolution", sf::Glsl::Vec2(WIDTH, WIDTH));
    auto time = sf::Clock();
    window.clear();
    while(window.isOpen()) {
        sf::Event currEvent;
        while(window.pollEvent(currEvent))
            if (currEvent.type == sf::Event::Closed) window.close();
        buffer.setUniform("iTime", (float)time.getElapsedTime().asSeconds());
        renderTexture.clear();
        renderTexture.draw(sprite, &buffer);
        renderTexture.display();
        texture.update(renderTexture.getTexture());

        window.clear();
        window.draw(sprite);
        window.display();
    }
}

Fragment Shader

#version 140
out vec4 out_Colour;

uniform sampler2D iChannel0;
uniform vec2 iResolution;
uniform float iTime;

void main(void) {
    vec2 spot = vec2(sin(iTime*5)*200+400, cos(iTime*15.0)*70+150);
    vec3 color = vec3(sin(iTime*5), sin(iTime*1), sin(iTime*10)) * 0.5 + 0.5;
    vec2 uv = (gl_FragCoord.xy - spot.xy) / iResolution.xy;
    vec3 blob = 1.0 - vec3(smoothstep(length(uv), 0, .02));
    vec3 stack = texture(iChannel0, gl_FragCoord.xy / iResolution.xy).xyz;
    stack -= vec3(0.003);
    out_Colour = vec4(stack + color * blob* 0.1, 1.0);
}

I get this weird result where half the screen is mirrored:

But if I render directly the buffer I don't get this result:

    window.clear();
    window.draw(sprite, &buffer);
    window.display();
    texture.update(window);