问:
Drag and drop for custom screen option
I need to create a custom screen option with angular
When there are places on the screen that can be dragged and dropped to another place.
Similar to what you see in known editors.
And  I want that during the towing, as soon as you pass any place that is allowed to grab the component, then the place will be marked.
And no less important, that once the component sticks, its size will change according to the size of the place where it is caught
As in the picture below.

I'm thinking about dividing the screen into a virtual grid that will show the places where you can stick.
I tried dragging and dropping CDK but I couldn't get the required result.

Does anyone have an idea how to do this or with CDK drag and drop or with another package?
Or even with other technology?

Title: Drag and drop for custom screen option


来源: stackexchange

问:
Can't set matplotlib.path.Path as clip_path in matplotlib. How to provide transform to patch?
I'm trying to animate a patch in matplotlib. The patch is supposed to be filled incrementally with a stroke of black while using the patch as a clip path. Essentially, I am trying to make these svg animations from the animCJK project in matplotlib. For that I extract the bezier curve info from the svg files for the patches (clip paths) as well as the stroking paths which can be found at the bottom of the svg files.

So what I have currently done is to copy this matplotlib example on clip paths and tried to replace the cirlce patch with my own patch that I create using the svgpath2mpl library. Then I would animate the filling of those patches as in the svg animations and put my own spin on them. The problem is that I get the following error when I set my patch from the svg file as the clip path instead of the circle patch from the matplotlib example:

```<code>Traceback (most recent call last):
  File "C:\Users\Chris\Desktop\quick.py", line 15, in <module>
    im.set_clip_path(patch)
  File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\artist.py", line 793, in set_clip_path
    self._clippath = TransformedPath(path, transform)
  File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\transforms.py", line 2708, in __init__
    _api.check_isinstance(Transform, transform=transform)
  File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\_api\__init__.py", line 92, in check_isinstance
    raise TypeError(
TypeError: 'transform' must be an instance of matplotlib.transforms.Transform, not a None
</code>```

So I need to provide transform=ax.transData to my patch (Path object) so that the clipping works like in the matplotlib example, but I can't seem to figure out how to do that. Can anyone tell me how to get this to work? Here's my code.

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cbook as cbook
from svgpath2mpl import parse_path

string = "M181 359C174 359 165 363 166 371C167 382 176 389 183 396C198 412 199 435 204 455C222 538 238 623 276 700C300 745 333 786 374 816C385 824 400 826 411 818C418 814 420 805 420 797C421 780 417 762 420 745C422 720 430 696 436 671C437 666 438 657 431 654C424 652 417 658 414 664C399 686 387 710 372 731C370 734 366 735 364 732C347 718 331 702 319 683C303 658 294 629 285 601C276 570 267 538 260 506C254 477 250 448 249 419C249 409 254 399 253 389C251 379 240 375 232 370C216 363 199 359 181 359Z"
patch = parse_path(string)

with cbook.get_sample_data('grace_hopper.jpg') as image_file:
    image = plt.imread(image_file)

fig, ax = plt.subplots()
im = ax.imshow(image)
im.set_clip_path(patch)

ax.axis('off')
plt.show()
```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to animate a patch in matplotlib. The patch is supposed to be filled incrementally with a stroke of black while using the patch as a clip path. Essentially, I am trying to make these svg animations from the animCJK project in matplotlib. For that I extract the bezier curve info from the svg files for the patches (clip paths) as well as the stroking paths which can be found at the bottom of the svg files.

So what I have currently done is to copy this matplotlib example on clip paths and tried to replace the cirlce patch with my own patch that I create using the svgpath2mpl library. Then I would animate the filling of those patches as in the svg animations and put my own spin on them. The problem is that I get the following error when I set my patch from the svg file as the clip path instead of the circle patch from the matplotlib example:

Traceback (most recent call last):
  File "C:\Users\Chris\Desktop\quick.py", line 15, in <module>
    im.set_clip_path(patch)
  File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\artist.py", line 793, in set_clip_path
    self._clippath = TransformedPath(path, transform)
  File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\transforms.py", line 2708, in __init__
    _api.check_isinstance(Transform, transform=transform)
  File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\_api\__init__.py", line 92, in check_isinstance
    raise TypeError(
TypeError: 'transform' must be an instance of matplotlib.transforms.Transform, not a None

So I need to provide transform=ax.transData to my patch (Path object) so that the clipping works like in the matplotlib example, but I can't seem to figure out how to do that. Can anyone tell me how to get this to work? Here's my code.

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cbook as cbook
from svgpath2mpl import parse_path

string = "M181 359C174 359 165 363 166 371C167 382 176 389 183 396C198 412 199 435 204 455C222 538 238 623 276 700C300 745 333 786 374 816C385 824 400 826 411 818C418 814 420 805 420 797C421 780 417 762 420 745C422 720 430 696 436 671C437 666 438 657 431 654C424 652 417 658 414 664C399 686 387 710 372 731C370 734 366 735 364 732C347 718 331 702 319 683C303 658 294 629 285 601C276 570 267 538 260 506C254 477 250 448 249 419C249 409 254 399 253 389C251 379 240 375 232 370C216 363 199 359 181 359Z"
patch = parse_path(string)

with cbook.get_sample_data('grace_hopper.jpg') as image_file:
    image = plt.imread(image_file)

fig, ax = plt.subplots()
im = ax.imshow(image)
im.set_clip_path(patch)

ax.axis('off')
plt.show()


问:
array of objects map is not a function
I'm new to React, I'm pulling an API, which is filled with an array of objects.
When trying to map it I get following error: "Uncaught TypeError: benchmarkData.map is not a function"

While I get the error, it actually does the job (when I log it I get the asked result), it just prevents loading the other elements.

This is how my API looks:

```<code>[
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "412",
"DEGEMAT": "235",
"DEGEMGW": "97.7",
"DEGEMMB": "3.39",
"DEGEMNV": "64.1",
"DEGEMSD": "13.2",
"DEGEMVD": "71.3",
"DEJAART": "2022",
"DELTMCE": "-",
"DEWEENR": "1"
},
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "436",
"DEGEMAT": "233",
"DEGEMGW": "120.1",
"DEGEMMB": "3.38",
"DEGEMNV": "64.2",
"DEGEMSD": "13.2",
"DEGEMVD": "71.4",
"DEJAART": "2022",
"DELTMCE": "ALL",
"DEWEENR": "1"
},
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "22",
"DEGEMAT": "213",
"DEGEMGW": "99.9",
"DEGEMMB": "3.23",
"DEGEMNV": "64.9",
"DEGEMSD": "12.7",
"DEGEMVD": "72.8",
"DEJAART": "2022",
"DELTMCE": "BBC",
"DEWEENR": "1"
}
]
</code>```

This is my React code:

```<code>useEffect(() => {
    if (benchmarkData) {
      setSupplierHasData(true);
      let loadingplaceFilter = [];
      const loadingPlaces = [];
      benchmarkData.map(item => { //!start of requested question code
        if(item.type === "drlvbmk") {
           loadingPlaces.push(item.DELPLCE, item.DELTMCE, item.DEELTCE)
        }
      }
      ); //!end of requested question code
      console.log(loadingPlaces);

      const uniqueLoadingplaces = [];
      loadingPlaces.map((item) => {
        var findItem = uniqueLoadingplaces.find((x) => x === item);
        if (!findItem) uniqueLoadingplaces.push(item);
      });
      console.log('uniqueloadingplaces', uniqueLoadingplaces);

      setFilters({
        ...filters,
        loadingplaces: loadingplaceFilter,
      });

      setFilterData(true);

  }, [benchmarkData]);
</code>```

Pulling the api:

```<code> useEffect(() => {
    const fetchBenchmarkData = async () => {
      setFetchNewData(false);
      console.log('current user active id :', suppliersState.suppliers.activeID, "current user active uuid:  ", suppliersState.suppliers.activeUUID);
      try  {
        await axios

          .get(
            `https://bpg-ap.ddev.site/jsonapi/benchmarking_get_data?supplierid=${suppliersState.suppliers.activeID}&date_from=1&date_to=2022`
          )
          .then(res => {
            setBenchmarkData(res.data);
            console.log('BENCHMARKINGRESULTAAT : ', res.data);
          });
        } catch(error) {
          setSupplierHasData(false);
          setChartData({});
            console.log(error);
        }
    };
    if (benchmarkData === null) {
      console.log('useEffect fired, fetch benchmarkData', benchmarkData);
      fetchBenchmarkData();
    }
  }, [benchmarkData, suppliersState.suppliers.activeID]);
</code>```

Logging benchmarkData results in:

I hope anyone can help me to solve this problem

Title: array of objects map is not a function

Body:
I'm new to React, I'm pulling an API, which is filled with an array of objects.
When trying to map it I get following error: "Uncaught TypeError: benchmarkData.map is not a function"

While I get the error, it actually does the job (when I log it I get the asked result), it just prevents loading the other elements.

This is how my API looks:

[
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "412",
"DEGEMAT": "235",
"DEGEMGW": "97.7",
"DEGEMMB": "3.39",
"DEGEMNV": "64.1",
"DEGEMSD": "13.2",
"DEGEMVD": "71.3",
"DEJAART": "2022",
"DELTMCE": "-",
"DEWEENR": "1"
},
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "436",
"DEGEMAT": "233",
"DEGEMGW": "120.1",
"DEGEMMB": "3.38",
"DEGEMNV": "64.2",
"DEGEMSD": "13.2",
"DEGEMVD": "71.4",
"DEJAART": "2022",
"DELTMCE": "ALL",
"DEWEENR": "1"
},
{
"type": "drgmbmk",
"test": "5782",
"DEAANTA": "22",
"DEGEMAT": "213",
"DEGEMGW": "99.9",
"DEGEMMB": "3.23",
"DEGEMNV": "64.9",
"DEGEMSD": "12.7",
"DEGEMVD": "72.8",
"DEJAART": "2022",
"DELTMCE": "BBC",
"DEWEENR": "1"
}
]

This is my React code:

useEffect(() => {
    if (benchmarkData) {
      setSupplierHasData(true);
      let loadingplaceFilter = [];
      const loadingPlaces = [];
      benchmarkData.map(item => { //!start of requested question code
        if(item.type === "drlvbmk") {
           loadingPlaces.push(item.DELPLCE, item.DELTMCE, item.DEELTCE)
        }
      }
      ); //!end of requested question code
      console.log(loadingPlaces);

      const uniqueLoadingplaces = [];
      loadingPlaces.map((item) => {
        var findItem = uniqueLoadingplaces.find((x) => x === item);
        if (!findItem) uniqueLoadingplaces.push(item);
      });
      console.log('uniqueloadingplaces', uniqueLoadingplaces);

      setFilters({
        ...filters,
        loadingplaces: loadingplaceFilter,
      });

      setFilterData(true);

  }, [benchmarkData]);

Pulling the api:

 useEffect(() => {
    const fetchBenchmarkData = async () => {
      setFetchNewData(false);
      console.log('current user active id :', suppliersState.suppliers.activeID, "current user active uuid:  ", suppliersState.suppliers.activeUUID);
      try  {
        await axios

          .get(
            `https://bpg-ap.ddev.site/jsonapi/benchmarking_get_data?supplierid=${suppliersState.suppliers.activeID}&date_from=1&date_to=2022`
          )
          .then(res => {
            setBenchmarkData(res.data);
            console.log('BENCHMARKINGRESULTAAT : ', res.data);
          });
        } catch(error) {
          setSupplierHasData(false);
          setChartData({});
            console.log(error);
        }
    };
    if (benchmarkData === null) {
      console.log('useEffect fired, fetch benchmarkData', benchmarkData);
      fetchBenchmarkData();
    }
  }, [benchmarkData, suppliersState.suppliers.activeID]);

Logging benchmarkData results in:

I hope anyone can help me to solve this problem


问:
Active Directory SSL certificate
I already setup wifi AD authorization. When users connect, they see an error that the certificate is self-signed and not trusted. I bought a signed SSL, but I don't know how to feed it to AD.

thanks in advance

```<code>i tried replacing the certificate but they are not the same at all
</code>```

Title: Active Directory SSL certificate

Body:
I already setup wifi AD authorization. When users connect, they see an error that the certificate is self-signed and not trusted. I bought a signed SSL, but I don't know how to feed it to AD.

thanks in advance

i tried replacing the certificate but they are not the same at all


问:
I created an authentication api with express, what is the best way of consuming the api with Vuejs
I have an authentication api with nodejs and express fully working with ejs template. But I’d like to know how to use vuejs for the frontend instead of ejs

I already built the ui with Vuejs, then I created the api with nodejs/express and tested it with ejs.

I’m having issues with the authentication system using my vuejs ui, I can’t seem to call the api and persist form data properly.

Thanks


问:
How to use validation groups in Spring MVC
I have a DTO, which will be used by 2 endpoints.

The two endpoints -

/groupA

/groupB

Consider the DTO with two fields, say fieldA and fieldB.

For /groupA, fieldA shouldn't be blank and fieldB can be blank
For /groupB, fieldB shouldn't be blank and fieldA can be blank

I understand that this can be achieved by validation groups. I created two interfaces GroupA and GroupB.

```<code>public interface GroupA {
}

public interface GroupB {
}

public class RequestDto {
  @NotBlank(groups = GroupA.class)
  private String fieldA;

  @NotBlank(groups = GroupB.class)
  private String fieldB;
}
</code>```

In the controller, I used @Validated annotation:

```<code>public ResponseEntity<ResponseDto> getResult(@Validated(GroupA.class                             @RequestBody @Validated RequestDto request)) {

...

}
</code>```

If I do not pass fieldA in request body, I expect the endpoint to give 400 BAD REQUEST. However, it is not functioning as expected. It is returning 200 OK response.

What am I missing ? This is the first time I'm using validation groups, so might have missed something.

I appreciate all the help!

Body:
I have a DTO, which will be used by 2 endpoints.

The two endpoints -

/groupA

/groupB

Consider the DTO with two fields, say fieldA and fieldB.

For /groupA, fieldA shouldn't be blank and fieldB can be blank
For /groupB, fieldB shouldn't be blank and fieldA can be blank

I understand that this can be achieved by validation groups. I created two interfaces GroupA and GroupB.

public interface GroupA {
}

public interface GroupB {
}

public class RequestDto {
  @NotBlank(groups = GroupA.class)
  private String fieldA;

  @NotBlank(groups = GroupB.class)
  private String fieldB;
}

In the controller, I used @Validated annotation:

public ResponseEntity<ResponseDto> getResult(@Validated(GroupA.class                             @RequestBody @Validated RequestDto request)) {

...

}

If I do not pass fieldA in request body, I expect the endpoint to give 400 BAD REQUEST. However, it is not functioning as expected. It is returning 200 OK response.

What am I missing ? This is the first time I'm using validation groups, so might have missed something.

I appreciate all the help!


问:
Apache httpd 2.4 allow /location access from multiple specific IPs
I am running Apache web server 2.4 and am trying to enable the server-status mod and page. I have the following in the bottom of the apache2.conf:

ExtendedStatus on
<Location /server-status>
SetHandler server-status
Require ip 127.0.0.1

When I then do "curl http://127.0.0.1/server-status" I get the customized 404 error and a bunch of html that are apparently served from one of the few virtual hosts running on this server.

What is the deciding factor that says which virtual host will serve the requests coming to the server by either internal or external ip address? Why is the location directive from apache2.conf not taking precedence?

I have tried adding Require ip xx.xx.xx.xx inside the location directive multiple times, each time using either localhost, 127.0.0.1, or my client ip address. It does not seem to want to serve properly.


问:
I want java selenium code to get the value from response tab under network in dev tools
I am using selenium 3, for testing purpose i want ID which will display in. 'Response' tab under network in developer tool,
I am not getting any code to perform this action.

Image response tab


问:
Unable to run Valgrind with Python
I am calling a .so library written in Go. I am trying to use Valgrind with Python but it is only printing the following info

```<code>root@xx:~# valgrind --leak-check=yes python test.py
==377711== Memcheck, a memory error detector
==377711== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==377711== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==377711== Command: /root/.pyenv/shims/python test.py
==377711==
2023/01/03 14:46:01 combine
printing in Python
combine
________________________________
2023/01/03 14:46:02 combine
printing in Python
combine
________________________________
</code>```

Prior to running this I already had done export PYTHONMALLOC=malloc.

Why is it not printing something like the one below?

```<code>ERROR SUMMARY: 0 errors from 0 contexts
</code>```

I am using Python 3.9

Title: Unable to run Valgrind with Python

Body:
I am calling a .so library written in Go. I am trying to use Valgrind with Python but it is only printing the following info

root@xx:~# valgrind --leak-check=yes python test.py
==377711== Memcheck, a memory error detector
==377711== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==377711== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==377711== Command: /root/.pyenv/shims/python test.py
==377711==
2023/01/03 14:46:01 combine
printing in Python
combine
________________________________
2023/01/03 14:46:02 combine
printing in Python
combine
________________________________

Prior to running this I already had done export PYTHONMALLOC=malloc.

Why is it not printing something like the one below?

ERROR SUMMARY: 0 errors from 0 contexts

I am using Python 3.9


问:
connect Raspberry Pi 4 to a remote MySql database located on a server
I have a new situation. I had a javascript running successfully on aArduino YUN board that was basically querying a MySql server located on a server with an IP address (aaa.bbb.ccc.ddd). I am basically trying to replace Arduino YUN with Raspberry Pi 4. This is what I did to run this javascript on the Raspebrry PI.Successfully installed all the modules that were there in the Arduino YUN board and all modules, packages have been successfully installed. Now I am running to issues when trying to access MySql server from the Raspberry PI. Looks like the script is giving null output and I don't know how to connect the Raspberry PI to MySql server or did I make all configurations correctly as in my old board Arduino YUN.

Here is code:

```<code>connect2mysql = require('remote_mysql_connection.js');

var queryMySql = "SELECT product FROM catalog WHERE product_id =123;";
console.log(connect2mysql.query(mysqlQuery))
</code>```

Here is the remote_mysql_connection.js script that I am importing:

remote_mysql_connection.js

```<code>var shell = require('shelljs');
module.exports = {
    user: 'test',
    host: 'aa.bbb.cc.ddd',
    password: 'blahblah',
    database: 'geeko',
    async: true,

    /* Parses MySQL text output into an array of row objects. */
    parseOutput: function(output)
    {
        var rows = [];
        var outputLines = output.match(/[^\r\n]+/gm);
        console.log(outputLines);
        var columnNames = outputLines[0].split('\t');  //first line of output contains column headers
        for(var n=1; n<outputLines.length; n++)
        {
            var row = {};
            var fields = outputLines[n].split('\t');  //the values for
            for(var c=0; c<columnNames.length; c++)
            {
                row[columnNames[c]] = fields[c];
            }
            rows.push(row);
        }

        return rows;
    },

    /* Executes a SQL query.  After the query is finished, it calls the passed callback function with the result. */
    query : function(query, callback)
    {
        var sql = "use "+this.database+"; "+query;
        var options = {silent:true, async:this.async};
        var command = 'mysql -u '+this.user+' -h '+this.host+' -p'+this.password+' -e "'+sql+'"';

        //shell.exec() runs the command, the output data is processed by the function supplied below
        shell.exec(command, options, function(code, output) {
            var result = [];
            console.log('Query:', query);
            console.log(output);

            //Parse the output if it is a select query
            if((/^(\s+)?select/i).test(query)) result = module.exports.parseOutput(output);

            if(callback) callback(result, output);  //pass result back to user supplied callback function
        });
    }
};
</code>```

Present output:

```<code>null
[ 2023-01-03T14:38:56.617Z ] 'Caught exception: TypeError: Cannot read property \'0\' of null'
TypeError: Cannot read property '0' of null
    at Object.parseOutput (/home/pi/Documents/.../remote_mysql_connection.js:15:32)
    at /home/pi/Documents/../remote_mysql_connection.js:44:63
    at /home/pi/node_modules/shelljs/src/exec.js:145:9
    at ChildProcess.exithandler (child_process.js:301:5)
    at ChildProcess.emit (events.js:198:13)
    at maybeClose (internal/child_process.js:982:16)
    at Socket.stream.socket.on (internal/child_process.js:389:11)
    at Socket.emit (events.js:198:13)
    at Pipe._handle.close (net.js:607:12)
Compilation failed.

</code>```

How to check and confirm connection between Raspberry Pi 4 and a remote MySql database located on a different server with an IP address?

UPDATE:

Interestingly, there seems to be a good connection between the RPi and remote MySql server (IP:'aa.bbb.cc.ddd'). How I know? I wrote a small Python script using the  same credentials as above javascript and MySql query I was using in the original program (which is JavaScript). The program ran successfully and gave the correct response. It is just a question of having all the required packages, and dependencies that support the MySql connection through JavaScript. Still don't why my JavaScript is not connecting to the remote MySql server when my python script connects successfully.

Body:
I have a new situation. I had a javascript running successfully on aArduino YUN board that was basically querying a MySql server located on a server with an IP address (aaa.bbb.ccc.ddd). I am basically trying to replace Arduino YUN with Raspberry Pi 4. This is what I did to run this javascript on the Raspebrry PI.Successfully installed all the modules that were there in the Arduino YUN board and all modules, packages have been successfully installed. Now I am running to issues when trying to access MySql server from the Raspberry PI. Looks like the script is giving null output and I don't know how to connect the Raspberry PI to MySql server or did I make all configurations correctly as in my old board Arduino YUN.

Here is code:

connect2mysql = require('remote_mysql_connection.js');

var queryMySql = "SELECT product FROM catalog WHERE product_id =123;";
console.log(connect2mysql.query(mysqlQuery))

Here is the remote_mysql_connection.js script that I am importing:

remote_mysql_connection.js

var shell = require('shelljs');
module.exports = {
    user: 'test',
    host: 'aa.bbb.cc.ddd',
    password: 'blahblah',
    database: 'geeko',
    async: true,

    /* Parses MySQL text output into an array of row objects. */
    parseOutput: function(output)
    {
        var rows = [];
        var outputLines = output.match(/[^\r\n]+/gm);
        console.log(outputLines);
        var columnNames = outputLines[0].split('\t');  //first line of output contains column headers
        for(var n=1; n<outputLines.length; n++)
        {
            var row = {};
            var fields = outputLines[n].split('\t');  //the values for
            for(var c=0; c<columnNames.length; c++)
            {
                row[columnNames[c]] = fields[c];
            }
            rows.push(row);
        }

        return rows;
    },

    /* Executes a SQL query.  After the query is finished, it calls the passed callback function with the result. */
    query : function(query, callback)
    {
        var sql = "use "+this.database+"; "+query;
        var options = {silent:true, async:this.async};
        var command = 'mysql -u '+this.user+' -h '+this.host+' -p'+this.password+' -e "'+sql+'"';

        //shell.exec() runs the command, the output data is processed by the function supplied below
        shell.exec(command, options, function(code, output) {
            var result = [];
            console.log('Query:', query);
            console.log(output);

            //Parse the output if it is a select query
            if((/^(\s+)?select/i).test(query)) result = module.exports.parseOutput(output);

            if(callback) callback(result, output);  //pass result back to user supplied callback function
        });
    }
};

Present output:

null
[ 2023-01-03T14:38:56.617Z ] 'Caught exception: TypeError: Cannot read property \'0\' of null'
TypeError: Cannot read property '0' of null
    at Object.parseOutput (/home/pi/Documents/.../remote_mysql_connection.js:15:32)
    at /home/pi/Documents/../remote_mysql_connection.js:44:63
    at /home/pi/node_modules/shelljs/src/exec.js:145:9
    at ChildProcess.exithandler (child_process.js:301:5)
    at ChildProcess.emit (events.js:198:13)
    at maybeClose (internal/child_process.js:982:16)
    at Socket.stream.socket.on (internal/child_process.js:389:11)
    at Socket.emit (events.js:198:13)
    at Pipe._handle.close (net.js:607:12)
Compilation failed.

How to check and confirm connection between Raspberry Pi 4 and a remote MySql database located on a different server with an IP address?

UPDATE:

Interestingly, there seems to be a good connection between the RPi and remote MySql server (IP:'aa.bbb.cc.ddd'). How I know? I wrote a small Python script using the  same credentials as above javascript and MySql query I was using in the original program (which is JavaScript). The program ran successfully and gave the correct response. It is just a question of having all the required packages, and dependencies that support the MySql connection through JavaScript. Still don't why my JavaScript is not connecting to the remote MySql server when my python script connects successfully.


问:
Use a value from a calculated field as the default value for a parameter in Tableau
I have a field called 'presenting issues' which contains labels such as 'Anxiety/Stress' etc. I have created a parameter that allows you to select a single label. I now need this parameter to default to the top presenting issue as the workbook opens. This can vary based off of the city I have selected so it won't necessarily be the same every time.

The top presenting issue is determined by the number of users who have a presenting issue in the selected city.

Thank you in advance!


问:
Is it possible to search databases using informatica for a specific field content
So we have databases like mssql and oracle and we use informatica to scan those databases for fields with personal identifiable information.  I have information given like social and name and I want to use informatica to scan the databases and give me a report of where they all are.  Does anyone have any suggestions.</p>


问:
Error : "failed to solve with frontend dockerfile.v0: failed to create LLB definition" when building a Docker image
I get this error

failed to solve with frontend dockerfile.v0: failed to create LLB definition

when I was trying to build this Docker image

**

```<code>FROM debian:jessie-slim
RUN apt-get update
RUN apt-get -y install iptables apt-utils iproute2 net-tools systemd telnet nano iputils-ping tcpdump inetutils-traceroute quagga isc-dhcp-server
RUN apt-get -f install
COPY  ./quagga /etc/quagga
COPY  ./dhcp/dhcpd.conf /etc/dhcp
COPY box_ext.sh /home/
RUN ["chmod", "+x", "/home/box_ext.sh"]
RUN mkdir /etc/scripts
ENV PATH "/etc/scripts:$PATH"
ENTRYPOINT /etc/init.d/quagga start && /bin/bash
```**
```

Body:
I get this error

failed to solve with frontend dockerfile.v0: failed to create LLB definition

when I was trying to build this Docker image

**

FROM debian:jessie-slim
RUN apt-get update
RUN apt-get -y install iptables apt-utils iproute2 net-tools systemd telnet nano iputils-ping tcpdump inetutils-traceroute quagga isc-dhcp-server
RUN apt-get -f install
COPY  ./quagga /etc/quagga
COPY  ./dhcp/dhcpd.conf /etc/dhcp
COPY box_ext.sh /home/
RUN ["chmod", "+x", "/home/box_ext.sh"]
RUN mkdir /etc/scripts
ENV PATH "/etc/scripts:$PATH"
ENTRYPOINT /etc/init.d/quagga start && /bin/bash
```**


问:
Match point clounds with an unknown dimension
I am trying to restore a point cloud based on another one. I have point clouds A and B with different point coordinate systems. Points in A are in the cartesian coordinate system (x, y, z). Points in B are described by a range, azimuth and elevation (r, theta, phi). However I do not know the elevation of the points in the cloud B. I only know that the two clouds are approximately the same but with a different scale. The set B as it is, would correspond in cartesian coordinates to a cloud of arcs, because of the unknown elevation. So I converted the A in the sperical coordinate sytem using the following formulas:

```<code>r = sqrt(x^2+y^2+z^2)
theta = arctan(x/z)
arcsin = arcsin(y/sqrt(x^2+y^2+z^2))
</code>```

But I am not sure how to proceed after this. It looks like an optimization problem, so I am trying to find an objective function, but I don't know how to formulate it.

I would appreciate any help on this.

Body:
I am trying to restore a point cloud based on another one. I have point clouds A and B with different point coordinate systems. Points in A are in the cartesian coordinate system (x, y, z). Points in B are described by a range, azimuth and elevation (r, theta, phi). However I do not know the elevation of the points in the cloud B. I only know that the two clouds are approximately the same but with a different scale. The set B as it is, would correspond in cartesian coordinates to a cloud of arcs, because of the unknown elevation. So I converted the A in the sperical coordinate sytem using the following formulas:

r = sqrt(x^2+y^2+z^2)
theta = arctan(x/z)
arcsin = arcsin(y/sqrt(x^2+y^2+z^2))

But I am not sure how to proceed after this. It looks like an optimization problem, so I am trying to find an objective function, but I don't know how to formulate it.

I would appreciate any help on this.


问:
AWS CRUD using Cognito User Authentication
I’m approaching AWS for the first time, and I’m trying to build an app using Amplify, API Gateway, Cognito, Lambda and Dynamo DB (I’m building some sort of a ToDo app).
I’ve learnt how to use lambda and dynamoDB without any authentication system and now I want to implement it.

I’ve already setup cognito, api gateway and lambda in order to access API with an IdToken, but what I’m not able to do is saving into dynamoDB the data of the user that called the API, as when I log the event inside CloudWatch I see that all the fields that refer to cognito are null (ex. “Context.identity” is null).
I need it so when an user want to see its data I’ll call the GET method which filters only that user’s data and retrieves it.

Anyone could please explain if this is the correct way to do it and what I’m missing, or if there’s an easier way to build this?


问:
Autogluon's predict function tries to load model.pkl from the wrong path
I'm using Autogluon package to train some models and then make predictions. The file structure in my project looks like this:

There is a folder called "Models" where I'm storing models for different chemical analytes. In each analyte's folder there is a learner.pkl, predictor.pkl, and a folder called "models" with trained models and trainer.pkl

Everything works fine until I call predict() method on TabularPredictor.

```<code>
model_savepath = "Models/ascorbic acid-model"
model = TabularPredictor.load(model_savepath, require_version_match=False, verbosity=4)

to_predict = data_to_train.iloc[[0]].drop("Final", axis=1)
model.predict(to_predict)

</code>```

Then I'm getting the following error:

```<code>
FileNotFoundError: [Errno 2] No such file or directory: 'Models/ascorbic acid-model/models//WeightedEnsemble_L2model.pkl'
</code>```

For some reason the file name is mixed with the folder name. It says it tries to load weightedensemble_L2model.pkl instead of weighedensemble_L2/model.pkl.

Why is that?

I tried changing the path or training model on linux instead of windows, nothing worked so far.

Body:
I'm using Autogluon package to train some models and then make predictions. The file structure in my project looks like this:

There is a folder called "Models" where I'm storing models for different chemical analytes. In each analyte's folder there is a learner.pkl, predictor.pkl, and a folder called "models" with trained models and trainer.pkl

Everything works fine until I call predict() method on TabularPredictor.

model_savepath = "Models/ascorbic acid-model"
model = TabularPredictor.load(model_savepath, require_version_match=False, verbosity=4)

to_predict = data_to_train.iloc[[0]].drop("Final", axis=1)
model.predict(to_predict)

Then I'm getting the following error:

FileNotFoundError: [Errno 2] No such file or directory: 'Models/ascorbic acid-model/models//WeightedEnsemble_L2model.pkl'

For some reason the file name is mixed with the folder name. It says it tries to load weightedensemble_L2model.pkl instead of weighedensemble_L2/model.pkl.

Why is that?

I tried changing the path or training model on linux instead of windows, nothing worked so far.


问:
how can i make it responsive
i cant make responsive please help me. im using bootstrap .container structure for automatic design.
they are

and they are css codes;

```<code>@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500&family=Oswald:wght@300&display=swap');

*{
    box-sizing: border-box;
    margin:0;
    padding: 0;
    background-color: #24252a;
}

li, a, button {
    font-family: "Montserrat" , sans-serif;
    font-weight: 500;
    font-size: 16px;
    color: #edf0f1;
    text-decoration: none;
}
header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30px 10%;
}
.logo{
    cursor:pointer
}

.nav_links{
    list-style: none;
}
.nav_links li{
    display: inline-block;
    padding: 0px 20px;
}

.nav_links li a{
    transition: all 0.3 ease 0s;
}

.nav_links li a:hover{
    color:#0088a9
}
button{
    padding: 9px 25px;
    background-color: rgba(0, 136, 169, alpha);
    border: none;
    border-radius: 50px;
    cursor: pointer;
    transition: all 0.3 ease 0s;

}
button:hover{
    background-color: rgba(0, 136, 169, 0.8);
}
</code>```

`

i did try ".container" structure for automatic design. but this is not working and my codes are broken.i cant do this. please help me for responsive design. ive just started.

Title: how can i make it responsive

Body:
i cant make responsive please help me. im using bootstrap .container structure for automatic design.
they are

and they are css codes;

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500&family=Oswald:wght@300&display=swap');

*{
    box-sizing: border-box;
    margin:0;
    padding: 0;
    background-color: #24252a;
}

li, a, button {
    font-family: "Montserrat" , sans-serif;
    font-weight: 500;
    font-size: 16px;
    color: #edf0f1;
    text-decoration: none;
}
header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30px 10%;
}
.logo{
    cursor:pointer
}

.nav_links{
    list-style: none;
}
.nav_links li{
    display: inline-block;
    padding: 0px 20px;
}

.nav_links li a{
    transition: all 0.3 ease 0s;
}

.nav_links li a:hover{
    color:#0088a9
}
button{
    padding: 9px 25px;
    background-color: rgba(0, 136, 169, alpha);
    border: none;
    border-radius: 50px;
    cursor: pointer;
    transition: all 0.3 ease 0s;

}
button:hover{
    background-color: rgba(0, 136, 169, 0.8);
}

`

i did try ".container" structure for automatic design. but this is not working and my codes are broken.i cant do this. please help me for responsive design. ive just started.


问:
labelImg using with m1 pro issue with pip install pip3 install pyqt5 lxml
I am currently trying to run labelImg on my mac m1pro. When trying to install qt5 with "pip3 install pyqt5 lxml" i get this error message:

`
Collecting PyQt5
Using cached PyQt5-5.15.7.tar.gz (3.2 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... error
error: subprocess-exited-with-error

× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [23 lines of output]
Querying qmake about your Qt installation...
Traceback (most recent call last):
File "/Users/romanxaver/miniforge3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 144, in prepare_metadata_for_build_wheel
hook = backend.prepare_metadata_for_build_wheel
AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

```<code>  During handling of the above exception, another exception occurred:

  Traceback (most recent call last):
    File "/Users/romanxaver/miniforge3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 351, in <module>
      main()
    File "/Users/romanxaver/miniforge3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 333, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "/Users/romanxaver/miniforge3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 148, in prepare_metadata_for_build_wheel
      whl_basename = backend.build_wheel(metadata_directory, config_settings)
    File "/private/var/folders/wm/t87_jx651gvfm3t05dzg24440000gn/T/pip-build-env-lmy12lan/overlay/lib/python3.9/site-packages/sipbuild/api.py", line 46, in build_wheel
      project = AbstractProject.bootstrap('wheel',
    File "/private/var/folders/wm/t87_jx651gvfm3t05dzg24440000gn/T/pip-build-env-lmy12lan/overlay/lib/python3.9/site-packages/sipbuild/abstract_project.py", line 87, in bootstrap
      project.setup(pyproject, tool, tool_description)
    File "/private/var/folders/wm/t87_jx651gvfm3t05dzg24440000gn/T/pip-build-env-lmy12lan/overlay/lib/python3.9/site-packages/sipbuild/project.py", line 601, in setup
      self.update(tool)
    File "project.py", line 166, in update
  sipbuild.exceptions.UserException
  [end of output]
</code>```

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.
`

Does anyone know the solution to this? When i try to install it with brew i get the following error at the point of "make qt5py3":

pyrcc5 -o libs/resources.py resources.qrc /Users/xxx/miniforge3/bin/python3: No module named PyQt5.pyrcc_main make: *** [qt5py3] Error 1

I wanted to install labelImg on my m1pro

Body:
I am currently trying to run labelImg on my mac m1pro. When trying to install qt5 with "pip3 install pyqt5 lxml" i get this error message:

`
Collecting PyQt5
Using cached PyQt5-5.15.7.tar.gz (3.2 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... error
error: subprocess-exited-with-error

× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [23 lines of output]
Querying qmake about your Qt installation...
Traceback (most recent call last):
File "/Users/romanxaver/miniforge3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 144, in prepare_metadata_for_build_wheel
hook = backend.prepare_metadata_for_build_wheel
AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

  During handling of the above exception, another exception occurred:

  Traceback (most recent call last):
    File "/Users/romanxaver/miniforge3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 351, in <module>
      main()
    File "/Users/romanxaver/miniforge3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 333, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "/Users/romanxaver/miniforge3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 148, in prepare_metadata_for_build_wheel
      whl_basename = backend.build_wheel(metadata_directory, config_settings)
    File "/private/var/folders/wm/t87_jx651gvfm3t05dzg24440000gn/T/pip-build-env-lmy12lan/overlay/lib/python3.9/site-packages/sipbuild/api.py", line 46, in build_wheel
      project = AbstractProject.bootstrap('wheel',
    File "/private/var/folders/wm/t87_jx651gvfm3t05dzg24440000gn/T/pip-build-env-lmy12lan/overlay/lib/python3.9/site-packages/sipbuild/abstract_project.py", line 87, in bootstrap
      project.setup(pyproject, tool, tool_description)
    File "/private/var/folders/wm/t87_jx651gvfm3t05dzg24440000gn/T/pip-build-env-lmy12lan/overlay/lib/python3.9/site-packages/sipbuild/project.py", line 601, in setup
      self.update(tool)
    File "project.py", line 166, in update
  sipbuild.exceptions.UserException
  [end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.
`

Does anyone know the solution to this? When i try to install it with brew i get the following error at the point of "make qt5py3":

pyrcc5 -o libs/resources.py resources.qrc /Users/xxx/miniforge3/bin/python3: No module named PyQt5.pyrcc_main make: *** [qt5py3] Error 1

I wanted to install labelImg on my m1pro


问:
How to get each product at the cart page of Drupal Commerce
When I override the cart page in the template views-view-table.html.twig, the array row.columns for each row of the table i.e. for each product contains only the following keys:

purchased_entity

unit_price__number

edit_quantity

remove_button

total_price__number

At that the first field purchased_entity is again the unit price instead of any product data e.g. ID or title. So the list at the cart page doesn't have any identifying information about the products a buyer added to the cart - only their prices.

When I look under the variable product_variation inside the template commerce-product-variation.html.twig when it's loaded by the cart page, it has only two available keys, again only prices: list_price and price.

How to get product ID under the variable row.columns or purchased_entity at the cart page?


问:
GSM Connection Control
I use GSM IoT module for my project. I write a library that connects gsm and send data periodically. But in some time (while sending with no problem) gsm operator disables connection (I think that is IP time to live interval close). How can I control the connection ?

I think AT#SGACT is true for this purpose. What is your advice.

I am controlling the CREG but in this case CREG is not changed (when operator force me to disconnect)

Title: GSM Connection Control


问:
Prevent bottom navigation view to hide floating action button
I am having some trouble making hide_bottom_view_on_scroll_behavior work as wished for the bottom navigation view.
The floating action button is partly hidden by the bottom navigation. I was expecting the fab to be above the bottom navigation since I have set the app:layout_anchor and app:layout_anchorGravity properly.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- my content here-->

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:liftOnScroll="true">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleGravity="top"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:toolbarId="@id/toolbar">

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbar"
            style="@style/Widget.BloodPressureWatcher.App.Toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="0dp"
            app:layout_collapseMode="pin"
            app:menu="@menu/menu_home" />

        <include
            <!-- some content-->
             />
    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    app:layout_anchor="@id/bottom_navigation"
    app:layout_anchorGravity="top|end"
    app:srcCompat="@drawable/ic_round_add_24" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    app:labelVisibilityMode="labeled"
    app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
    app:menu="@menu/bottom_navigation_menu" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Body:
I am having some trouble making hide_bottom_view_on_scroll_behavior work as wished for the bottom navigation view.
The floating action button is partly hidden by the bottom navigation. I was expecting the fab to be above the bottom navigation since I have set the app:layout_anchor and app:layout_anchorGravity properly.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:liftOnScroll="true">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleGravity="top"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:toolbarId="@id/toolbar">

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbar"
            style="@style/Widget.BloodPressureWatcher.App.Toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="0dp"
            app:layout_collapseMode="pin"
            app:menu="@menu/menu_home" />

        <include

             />
    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    app:layout_anchor="@id/bottom_navigation"
    app:layout_anchorGravity="top|end"
    app:srcCompat="@drawable/ic_round_add_24" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    app:labelVisibilityMode="labeled"
    app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
    app:menu="@menu/bottom_navigation_menu" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>


问:
Using Dismax as parser, why doesn't Solr always expand synonyms?
Our application does some parsing of its own before the query is sent to Solr, which means that searching for the word court produces the following query:

((+court))

This works fine using the Standard Query Parser. But using the Dismax parser, synonyms no longer get expanded, yielding less search results. Using Solr Admin, I see that if I remove the parentheses the synonyms do get expanded.

Is there a reason that the parentheses cause different behaviour using Dismax? How do I get them to behave consistently?


问:
WSL2 Migration - Backup/Restore
I am using WSL2 on my development PC and I need to move to the new PC. What is the recommended approach to migrate all "WSL distributions" to the new PC ?

Do I need to back up each "WSL distributions" separately by command(s) like:

wsl --export Ubuntu-20.04 C:\WSL-Backup\ubuntu.tar

Or is there any "magic backup-all" command ?
I do not think that copying whole directory \\wsl$\ would be the right way to do the trick.

The question can be put simpler: "How to automate WSL backup? In order to make sure that it can be recovered later"

Title: WSL2 Migration - Backup/Restore


问:
Include dependent unmanaged C/C++ DLL in upper managed reference [managed C++]
I have some managed Visual C++ project which uses/links to an unmanaged DLL and serves as sort of a interop proxy between the two worlds, with some additional bells and whistles. It all works fine, the problem is referencing and deployment. When proxy project compiles and links it produces a managed DLL and pdb/xml. However, the unmanaged DLL is not included automatically. I have added the post-build xcopy command to dump it in the output and now the output has the file.

However, when this managed project is referenced by a managed client, say a test c# console app, the build process does not transfer the unmanaged DLL to console app output. Only the proxy dll/pdb/xml are there, as if the xcopy/content-of-build is ignored. Simply put the Add Project Reference has no idea that the unmanaged DLL exists at all.

What do I do in the proxy project to make sure that referencing app collects the unmanaged DLL as well? Is there some manifest to be edited/created?

I also want to turn this into a NuGet package and detach project source from the clients. What can I do there to make sure unmanaged DLL is included, and subsequently deployed with user app?


问:
React Hook Form w/ FormProvider and MUI - Not working
I have been trying to abstract my form components for some time now. I took the example of RHF JS and rewrote it in Typescript.

Unfortunately, I do not get any output of the validation results. When I submit the form nothing happens either. My understanding is that I need to pass the FormContext through to the last component.

Can anyone with experience help me?

App.tsx

import { yupResolver } from "@hookform/resolvers/yup";
import { Button, Grid, TextField } from "@mui/material";
import { memo } from "react";
import {
  FormProvider,
  useForm,
  useFormContext,
  UseFormReturn,
} from "react-hook-form";
import { object, SchemaOf, string } from "yup";

type FormData = {
  name: string;
};

const schema: SchemaOf<FormData> = object().shape({
  name: string()
    .required("Input is Required")
    .matches(/^[a-zA-Z0-9]+$/, "Only alphanummeric"),
});

type TextInputProps = {
  methods: UseFormReturn;
  name: string;
  label: string;
};

// we can use React.memo to prevent re-render except isDirty state changed
const TextFieldMemo = memo(
  ({ methods, name, label }: TextInputProps) => (
    <TextField
      label={label}
      variant="outlined"
      error={!!methods.formState.errors[name]}
      helperText={
        (methods.formState.errors[name]?.message as unknown as string) ?? ""
      }
      fullWidth
      margin="normal"
      {...methods.register(name)}
      InputLabelProps={{
        shrink: true,
      }}
      FormHelperTextProps={{
        sx: {
          position: "absolute",
          bottom: "-1.5rem",
        },
      }}
    />
  ),
  (prevProps, nextProps) =>
    prevProps.methods.formState.isDirty ===
      nextProps.methods.formState.isDirty &&
    prevProps.methods.formState.errors !== nextProps.methods.formState.errors
);

export const TextFieldMemoContainer = () => {
  const methods = useFormContext();

  return <TextFieldMemo methods={methods} name="name" label="Name" />;
};

export default function App() {
  const methods = useForm<FormData>({
    resolver: yupResolver(schema),
    mode: "onChange",
  });

  const { isDirty } = methods.formState;
  const onSubmit = (form: FormData) => {
    console.log(isDirty);
    console.log(form);
  };

  return (
    <Grid container>
      <FormProvider {...methods}>
        <form onSubmit={methods.handleSubmit(onSubmit)}>
          <Grid item>
            <TextFieldMemoContainer />
          </Grid>

          <Grid item>
            <Button
              type="submit"
              disabled={
                !methods.formState.isDirty || !methods.formState.isValid
              }
            >
              Submit
            </Button>
          </Grid>
        </form>
      </FormProvider>
    </Grid>
  );
}
```

Thank you all in advance.

StackBlitz MRE

Body:
I have been trying to abstract my form components for some time now. I took the example of RHF JS and rewrote it in Typescript.

Unfortunately, I do not get any output of the validation results. When I submit the form nothing happens either. My understanding is that I need to pass the FormContext through to the last component.

Can anyone with experience help me?

App.tsx

import { yupResolver } from "@hookform/resolvers/yup";
import { Button, Grid, TextField } from "@mui/material";
import { memo } from "react";
import {
  FormProvider,
  useForm,
  useFormContext,
  UseFormReturn,
} from "react-hook-form";
import { object, SchemaOf, string } from "yup";

type FormData = {
  name: string;
};

const schema: SchemaOf<FormData> = object().shape({
  name: string()
    .required("Input is Required")
    .matches(/^[a-zA-Z0-9]+$/, "Only alphanummeric"),
});

type TextInputProps = {
  methods: UseFormReturn;
  name: string;
  label: string;
};

// we can use React.memo to prevent re-render except isDirty state changed
const TextFieldMemo = memo(
  ({ methods, name, label }: TextInputProps) => (
    <TextField
      label={label}
      variant="outlined"
      error={!!methods.formState.errors[name]}
      helperText={
        (methods.formState.errors[name]?.message as unknown as string) ?? ""
      }
      fullWidth
      margin="normal"
      {...methods.register(name)}
      InputLabelProps={{
        shrink: true,
      }}
      FormHelperTextProps={{
        sx: {
          position: "absolute",
          bottom: "-1.5rem",
        },
      }}
    />
  ),
  (prevProps, nextProps) =>
    prevProps.methods.formState.isDirty ===
      nextProps.methods.formState.isDirty &&
    prevProps.methods.formState.errors !== nextProps.methods.formState.errors
);

export const TextFieldMemoContainer = () => {
  const methods = useFormContext();

  return <TextFieldMemo methods={methods} name="name" label="Name" />;
};

export default function App() {
  const methods = useForm<FormData>({
    resolver: yupResolver(schema),
    mode: "onChange",
  });

  const { isDirty } = methods.formState;
  const onSubmit = (form: FormData) => {
    console.log(isDirty);
    console.log(form);
  };

  return (
    <Grid container>
      <FormProvider {...methods}>
        <form onSubmit={methods.handleSubmit(onSubmit)}>
          <Grid item>
            <TextFieldMemoContainer />
          </Grid>

          <Grid item>
            <Button
              type="submit"
              disabled={
                !methods.formState.isDirty || !methods.formState.isValid
              }
            >
              Submit
            </Button>
          </Grid>
        </form>
      </FormProvider>
    </Grid>
  );
}

Thank you all in advance.

StackBlitz MRE


问:
How to convert my foreach loop into stream in java
I want to achieve the below logic using streams in java.

for (Plan plan : organization.getPlan()) {
            if(plan.getUserCount()==0) {
                return DataFetcherResult.<com.xerago.acquigo.poc.dgmodels.types.User>newResult().error(
                        GraphqlErrorBuilder.newError()
                                .message("User Count Exceeded!!")
                                .errorType(ErrorType.FAILED_PRECONDITION)
                                .build())
                .build();
            }
                plan.setUserCount(plan.getUserCount()-1);
            }
```

I want to return error graphql message when specific conditions are met or do the else part using stream

Body:
I want to achieve the below logic using streams in java.

for (Plan plan : organization.getPlan()) {
            if(plan.getUserCount()==0) {
                return DataFetcherResult.<com.xerago.acquigo.poc.dgmodels.types.User>newResult().error(
                        GraphqlErrorBuilder.newError()
                                .message("User Count Exceeded!!")
                                .errorType(ErrorType.FAILED_PRECONDITION)
                                .build())
                .build();
            }
                plan.setUserCount(plan.getUserCount()-1);
            }

I want to return error graphql message when specific conditions are met or do the else part using stream


问:
React development with multiple .env files
I have a ReactJs application that was created using Create-React-App and I am looking for an option to work with multiple .env files with custom environment variables for various environments, like env.local, env.qa, env.development, env.stage, and env.production. I understand how to use env-cmd (which seems like the widely suggested solution for my case). However, it has not been updated in a long while and I am not too certain if that is an ideal choice for my case now. Can anyone please suggest an alternative or advise on this regard? Thank you.


问:
Need to modify this macro to work on selected text instead of whole document
I derived and modified this macro to subscript numbers in chemical formulae and to superscript numbers for variables used in patent genera (e.g., R, X, Y, or Z) in a Word document.  The macro works fine on a whole document, but I would like to modify it so that it only work on selected text.

I have tried all sorts of manipulations based on information from the internet, but none successfully limit the macro to text selected in a Word document.  I'm not particularly well-versed in VBA, so there was a lot trial and error. Any help would be appreciated.

I realized that even on a whole document this macro has some issues.  I removed the commas in between characters in the bracketed searchText characters.  But how do I get the macro to search for terms like "Na", "Cl" or "Br".  Those are not recognized when in the brackets.

```<code>Dim Selection As Word.Range
    Dim searchText As String
    Dim found As Boolean

    Set Selection = ActiveDocument.Content
    searchText = "[RXYZ][1-9][0-9]"
    With Selection.Find
        .Text = searchText
        .MatchWildcards = True
        .Wrap = wdFindStop
        found = .Execute
        Do While found
            Selection.Collapse wdCollapseEnd
            Selection.MoveStart wdCharacter, -2
            Selection.Font.Superscript = True
            Selection.End = ActiveDocument.Content.End
            found = .Execute
        Loop
    End With
    Set Selection = ActiveDocument.Content
    searchText = "[RXYZ][1-9]"
    With Selection.Find
        .Text = searchText
        .MatchWildcards = True
        .Wrap = wdFindStop
        found = .Execute
        Do While found
            Selection.Collapse wdCollapseEnd
            Selection.MoveStart wdCharacter, -1
            Selection.Font.Superscript = True
            Selection.End = ActiveDocument.Content.End
            found = .Execute
        Loop
    End With
    Set Selection = ActiveDocument.Content
    searchText = "[CH][1-9][0-9]"
    With Selection.Find
        .Text = searchText
        .MatchWildcards = True
        .Wrap = wdFindStop
        found = .Execute
        Do While found
            Selection.Collapse wdCollapseEnd
            Selection.MoveStart wdCharacter, -2
            Selection.Font.Subscript = True
            Selection.End = ActiveDocument.Content.End
            found = .Execute
        Loop
    End With
    Set Selection = ActiveDocument.Content
    searchText = "[CHNOSFIB,Na,Cl,Br][1-9]"
    With Selection.Find
        .Text = searchText
        .MatchWildcards = True
        .Wrap = wdFindStop
        found = .Execute
        Do While found
            Selection.Collapse wdCollapseEnd
            Selection.MoveStart wdCharacter, -1
            Selection.Font.Subscript = True
            Selection.End = ActiveDocument.Content.End
            found = .Execute
        Loop
    End With
End Sub
</code>```
```<code></code>```

Body:
I derived and modified this macro to subscript numbers in chemical formulae and to superscript numbers for variables used in patent genera (e.g., R, X, Y, or Z) in a Word document.  The macro works fine on a whole document, but I would like to modify it so that it only work on selected text.

I have tried all sorts of manipulations based on information from the internet, but none successfully limit the macro to text selected in a Word document.  I'm not particularly well-versed in VBA, so there was a lot trial and error. Any help would be appreciated.

I realized that even on a whole document this macro has some issues.  I removed the commas in between characters in the bracketed searchText characters.  But how do I get the macro to search for terms like "Na", "Cl" or "Br".  Those are not recognized when in the brackets.

Dim Selection As Word.Range
    Dim searchText As String
    Dim found As Boolean

    Set Selection = ActiveDocument.Content
    searchText = "[RXYZ][1-9][0-9]"
    With Selection.Find
        .Text = searchText
        .MatchWildcards = True
        .Wrap = wdFindStop
        found = .Execute
        Do While found
            Selection.Collapse wdCollapseEnd
            Selection.MoveStart wdCharacter, -2
            Selection.Font.Superscript = True
            Selection.End = ActiveDocument.Content.End
            found = .Execute
        Loop
    End With
    Set Selection = ActiveDocument.Content
    searchText = "[RXYZ][1-9]"
    With Selection.Find
        .Text = searchText
        .MatchWildcards = True
        .Wrap = wdFindStop
        found = .Execute
        Do While found
            Selection.Collapse wdCollapseEnd
            Selection.MoveStart wdCharacter, -1
            Selection.Font.Superscript = True
            Selection.End = ActiveDocument.Content.End
            found = .Execute
        Loop
    End With
    Set Selection = ActiveDocument.Content
    searchText = "[CH][1-9][0-9]"
    With Selection.Find
        .Text = searchText
        .MatchWildcards = True
        .Wrap = wdFindStop
        found = .Execute
        Do While found
            Selection.Collapse wdCollapseEnd
            Selection.MoveStart wdCharacter, -2
            Selection.Font.Subscript = True
            Selection.End = ActiveDocument.Content.End
            found = .Execute
        Loop
    End With
    Set Selection = ActiveDocument.Content
    searchText = "[CHNOSFIB,Na,Cl,Br][1-9]"
    With Selection.Find
        .Text = searchText
        .MatchWildcards = True
        .Wrap = wdFindStop
        found = .Execute
        Do While found
            Selection.Collapse wdCollapseEnd
            Selection.MoveStart wdCharacter, -1
            Selection.Font.Subscript = True
            Selection.End = ActiveDocument.Content.End
            found = .Execute
        Loop
    End With
End Sub


问:
syntax error, unexpected string content "", expecting "-" or identifier or variable or number in C:\xampp\htdocs\TimeTable\Backend\new.php on line 61
I'm trying to insert data into a database but couldn't. Below is my code

```<code><?php

$servername = "localhost";
$username = "root";
$password = "";
$database =  "routine maker";

$conn = mysqli_connect($servername, $username, $password, $database);

if(!$conn){
    die("Sorry we failed to connect: ". mysqli_connect_error());
}else{
    echo '<script>alert("Connection was successful");</script>';
}

$sql = `INSERT INTO check (teacherName, subject , class) VALUES ("skg", "Doe", 4)`;
if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
</code>```

i was expecting the data to be inserted.

Body:
I'm trying to insert data into a database but couldn't. Below is my code

<?php

$servername = "localhost";
$username = "root";
$password = "";
$database =  "routine maker";

$conn = mysqli_connect($servername, $username, $password, $database);

if(!$conn){
    die("Sorry we failed to connect: ". mysqli_connect_error());
}else{
    echo '';
}

$sql = `INSERT INTO check (teacherName, subject , class) VALUES ("skg", "Doe", 4)`;
if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

i was expecting the data to be inserted.


问:
Prevent Flex Grow Before The Content is Full
How can we make the flex items' height grow only when the text in the second flex item is full of the text?

Someone pointed me to this link, but it's not working for me.

function addDummyText() {
  const span = document.getElementById("second-row-span");

  span.textContent = span.textContent + " Lorem ipsum dolor sit amet ";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
    height: 100%;
}

.flex-container {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: stretch;
    height: 100%;
    }

.flex-item:nth-child(1) {
    order: 0;
    flex: 1 1 auto;
    align-self: auto;
    background-color: red;
    }

.flex-item:nth-child(2) {
    order: 0;
    flex: 2 1 auto;
    align-self: auto;
  background-color: blue;
    }

.flex-item:nth-child(3) {
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
  background-color: grey;
    }</code>```

1 <input type="button" onclick="addDummyText()" value="add text" />

2

3

```

Body:
How can we make the flex items' height grow only when the text in the second flex item is full of the text?

Someone pointed me to this link, but it's not working for me.

function addDummyText() {
  const span = document.getElementById("second-row-span");

  span.textContent = span.textContent + " Lorem ipsum dolor sit amet ";
}

html,
body {
    height: 100%;
}

.flex-container {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: stretch;
    height: 100%;
    }

.flex-item:nth-child(1) {
    order: 0;
    flex: 1 1 auto;
    align-self: auto;
    background-color: red;
    }

.flex-item:nth-child(2) {
    order: 0;
    flex: 2 1 auto;
    align-self: auto;
  background-color: blue;
    }

.flex-item:nth-child(3) {
    order: 0;
    flex: 0 1 auto;
    align-self: auto;
  background-color: grey;
    }

1 <input type="button" onclick="addDummyText()" value="add text" />

2

3


问:
Removing Item from Scene unsuccessful and causes error
Removing a QGraphicsPathItem from a QGraphicsScene raises "QGraphicsScene::removeItem: item 0x204f6a20880's scene (0x0) is different from this scene (0x204f7e519c0)".

I also printed the .scene() method of the item and printed the scene, both of which are the same - "<examples.example_calculator.nodes.operations.GraphScene object at 0x00000204F79E5C10>".
So I do not understand how the scene I am deleting the item from, is not the same as the one that the item is in, which is proved true by my two print statements, however the error still comes up.

Here is the code:

```<code>class GraphCurve(QGraphicsView):
    def __init__(self, scene):
        super().__init__()
        self.scene = scene
        self.setScene(scene)
        self.setSceneRect(0,0,self.scene.sx, self.scene.sy)
        self.pntrad = 10
        self.selected=None
        self.cpoints=[]
        self.ccpoints=[]
        self.points = []
        self.paths = []

######WHERE THE ERROR COMES UP######
def updateCurve(self, mvpnt):
        try:
            x = self.cpoints.index(mvpnt)
            mvpnt = self.points[x]
        except:
            try:
                x = self.ccpoints.index(mvpnt)
                mvpnt = self.points[x]
            except:
                pass
        try:
            ind = self.points.index(mvpnt)
            ######WHERE THE ERROR COMES UP##########################################################
            print(str(self.scene)) #####MARK THIS AS A#####
            print(str(self.paths[ind-1].scene())) #####SAME AS A#####
            self.scene.removeItem(self.paths[ind-1])
        except:
            pass
        try:
            ######WHERE THE ERROR COMES UP##########################################################
            self.scene.removeItem(self.paths[ind])
        except:
            pass
        points = [self.points[ind], self.points[ind-1]]
        for x in points:
            try:
                drawpath = QPainterPath()
                drawpath.moveTo(QPointF(x.pos().x()+self.pntrad/2, x.pos().y()+self.pntrad/2))
                drawpath.cubicTo(QPointF(self.ccpoints[self.points.index(x)].pos().x()+(self.pntrad/2), self.ccpoints[self.points.index(x)].pos().y()+(self.pntrad/2)),
                                QPointF(self.cpoints[self.points.index(x)+1].pos().x()+(self.pntrad/2), self.cpoints[self.points.index(x)+1].pos().y()+(self.pntrad/2)),
                                QPointF(self.points[self.points.index(x)+1].pos().x()+(self.pntrad/2), self.points[self.points.index(x)+1].pos().y()+(self.pntrad/2)))

                ######WHERE THE ITEM IS CREATED#####################################################
                path = self.scene.addPath(drawpath)
                print(str(path.scene())) #####THIS IS SAME AS A#####
                self.paths.append(path)
            except:
                pass

</code>```

Body:
Removing a QGraphicsPathItem from a QGraphicsScene raises "QGraphicsScene::removeItem: item 0x204f6a20880's scene (0x0) is different from this scene (0x204f7e519c0)".

I also printed the .scene() method of the item and printed the scene, both of which are the same - "<examples.example_calculator.nodes.operations.GraphScene object at 0x00000204F79E5C10>".
So I do not understand how the scene I am deleting the item from, is not the same as the one that the item is in, which is proved true by my two print statements, however the error still comes up.

Here is the code:

class GraphCurve(QGraphicsView):
    def __init__(self, scene):
        super().__init__()
        self.scene = scene
        self.setScene(scene)
        self.setSceneRect(0,0,self.scene.sx, self.scene.sy)
        self.pntrad = 10
        self.selected=None
        self.cpoints=[]
        self.ccpoints=[]
        self.points = []
        self.paths = []

######WHERE THE ERROR COMES UP######
def updateCurve(self, mvpnt):
        try:
            x = self.cpoints.index(mvpnt)
            mvpnt = self.points[x]
        except:
            try:
                x = self.ccpoints.index(mvpnt)
                mvpnt = self.points[x]
            except:
                pass
        try:
            ind = self.points.index(mvpnt)
            ######WHERE THE ERROR COMES UP##########################################################
            print(str(self.scene)) #####MARK THIS AS A#####
            print(str(self.paths[ind-1].scene())) #####SAME AS A#####
            self.scene.removeItem(self.paths[ind-1])
        except:
            pass
        try:
            ######WHERE THE ERROR COMES UP##########################################################
            self.scene.removeItem(self.paths[ind])
        except:
            pass
        points = [self.points[ind], self.points[ind-1]]
        for x in points:
            try:
                drawpath = QPainterPath()
                drawpath.moveTo(QPointF(x.pos().x()+self.pntrad/2, x.pos().y()+self.pntrad/2))
                drawpath.cubicTo(QPointF(self.ccpoints[self.points.index(x)].pos().x()+(self.pntrad/2), self.ccpoints[self.points.index(x)].pos().y()+(self.pntrad/2)),
                                QPointF(self.cpoints[self.points.index(x)+1].pos().x()+(self.pntrad/2), self.cpoints[self.points.index(x)+1].pos().y()+(self.pntrad/2)),
                                QPointF(self.points[self.points.index(x)+1].pos().x()+(self.pntrad/2), self.points[self.points.index(x)+1].pos().y()+(self.pntrad/2)))

                ######WHERE THE ITEM IS CREATED#####################################################
                path = self.scene.addPath(drawpath)
                print(str(path.scene())) #####THIS IS SAME AS A#####
                self.paths.append(path)
            except:
                pass


问:
Can't resolve 'node_modules/@angular/cdk/overlay-prebuilt.css'
I've tried to migrate Angular 13 to Angular 15 and after this I get error message:

./node_modules/@app/app-core/theme/app-theme.scss - Error: Module build failed (from ./node_modules/css-loader/dist/cjs.js):
Error: Can't resolve 'node_modules/@angular/cdk/overlay-prebuilt.css' in '/Users/user/node_modules/@app/app-core/theme'

Angular.json file has configurations:

```<code>"assets": [
  "src/assets",
  {
    "glob": "**",
    "input": "node_modules/@app/app-core/theme",
    "output": "app-core"
  }
],
"styles": [
  "node_modules/@app/app-core/theme/app-theme.scss",
  "src/styles.sass"
],
</code>```

In app-theme.scss:

```<code>@import 'font-family';
@import 'variables';
@import 'reboot';
@import 'mixins';
@import 'node_modules/@angular/cdk/overlay-prebuilt.css';
@import 'buttons';
@import '_grid';
@import '_container';
@import 'main';
</code>```

app-theme.scss is file which I import to my app and I can't change it globally but if I changed locally:

```<code>@import 'node_modules/@angular/cdk/overlay-prebuilt.css';
</code>```

to

```<code>@import '~@angular/cdk/overlay-prebuilt.css';
</code>```

The problem didn't occur and app is running.

I've tried deleting node-modules and package-lock.json and reinstall all dependencies but it doesn't work.

Body:
I've tried to migrate Angular 13 to Angular 15 and after this I get error message:

./node_modules/@app/app-core/theme/app-theme.scss - Error: Module build failed (from ./node_modules/css-loader/dist/cjs.js):
Error: Can't resolve 'node_modules/@angular/cdk/overlay-prebuilt.css' in '/Users/user/node_modules/@app/app-core/theme'

Angular.json file has configurations:

"assets": [
  "src/assets",
  {
    "glob": "**",
    "input": "node_modules/@app/app-core/theme",
    "output": "app-core"
  }
],
"styles": [
  "node_modules/@app/app-core/theme/app-theme.scss",
  "src/styles.sass"
],

In app-theme.scss:

@import 'font-family';
@import 'variables';
@import 'reboot';
@import 'mixins';
@import 'node_modules/@angular/cdk/overlay-prebuilt.css';
@import 'buttons';
@import '_grid';
@import '_container';
@import 'main';

app-theme.scss is file which I import to my app and I can't change it globally but if I changed locally:

@import 'node_modules/@angular/cdk/overlay-prebuilt.css';

to

@import '~@angular/cdk/overlay-prebuilt.css';

The problem didn't occur and app is running.

I've tried deleting node-modules and package-lock.json and reinstall all dependencies but it doesn't work.


问:
How to programmatically mimic latency between server and client in nodejs?
I am writing a test script for nodejs. The test case look like this:

var http = require('http');
var net = require('net');

// Here is server
var server = http.createSever(function (req, res) {
   res.end('ok');
}).listen();

var port = server.address().port;

// Here is client
var numRequest = 20;
var client = net.connect({port: port, allowHalfOpen: true});
for (var i = 0; i < numRequest; i++) {
    client.write('GET / HTTP/1.1\r\n' + 'Host: some.host.name\r\n' + '\r\n\r\n');
}
client.end();
```

Since both the server and the client runs on my local machine, the server receives the request immediately. However, I want to mimic the scenario, where the server receives the request after a period of time. In particular, I want to mimic the scenario, the http connection is closed before server receives all the request. So, the question is, how to programmatically mimic such a scenario? Thx :)

Body:
I am writing a test script for nodejs. The test case look like this:

var http = require('http');
var net = require('net');

// Here is server
var server = http.createSever(function (req, res) {
   res.end('ok');
}).listen();

var port = server.address().port;

// Here is client
var numRequest = 20;
var client = net.connect({port: port, allowHalfOpen: true});
for (var i = 0; i < numRequest; i++) {
    client.write('GET / HTTP/1.1\r\n' + 'Host: some.host.name\r\n' + '\r\n\r\n');
}
client.end();

Since both the server and the client runs on my local machine, the server receives the request immediately. However, I want to mimic the scenario, where the server receives the request after a period of time. In particular, I want to mimic the scenario, the http connection is closed before server receives all the request. So, the question is, how to programmatically mimic such a scenario? Thx :)


问:
Issue when updating a product in magento 2 from command line

Update the product status in Magento 2

When updating the status of a product I get the following issue:

UpdateStatus.php

```<code>    public function __construct(
        ProductRepositoryInterface $productRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        Product $product,
        Configurable $configurable,
        StockItem $stockItem,
        State $state
    )
    {
        parent::__construct();
        $this->productRepository = $productRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->_product = $product;
        $this->configurable = $configurable;
        $this->stockItem = $stockItem;
        $this->state = $state;
    }

    protected function execute(InputInterface $input, OutputInterface $output): ?int
    {
        $this->state->setAreaCode(Area::AREA_ADMINHTML);

        $product = $this->_product->loadByAttribute('sku', '46-50953763');
        $product->setStatus(2);
        $product->save();

        return 0;
    }
</code>```

And also I tried using the repository:

```<code>        $product = $this->productRepository->get('46-50953763');
        $product->setStatus(2);

        try {
            $this->productRepository->save($product);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        }
</code>```

What is the way to update a magento product from command line?

Body:
Update the product status in Magento 2

When updating the status of a product I get the following issue:

UpdateStatus.php

    public function __construct(
        ProductRepositoryInterface $productRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        Product $product,
        Configurable $configurable,
        StockItem $stockItem,
        State $state
    )
    {
        parent::__construct();
        $this->productRepository = $productRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->_product = $product;
        $this->configurable = $configurable;
        $this->stockItem = $stockItem;
        $this->state = $state;
    }

    protected function execute(InputInterface $input, OutputInterface $output): ?int
    {
        $this->state->setAreaCode(Area::AREA_ADMINHTML);

        $product = $this->_product->loadByAttribute('sku', '46-50953763');
        $product->setStatus(2);
        $product->save();

        return 0;
    }

And also I tried using the repository:

        $product = $this->productRepository->get('46-50953763');
        $product->setStatus(2);

        try {
            $this->productRepository->save($product);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        }

What is the way to update a magento product from command line?


问:
ThreeJS Canvas Texture returns the entire canvas with the drawing inside of it instead of just the drawing
I am using react, three js, react-three-fiber

I want to place 10 points on the scene, the points are to be circles. I was able to place the points but by default they are squares.

I tried to draw a circle inside of a canvas and use that as a texture for the points but instead the point textures are now squares with circles in them:

```<code>// Texture for Points
    const getTexture = (size, color) => {
        var matCanvas = document.createElement('canvas');
        matCanvas.width = size;
        matCanvas.height = size;
        var matContext = matCanvas.getContext('2d');

        // create texture object from canvas.
        var texture = new THREE.Texture(matCanvas);

        // Draw a circle
        var center = size / 2;
        matContext.beginPath();
        matContext.arc(center, center, size/2, 0, 2 * Math.PI, false);
        matContext.closePath();
        matContext.fillStyle = color;
        matContext.fill();

        // need to set needsUpdate
        texture.needsUpdate = true;

        // return a texture made from the canvas
        return texture;
    }

</code>```

And

```<code>return (
        <points args={[geometry]}>
            <pointsMaterial
                size={1}
                map={getTexture(100, 'red')}
            />
        </points>
    )
</code>```

Body:
I am using react, three js, react-three-fiber

I want to place 10 points on the scene, the points are to be circles. I was able to place the points but by default they are squares.

I tried to draw a circle inside of a canvas and use that as a texture for the points but instead the point textures are now squares with circles in them:

// Texture for Points
    const getTexture = (size, color) => {
        var matCanvas = document.createElement('canvas');
        matCanvas.width = size;
        matCanvas.height = size;
        var matContext = matCanvas.getContext('2d');

        // create texture object from canvas.
        var texture = new THREE.Texture(matCanvas);

        // Draw a circle
        var center = size / 2;
        matContext.beginPath();
        matContext.arc(center, center, size/2, 0, 2 * Math.PI, false);
        matContext.closePath();
        matContext.fillStyle = color;
        matContext.fill();

        // need to set needsUpdate
        texture.needsUpdate = true;

        // return a texture made from the canvas
        return texture;
    }

And

return (
        <points args={[geometry]}>
            <pointsMaterial
                size={1}
                map={getTexture(100, 'red')}
            />
        </points>
    )


问:
How to find the best match for imperfect string in large dataset - Python AutoSub to real subtitle match
Lets say I have a 30 second clip from a long-running (many seasons/episodes) TV show and my goal is to add the official (real) subtitles from the show to the clip.

I do not know what episode or season the clip is from.

Downloading all subtitles for all seasons/episodes of the TV Show and running speech-to-text SW to generate auto-subs for the clip is done/trivial.

These auto-subs are imperfect.  They combine what should be multiple lines of dialog into a single line, they add dialog where there is none (thinking a shattering window sounds like someone saying "Thank You", etc.

Now that I have my imperfect clip auto-subs, what is the best way to go about matching them to a specific episode from my database of all subtitles from every episode (lets say this is very large like Law and Order or The Simpsons)?

Additionally, lets say I want to prioritize retrieve time.  Lets say I will get 10 new clips every day to process and I will very rarely add to the database (like adding the subs for the new episode of The Simpsons once per week).

Here is an example of auto-generated subtitles (.srt):

```<code>2
00:00:15,570 --> 00:00:19,240
we are that's odd

3
00:00:19,240 --> 00:00:21,279
it's our house but somehow it looks a

4
00:00:21,279 --> 00:00:23,619
little different mom my lips are too

5
00:00:23,619 --> 00:00:24,939
thin can I please get collagen
</code>```

And here is an example of the "real" subtitles that should be found/matched:

```<code>34
00:01:27,000 --> 00:01:29,568
Well, here we are.

35
00:01:29,636 --> 00:01:31,137
That's odd.

36
00:01:31,204 --> 00:01:33,639
It's our house, but somehow
it looks a little different.

37
00:01:33,707 --> 00:01:35,441
Mom, my lips
are too thin.

38
00:01:35,509 --> 00:01:37,243
Can I please get
collagen injections?
</code>```

Any strategies/libraries come to mind?

Any methods other than auto-sub matching that would be more effective?

Python preferred for individual libraries but open to anything!

Thanks!

Body:
Lets say I have a 30 second clip from a long-running (many seasons/episodes) TV show and my goal is to add the official (real) subtitles from the show to the clip.

I do not know what episode or season the clip is from.

Downloading all subtitles for all seasons/episodes of the TV Show and running speech-to-text SW to generate auto-subs for the clip is done/trivial.

These auto-subs are imperfect.  They combine what should be multiple lines of dialog into a single line, they add dialog where there is none (thinking a shattering window sounds like someone saying "Thank You", etc.

Now that I have my imperfect clip auto-subs, what is the best way to go about matching them to a specific episode from my database of all subtitles from every episode (lets say this is very large like Law and Order or The Simpsons)?

Additionally, lets say I want to prioritize retrieve time.  Lets say I will get 10 new clips every day to process and I will very rarely add to the database (like adding the subs for the new episode of The Simpsons once per week).

Here is an example of auto-generated subtitles (.srt):

2
00:00:15,570 --> 00:00:19,240
we are that's odd

3
00:00:19,240 --> 00:00:21,279
it's our house but somehow it looks a

4
00:00:21,279 --> 00:00:23,619
little different mom my lips are too

5
00:00:23,619 --> 00:00:24,939
thin can I please get collagen

And here is an example of the "real" subtitles that should be found/matched:

34
00:01:27,000 --> 00:01:29,568
Well, here we are.

35
00:01:29,636 --> 00:01:31,137
That's odd.

36
00:01:31,204 --> 00:01:33,639
It's our house, but somehow
it looks a little different.

37
00:01:33,707 --> 00:01:35,441
Mom, my lips
are too thin.

38
00:01:35,509 --> 00:01:37,243
Can I please get
collagen injections?

Any strategies/libraries come to mind?

Any methods other than auto-sub matching that would be more effective?

Python preferred for individual libraries but open to anything!

Thanks!


问:
How to use "useI18n" on "server/api" directory
I'm using @nuxtjs/i18n version ^8.0.0-beta.7 and here is my nuxt.config.ts:

```<code>import en from "./locales/en.json";

export default defineNuxtConfig({
  typescript: { strict: true, shim: false },
  components: true,
  runtimeConfig: {
    //...
  },
  modules: [
    "@nuxtjs/i18n",
    //...
  ],
  vueuse: { ssrHandlers: true },
  i18n: {
    vueI18n: {
      legacy: false,
      locale: "en",
      availableLocales: ["en", "fr"],
      messages: { en },
    },
  },
});

</code>```

locales/en.json

{
  "foo": "bar"
}

```
<p>All components inside <code>pages</code> and <code>components</code> are working fine, however when I do the same thing with <code>server/api</code> directory the error occurs:</p>
```[nuxt] [request error] [unhandled] [500] useI18n is not defined                                                                         21:49:12
  at /D:/Projects/saucemoe/.nuxt/dev/index.mjs:547:17
  at /D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:668:47
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async Object.handler (/D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:723:19)
  at async Server.toNodeHandle (/D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:798:7)
```
<p><code>server/api/test.get.ts</code></p>
```export default defineEventHandler((event) => {
  const { t } = useI18n();
  const foo = t("foo");

  return { foo };
});

```
<p>But if I add <code>import { useI18n } from "vue-i18n";</code> I get another error:</p>
```[nuxt] [request error] [unhandled] [500] Must be called at the top of a setup function                                                  21:59:08
  at createCompileError (/D:/Projects/saucemoe/node_modules/@intlify/message-compiler/dist/message-compiler.mjs:54:19)
  at createI18nError (/D:/Projects/saucemoe/node_modules/vue-i18n/dist/vue-i18n.mjs:92:12)
  at useI18n (/D:/Projects/saucemoe/node_modules/vue-i18n/dist/vue-i18n.mjs:2229:15)
  at /D:/Projects/saucemoe/.nuxt/dev/index.mjs:548:17
  at /D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:668:47
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async Object.handler (/D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:723:19)
  at async Server.toNodeHandle (/D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:798:7)
```
```import { useI18n } from "vue-i18n";

export default defineEventHandler((event) => {
  const { t } = useI18n();
  const foo = t("foo");

  return { foo };
});

```

So in summary, how can I use useI18n in server/api directory, many thanks.

Body:
I'm using @nuxtjs/i18n version ^8.0.0-beta.7 and here is my nuxt.config.ts:

import en from "./locales/en.json";

export default defineNuxtConfig({
  typescript: { strict: true, shim: false },
  components: true,
  runtimeConfig: {
    //...
  },
  modules: [
    "@nuxtjs/i18n",
    //...
  ],
  vueuse: { ssrHandlers: true },
  i18n: {
    vueI18n: {
      legacy: false,
      locale: "en",
      availableLocales: ["en", "fr"],
      messages: { en },
    },
  },
});

locales/en.json

{
  "foo": "bar"
}

All components inside pages and components are working fine, however when I do the same thing with server/api directory the error occurs:

[nuxt] [request error] [unhandled] [500] useI18n is not defined                                                                         21:49:12
  at /D:/Projects/saucemoe/.nuxt/dev/index.mjs:547:17
  at /D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:668:47
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async Object.handler (/D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:723:19)
  at async Server.toNodeHandle (/D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:798:7)

server/api/test.get.ts

export default defineEventHandler((event) => {
  const { t } = useI18n();
  const foo = t("foo");

  return { foo };
});

But if I add import { useI18n } from "vue-i18n"; I get another error:

[nuxt] [request error] [unhandled] [500] Must be called at the top of a setup function                                                  21:59:08
  at createCompileError (/D:/Projects/saucemoe/node_modules/@intlify/message-compiler/dist/message-compiler.mjs:54:19)
  at createI18nError (/D:/Projects/saucemoe/node_modules/vue-i18n/dist/vue-i18n.mjs:92:12)
  at useI18n (/D:/Projects/saucemoe/node_modules/vue-i18n/dist/vue-i18n.mjs:2229:15)
  at /D:/Projects/saucemoe/.nuxt/dev/index.mjs:548:17
  at /D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:668:47
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async Object.handler (/D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:723:19)
  at async Server.toNodeHandle (/D:/Projects/saucemoe/node_modules/h3/dist/index.mjs:798:7)

import { useI18n } from "vue-i18n";

export default defineEventHandler((event) => {
  const { t } = useI18n();
  const foo = t("foo");

  return { foo };
});

So in summary, how can I use useI18n in server/api directory, many thanks.


问:
Terraform Pass Variable (Object) to Templatefile
I have the following variable that I would like to have rendered in a template file. All values of the variable are optional.

The template itself contains other variables, but these are usually just simple strings.

```<code>variable "security_context" {
  type = object({
    allow_privilege_escalation = optional(bool)
    read_only_root_filesystem  = optional(bool)
    run_as_non_root            = optional(bool)
    privileged                 = optional(bool)
    capabilities = optional(object({
      add  = optional(list(string))
      drop = optional(list(string))
    }))
  })
  default = null
}

resource "helm_release" "test" {
  ...
  values = [templatefile("${path.module}/values-override.yaml.tpl",
    {
      ...
      sec_context = var.security_context
    }
  )]
}
</code>```

My template file looks like this:

```<code>
%{ if main_container_sec_context != null }
securityContext:
  %{ if sec_context.allow_privilege_escalation != null }
  allowPrivilegeEscalation: ${sec_context.allow_privilege_escalation}
  %{ endif }
  %{ if sec_context.read_only_root_filesystem != null }
  readOnlyRootFilesystem: ${sec_context.read_only_root_filesystem}
  %{ endif }
  %{ if sec_context.run_as_non_root != null }
  runAsNonRoot: ${sec_context.run_as_non_root}
  %{ endif }
  %{ if sec_context.privileged != null }
  privileged: ${sec_context.privileged}
  %{ endif }
%{ endif }

</code>```

For the bool values, this approach works, but it's a lot of code. Can this be reduced by iterating over the values?

What would be the best way to integrate the lists (capabilities: add and drop)?

Body:
I have the following variable that I would like to have rendered in a template file. All values of the variable are optional.

The template itself contains other variables, but these are usually just simple strings.

variable "security_context" {
  type = object({
    allow_privilege_escalation = optional(bool)
    read_only_root_filesystem  = optional(bool)
    run_as_non_root            = optional(bool)
    privileged                 = optional(bool)
    capabilities = optional(object({
      add  = optional(list(string))
      drop = optional(list(string))
    }))
  })
  default = null
}

resource "helm_release" "test" {
  ...
  values = [templatefile("${path.module}/values-override.yaml.tpl",
    {
      ...
      sec_context = var.security_context
    }
  )]
}

My template file looks like this:

%{ if main_container_sec_context != null }
securityContext:
  %{ if sec_context.allow_privilege_escalation != null }
  allowPrivilegeEscalation: ${sec_context.allow_privilege_escalation}
  %{ endif }
  %{ if sec_context.read_only_root_filesystem != null }
  readOnlyRootFilesystem: ${sec_context.read_only_root_filesystem}
  %{ endif }
  %{ if sec_context.run_as_non_root != null }
  runAsNonRoot: ${sec_context.run_as_non_root}
  %{ endif }
  %{ if sec_context.privileged != null }
  privileged: ${sec_context.privileged}
  %{ endif }
%{ endif }

For the bool values, this approach works, but it's a lot of code. Can this be reduced by iterating over the values?

What would be the best way to integrate the lists (capabilities: add and drop)?


问:
Is it possible to use a task for formatting on save in VSCode?
I use a custom code formatter (forge fmt) to format my Solidity code, but this formatter is not part of any VSCode extension.

I would like to use it to format on save. What I typically do to enable format on save in VSCode is add the following settings (in this example, I am using the Prettier VSCode extension):

{
  "editor.formatOnSave": true,
  "[solidity]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
```

The trouble is that the defaultFormatter setting expects the name of an extension, but there isn't any bespoke VSCode extension for my formatter at the moment.

Would it be possible to instead use a task for formatting on save?

Update: it looks like there is actually an extension that has support for my custom formatter. Still, I wish to keep my question open, because I will probably bump into this problem again in the future.

Body:
I use a custom code formatter (forge fmt) to format my Solidity code, but this formatter is not part of any VSCode extension.

I would like to use it to format on save. What I typically do to enable format on save in VSCode is add the following settings (in this example, I am using the Prettier VSCode extension):

{
  "editor.formatOnSave": true,
  "[solidity]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }

The trouble is that the defaultFormatter setting expects the name of an extension, but there isn't any bespoke VSCode extension for my formatter at the moment.

Would it be possible to instead use a task for formatting on save?

Update: it looks like there is actually an extension that has support for my custom formatter. Still, I wish to keep my question open, because I will probably bump into this problem again in the future.


问:
struglling to know how to bulid an index that evaluate a preformance , basic statistics
i have the following data

sector A

total number of product registering in sector A 100
product A  20
product B  80

sector A performance
complete orders 90
incomplete orders 10

i have other sectors too B,C,D
and they all have product and processors to asses

i want all the sectors to be evaluated in the same percentage out of 100%
one percentage that includes A,b,c and D sector
please do not close my question
just give me one word to the solution and i will look into it .

thank you and HELP