问:
Moving a PHP Laradock project to Mac M1
I need to be able to develop an old Laradock project on my new M1. So far, I have nearly everything up and running. The one holdout that I have is HHVM. HHVM doesn't support M1 in any way, so I need to move the project away from it. I get this when attempting to start docker with HHVM:

```<code>failed to solve: executor failed running [/bin/sh -c apt-get update -y   && apt-get install -y software-properties-common wget   && wget -O - http://dl.hhvm.com/conf/hhvm.gpg.key | sudo apt-key add -   && add-apt-repository "deb http://dl.hhvm.com/ubuntu $(lsb_release -sc) main"   && apt-get update -y   && apt-get install -y hhvm   && apt-get clean   && rm -rf /var/lib/apt/lists/*]: exit code: 100
</code>```

I suspect I need to replace HHVM's functionality with PHP-FPM. I'm a little stumped on where to go with it, though. I was not the one that initially built this program, and PHP isn't my forte. I have a hard time finding anything online about this issue, though I'd imagine people have to have encountered it since M1 has come along.

If I comment out HHVM in laradock, docker-compose.yml then I can get everything else to build - I also get 500s when attempting to access the project.

I'm not sure where to even go with this issue.

Title: Moving a PHP Laradock project to Mac M1

Body:
I need to be able to develop an old Laradock project on my new M1. So far, I have nearly everything up and running. The one holdout that I have is HHVM. HHVM doesn't support M1 in any way, so I need to move the project away from it. I get this when attempting to start docker with HHVM:

failed to solve: executor failed running [/bin/sh -c apt-get update -y   && apt-get install -y software-properties-common wget   && wget -O - http://dl.hhvm.com/conf/hhvm.gpg.key | sudo apt-key add -   && add-apt-repository "deb http://dl.hhvm.com/ubuntu $(lsb_release -sc) main"   && apt-get update -y   && apt-get install -y hhvm   && apt-get clean   && rm -rf /var/lib/apt/lists/*]: exit code: 100

I suspect I need to replace HHVM's functionality with PHP-FPM. I'm a little stumped on where to go with it, though. I was not the one that initially built this program, and PHP isn't my forte. I have a hard time finding anything online about this issue, though I'd imagine people have to have encountered it since M1 has come along.

If I comment out HHVM in laradock, docker-compose.yml then I can get everything else to build - I also get 500s when attempting to access the project.

I'm not sure where to even go with this issue.


来源: stackexchange

问:
Creating Wired Virtual Router in Windows 10/11 for sharing VPN internet
There are many tutorials on how to make Vitrual Router and share
VPN TAP interface internate with the WiFi card as a HotSpot in Windows 10.

That said I have not found any tutorial on how to create a Wired (Ethernet) Virtual Router in Windows 10 that I can share my VPN connection (TAP+TUN interfaces) on that wired network interface.

Any workable code or windows powershell commands is really appreciated, I need to share
the VPN TAP and TUN adapter internet to other devices via Ethernet cable (Wired Virtual Router).

I am using Windows 10 pro.

ContentLicense: CC BY-SA 4.0


问:
Formik uses HTML element value instead of setFieldValue
So I'm using Formik for a form and want to create a custom input field with some async data, however when i submit my form the value being sent is the one shown on in the HTML and not the one i store in Formik using setFieldValue.

Does the <Input> elements value have to be the one i send regardless of setFieldValue? These are different values, where one is the name of my object and the other is an internal ID.

My <Input> uses this logic for it's value.

```<code>value={name ?? searchTerm}
</code>```

Where it shows the searchTerm until you choose from a list.

```<code>setFieldValue("id", id);
</code>```

And then i set the result of the async code with this.

Body:
So I'm using Formik for a form and want to create a custom input field with some async data, however when i submit my form the value being sent is the one shown on in the HTML and not the one i store in Formik using setFieldValue.

Does the <Input> elements value have to be the one i send regardless of setFieldValue? These are different values, where one is the name of my object and the other is an internal ID.

My <Input> uses this logic for it's value.

value={name ?? searchTerm}

Where it shows the searchTerm until you choose from a list.

setFieldValue("id", id);

And then i set the result of the async code with this.


问:
Failed to Install PyQt5 in Jetson Ubuntu Env with Python 3.8.16
I am having Jetson with Ubuntu Environment and using Python 3.8.16. I need to install PyQt5 and I have follow many suggestions from the open source to install pyqt5, including upgrade my pip to the latest version. However, I am still failed to install as it prompt out failed to build wheel for sip during the installation. Any suggestion to solve this?</p>


问:
Cant decode/encode query commas with react-query-params
Im stucked 3 days already on this. I cant put in browser decoded URL parameter. I need just put string in the browser URL. I Have problems with commas symbol.

Im using react-query-params and qs.stringify for a string

```<code>  const filtrToClientQuery = qs.stringify(
    { ...filterActive },
    { arrayFormat: "comma", delimiter: ";" }

  const decodefiltrToClientQuery = decodeURIComponent(filtrToClientQuery);
</code>```

This is result decodefiltrToClientQuery string what i want to put in client browser (in console.log result is fine)

```<code>"color=red,yellow;resolution=1024"
</code>```

But when i put query in browser with setQuery

```<code>       <button
              className="set-btn"
              onClick={() => setQuery(decodefiltrToClientQuery)}
            >
              setFilter
            </button>
</code>```

Then i get this result

```<code>foo=color%3Dred%2Cyellow%3Bresolution%3D1024
</code>```

Im really stuck on this long time. Can somebody habe some solution?

Body:
Im stucked 3 days already on this. I cant put in browser decoded URL parameter. I need just put string in the browser URL. I Have problems with commas symbol.

Im using react-query-params and qs.stringify for a string

  const filtrToClientQuery = qs.stringify(
    { ...filterActive },
    { arrayFormat: "comma", delimiter: ";" }

  const decodefiltrToClientQuery = decodeURIComponent(filtrToClientQuery);

This is result decodefiltrToClientQuery string what i want to put in client browser (in console.log result is fine)

"color=red,yellow;resolution=1024"

But when i put query in browser with setQuery

       <button
              className="set-btn"
              onClick={() => setQuery(decodefiltrToClientQuery)}
            >
              setFilter
            </button>

Then i get this result

foo=color%3Dred%2Cyellow%3Bresolution%3D1024

Im really stuck on this long time. Can somebody habe some solution?


问:
How to limit height of plotlines in highchart graphs?
by default the plotlines are infinite but i want to restrict the height of plotlines
how can i achieve that without using below code

I want solution in ReactJS.
please help me with this if possible
thanks ✌

I have tried searching documentation but couldn't find any existing solution.


问:
AngularJS Dropdown Multiselect virtual scrolling
I use AngularJS Dropdown Multiselect and try to display a very large list of item (around 5000), from the docs "scrollable" means "Indicates if the dropdown is scrollable, useful if you have a lot of items.". I thought this is virtual scrolling feature, but it is not. Does anyone know any solution in this case?</p>


问:
Openapi - Api-First approach and third-party classes as response
Let's assume I want to follow the API-first approach with openapi. The response of an endpoint should be a JSON of Java objects whose classes are implemented in a third-party library. Thus, they already exist and are not under my control.

What is the best option here to specify the API?

Define a new DTO type in my openapi spec and implement a mapper from existing class to generated DTO class? Feels like boilerplate code.

define the response to be a string and mention in the description that the String encodes a JSON of an existing-class object. This would cleary generate ugly code.

There isn't a way to reference existing Java classes in the spec file, I guess.


问:
How to Effectively use Concurrency of Cloud Run
We are trying to hit a cloud run service using a for loop in python.
What we expect from our for loop is that it bombards the service with request hits so that the service scales and add more container instances to cater to the requests.
But on the contrary what we are witnessing is that our for loop waits for the service to complete the response and then makes another hit which usually takes around 30 seconds to complete. So effectively we are able to make only 2 hits per minute.
What can we do to make sure that the hits are made right one after the other and does not wait for the service to complete the task for each hit.

for i in range(len(checkin_list)):

    todo = {
          "hotelurl_json"  :  hotel_dict ,
            "checkin"      :  checkin_list[i] ,
            "checkout"     :  checkout_list[i]
        }

    requests.post(api_url, json=todo)

```

I have attached screenshot the system configuration and of the metrics screen

Cloud Run service configuration

Metrics screen

Body:
We are trying to hit a cloud run service using a for loop in python.
What we expect from our for loop is that it bombards the service with request hits so that the service scales and add more container instances to cater to the requests.
But on the contrary what we are witnessing is that our for loop waits for the service to complete the response and then makes another hit which usually takes around 30 seconds to complete. So effectively we are able to make only 2 hits per minute.
What can we do to make sure that the hits are made right one after the other and does not wait for the service to complete the task for each hit.

for i in range(len(checkin_list)):

    todo = {
          "hotelurl_json"  :  hotel_dict ,
            "checkin"      :  checkin_list[i] ,
            "checkout"     :  checkout_list[i]
        }

    requests.post(api_url, json=todo)

I have attached screenshot the system configuration and of the metrics screen

Cloud Run service configuration

Metrics screen


问:
PhpStorm : Use files from one project in other projects without copying them?
I have one project which contains some PHP services that I use as a template in all my other projects.

Is it possible to add these files to a new project without actually copying them to the new project's directory? Or, they could be copied but I want changes to one of the copies to affect the template.

For example. Template project contains

folder service with files "1.php", "2.php", "3.php"

and folder util with "u1.php" and "u2.php".

I want to use these files in one or more new projects but without copying them.

They should merge with the files of the new project and be treated as if they are in the new project's directory.

If the new project also has a folder "service" with files "4.php" and "5.php" the files 1 2 and 3 from the template should show  there too.

And if I were to edit service/1.php in the new project, the original file in the template project would get changed as well.

Is something like this possible?


问:
Pandas: Add missing column name
I have a csv file which is missing the first two column names, therefore looking like that:

```<code>,,MedKD,AvgKD,Q,AKD,PKD(.2),GPKD(.2),FS
Genomics,First Query,0.007704,0.008301,0.005379,0.002975,0.000551,0.000547,0.000100
Genomics,PayOff,44,51,62,17,82,3,-
Genomics,Convergence,-,-,*,*,4062,*,-
Genomics,Robustness,-,-,8E-07,3E-07,5E-08,1E-08,-
Genomics,Time,0.968427,1.007088,1.445911,0.313453,1.088019,1.142605,2.277355
Power,First Query,0.000084,0.000049,0.000034,0.000035,0.000016,0.000016,0.000014
Power,PayOff,4,2,2,1,0,0,-
Power,Convergence,-,-,7,12,16,1993,-
Power,Robustness,-,-,9E-11,7E-11,2E-11,2E-11,-
Power,Time,0.017216,0.023430,0.019345,0.022128,0.017878,0.019799,0.044971
</code>```

When reading into a pandas dataframe, it therefore looks like that:

I have tried all sorts of ways to give the first two a name, but every time, I just overwrote the other ones, but did not touch the first ones.
Example:

```<code>m.columns = ['Dataset', 'Measure'] + m.columns[2:].tolist()
</code>```

This only results in moving all the other ones to the right, starting with MedKD

How is it possible to insert those by using pandas?

Title: Pandas: Add missing column name

Body:
I have a csv file which is missing the first two column names, therefore looking like that:

,,MedKD,AvgKD,Q,AKD,PKD(.2),GPKD(.2),FS
Genomics,First Query,0.007704,0.008301,0.005379,0.002975,0.000551,0.000547,0.000100
Genomics,PayOff,44,51,62,17,82,3,-
Genomics,Convergence,-,-,*,*,4062,*,-
Genomics,Robustness,-,-,8E-07,3E-07,5E-08,1E-08,-
Genomics,Time,0.968427,1.007088,1.445911,0.313453,1.088019,1.142605,2.277355
Power,First Query,0.000084,0.000049,0.000034,0.000035,0.000016,0.000016,0.000014
Power,PayOff,4,2,2,1,0,0,-
Power,Convergence,-,-,7,12,16,1993,-
Power,Robustness,-,-,9E-11,7E-11,2E-11,2E-11,-
Power,Time,0.017216,0.023430,0.019345,0.022128,0.017878,0.019799,0.044971

When reading into a pandas dataframe, it therefore looks like that:

I have tried all sorts of ways to give the first two a name, but every time, I just overwrote the other ones, but did not touch the first ones.
Example:

m.columns = ['Dataset', 'Measure'] + m.columns[2:].tolist()

This only results in moving all the other ones to the right, starting with MedKD

How is it possible to insert those by using pandas?


问:
how to convert mp3 to wav and calculate psnr in python
i want to convert my mp3 to wav file so i can input it on psnr. but when i tried to convert it, i cannot do that. can someone check my code? i was trying this code to convert and the psnr code from here

```<code>import scipy.io.wavfile as wavfile
import os.path
from subprocess import call

if (not os.path.isfile(file)):
  wavConvertCommand = \
    [file,
    "-i", fileMp3, "-acodec", "pcm_u8", "-ar", "22050", fileWav]
  call(wavConvertCommand)

def snr(file):
  if (os.path.isfile(file)):
    data = wavfile.read(file)[1]
    singleChannel = data
    try:
      singleChannel = numpy.sum(data, axis=1)
    except:
      # was mono after all
      pass

    norm = singleChannel / (max(numpy.amax(singleChannel), -1 * numpy.amin(singleChannel)))
    return stats.signaltonoise(norm)
</code>```

my file location

F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\media\mp3\ytmp3free.cc_bebe-rexha-meant-to-be-lyrics-ft-florida-georgia-line-youtubemp3free.org_1_2uxNfcC.mp3

Body:
i want to convert my mp3 to wav file so i can input it on psnr. but when i tried to convert it, i cannot do that. can someone check my code? i was trying this code to convert and the psnr code from here

import scipy.io.wavfile as wavfile
import os.path
from subprocess import call

if (not os.path.isfile(file)):
  wavConvertCommand = \
    [file,
    "-i", fileMp3, "-acodec", "pcm_u8", "-ar", "22050", fileWav]
  call(wavConvertCommand)

def snr(file):
  if (os.path.isfile(file)):
    data = wavfile.read(file)[1]
    singleChannel = data
    try:
      singleChannel = numpy.sum(data, axis=1)
    except:
      # was mono after all
      pass

    norm = singleChannel / (max(numpy.amax(singleChannel), -1 * numpy.amin(singleChannel)))
    return stats.signaltonoise(norm)

my file location

F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\media\mp3\ytmp3free.cc_bebe-rexha-meant-to-be-lyrics-ft-florida-georgia-line-youtubemp3free.org_1_2uxNfcC.mp3


问:
SwiftUI: How wrong is to call the objectWillChange.send() after the change in the model data happened?
I'm trying to better understand the mechanism how SwiftUI gets notified about changes in observed data and invalidates UI.

In particular, I wonder if something won't work correctly (e.g. animations?) when objectWillChange.send() is called on ObservableObject after the underlying data model have changed, and more importantly why is that.

If it doesn't matter when the synthesized publisher notifies its observers after the change, then why is it named objectWillChange and not objectDidChange?

Let's say I have a view model like this the following and it observes changes in some model via a delegate method (the code is simplified for the example purposes):

```<code>
protocol ModelDelegate: AnyObject {
    func modelDidChange() {
}

class Model {

  weak var delegate: ModelDelegate?

  var stroredString: String {
    didSet { self.delegate?.modelDidChange() }
  }

}

class ViewModel: ObservableObject {

  private let model: Model = Model(delegate: self)

  var calculatedProperty: String { model.storedString }

}

extension ViewModel: ModelDelegate {

  func modelDidChange() {
    // we get called when the change has already happened.
    // is it wrong to publish the change via objectWillChange?
    self.objectWillChange.send()
  }
}
</code>```

And then the View looks like this:

```<code>struct MyView: View {

  @ObservedObject private var viewModel: ViewModel

  var body: some View {
    Text(self.viewModel.calculatedProperty)
  }
}
</code>```

Question

Can I expect that something's not going to work correctly when objectWillChange.send() is called on ObservableObject after the underlying data model have changed? If yes, in which case and more importantly, why is that?

If it doesn't matter when the synthesized publisher notifies its observers after the change, then why is it named objectWillChange and not objectDidChange?

Body:
I'm trying to better understand the mechanism how SwiftUI gets notified about changes in observed data and invalidates UI.

In particular, I wonder if something won't work correctly (e.g. animations?) when objectWillChange.send() is called on ObservableObject after the underlying data model have changed, and more importantly why is that.

If it doesn't matter when the synthesized publisher notifies its observers after the change, then why is it named objectWillChange and not objectDidChange?

Let's say I have a view model like this the following and it observes changes in some model via a delegate method (the code is simplified for the example purposes):

protocol ModelDelegate: AnyObject {
    func modelDidChange() {
}

class Model {

  weak var delegate: ModelDelegate?

  var stroredString: String {
    didSet { self.delegate?.modelDidChange() }
  }

}

class ViewModel: ObservableObject {

  private let model: Model = Model(delegate: self)

  var calculatedProperty: String { model.storedString }

}

extension ViewModel: ModelDelegate {

  func modelDidChange() {
    // we get called when the change has already happened.
    // is it wrong to publish the change via objectWillChange?
    self.objectWillChange.send()
  }
}

And then the View looks like this:

struct MyView: View {

  @ObservedObject private var viewModel: ViewModel

  var body: some View {
    Text(self.viewModel.calculatedProperty)
  }
}

Question

Can I expect that something's not going to work correctly when objectWillChange.send() is called on ObservableObject after the underlying data model have changed? If yes, in which case and more importantly, why is that?

If it doesn't matter when the synthesized publisher notifies its observers after the change, then why is it named objectWillChange and not objectDidChange?


问:
Adding a background image to a Blazor chart
We have to migrate and modernize an old application using new development tools and I try to find the tools which can reproduce the features we had so far.
Having a background image in the chart is one of them.

So far I couldn't find a Blazor chart component to which I can add a background image in the chart area only as shown in the attached picture (sorry I'm not allowed to add pictures yet).

Usually in the solutions I already explored like Syncfusion, Mudblazor, and others, the background image can only be added to the whole component.

Maybe someone had a similar issue and found a solution.

Thank you


问:
How to combine tables in a (fairly complicated) BigQuery Query?
So I have a SQL Query that pulls the IP Addresses from the Google Workspace activity logs in BigQuery and then transforms them to Geolocation data.

This all works perfectly fine. However, I also want to pull in the email address of the users as well, and I can't figure out the best way to achieve this.

The email address is available in the table workspace-data.Logs.activity

Example to get the email address:

```<code>SELECT
  DISTINCT(email)
FROM
  `workspace-data.Logs.activity`
</code>```

The IP Address is in the same table as email, accessed via ip_address

Here is my current SQL Query:

```<code>WITH
  source_of_ip_addresses AS (
  SELECT
    REGEXP_REPLACE(SAFE_CONVERT_BYTES_TO_STRING(ip_address), 'xxx', '0') ip,
    COUNT(1) c
  FROM
    `workspace-data.Logs.activity`
  WHERE
    SAFE_CONVERT_BYTES_TO_STRING(ip_address) IS NOT NULL
  GROUP BY
    1 )
SELECT
  city_name,
  country_name,
  country_iso_code,
  SUM(c) c,
  ST_GEOGPOINT(AVG(longitude), AVG(latitude)) point
FROM (
  SELECT
    ip,
    city_name,
    country_name,
    country_iso_code,
    c,
    latitude,
    longitude,
    geoname_id
  FROM (
    SELECT
      *,
      NET.SAFE_IP_FROM_STRING(ip) & NET.IP_NET_MASK(4,
        mask) network_bin
    FROM
      source_of_ip_addresses,
      UNNEST(GENERATE_ARRAY(9,32)) mask
    WHERE
      BYTE_LENGTH(NET.SAFE_IP_FROM_STRING(ip)) = 4 )
  JOIN
    `fh-bigquery.geocode.201806_geolite2_city_ipv4_locs`
  USING
    (network_bin,
      mask) )
WHERE
  city_name IS NOT NULL
GROUP BY
  city_name,
  country_name,
  country_iso_code,
  geoname_id
ORDER BY
  c DESC
</code>```

What would be the best way to incorporate the email addresses for the users alongside the transformed Geolocation data?

Currently, the query will output the following table:

Row
city_name
country_name
country_iso_code
c
point

1
Mountain View
United States
US
50639
POINT(-122.0574 37.4192)

2
Houston
United States
US
24671
POINT(-95.3454 29.9668)

3
Jacksonville
United States
US
6717
POINT(-81.6236 30.19675)

But I would like for it to output:

Row
Email
city_name
country_name
country_iso_code
c
point

1
bob@someaddress.com
Mountain View
United States
US
165
POINT(-122.0574 37.4192)

2
frodo@someaddress.com
Houston
United States
US
134
POINT(-95.3454 29.9668)

3
darth@someaddress.com
Jacksonville
United States
US
292
POINT(-81.6236 30.19675)

Body:
So I have a SQL Query that pulls the IP Addresses from the Google Workspace activity logs in BigQuery and then transforms them to Geolocation data.

This all works perfectly fine. However, I also want to pull in the email address of the users as well, and I can't figure out the best way to achieve this.

The email address is available in the table workspace-data.Logs.activity

Example to get the email address:

SELECT
  DISTINCT(email)
FROM
  `workspace-data.Logs.activity`

The IP Address is in the same table as email, accessed via ip_address

Here is my current SQL Query:

WITH
  source_of_ip_addresses AS (
  SELECT
    REGEXP_REPLACE(SAFE_CONVERT_BYTES_TO_STRING(ip_address), 'xxx', '0') ip,
    COUNT(1) c
  FROM
    `workspace-data.Logs.activity`
  WHERE
    SAFE_CONVERT_BYTES_TO_STRING(ip_address) IS NOT NULL
  GROUP BY
    1 )
SELECT
  city_name,
  country_name,
  country_iso_code,
  SUM(c) c,
  ST_GEOGPOINT(AVG(longitude), AVG(latitude)) point
FROM (
  SELECT
    ip,
    city_name,
    country_name,
    country_iso_code,
    c,
    latitude,
    longitude,
    geoname_id
  FROM (
    SELECT
      *,
      NET.SAFE_IP_FROM_STRING(ip) & NET.IP_NET_MASK(4,
        mask) network_bin
    FROM
      source_of_ip_addresses,
      UNNEST(GENERATE_ARRAY(9,32)) mask
    WHERE
      BYTE_LENGTH(NET.SAFE_IP_FROM_STRING(ip)) = 4 )
  JOIN
    `fh-bigquery.geocode.201806_geolite2_city_ipv4_locs`
  USING
    (network_bin,
      mask) )
WHERE
  city_name IS NOT NULL
GROUP BY
  city_name,
  country_name,
  country_iso_code,
  geoname_id
ORDER BY
  c DESC

What would be the best way to incorporate the email addresses for the users alongside the transformed Geolocation data?

Currently, the query will output the following table:

Row
city_name
country_name
country_iso_code
c
point

1
Mountain View
United States
US
50639
POINT(-122.0574 37.4192)

2
Houston
United States
US
24671
POINT(-95.3454 29.9668)

3
Jacksonville
United States
US
6717
POINT(-81.6236 30.19675)

But I would like for it to output:

Row
Email
city_name
country_name
country_iso_code
c
point

1
bob@someaddress.com
Mountain View
United States
US
165
POINT(-122.0574 37.4192)

2
frodo@someaddress.com
Houston
United States
US
134
POINT(-95.3454 29.9668)

3
darth@someaddress.com
Jacksonville
United States
US
292
POINT(-81.6236 30.19675)


问:
Place sprites at certain positions using a shader

What I achieved:

I created a shader (based on this code with this plant asset) that takes a black and white reference image (like a height map) and places plants on a grid determined by the darkness/lightness-value of the respective pixel.

Where I am stuck:

I am trying to get a more organic look (instead of looking like a tileset) so I used poisson-disc-sampling to get random-looking coordinates for where I want to place the plants. In "normal" code I'd just loop through the array of the generated coordinates and draw a sprite ... but I have no clue how to do that with a shader.

Question:

Is it even possible to use a shader to place images at certain positions?

(I could obviously generate a static image but I am planning to adjust the shader to simulate wind going over the vegetation like this)

Thanks already in advance for any tip or help!


问:
Is there a way to have formdata conform to an interface or type?
I am creating a form in React with TS like so

VendingMachine.tsx

```<code>interface Drink {
    Drink: string,
    Money: number,
    Sugar: number
}

export default function VendingMachine(){

    const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget); // This returns me form data from my <inputs />
        const fieldValues = Object.fromEntries(formData.entries()) // This need to be of the shape of the Drink interface above
    }

    return (
        <form onSubmit={handleFormSubmit}>
        {
            ["Drink", "Money", "Sugar"].map(name => (
                <VendingMachineInput key={name} name={name} /> // <input /> component
            ))
        }
        <input type="submit" value="Get me a beverage!" />
        </form>
    )
}
</code>```

VendingMachineInput component is nothing but multiple input types.

In my handleSubmit function in VendingMachine component I get an object by using FormData like so

```<code>{
    "Drink": "Tea",
    "Money": "2",
    "Sugar": "1"
}
</code>```

But its inferred type is

const fieldValues: {[k:string]: FormDataEntryValue} = Object.fromEntries(formData.entries())

My question is how to I convert this fieldValues in my handleSubmit function to be of the shape of interface Drink above?

Body:
I am creating a form in React with TS like so

VendingMachine.tsx

interface Drink {
    Drink: string,
    Money: number,
    Sugar: number
}

export default function VendingMachine(){

    const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget); // This returns me form data from my <inputs />
        const fieldValues = Object.fromEntries(formData.entries()) // This need to be of the shape of the Drink interface above
    }

    return (
        <form onSubmit={handleFormSubmit}>
        {
            ["Drink", "Money", "Sugar"].map(name => (
                <VendingMachineInput key={name} name={name} /> // <input /> component
            ))
        }
        <input type="submit" value="Get me a beverage!" />
        </form>
    )
}

VendingMachineInput component is nothing but multiple input types.

In my handleSubmit function in VendingMachine component I get an object by using FormData like so

{
    "Drink": "Tea",
    "Money": "2",
    "Sugar": "1"
}

But its inferred type is

const fieldValues: {[k:string]: FormDataEntryValue} = Object.fromEntries(formData.entries())

My question is how to I convert this fieldValues in my handleSubmit function to be of the shape of interface Drink above?


问:
ReactJS - Overwrite State Value while Form input for dynamic field
I have case that I need to setState dynamically from Form at Modal. But need to overwrite for same field name but add more array for different field name.

For example, if field_1 is empty and user fill in field_1 the date will store to state, and if user fill in the field_1 again, the data will overwrite the field_1. And also if user fill in field_2, state will add new array.

Here's my code:

```<code>const [data, setData] = useState([]);
const [comment, setComment] = useState([]);
const inputRef = useRef('');

const dataItem = [
{
    name: "Data 1",
    value: "field_1"
  },
  {
    name: "Data 2",
    value: "field_2"
  },
];

const openModal = (e) => {
   setData(e);
   showModals();
};

const handleInput = (name, value) => {
 setComment({ comments: [{ name = [value:value]}, ...comment] });
};

const [showModals, hideModal] = useModal(
() => (
   <ReactModal>
      <input name={modalData.value} ref={inputRef} />
      <button onClick={() => handleInput(modalData.value, inputRef.current.value}>Save Comment</button>
   </ReactModal>
 ),[modalData, modalDataNew]);

{dataItem.map((item, index) => (
  <button
   key={index}
   onClick={() => openModal({
     value: item.value,
     name: item.name
    })}>
   {item.name}
  </button>
))}
</code>```

I need to create state like this if user fill the field_1:

```<code>{ "comment": {
    "field_1": {
        "value": "Comment 1"
    }
  }
}
</code>```

And need to change state like this if user change the field_1:

```<code>{ "comment": {
    "field_1": {
        "value": "Comment changed"
    }
  }
}
</code>```

And need to add more array if user fill in field_2:

```<code>{ "comment": {
    "field_1": {
        "value": "Comment changed"
    },
     "field_2": {
        "value": "Comment 2"
    }
  }
}
</code>```

Body:
I have case that I need to setState dynamically from Form at Modal. But need to overwrite for same field name but add more array for different field name.

For example, if field_1 is empty and user fill in field_1 the date will store to state, and if user fill in the field_1 again, the data will overwrite the field_1. And also if user fill in field_2, state will add new array.

Here's my code:

const [data, setData] = useState([]);
const [comment, setComment] = useState([]);
const inputRef = useRef('');

const dataItem = [
{
    name: "Data 1",
    value: "field_1"
  },
  {
    name: "Data 2",
    value: "field_2"
  },
];

const openModal = (e) => {
   setData(e);
   showModals();
};

const handleInput = (name, value) => {
 setComment({ comments: [{ name = [value:value]}, ...comment] });
};

const [showModals, hideModal] = useModal(
() => (
   <ReactModal>
      <input name={modalData.value} ref={inputRef} />
      <button onClick={() => handleInput(modalData.value, inputRef.current.value}>Save Comment</button>
   </ReactModal>
 ),[modalData, modalDataNew]);

{dataItem.map((item, index) => (
  <button
   key={index}
   onClick={() => openModal({
     value: item.value,
     name: item.name
    })}>
   {item.name}
  </button>
))}

I need to create state like this if user fill the field_1:

{ "comment": {
    "field_1": {
        "value": "Comment 1"
    }
  }
}

And need to change state like this if user change the field_1:

{ "comment": {
    "field_1": {
        "value": "Comment changed"
    }
  }
}

And need to add more array if user fill in field_2:

{ "comment": {
    "field_1": {
        "value": "Comment changed"
    },
     "field_2": {
        "value": "Comment 2"
    }
  }
}


问:
Creating Containerized Applications on Azure with a VNet
I have a set of containerized http services that I wrote, the services are configured using a docker-compose.yml and a collection of Dockerfiles to build the service images.  I would like to be able to host my docker-compose.yml setup on Azure, specifically one of my http services requires the ability to rotate which outbound Public IP Address it is making requests from (similar to a proxy.)

I have looked at the following resources:

Azure App Service

Container App

Container Instances

Virtual Machine

I have been able to deploy my app successfully and test it on all of the solutions, however, my issue is that one of my services needs to rotate the outbound IP Address that it is making requests from (kind of like using a proxy to make requests.)

I can accomplish this with a virtual machine and by adding a VNet with multiple IP Address resources associated.  This works perfectly fine but using the virtual machine alienates me from the benefits of azure's other managed container services.

I Have read the docs for App Service, Container App, and Container Instances and it doesn't seem like it's possible to assign these resources to a VNet with my current configuration.

Any advice on how I could go about solving my problem is appreciated.


问:
Optimising first solution strategy for VRP
I'm trying to pick the best first solution strategy to use on a VRP.

My use case is that an individual case takes around 60 seconds to solve on average, but i need to run hundreds or thousands of cases sequentially such that my whole solution takes hours.

I can trade off finding the optimal solution against time; a good solution is usually good enough.

Using the different strategies, i get solve times between 1 and 120 seconds.

My questions:

Is it reasonable to assume that the best strategy for one case will also be the best for other cases given my model does not change much - just different pickup nodes and time windows?

Has anyone tried first testing each strategy then picking the best to use for the rest of the cases?

If i was to set the limit time to e.g. 1 second, would the strategy that gives the lowest objective function after say 1s also be likely to give the best solution strategy after 60s, unlimited?

Many thanks!


问:
Firebase Recyler Adapter
FirebaseRecyclerAdapter cannot be implemented when I use it, as shown below:

```<code>import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;

public class AddClassAdapter extends FirebaseRecylerAdapter{

}
</code>```

Image of Error

Even though I've implemented these things on build.gradle module

```<code>implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.google.firebase:firebase-auth:21.1.0'
    implementation 'com.google.firebase:firebase-firestore:24.4.1'
    implementation 'com.google.firebase:firebase-database:20.1.0'
    implementation 'com.google.firebase:firebase-storage:20.1.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
    implementation platform('com.google.firebase:firebase-bom:31.1.0')
    implementation 'com.google.firebase:firebase-database'
    implementation'com.squareup.picasso:picasso:2.71828'
    implementation 'io.github.muddz:styleabletoast:2.4.0'
    implementation 'com.makeramen:roundedimageview:2.3.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation 'com.firebaseui:firebase-ui-database:0.4.0'
</code>```

Title: Firebase Recyler Adapter

Body:
FirebaseRecyclerAdapter cannot be implemented when I use it, as shown below:

import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;

public class AddClassAdapter extends FirebaseRecylerAdapter{

}

Image of Error

Even though I've implemented these things on build.gradle module

implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.google.firebase:firebase-auth:21.1.0'
    implementation 'com.google.firebase:firebase-firestore:24.4.1'
    implementation 'com.google.firebase:firebase-database:20.1.0'
    implementation 'com.google.firebase:firebase-storage:20.1.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
    implementation platform('com.google.firebase:firebase-bom:31.1.0')
    implementation 'com.google.firebase:firebase-database'
    implementation'com.squareup.picasso:picasso:2.71828'
    implementation 'io.github.muddz:styleabletoast:2.4.0'
    implementation 'com.makeramen:roundedimageview:2.3.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation 'com.firebaseui:firebase-ui-database:0.4.0'


问:
Employee shift scheduling optimization of multiple constraints
I am working on filling a daily schedule. During each day there are a number of tasks that have different shift lengths. For example, task_1 has three 8 hour shifts during a 24 hour period and task_2 has six 4 hour shifts during a 24 hour period. There is also a task which is only done during certain hours and consists of four 4 hour shifts during a 24 hour period.

On top of that, certain tasks require a group of employees with different experience levels. Employees can either be simple workers or team leaders. The group of employees is divided into three teams where each team consists of a number of leaders and workers. A constraint I have is that for tasks that require multiple employees , the employees need to be from the same team. For example, group_1 consists of 2 leaders and 3 workers [leader_1, leader_2, worker_1, worker_2, worker_3]. Task_1 requires a team leader and two employees and they need to be from the same group. I can schedule [leader_1, worker_1, worker_2] to the first shift but for the second shift I would only have 1 leader and 1 worker and would need to schedule employees from another group.

I am trying to schedule employees so that there is a maximum amount of time between shifts, i.e. they have as much downtime between shifts as possible. I'm hoping to find a way to automate the scheduling and have been looking at examples of or-tools and pyomo. Right now I don't even have an example code since I'm trying to understand if what I am trying to do is possible with the amount of variables and constraints I have.

Any help would be much appreciated!


问:
Razor cshtml : Open a modal with data-toggle/data-target inside a post form
I'm stuck on a problem right now:

In my cshtml file,
I have a table which display multiple datas, and on each rows we have an "Edit" button.
The Table

This button (submit) have to open a modal to Edit the data selected.
the button

It is doing stuff in the Cshtml.cs
function used in cshtml.cs

and this is the modal it has to open in the cshtml :
Modal

What is happening?

The call to the function is well executed, and my modal is opening well with the datas in it.
BUT , it is closing right after it appears (between 0.1 and 1 second)

In fact, my submit button is inside a Post form, which permit me to call the csharp function.
But I think the post thing is closing my modal because of a page reset.

button inside the form

I dont know how to solve it, and I'm searching here for help.
Thank you very much for reading this.


问:
Redux - Slice doesn't store data in state?
I want to create a Slice that returns some data.

The Problem: from the redux-logger (action) I can tell that the requested data is returned, but isn't stored in a state...

This is the slice:

```<code>const postSlice = createSlice({
  name: 'postboxApp/post',
  initialState: [],
  reducers: {
    newPost: (state, action) => PostModel(),
    resetPost: () => null,
  },
  extraReducers: {
    [getPost.fulfilled]: (state, action) => action.payload,
  },
});
</code>```

Here is the way I call the Asny Thunk:

dispatch(getPost(routeParams.id));

Does anyone see my mistake?

Body:
I want to create a Slice that returns some data.

The Problem: from the redux-logger (action) I can tell that the requested data is returned, but isn't stored in a state...

This is the slice:

const postSlice = createSlice({
  name: 'postboxApp/post',
  initialState: [],
  reducers: {
    newPost: (state, action) => PostModel(),
    resetPost: () => null,
  },
  extraReducers: {
    [getPost.fulfilled]: (state, action) => action.payload,
  },
});

Here is the way I call the Asny Thunk:

dispatch(getPost(routeParams.id));

Does anyone see my mistake?


问:
TextArea dont auto-resize correct when starting on one row
I having some trouble to get a textarea to auto expand from one row.
It works when I have 3 or more rows and one row, but the two first looks weird.

Can't find a good way of knowing when the text is clipped like that. Because the lenght of the input will be dynamic.
I have seen solutions that kind of work here on Stackoverflow, but I must have the total height of the input to start at 40px; And the solutions I have seen cant handle that case.

(Dont mind the black-border for the textarea, for some reason codeSandBox shows it but not for me.)

I have a codeSandbox that shows the issue:
https://codesandbox.io/s/affectionate-yalow-fnqnep?file=/src/App.js:241-296

Anyone had a similliar issue or could point me in the right direction?

Edit:
Working React component:

```<code>import React, { useState, useEffect } from "react";
import styled from "styled-components";

const InputWrapper = styled.div`
  display: inline-flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
  padding: 8px 16px;
  border-radius: 6px;
  background-color: white;
  border: 1px solid black;
`;

const StyledTextArea = styled.textarea`
  width: 100%;
  max-height: 300px;
  font-size: 16px;
  background-color: white;
  line-height: 18px;
  resize: none;
  transition: all 300ms;
  border: none;
  overflow: hidden;
`;
const TextArea = ({ value, placeholder, handleEvent }) => {
  const [textAreaRef, setTextAreaRef] = useState(React.createRef());
  const updateHeight = () => {
    const updatedTextArea = { ...textAreaRef };
    updatedTextArea.current.style.height = "";
    updatedTextArea.current.style.height = `${updatedTextArea.current.scrollHeight}px`;
    setTextAreaRef(updatedTextArea);
  };

  useEffect(() => updateHeight(), [value]);

  return (
    <InputWrapper>
      <StyledTextArea
        ref={textAreaRef}
        value={value}
        rows={1}
        placeholder={placeholder}
        onChange={handleEvent}
      />
    </InputWrapper>
  );
};

export default TextArea;
</code>```

Body:
I having some trouble to get a textarea to auto expand from one row.
It works when I have 3 or more rows and one row, but the two first looks weird.

Can't find a good way of knowing when the text is clipped like that. Because the lenght of the input will be dynamic.
I have seen solutions that kind of work here on Stackoverflow, but I must have the total height of the input to start at 40px; And the solutions I have seen cant handle that case.

(Dont mind the black-border for the textarea, for some reason codeSandBox shows it but not for me.)

I have a codeSandbox that shows the issue:
https://codesandbox.io/s/affectionate-yalow-fnqnep?file=/src/App.js:241-296

Anyone had a similliar issue or could point me in the right direction?

Edit:
Working React component:

import React, { useState, useEffect } from "react";
import styled from "styled-components";

const InputWrapper = styled.div`
  display: inline-flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
  padding: 8px 16px;
  border-radius: 6px;
  background-color: white;
  border: 1px solid black;
`;

const StyledTextArea = styled.textarea`
  width: 100%;
  max-height: 300px;
  font-size: 16px;
  background-color: white;
  line-height: 18px;
  resize: none;
  transition: all 300ms;
  border: none;
  overflow: hidden;
`;
const TextArea = ({ value, placeholder, handleEvent }) => {
  const [textAreaRef, setTextAreaRef] = useState(React.createRef());
  const updateHeight = () => {
    const updatedTextArea = { ...textAreaRef };
    updatedTextArea.current.style.height = "";
    updatedTextArea.current.style.height = `${updatedTextArea.current.scrollHeight}px`;
    setTextAreaRef(updatedTextArea);
  };

  useEffect(() => updateHeight(), [value]);

  return (
    <InputWrapper>


问:
Swift catch objc NSError
I defined a class as follows

```<code>@interface TestModel : NSObject

- (BOOL)test1:(NSError * _Nullable * _Nullable)error;

- (int)test2:(NSError * _Nullable * _Nullable)error;

@end

@implementation TestModel

- (BOOL)test1:(NSError * _Nullable * _Nullable)error {
    return YES;
}

- (int)test2:(NSError * _Nullable * _Nullable)error {
    if (error) {
        *error = [NSError errorWithDomain:@"domain" code:0 userInfo:nil];
    }
    return 9;
}

@end
</code>```

I use them like this in Swift

```<code>@objcMembers
@objc public class Utils: NSObject {
    func test() {
        do {
            let value = try TestModel().test1()
            print("success value: \(value)")
        } catch  {
            print("failed error: \(error)")
        }

        var error: NSError?
        let value = TestModel().test2(&error)
        print("value>>>>>> \(value)")
    }
}
</code>```

Then, I got result

```<code>success value: ()
value>>>>>> 9
</code>```

There are two problems here, I don't really understand.

Why does test1 need catch exceptions, but test2 does not?

Why does test1 not return a value?

Title: Swift catch objc NSError

Body:
I defined a class as follows

@interface TestModel : NSObject

- (BOOL)test1:(NSError * _Nullable * _Nullable)error;

- (int)test2:(NSError * _Nullable * _Nullable)error;

@end

@implementation TestModel

- (BOOL)test1:(NSError * _Nullable * _Nullable)error {
    return YES;
}

- (int)test2:(NSError * _Nullable * _Nullable)error {
    if (error) {
        *error = [NSError errorWithDomain:@"domain" code:0 userInfo:nil];
    }
    return 9;
}

@end

I use them like this in Swift

@objcMembers
@objc public class Utils: NSObject {
    func test() {
        do {
            let value = try TestModel().test1()
            print("success value: \(value)")
        } catch  {
            print("failed error: \(error)")
        }

        var error: NSError?
        let value = TestModel().test2(&error)
        print("value>>>>>> \(value)")
    }
}

Then, I got result

success value: ()
value>>>>>> 9

There are two problems here, I don't really understand.

Why does test1 need catch exceptions, but test2 does not?

Why does test1 not return a value?


问:
Error testing coverage , should update recommendation state when data is gotten successfully
I'm a beginner in flutter and currently learning testing . here i found an error in my project when i run the program.please help me fix it

i got this error

```<code> C:\src\flutter\bin\cache\dart-sdk\bin\dart.exe test C:\Expert1\ditonton-master-main\test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart -p vm --plain-name 'Get Televisi Recommendations should get data from the use case'
04:51 +169 -4: C:\Expert1\ditonton-master-main\test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart: Get Televisi Recommendations should update recommendation state when data is gotten successfully [E]
    Actual: [
              Televisi:Televisi(2000-09-09 09:09:09.591918, backdropPath, [1, 2, 3], 1, original_name, overview, 1.0, posterPath, [origin_country, origin_country], name, original_language, 1.0, 1)
            ]

  package:test_api                                                                        expect
  package:flutter_test/src/widget_tester.dart 460:16                                      expect
  test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart 141:11  main.<fn>.<fn>
</code>```

for more detailed code you can see in my repository .here I met 3 errors when testing, and I don't know how to fix it, help me
https://github.com/rinaoktavira/ditonton-master

Body:
I'm a beginner in flutter and currently learning testing . here i found an error in my project when i run the program.please help me fix it

i got this error

 C:\src\flutter\bin\cache\dart-sdk\bin\dart.exe test C:\Expert1\ditonton-master-main\test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart -p vm --plain-name 'Get Televisi Recommendations should get data from the use case'
04:51 +169 -4: C:\Expert1\ditonton-master-main\test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart: Get Televisi Recommendations should update recommendation state when data is gotten successfully [E]
    Actual: [
              Televisi:Televisi(2000-09-09 09:09:09.591918, backdropPath, [1, 2, 3], 1, original_name, overview, 1.0, posterPath, [origin_country, origin_country], name, original_language, 1.0, 1)
            ]

  package:test_api                                                                        expect
  package:flutter_test/src/widget_tester.dart 460:16                                      expect
  test\presentation\provider\televisi_provider\televisi_detail_notifier_test.dart 141:11  main.<fn>.<fn>

for more detailed code you can see in my repository .here I met 3 errors when testing, and I don't know how to fix it, help me
https://github.com/rinaoktavira/ditonton-master


问:
How do I import files from the same directory in order to run scripts in GCP shell
I am trying to run the command gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app but I am getting the following error :

```<code>  File "/home/oscarmarinoa/API-deployment-GCP/main.py", line 2, in <module>
    import models
  File "/home/oscarmarinoa/API-deployment-GCP/models.py", line 2, in <module>
    from .database import Base
ImportError: attempted relative import with no known parent package
</code>```

My guess is that the problem is related to the first lines of my main.py script and my folder structure

```<code>from fastapi import FastAPI, Depends
import models
from database import engine, SessionLocal
from sqlalchemy.orm import Session
import Funciones

project
│   Funciones.py
|   Readme
|   app.yaml
│   database.py
|   main.py
|   models.py
|   requirements.py
|   schemas.py
</code>```

I tried changing the way I imported the file from other scripts...Initially my code was like this but I was getting errors because of schemas and models:

```<code>from . import schemas, models
from .database import engine, SessionLocal
from . import Funciones
</code>```

So I erased the dots in each of the lines but I get the problem mentioned previously.

Body:
I am trying to run the command gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app but I am getting the following error :

  File "/home/oscarmarinoa/API-deployment-GCP/main.py", line 2, in <module>
    import models
  File "/home/oscarmarinoa/API-deployment-GCP/models.py", line 2, in <module>
    from .database import Base
ImportError: attempted relative import with no known parent package

My guess is that the problem is related to the first lines of my main.py script and my folder structure

from fastapi import FastAPI, Depends
import models
from database import engine, SessionLocal
from sqlalchemy.orm import Session
import Funciones

project
│   Funciones.py
|   Readme
|   app.yaml
│   database.py
|   main.py
|   models.py
|   requirements.py
|   schemas.py

I tried changing the way I imported the file from other scripts...Initially my code was like this but I was getting errors because of schemas and models:

from . import schemas, models
from .database import engine, SessionLocal
from . import Funciones

So I erased the dots in each of the lines but I get the problem mentioned previously.


问:
React Native, Requeting Read SMS Permission not work
I want to read phone sms using expo react-native, I'm sending request to read sms permission and nothing is happening.

When I click the button it's not opening the alert modal

here is my code:

import 'react-native-gesture-handler';
import '@babel/helper-skip-transparent-expression-wrappers'
import { StatusBar } from 'expo-status-bar';
import React,{useState,useEffect,useRef} from 'react';
import { StyleSheet, Text, View,Button } from 'react-native';
import RootStackScreen from './android/screens/RootStackScreen'
import { NavigationContainer } from '@react-navigation/native';
import { Alert, PermissionsAndroid } from 'react-native';

export default function App() {

  async function requestSmsPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_SMS,
      {
        title: 'My App SMS Permission',
        message:
          'My App needs access to your SMS messages ' +
          'so you can read them in the app.',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('You can read SMS messages');
    } else {
      console.log('SMS permission denied');
    }
  } catch (err) {
    console.log(err);
  }
}

  return (
     <>
     <View style={{marginTop: 200}}></View>
      <Button
      title="Request SMS Permission"
      onPress={requestSmsPermission}
      style={{marginTop: 400}}
    />
     </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});```

I want the codes to ask user permission to read sms using expo, react-native

Body:
I want to read phone sms using expo react-native, I'm sending request to read sms permission and nothing is happening.

When I click the button it's not opening the alert modal

here is my code:

import 'react-native-gesture-handler';
import '@babel/helper-skip-transparent-expression-wrappers'
import { StatusBar } from 'expo-status-bar';
import React,{useState,useEffect,useRef} from 'react';
import { StyleSheet, Text, View,Button } from 'react-native';
import RootStackScreen from './android/screens/RootStackScreen'
import { NavigationContainer } from '@react-navigation/native';
import { Alert, PermissionsAndroid } from 'react-native';

export default function App() {

  async function requestSmsPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_SMS,
      {
        title: 'My App SMS Permission',
        message:
          'My App needs access to your SMS messages ' +
          'so you can read them in the app.',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('You can read SMS messages');
    } else {
      console.log('SMS permission denied');
    }
  } catch (err) {
    console.log(err);
  }
}

  return (
     <>
     <View style={{marginTop: 200}}></View>
      <Button
      title="Request SMS Permission"
      onPress={requestSmsPermission}
      style={{marginTop: 400}}
    />
     </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

I want the codes to ask user permission to read sms using expo, react-native


问:
C++ variadic template complains about format not a string literal and no format arguments
I want to write a formatToStr() which receives a format in const char* and returns the formatted string.

My formatToStr() sometimes may not receive parameters, as printf() function.

```<code>#include <string>

template<typename... Args>
static inline std::string formatToStr(const char* format, const Args&... args) {
        char buff[1024];
        snprintf(buff, sizeof(buff), format, args...);
        return std::string(buff);
}

int main() {
        printf("%s\n", FormatToStr("test").c_str());
        return 0;
}
</code>```

This code provides a warning:

```<code>$ g++ --version
g++ (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
...
$ g++ ./z.cpp
./z.cpp: In instantiation of ‘std::string formatToStr(const char*, const Args& ...) [with Args = {}; std::string = std::__cxx11::basic_string<char>]’:
./z.cpp:11:28:   required from here
./z.cpp:6:17: warning: format not a string literal and no format arguments [-Wformat-security]
    6 |         snprintf(buff, sizeof(buff), format, args...);
      |         ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

Is there a way to write better code to remove this warning?
I can always ignore it, but I wish to solve it in a better way.

```<code>#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
...
#pragma GCC diagnostic pop
</code>```

Thanks

-- EDIT --

Doesn't seem like __attribute__((__format__ (__printf__, 1, 0))) from here works. So, I think it's ok to re-open the question for commenting or answering.

Body:
I want to write a formatToStr() which receives a format in const char* and returns the formatted string.

My formatToStr() sometimes may not receive parameters, as printf() function.

#include <string>

template<typename... Args>
static inline std::string formatToStr(const char* format, const Args&... args) {
        char buff[1024];
        snprintf(buff, sizeof(buff), format, args...);
        return std::string(buff);
}

int main() {
        printf("%s\n", FormatToStr("test").c_str());
        return 0;
}

This code provides a warning:

$ g++ --version
g++ (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
...
$ g++ ./z.cpp
./z.cpp: In instantiation of ‘std::string formatToStr(const char*, const Args& ...) [with Args = {}; std::string = std::__cxx11::basic_string<char>]’:
./z.cpp:11:28:   required from here
./z.cpp:6:17: warning: format not a string literal and no format arguments [-Wformat-security]
    6 |         snprintf(buff, sizeof(buff), format, args...);
      |         ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Is there a way to write better code to remove this warning?
I can always ignore it, but I wish to solve it in a better way.

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
...
#pragma GCC diagnostic pop

Thanks

-- EDIT --

Doesn't seem like __attribute__((__format__ (__printf__, 1, 0))) from here works. So, I think it's ok to re-open the question for commenting or answering.


问:
plotly Dash time range
is there any way in Plotly dash to create a time range, in this a callback will be executed other than dcc.DatePickerRange?
I want to create a time range for less than a day, but I have not found any method!
any ideas?

Thanks

Title: plotly Dash time range


问:
Remove marker is disabled after one marker remove from map
I am using the react-leaflet/core library together with the plugin Leaflet-Geoman which using the removalMode to delete the marker from map

Below is my code

```<code>import { useLeafletContext } from "@react-leaflet/core";
const Geoman = (props) => {

    const context = useLeafletContext();
     useEffect(() => {
        const leafletContainer = context.layerContainer || context.map;

        (leafletContainer as any).pm.addControls({
            drawMarker: true,
            dragMode: false,
            removalMode: true,
        });
        (leafletContainer as any).pm.Toolbar.buttons.removalMode._button.title = 'Delete Data'";

        (leafletContainer as any).on("pm:remove", (e) => {
            //  Delete code for marker
        });

        return (<></>);
};
</code>```

But it is working for only one time, to do second time need to click again on Remove button

Is there any solution to do it only once sop i can delete multiple markers from map

Body:
I am using the react-leaflet/core library together with the plugin Leaflet-Geoman which using the removalMode to delete the marker from map

Below is my code

import { useLeafletContext } from "@react-leaflet/core";
const Geoman = (props) => {

    const context = useLeafletContext();
     useEffect(() => {
        const leafletContainer = context.layerContainer || context.map;

        (leafletContainer as any).pm.addControls({
            drawMarker: true,
            dragMode: false,
            removalMode: true,
        });
        (leafletContainer as any).pm.Toolbar.buttons.removalMode._button.title = 'Delete Data'";

        (leafletContainer as any).on("pm:remove", (e) => {
            //  Delete code for marker
        });

        return (<></>);
};

But it is working for only one time, to do second time need to click again on Remove button

Is there any solution to do it only once sop i can delete multiple markers from map


问:
Blazor Wasm download static file for offline mode
As other apps, my blazor PWA app is loading images and content from server (static wwwroot files) when needed, so when user goes to the page that use those content.

I would like to embed some files at startup (with a loader) to be sure that in case of Offline moment user still have necessary content.

I see two ways :

finding a way to tell blazor that it needs extra statics content at startup

make a special "download page" that will download necessary content to localstorage of the browser. This could be a solution but I think a bit more long to code, because I'll have to code a "writer/reader" service.

Any idea ?


问:
Can hashmaps store vectors of vectors?
So for a uni project I have to find the most time efficient algorithm to a problem given. I know I will have to store 2 dimensional vectors (a matrix) somewhere. This could be a list, a hashmap,  the order doesn't matter I just need eficiency in adding new matrixes and in looking them up.

So for instance each element would be a matrix like this:

```<code>[[0,1]
 [0,0]]
</code>```

And i want to store multiple of these inside some data structure.
I was thinking of using vectors for the matrix itself and a hashmap, if possible, to store the matrixes.

If i used the hashmaps what would i use as keys? Maybe the number of matrixes already inside the hashmap? Would that work and would that be time efficient?

Thank you

Title: Can hashmaps store vectors of vectors?

Body:
So for a uni project I have to find the most time efficient algorithm to a problem given. I know I will have to store 2 dimensional vectors (a matrix) somewhere. This could be a list, a hashmap,  the order doesn't matter I just need eficiency in adding new matrixes and in looking them up.

So for instance each element would be a matrix like this:

[[0,1]
 [0,0]]

And i want to store multiple of these inside some data structure.
I was thinking of using vectors for the matrix itself and a hashmap, if possible, to store the matrixes.

If i used the hashmaps what would i use as keys? Maybe the number of matrixes already inside the hashmap? Would that work and would that be time efficient?

Thank you


问:
Issue with creating weak encryptor
I have this code that I'm trying to use to decrypt some byte array

```<code> public static class DESCryptoExtensions
{
    public static byte[] Encrypt(byte[] data, byte[] key, byte[] IV)
    {
        MemoryStream mStream = new MemoryStream();
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Padding = PaddingMode.None;
        CryptoStream cStream = new CryptoStream(mStream,
            des.CreateWeakEncryptor(key, IV),
            CryptoStreamMode.Write);
        cStream.Write(data, 0, data.Length);
        cStream.FlushFinalBlock();
        byte[] ret = mStream.ToArray();
        cStream.Close();
        mStream.Close();
        return ret;
    }

    public static byte[] Decrypt(byte[] data, byte[] key, byte[] IV)
    {
        MemoryStream msDecrypt = new MemoryStream(data);
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Padding = PaddingMode.None;
        CryptoStream csDecrypt = new CryptoStream(msDecrypt,
            des.CreateWeakDecryptor(key, IV),
            CryptoStreamMode.Read);
        byte[] fromEncrypt = new byte[data.Length];
        csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
        return fromEncrypt;
    }

    #region DESCryptoExtensions
    public static ICryptoTransform CreateWeakEncryptor(this DESCryptoServiceProvider cryptoProvider, byte[] key, byte[] iv)
    {
        MethodInfo mi = cryptoProvider.GetType().GetMethod("_NewEncryptor", BindingFlags.NonPublic | BindingFlags.Instance);
        object[] Par = { key, cryptoProvider.Mode, iv, cryptoProvider.FeedbackSize, 0 };
        ICryptoTransform trans = mi.Invoke(cryptoProvider, Par) as ICryptoTransform;
        return trans;
    }
    public static ICryptoTransform CreateWeakEncryptor(this DESCryptoServiceProvider cryptoProvider)
    {
        return CreateWeakEncryptor(cryptoProvider, cryptoProvider.Key, cryptoProvider.IV);
    }
    public static ICryptoTransform CreateWeakDecryptor(this DESCryptoServiceProvider cryptoProvider, byte[] key, byte[] iv)
    {
        return CreateWeakEncryptor(cryptoProvider, key, iv);
    }
    public static ICryptoTransform CreateWeakDecryptor(this DESCryptoServiceProvider cryptoProvider)
    {
        return CreateWeakDecryptor(cryptoProvider, cryptoProvider.Key, cryptoProvider.IV);
    }
    #endregion
}
</code>```

Now I try to run this code like so..

```<code>   byte[] challenge = new byte[] { 0x93, 0x9d, 0x2c, 0x2e, 0xa1, 0x65, 0x75, 0xd5 };

byte[] rndA = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

byte[] key = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

var iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

var test = DESCryptoExtensions.Decrypt(challenge, key, iv);
</code>```

And then I get an error on this line..

```<code> ICryptoTransform trans = mi.Invoke(cryptoProvider, Par) as ICryptoTransform;

 Object reference not set to an instance of an object.
</code>```

All I want to do is to decrypt the challenge byte array using the key byte array.. using DES decryption..PLEASE DON'T SUGGEST I CHANGE THE KEY..I've been down a rabbit hole with this stuff so help is appreciated

Title: Issue with creating weak encryptor

Body:
I have this code that I'm trying to use to decrypt some byte array

 public static class DESCryptoExtensions
{
    public static byte[] Encrypt(byte[] data, byte[] key, byte[] IV)
    {
        MemoryStream mStream = new MemoryStream();
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Padding = PaddingMode.None;
        CryptoStream cStream = new CryptoStream(mStream,
            des.CreateWeakEncryptor(key, IV),
            CryptoStreamMode.Write);
        cStream.Write(data, 0, data.Length);
        cStream.FlushFinalBlock();
        byte[] ret = mStream.ToArray();
        cStream.Close();
        mStream.Close();
        return ret;
    }

    public static byte[] Decrypt(byte[] data, byte[] key, byte[] IV)
    {
        MemoryStream msDecrypt = new MemoryStream(data);
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Padding = PaddingMode.None;
        CryptoStream csDecrypt = new CryptoStream(msDecrypt,
            des.CreateWeakDecryptor(key, IV),
            CryptoStreamMode.Read);
        byte[] fromEncrypt = new byte[data.Length];
        csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
        return fromEncrypt;
    }

    #region DESCryptoExtensions
    public static ICryptoTransform CreateWeakEncryptor(this DESCryptoServiceProvider cryptoProvider, byte[] key, byte[] iv)
    {
        MethodInfo mi = cryptoProvider.GetType().GetMethod("_NewEncryptor", BindingFlags.NonPublic | BindingFlags.Instance);
        object[] Par = { key, cryptoProvider.Mode, iv, cryptoProvider.FeedbackSize, 0 };
        ICryptoTransform trans = mi.Invoke(cryptoProvider, Par) as ICryptoTransform;
        return trans;
    }
    public static ICryptoTransform CreateWeakEncryptor(this DESCryptoServiceProvider cryptoProvider)
    {
        return CreateWeakEncryptor(cryptoProvider, cryptoProvider.Key, cryptoProvider.IV);
    }
    public static ICryptoTransform CreateWeakDecryptor(this DESCryptoServiceProvider cryptoProvider, byte[] key, byte[] iv)
    {
        return CreateWeakEncryptor(cryptoProvider, key, iv);
    }
    public static ICryptoTransform CreateWeakDecryptor(this DESCryptoServiceProvider cryptoProvider)
    {
        return CreateWeakDecryptor(cryptoProvider, cryptoProvider.Key, cryptoProvider.IV);
    }
    #endregion
}

Now I try to run this code like so..

   byte[] challenge = new byte[] { 0x93, 0x9d, 0x2c, 0x2e, 0xa1, 0x65, 0x75, 0xd5 };

byte[] rndA = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

byte[] key = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

var iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

var test = DESCryptoExtensions.Decrypt(challenge, key, iv);

And then I get an error on this line..

 ICryptoTransform trans = mi.Invoke(cryptoProvider, Par) as ICryptoTransform;

 Object reference not set to an instance of an object.

All I want to do is to decrypt the challenge byte array using the key byte array.. using DES decryption..PLEASE DON'T SUGGEST I CHANGE THE KEY..I've been down a rabbit hole with this stuff so help is appreciated


问:
What can I do with the ADB USB Interface of an Android device?
I have an Android device (Samsung Galaxy A20e) and a Windows computer. If I connect both with the USB cable and enable the USB debugging inside the settings of Android, I can connect from my Windows App (.Net C#) by using the ADB interface of the USB device.

The device ID of this interface is \\?\USB#VID_04E8&PID_6860&ADB#8&324af34&11&0003#{dee824ef-729b-4a0e-9c14-b7117d33a817}.

To connect the Android device, I can use CreateFile with FILE_FLAG_OVERLAPPED with the device ID as filename to get a file handle. With this and the WinUsb_Initialize method, I can get a WinUsb handle. This allows me to send data to the Android device.

For example, I can use WinUsb_ControlTransfer with the commands 51, 52 and 53 to start the Android Accessoy Mode.

What else can I do with the ADB USB interface of an Android device?

Is there a description of all features available somewhere?


问:
Deployed react app(with react-routing) on nginx server giving error - TypeError: Cannot read properties of null (reading 'useContext')
I have deployed my react app on the Nginx server and on the console it is giving me these errors -

I get these errors while rerouting the page to a different page (using react routers)

On my local machine, no errors are coming, and everything is working as expected. I ran my build folder on my local machine using HTTP-server to validate if my build files have issues, but it is also running absolutely fine. I am not able to debug it and not sure really what is causing this issue when I deploy the files on Nginx server. Any pointers or ideas?

This is my react-router code -

```<code><Provider store={store}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/admin" element={<AdminPanel />}>
            <Route path="/admin/dashboard" element={<Dashboard/>} />
            <Route path="/admin/clients" element={<Clients/>} />
            <Route path="/admin/members" element={<Members/>} />
            <Route path="/admin/datasets" element={<Dataset/>} />
            <Route path="/admin/schema" element={<Schema/>} />
            <Route path="/admin/toolconstants" element={<ToolConstants/>} />
            <Route path="/admin/roles" element={<Roles/>} />
          </Route>
          <Route path="/annotation" element={<AnnotationDashboard />} />
        </Routes>
      </BrowserRouter>
    </Provider>
</code>```

From / I am routing to /admin/dashboard

Deployment team is deploying this app to nginx server where it is throwing these errors.

Below is the Nginx config file -

```<code>server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html =404;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

</code>```

Body:
I have deployed my react app on the Nginx server and on the console it is giving me these errors -

I get these errors while rerouting the page to a different page (using react routers)

On my local machine, no errors are coming, and everything is working as expected. I ran my build folder on my local machine using HTTP-server to validate if my build files have issues, but it is also running absolutely fine. I am not able to debug it and not sure really what is causing this issue when I deploy the files on Nginx server. Any pointers or ideas?

This is my react-router code -

<Provider store={store}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/admin" element={<AdminPanel />}>
            <Route path="/admin/dashboard" element={<Dashboard/>} />
            <Route path="/admin/clients" element={<Clients/>} />
            <Route path="/admin/members" element={<Members/>} />
            <Route path="/admin/datasets" element={<Dataset/>} />
            <Route path="/admin/schema" element={<Schema/>} />
            <Route path="/admin/toolconstants" element={<ToolConstants/>} />
            <Route path="/admin/roles" element={<Roles/>} />
          </Route>
          <Route path="/annotation" element={<AnnotationDashboard />} />
        </Routes>
      </BrowserRouter>
    </Provider>

From / I am routing to /admin/dashboard

Deployment team is deploying this app to nginx server where it is throwing these errors.

Below is the Nginx config file -

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html =404;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}


问:
How does "top" work in "Generate Answer" in Azure QnA maker service
I referred Generate Answer API. My KB has around 2600 QnA pairs and I observed that when I used "top 10", queried using "question", it provided different top results compared to when I used "top 100". My assumption is when "top 10" is used, this API gets first 10 results for that "Question" and stops after that and provides score for them relatively, where as, when "top 100" is used it gets first 100 results and provides scores for them. Is my analysis right? In order to get correct responses should I have "top: [total pairs in KB]"?</p>


问:
Rebasing with VSCode as git default editor in a "Remote SSH" connection
There are many questions throughout SO about using VSCode as git's default editor.

The answer to all of them is to set

git config --global core.editor "code --wait"
```
<p>(or <code>"code -w"</code>)</p>
<p>However, this isn't behaving properly for me. I don't know if it's related, but I'm doing this via Remote SSH. And indeed, setting <code>"code --wait"</code> and then trying an interactive rebase gives me:</p>
<pre class="lang-bash prettyprint-override"><code>$ git rebase -i --root
hint: Waiting for your editor to close the file...
</code>```

So the --wait flag is clearly doing what it's meant to do. Likewise, a new tab is opened titled "git-rebase-todo"! However, the tab is empty except for an error: "The editor could not be opened because the file was not found."

If I try to open the file in a second tab, it also shows the same error. If I close the file, the rebase proceeds normally (as if I'd accepted the default "pick-all" setting).

I've also seen some references to using "code -n --wait", and this does actually work!... sort of. It gets the job done, but since -n creates a new window, this actually generates a new SSH connection for each step (if I mark 10 commits as "edit", then it will open each commit in a new window, each of which takes a few seconds to complete the SSH connection).

Is there a way for this to "just work"? A setting that works across a "Remote SSH" connection that simply opens a new tab with the git-rebase-todo file that I can modify as needed and then all changes happen on the one window I'm using?

For the record, using nano or some other terminal-based editor works as intended: I make the changes there, and then the entire rebase happens one commit at a time on the currently open window/connection. I just want this same behavior without having to use a terminal-based editor.

Also, other operations (i.e. writing commit messages) work as expected with VSCode. The issue seems to only be when rebasing.

Body:
There are many questions throughout SO about using VSCode as git's default editor.

The answer to all of them is to set

git config --global core.editor "code --wait"

(or "code -w")

However, this isn't behaving properly for me. I don't know if it's related, but I'm doing this via Remote SSH. And indeed, setting "code --wait" and then trying an interactive rebase gives me:

$ git rebase -i --root
hint: Waiting for your editor to close the file...

So the --wait flag is clearly doing what it's meant to do. Likewise, a new tab is opened titled "git-rebase-todo"! However, the tab is empty except for an error: "The editor could not be opened because the file was not found."

If I try to open the file in a second tab, it also shows the same error. If I close the file, the rebase proceeds normally (as if I'd accepted the default "pick-all" setting).

I've also seen some references to using "code -n --wait", and this does actually work!... sort of. It gets the job done, but since -n creates a new window, this actually generates a new SSH connection for each step (if I mark 10 commits as "edit", then it will open each commit in a new window, each of which takes a few seconds to complete the SSH connection).

Is there a way for this to "just work"? A setting that works across a "Remote SSH" connection that simply opens a new tab with the git-rebase-todo file that I can modify as needed and then all changes happen on the one window I'm using?

For the record, using nano or some other terminal-based editor works as intended: I make the changes there, and then the entire rebase happens one commit at a time on the currently open window/connection. I just want this same behavior without having to use a terminal-based editor.

Also, other operations (i.e. writing commit messages) work as expected with VSCode. The issue seems to only be when rebasing.


问:
Npm installing react-viro
I want to test the react-Viro npm package on windows machine, but I am facing trouble when executing the npm install command

npm install --save @viro-community/react-viro

I get this

```<code>npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: partner@1.0.0
npm ERR! Found: react-native@0.68.2
npm ERR! node_modules/react-native
npm ERR!   react-native@"0.68.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react-native@"0.65.1" from @viro-community/react-viro@2.23.0
npm ERR! node_modules/@viro-community/react-viro
npm ERR!   @viro-community/react-viro@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\PC\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\PC\AppData\Local\npm-cache\_logs\2022-12-08T14_44_36_980Z-debug-0.log
</code>```

although I tried --legacy-peer-deps

and it stopped on this message

```<code>reify:fsevents: sill reify mark deleted [
</code>```

Title: Npm installing react-viro

Body:
I want to test the react-Viro npm package on windows machine, but I am facing trouble when executing the npm install command

npm install --save @viro-community/react-viro

I get this

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: partner@1.0.0
npm ERR! Found: react-native@0.68.2
npm ERR! node_modules/react-native
npm ERR!   react-native@"0.68.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react-native@"0.65.1" from @viro-community/react-viro@2.23.0
npm ERR! node_modules/@viro-community/react-viro
npm ERR!   @viro-community/react-viro@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\PC\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\PC\AppData\Local\npm-cache\_logs\2022-12-08T14_44_36_980Z-debug-0.log

although I tried --legacy-peer-deps

and it stopped on this message

reify:fsevents: sill reify mark deleted [


问:
Why Nuxt repeatable params doesn't work as expected?
I have these extended routes:

```<code>router: {
    linkActiveClass: '',
    linkExactActiveClass: 'active',
    extendRoutes(routes, resolve) {
        routes.push(
            {
                name: 'shop-page',
                path: '/shop/:slug/page/:page?',
                component: resolve(__dirname, 'src/pages/shop/_slug.vue'),

            },
          {
            name: 'shopFilter',
            path: '/shop/:slug/filter/:filters*',
            component: resolve(__dirname, 'src/pages/shop/_slug.vue'),
          },
          {
            name: 'shop-filter-page',
            path: '/shop/:slug/filter/:filters*/page/:page?',
            component: resolve(__dirname, 'src/pages/shop/_slug.vue'),

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

I have this path (the last one):

'/shop/:slug/filter/:filters*/page/:page?'

and the next url:

http://localhost:4003/shop/focare-seminee_2/filter/putere_6up-to10/sticla_standard/page/2

Nuxt take the expression '/page/2' and add to the filter repeatable params instead of page params!

I have a vue application with the same routes, and then works as expected: until '/page' goes to filter, and what is after '/page/' goes to page.

What is the problem in Nuxt? I have 2.15.7 version of Nuxt! Thanks

I tried to find a solution around the other topics, but I didn't find anything :(

Body:
I have these extended routes:

router: {
    linkActiveClass: '',
    linkExactActiveClass: 'active',
    extendRoutes(routes, resolve) {
        routes.push(
            {
                name: 'shop-page',
                path: '/shop/:slug/page/:page?',
                component: resolve(__dirname, 'src/pages/shop/_slug.vue'),

            },
          {
            name: 'shopFilter',
            path: '/shop/:slug/filter/:filters*',
            component: resolve(__dirname, 'src/pages/shop/_slug.vue'),
          },
          {
            name: 'shop-filter-page',
            path: '/shop/:slug/filter/:filters*/page/:page?',
            component: resolve(__dirname, 'src/pages/shop/_slug.vue'),

          }
        )
      }
},

I have this path (the last one):

'/shop/:slug/filter/:filters*/page/:page?'

and the next url:

http://localhost:4003/shop/focare-seminee_2/filter/putere_6up-to10/sticla_standard/page/2

Nuxt take the expression '/page/2' and add to the filter repeatable params instead of page params!

I have a vue application with the same routes, and then works as expected: until '/page' goes to filter, and what is after '/page/' goes to page.

What is the problem in Nuxt? I have 2.15.7 version of Nuxt! Thanks

I tried to find a solution around the other topics, but I didn't find anything :(


问:
How to copy a void* parameter in a char* in C
i have this function that accept void item and it has to copy into a string and compare them...This because in future i wanto to modify the copy in upper case and i don't want that the element passed by parameter change. How i can i do it? Address Sanitaizer give me alway a different error despite i tried different way to allocate the variable.

```<code>int compare_string(void* item1, void* item2){
    char *a =" ";
    char *b= " ";
    strcpy(a,item1);
    strcpy(b,item2);
    if(strcmp(a,b)==0) return 0;
    else if(strcmp(a,b)>0) return 1;
    else return -1;
}
</code>```
```<b>==12556==ERROR: AddressSanitizer: SEGV on unknown address 0x555d336ce39d (pc 0x148b654e2168 bp 0x7ffebf70ead0 sp 0x7ffebf70eaa8 T0)</b>
==12556==The signal is caused by a WRITE memory access.
    #0 0x148b654e2168  (/lib/x86_64-linux-gnu/libc.so.6+0x19f168)
    #1 0x555d336cd265 in compare_string (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x2265)
    #2 0x555d336cd110 in search_skip_list (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x2110)
    #3 0x555d336cc86c in search_in_file (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x186c)
    #4 0x555d336cca1e in main (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x1a1e)
    #5 0x148b6536cd8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
    #6 0x148b6536ce3f in __libc_start_main_impl ../csu/libc-start.c:392
    #7 0x555d336cc304 in _start (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x1304)

AddressSanitizer can not provide additional info.
```

i solved in this way: (i posted cause strlen doesn't worked but now yes, i think that i forgot some poninters before and i posted the older version)

```<code>int compare_string(void* item1, void* item2){
    char *a =malloc(strlen(item1)*sizeof(char*));
    char *b= malloc(strlen(item2)*sizeof(char*));
    strcpy(a,item1);strcpy(b,item2);
    if(strcmp(a,b)==0) {
        free(a);free(b);
        return 0;
    }
    else if(strcmp(a,b)>0) {
        free(a);free(b);
        return 1;
    }
    else {
        free(a);free(b);
        return -1;
    }
}
</code>```

Body:
i have this function that accept void item and it has to copy into a string and compare them...This because in future i wanto to modify the copy in upper case and i don't want that the element passed by parameter change. How i can i do it? Address Sanitaizer give me alway a different error despite i tried different way to allocate the variable.

int compare_string(void* item1, void* item2){
    char *a =" ";
    char *b= " ";
    strcpy(a,item1);
    strcpy(b,item2);
    if(strcmp(a,b)==0) return 0;
    else if(strcmp(a,b)>0) return 1;
    else return -1;
}

==12556==ERROR: AddressSanitizer: SEGV on unknown address 0x555d336ce39d (pc 0x148b654e2168 bp 0x7ffebf70ead0 sp 0x7ffebf70eaa8 T0)
==12556==The signal is caused by a WRITE memory access.
    #0 0x148b654e2168  (/lib/x86_64-linux-gnu/libc.so.6+0x19f168)
    #1 0x555d336cd265 in compare_string (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x2265)
    #2 0x555d336cd110 in search_skip_list (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x2110)
    #3 0x555d336cc86c in search_in_file (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x186c)
    #4 0x555d336cca1e in main (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x1a1e)
    #5 0x148b6536cd8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
    #6 0x148b6536ce3f in __libc_start_main_impl ../csu/libc-start.c:392
    #7 0x555d336cc304 in _start (/home/matteo/Scrivania/Algo/laboratorio-algoritmi-2021-2022-main/Esercizio 2/ex2/build/main+0x1304)

AddressSanitizer can not provide additional info.

i solved in this way: (i posted cause strlen doesn't worked but now yes, i think that i forgot some poninters before and i posted the older version)

int compare_string(void* item1, void* item2){
    char *a =malloc(strlen(item1)*sizeof(char*));
    char *b= malloc(strlen(item2)*sizeof(char*));
    strcpy(a,item1);strcpy(b,item2);
    if(strcmp(a,b)==0) {
        free(a);free(b);
        return 0;
    }
    else if(strcmp(a,b)>0) {
        free(a);free(b);
        return 1;
    }
    else {
        free(a);free(b);
        return -1;
    }
}


问:
Is it safe to use localhost on firebase?
I've been using Firebase as a backend for my website and mobile application. I was checking through the Settings tab under Authentication in the firebase project for my app.

I see the following under Authorised Domains

Authorised Domain
Type

localhost
Default

rs-mynotes.firebaseapp.com
Default

rs-mynotes.web.app
Default

The fact that localhost exists there is a little concerning to me.

Is it possible for others to exploit my application from their own devices?

Should I delete it from that list?

If I do, would it affect me in any way during development / testing of the app?

Thanks in advance for the help.


问:
How to insert a path in between my current path
I have a function that handles file download. When i click a download button it replaces my whole pathname:

from e.g.:

```<code>https://localhost:3000/list/2/items
</code>```

to e.g.:

```<code>blob:https://localhost:3000/fileName
</code>```

How to insert that /list/2/items to make my pathname look like this:

```<code>blob:https://localhost:3000/list/2/items/fileName
</code>```
```<code>  const fileDownload = (filename: string | null, blob: Blob) => {
  const blobURL =
    window.URL && window.URL.createObjectURL
      ? window.URL.createObjectURL(blob)
      : window.webkitURL.createObjectURL(blob);
  const tempLink = document.createElement("a");
  tempLink.style.display = "none";
  tempLink.href = blobURL;

  if (filename) {
    tempLink.setAttribute("download", filename.slice(21));
  }
  document.body.appendChild(tempLink);

  tempLink.click();
};
</code>```

Body:
I have a function that handles file download. When i click a download button it replaces my whole pathname:

from e.g.:

https://localhost:3000/list/2/items

to e.g.:

blob:https://localhost:3000/fileName

How to insert that /list/2/items to make my pathname look like this:

blob:https://localhost:3000/list/2/items/fileName

  const fileDownload = (filename: string | null, blob: Blob) => {
  const blobURL =
    window.URL && window.URL.createObjectURL
      ? window.URL.createObjectURL(blob)
      : window.webkitURL.createObjectURL(blob);
  const tempLink = document.createElement("a");
  tempLink.style.display = "none";
  tempLink.href = blobURL;

  if (filename) {
    tempLink.setAttribute("download", filename.slice(21));
  }
  document.body.appendChild(tempLink);

  tempLink.click();
};


问:
How to split a screen into virtual screen with nvidia graphic card on linux
I have a 4 k monitor that i have splitted into 4 virtual monitor with the intel gpu using xrandr commands at x startup. Now, I recently bought and nvidia 1050 ti and i can’t get my 4 virtuals display working. I don’t know why, xrand does not output errors.
( I use nvidia's drivers 470.141.03 )

This is how i setup the virtuals monitors

```<code>xrandr --setmonitor DP-0-1 1920/300x1080/170+0+0 DP-0
xrandr --setmonitor DP-0-2 1920/300x1080/170+1920+0 none
xrandr --setmonitor DP-0-3 1920/300x1080/170+0+1080 none
xrandr --setmonitor DP-0-4 1920/300x1080/170+1920+1080 none
</code>```

And after i can see that the monitors have been created successfully

```<code>xrandr --listactivemonitors
Monitors: 4
0: DP-0-1 1920/300x1080/170+0+0 DP-0
1: DP-0-2 1920/300x1080/170+1920+0
2: DP-0-3 1920/300x1080/170+0+1080
3: DP-0-4 1920/300x1080/170+1920+1080
</code>```

But when i want to maximaze one window, she's take the whole 4k monitor, that is not supposed to happen, she should maximize to one of the 4 virtual screen.

I would be very please if someone that have the same problem could answered me.

Body:
I have a 4 k monitor that i have splitted into 4 virtual monitor with the intel gpu using xrandr commands at x startup. Now, I recently bought and nvidia 1050 ti and i can’t get my 4 virtuals display working. I don’t know why, xrand does not output errors.
( I use nvidia's drivers 470.141.03 )

This is how i setup the virtuals monitors

xrandr --setmonitor DP-0-1 1920/300x1080/170+0+0 DP-0
xrandr --setmonitor DP-0-2 1920/300x1080/170+1920+0 none
xrandr --setmonitor DP-0-3 1920/300x1080/170+0+1080 none
xrandr --setmonitor DP-0-4 1920/300x1080/170+1920+1080 none

And after i can see that the monitors have been created successfully

xrandr --listactivemonitors
Monitors: 4
0: DP-0-1 1920/300x1080/170+0+0 DP-0
1: DP-0-2 1920/300x1080/170+1920+0
2: DP-0-3 1920/300x1080/170+0+1080
3: DP-0-4 1920/300x1080/170+1920+1080

But when i want to maximaze one window, she's take the whole 4k monitor, that is not supposed to happen, she should maximize to one of the 4 virtual screen.

I would be very please if someone that have the same problem could answered me.