问:
Pandas read_html always returns NaNs for table
I have tried many variations suggested here already but I have yet to fix the problem. I started with

```<code>page = requests.get('http://eresearch.fidelity.com/eresearch/markets_sectors/sectors/sectors_in_market.jhtml?tab=industries&sector=10')
df_list = pd.read_html(page.text)
</code>```

and I can see the correct headers so I am looking at the right location. I then tried changing the flavors to bs4 and html5lib with no change. I always see NaN for the data values and only have one index, index 0, when there should be 3 or 4. My original attempt is the same as another section of code for a different table from the same website and it worked perfectly.
(also first post, please let me know how I can improve them)

答:
Unfortunately, I had to use selenium to retrieve the dataframe. But if that is not a problem feel free to try the following:

```<code>from selenium import webdriver
import pandas as pd

driver = webdriver.Chrome('<PATH_TO_WEBDRIVER>')
driver.get('https://eresearch.fidelity.com/eresearch/markets_sectors/sectors/sectors_in_market.jhtml?tab=industries&sector=10')
df = pd.read_html(driver.find_element_by_id('tableSort').get_attribute('outerHTML'))[0]
</code>```

Using this script, I got the following df:

Body:
I have tried many variations suggested here already but I have yet to fix the problem. I started with

page = requests.get('http://eresearch.fidelity.com/eresearch/markets_sectors/sectors/sectors_in_market.jhtml?tab=industries&sector=10')
df_list = pd.read_html(page.text)

and I can see the correct headers so I am looking at the right location. I then tried changing the flavors to bs4 and html5lib with no change. I always see NaN for the data values and only have one index, index 0, when there should be 3 or 4. My original attempt is the same as another section of code for a different table from the same website and it worked perfectly.
(also first post, please let me know how I can improve them)

Body:
Unfortunately, I had to use selenium to retrieve the dataframe. But if that is not a problem feel free to try the following:

from selenium import webdriver
import pandas as pd

driver = webdriver.Chrome('<PATH_TO_WEBDRIVER>')
driver.get('https://eresearch.fidelity.com/eresearch/markets_sectors/sectors/sectors_in_market.jhtml?tab=industries&sector=10')
df = pd.read_html(driver.find_element_by_id('tableSort').get_attribute('outerHTML'))[0]

Using this script, I got the following df:


来源: stackexchange

问:
How do I account for daylight savings time when retrieving current time in PHP?
When getting the time via PHP script (time()), during Daylight Savings Time it seems to return a time value that is one hour off. Is there any way to get the correct time, accounting for Daylight Savings Time?

答: Set correct timezone using date_default_timezone_set()

ContentLicense: CC BY-SA 3.0


问:
Error on deploying Next.js on AWS Amplify
I was hosting my Next.js web app with SSR on AWS Amplify, until one day I was getting error 503.

Digging in the AWS console, I came across a CloudWatch log for the lambda function that handles the SSR part of the app.

```<code>2021-12-02T19:40:49.972Z    1bb29425-4acf-44aa-aabb-ba5afa558512    ERROR   Invoke Error    {
"errorType": "Error",
"errorMessage": "Cannot find module '@grpc/grpc-js/package.json'\nRequire stack:\n- /codebuild/output/src947501987/src/focalpick-client/node_modules/@firebase/firestore/dist/index.node.mjs",
"code": "MODULE_NOT_FOUND",
"requireStack": [
    "/codebuild/output/src947501987/src/focalpick-client/node_modules/@firebase/firestore/dist/index.node.mjs"
],
"stack": [
    "Error: Cannot find module '@grpc/grpc-js/package.json'",
    "Require stack:",
    "- /codebuild/output/src947501987/src/focalpick-client/node_modules/@firebase/firestore/dist/index.node.mjs",
    "    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)",
    "    at Function.Module._load (internal/modules/cjs/loader.js:746:27)",
    "    at Module.require (internal/modules/cjs/loader.js:974:19)",
    "    at require (internal/modules/cjs/helpers.js:93:18)",
    "    at Object.578847 (/var/task/chunks/559.js:500372:34)",
    "    at __webpack_require__ (/var/task/webpack-runtime.js:25:43)",
    "    at Object.526541 (/var/task/chunks/962.js:2299:22)",
    "    at __webpack_require__ (/var/task/webpack-runtime.js:25:43)",
    "    at Module.778514 (/var/task/chunks/962.js:2021:20)",
    "    at __webpack_require__ (/var/task/webpack-runtime.js:25:43)"
]}
</code>```

The error says that it cannot find module @grpc/grpc-js. It seems that this is a package that Firebase uses internally. I tried installing the package in my repository, re-deployed the Amplify app, but this wouldn't help. Trying to deploy a clean next app worked though.

All the issues and questions I've read didn't help me find a solution.

答: This was happening to me on next@12.0.9, After testing many many things, I just downgraded the version to next@12.0.8 and it started working.</p>

ContentLicense: CC BY-SA 4.0

Body:
I was hosting my Next.js web app with SSR on AWS Amplify, until one day I was getting error 503.

Digging in the AWS console, I came across a CloudWatch log for the lambda function that handles the SSR part of the app.

2021-12-02T19:40:49.972Z    1bb29425-4acf-44aa-aabb-ba5afa558512    ERROR   Invoke Error    {
"errorType": "Error",
"errorMessage": "Cannot find module '@grpc/grpc-js/package.json'\nRequire stack:\n- /codebuild/output/src947501987/src/focalpick-client/node_modules/@firebase/firestore/dist/index.node.mjs",
"code": "MODULE_NOT_FOUND",
"requireStack": [
    "/codebuild/output/src947501987/src/focalpick-client/node_modules/@firebase/firestore/dist/index.node.mjs"
],
"stack": [
    "Error: Cannot find module '@grpc/grpc-js/package.json'",
    "Require stack:",
    "- /codebuild/output/src947501987/src/focalpick-client/node_modules/@firebase/firestore/dist/index.node.mjs",
    "    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)",
    "    at Function.Module._load (internal/modules/cjs/loader.js:746:27)",
    "    at Module.require (internal/modules/cjs/loader.js:974:19)",
    "    at require (internal/modules/cjs/helpers.js:93:18)",
    "    at Object.578847 (/var/task/chunks/559.js:500372:34)",
    "    at __webpack_require__ (/var/task/webpack-runtime.js:25:43)",
    "    at Object.526541 (/var/task/chunks/962.js:2299:22)",
    "    at __webpack_require__ (/var/task/webpack-runtime.js:25:43)",
    "    at Module.778514 (/var/task/chunks/962.js:2021:20)",
    "    at __webpack_require__ (/var/task/webpack-runtime.js:25:43)"
]}

The error says that it cannot find module @grpc/grpc-js. It seems that this is a package that Firebase uses internally. I tried installing the package in my repository, re-deployed the Amplify app, but this wouldn't help. Trying to deploy a clean next app worked though.

All the issues and questions I've read didn't help me find a solution.


问:
Is therer such a thing as the height of a node in a BST?
I'm getting confused the more I search. Does the term "height" only apply to the root node of a BST? Or does each node have its own corresponding height? Similarly, does each node of a BST have a corresponding level?</p>

答: Height of a BST or any binary tree is the total number of edges from the root node to the most distant leaf node. You are probably getting confused with recursion when a node on another level is passed as the root. For every node, it is the parent of its subtree, so it is the root for that subtree. That's how recursion works.</p>


问:
No Routes element found in React Router Dom
This is odd.  Following along with the tutorial, I'm attempting to create a group of routes.  However, the actual Routes element cannot be found:

The BrowserRouter and individual Route elements seem to be working fine, however.

I'm using the latest version of React Router Dom (6.2.1).  Any ideas?

答:
Appears to be a PhpStorm issue.  Viewing the project in VS Code gives no errors on the element, and shows its signature and location:

Whereas the problem persists in PhpStorm even after a restart.


问:
Selecting a div matching an attribute using JQuery is failing
I go to https://www.tradingview.com/chart/?symbol=BINANCE:BTCUSDTPERP and press OPT+g (ALT+g for non-mac) and a TimeRange overlay appears.

I'm trying to simulate clicking on the 'Custom range' tab using JavaScript from the console.

But $('#overlap-manager-root > div > [attribute="CustomRange"]') fails to retrieve it.

This is odd to me because $('#overlap-manager-root > div button') successfully picks out the 2 buttons.

I'm using https://api.jquery.com/attribute-equals-selector/ for reference.

答:
The > combinator is for direct descendants. This means the element after the > needs to be in the parent element (the element named before >) directly and not in some child element.

For example, #overlap-manager-root > div > [data-value="CustomRange"] would match

```<code><div id="overlap-manager-root">
   <div>
       <button data-value="CustomRange"></button>
   </div>
</div>
</code>```

But would not match

```<code><div id="overlap-manager-root">
   <div>
       <div id="someotherdiv">
          <button data-value="CustomRange"></button>
       </div>
   </div>
</div>
</code>```

Removing the > will make it look for any element within the subhierarchy and not just the direct children.

So switch the selector to

```<code>#overlap-manager-root > div [data-value="CustomRange"]
</code>```

and this should find your element.

Body:
The > combinator is for direct descendants. This means the element after the > needs to be in the parent element (the element named before >) directly and not in some child element.

For example, #overlap-manager-root > div > [data-value="CustomRange"] would match

<div id="overlap-manager-root">
   <div>
       <button data-value="CustomRange"></button>
   </div>
</div>

But would not match

<div id="overlap-manager-root">
   <div>
       <div id="someotherdiv">
          <button data-value="CustomRange"></button>
       </div>
   </div>
</div>

Removing the > will make it look for any element within the subhierarchy and not just the direct children.

So switch the selector to

#overlap-manager-root > div [data-value="CustomRange"]

and this should find your element.


问:
Objective - Zip Only works for text files?
I'm working with Objective Zip library in order to unzip files in iPhone.

All works fine excepts, that with text files there are not problem are uncompressed without problem and the file is correct. But with compressed png files are all corrupted. The sizes of the files are all equal to original file but are all corrupted.

This is the code:

```<code>-(void)installPackageFromZipFile:(NSString *)zipFile
{
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];

    ZipFile *unzipFile= [[ZipFile alloc] initWithFileName:zipFile mode:ZipFileModeUnzip];
    packageRegisterController *pckReg = [[packageRegisterController alloc] init];

    [unzipFile goToFirstFileInZip];

    NSArray *infos= [unzipFile listFileInZipInfos];

    for (FileInZipInfo *info in infos)
    {
        NSLog([NSString stringWithFormat:@"File Found in Zip File- %@ Size:%d", info.name, info.length]);

        ZipReadStream *read = [unzipFile readCurrentFileInZip];

        if (![pckReg detectIfFileExists:[documentsDir stringByAppendingPathComponent:info.name]])
        {

            NSMutableData *data = [[NSMutableData alloc] initWithLength:info.length];

            int bytesRead = [read readDataWithBuffer:data];

            [data writeToFile:[documentsDir stringByAppendingPathComponent:info.name] atomically:NO];

            [read finishedReading];

            [data release];

            if ([[NSString stringWithFormat:@"%@",info.name] isEqualToString:@"TEMAMANIFEST.xml"])
            {
                if([self parseManifest:[documentsDir stringByAppendingPathComponent:info.name]])
                    if ([pckReg validateManifestId:self.temaToInstall.idManifest])
                        [self installManifest];

            }

        }
        [unzipFile goToNextFileInZip];
    }

    [unzipFile close];
    [unzipFile release];
}
</code>```

This function decompress all files with good sizes and text files are ok, but not png.

Could someone help me?

答:
Are you trying to view the images within the iPhone app, or are you zipping them, unzipping them on a Mac and trying to view them there?

PNGs are 'optimised' when built for iPhone and as a result aren't viewable on a mac without being 'unoptimised'.

When PNGs are copied to an iPhone app bundle they are sent through the pngcrush utility which takes the alpha channel value of the image and premultiplies it with the other colour channels, Red, Blue, and Green. The result is an un-viewable image on a Mac, but a speedy, easily renderable image on an iPhone.

This is done because the iPhone's graphics processor does not do alpha multiplying in hardware, but does it in software, which makes it slow. The pngcrush utility does all the alpha multiplying required during the build process so that all the images can be rendered by the hardware graphics processor really quickly.

Body:
I'm working with Objective Zip library in order to unzip files in iPhone.

All works fine excepts, that with text files there are not problem are uncompressed without problem and the file is correct. But with compressed png files are all corrupted. The sizes of the files are all equal to original file but are all corrupted.

This is the code:

-(void)installPackageFromZipFile:(NSString *)zipFile
{
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];

    ZipFile *unzipFile= [[ZipFile alloc] initWithFileName:zipFile mode:ZipFileModeUnzip];
    packageRegisterController *pckReg = [[packageRegisterController alloc] init];

    [unzipFile goToFirstFileInZip];

    NSArray *infos= [unzipFile listFileInZipInfos];

    for (FileInZipInfo *info in infos)
    {
        NSLog([NSString stringWithFormat:@"File Found in Zip File- %@ Size:%d", info.name, info.length]);

        ZipReadStream *read = [unzipFile readCurrentFileInZip];

        if (![pckReg detectIfFileExists:[documentsDir stringByAppendingPathComponent:info.name]])
        {

            NSMutableData *data = [[NSMutableData alloc] initWithLength:info.length];

            int bytesRead = [read readDataWithBuffer:data];

            [data writeToFile:[documentsDir stringByAppendingPathComponent:info.name] atomically:NO];

            [read finishedReading];

            [data release];

            if ([[NSString stringWithFormat:@"%@",info.name] isEqualToString:@"TEMAMANIFEST.xml"])
            {
                if([self parseManifest:[documentsDir stringByAppendingPathComponent:info.name]])
                    if ([pckReg validateManifestId:self.temaToInstall.idManifest])
                        [self installManifest];

            }

        }
        [unzipFile goToNextFileInZip];
    }

    [unzipFile close];
    [unzipFile release];
}

This function decompress all files with good sizes and text files are ok, but not png.

Could someone help me?


问:
Using VB.NET Tuples in an Office VSTO solution, understanding .NET Framework 4.7+ dependencies
For a VB.NET Office VSTO solution, I would like to start using Tuples.

What worries me somewhat is this requirement in terms of .NET Framework.

VB.NET Tuples are not supported until .NET Framework 4.7, see Microsoft info here.

I don't mind requiring .NET Framework 4.7 or higher, but I worry about problems with other VSTO addins running in the Office application (in this case Visio, but also developing for Excel) that require older versions of .NET.

So far I have limited the solution to using .NET Framework 3.5 compatible features. I don't mind requiring .NET Framework 4.7 or higher be installed but I want to avoid issues with other VSTO add-ins that are running at the same time.

What happens when multiple Office VSTO add-ins are running at the same time but require different .NET Frameworks? I cannot find clear info about this on the Microsoft website.

Thank you for sharing your insights!

答: You won't have any problems - all VSTO addins run in their own environment with the exact version of .Net run-time that the addin requests. Multiple versions of .Net run-time can be loaded in a given process (outlook.exe).</p>


问:
Python finally block not catching errors
Take a look at a chunk of code:

```<code>move = [None, 20, 5, True, "a"]
valnum = 0
    for val in move:
        try:
            if val >= 15:
                val -= 3
                move[valnum] = val
        finally:
            valnum += 1
print(move)
</code>```

When run, it gives this error:

```<code>TypeError: '>=' not supported between instances of 'NoneType' and 'int'
</code>```

Isn't the whole point of the finally statement to avoid errors like this?

EDIT: Thank you for your help. I don't think I made myself clear enough in my question. After your suggestions, I coded it to this:

```<code>move = [None, 20, 5, True, "a", 19]
valnum = 0
for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
print(move)
</code>```

And the output now becomes:

```<code>[None, 17, 16, True, 'a', 19]
</code>```

It's easy to see what went wrong. The exception block only runs when there is an error, but I need the block to run no matter if there is an error or not. Is there a solution to this, other than just:

```<code>move = [None, 20, 5, True, "a", 19]
valnum = 0
for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
        continue
    valnum += 1
print(move)
</code>```

答:
No, it is not.

It is there to make sure something always gets executed, no matter if there is an exception or not. It does not catch the exception, for that you need an except block.

For example:

```<code>for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
</code>```

finally blocks are useful for things like resource cleanup, closing files, that sort of thing.

Based on the comment by Big Bird, here is how you would run the code and also ignore the error:

```<code>for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        pass  # catch the error and ignore it
    valnum += 1
</code>```

Edited yet again, I realised what you wanted to do only now, since I'd been too focussed on how you were trying to do it. I suggest not caring about valnum at all, instead doing this:

```<code>move = [None, 20, 5, True, "a", 19]
for index, val in enumerate(move):
    try:
        if val >= 15:
            val -= 3
            move[index] = val
    except TypeError:
        pass
print(move)
</code>```

Body:
Take a look at a chunk of code:

move = [None, 20, 5, True, "a"]
valnum = 0
    for val in move:
        try:
            if val >= 15:
                val -= 3
                move[valnum] = val
        finally:
            valnum += 1
print(move)

When run, it gives this error:

TypeError: '>=' not supported between instances of 'NoneType' and 'int'

Isn't the whole point of the finally statement to avoid errors like this?

EDIT: Thank you for your help. I don't think I made myself clear enough in my question. After your suggestions, I coded it to this:

move = [None, 20, 5, True, "a", 19]
valnum = 0
for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
print(move)

And the output now becomes:

[None, 17, 16, True, 'a', 19]

It's easy to see what went wrong. The exception block only runs when there is an error, but I need the block to run no matter if there is an error or not. Is there a solution to this, other than just:

move = [None, 20, 5, True, "a", 19]
valnum = 0
for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
        continue
    valnum += 1
print(move)

Body:
No, it is not.

It is there to make sure something always gets executed, no matter if there is an exception or not. It does not catch the exception, for that you need an except block.

For example:

for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1

finally blocks are useful for things like resource cleanup, closing files, that sort of thing.

Based on the comment by Big Bird, here is how you would run the code and also ignore the error:

for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        pass  # catch the error and ignore it
    valnum += 1

Edited yet again, I realised what you wanted to do only now, since I'd been too focussed on how you were trying to do it. I suggest not caring about valnum at all, instead doing this:

move = [None, 20, 5, True, "a", 19]
for index, val in enumerate(move):
    try:
        if val >= 15:
            val -= 3
            move[index] = val
    except TypeError:
        pass
print(move)


答:
What you want to use is 'except' for handling that. Your code should look like:

```<code>move = [None, 20, 5, True, "a"]
valnum = 0
for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
print(move)
</code>```

When you use finally, it means that the code inside finally will run after the try condition as a clean-up action.
You can check the documentation for more information on the finally action: https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions

Looking at your code and use, you can simply

Title: Python finally block not catching errors

Body:
What you want to use is 'except' for handling that. Your code should look like:

move = [None, 20, 5, True, "a"]
valnum = 0
for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
print(move)

When you use finally, it means that the code inside finally will run after the try condition as a clean-up action.
You can check the documentation for more information on the finally action: https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions

Looking at your code and use, you can simply


问:
Action not running with CakePHP Js->submit()
I'm using CakePHP 1.3, and trying to make a simple message posting board with ajax. I'm trying to use the Js helper to submit a form on the index page, then refresh the message board's div to include the new message. This is all on a single page.

I have previously posted on this, but I wanted to rephrase the question and include some updates. The previous question can be seen here How to use Js->submit() in CakePHP?

When I came back to this project after a couple days, I immediately tested and the form worked (sort of). Submitting the form added a message to the database (it didn't display the message, but I haven't attacked that part yet). It worked 2 times, adding 2 messages. Then I opened the controller file and commented out some debug code, and it stopped working. It appears the action is not being called.

Here is my messages_controller.php:

```<code><?php

class MessagesController extends AppController {

 function index() {
  $messages = $this->Message->find('all');
  $this->set('messages',$messages);
 }

 function add() {

  $this->autoRender = false;
  $this->Session->setFlash('Add action called');

  if($this->RequestHandler->isAjax()) {

   $this->Session->setFlash('Ajax request made');
   $this->layout = 'ajax';

   if(!empty($this->data)) {

    if($this->Message->save($this->data)) {

     $this->Session->setFlash('Your Message has been posted');
    }
   }
  }
 }

}

?>
</code>```

Here is the index.ctp for my Message class

```<code><div id="guestbook" class="section_box">

 <h3  id="toggle_guestbook"><div class="toggle_arrow"></div>Sign our Guestbook</h3>

 <?php

 echo $this->Form->create('Message');
 echo $this->Form->input('name', array('label' => 'From:'));
 echo $this->Form->input('text', array('label' => 'Message:'));
 echo $this->Js->submit('Post Your Message', array(
  'url' => array(
   'controller' => 'messages',
   'action' => 'add'
  ),
  'update' => '#message_board'
 ));
 echo $this->Form->end();

 echo $this->Js->writeBuffer(array('inline' => 'true'));
 ?>

 <div id="message_board">

  <?php foreach($messages as $message) { ?>

   <div class="message">

    <p class="message_txt">
     <?php echo $message['Message']['text']; ?>
    </p>

    <div>

     <div class="message_name">
      <?php echo $message['Message']['name']; ?>
     </div>

     <div class="message_date">
      <small>
       <?php echo $message['Message']['date']; ?>
      </small>
     </div>

    </div>

   </div>

  <?php } ?>

 </div>

</div>
</code>```

When the submit button is clicked, I can see in the console that a POST is made to http://localhost/messages/add with the correct data. But there doesn't appear to be a response. The flash message "Add action called" is NOT set from the controller (or any of the flash messages, for that matter) and the contents of #message_board are emptied.

If I refresh the page at this point, the SECOND flash message appears ("Ajax request made"), and the contents of the #message_board are restored. However the new message was not saved, its the same 2 messages from before.

I'm stumped. I have a feeling maybe there are bigger issues causing my problem, but I can't see it. Any help would be appreciated.

答:
I tried to use the same solution as you used but it's not working. Ajax is ok when I access it directly in the URL, and I have the impression that the click is doing nothing. When I use

```<code>   <fieldset><legend><?php __(' Run 1');?></legend>
<div id="formUpdateID"><div id="#error-message"></div>
<?php
$orders=array_merge($emptyarray,$orders['r1']['Order']);
   echo $this->Form->create('Order');
   echo $this->Form->input('id', array('value'=>$orders['id'],'type' =>'hidden'));
    echo $this->Form->input('race_id', array('value'=> $orders['race_id'],'type' =>'hidden'));
    echo $this->Form->input('driver_id', array('value'=>$session->read('Auth.User.driver_id'),'type' =>'hidden'));

    echo $this->Form->input('run', array('value'=>$run,'type' =>'hidden'));
    echo $this->Form->input('pm', array('value'=>$orders['pm'],'error'=>$err[$run]));
    echo $this->Form->input('pr', array('value'=>$orders['pr'],'error'=>$err[$run]));
    echo $this->Form->input('fuel', array('value'=>$orders['fuel'],'error'=>$err[$run]));
    echo $this->Form->input('pit', array('value'=>$orders['pit'],'label' => __('Pit on lap '),'error'=>$err[$run]));
    echo $this->Form->input('tyre_type', array('value'=>$orders['tyre_type'],'error'=>$err[$run]));
echo $this->Js->submit('Modify', array(
'url' => array(
    'controller' => 'orders',
    'action' => 'ajax_edit'
),
'update' => '#error_message'
));
echo $this->Form->end();

     ?>
     <?php pr($this->validationErrors); ?>
     </div></fieldset>
</code>```

in view and in controller "orders":

```<code>   function ajax_edit($id=null){

        $this->autoRender = false;

       if($this->RequestHandler->isAjax()) {
    die(debug('In Ajax'));

        $this->layout = 'ajax';

    debug('didn\'t validate logic');
    }
    echo 'hi';
}
</code>```

None of the messages are displayed.

I have some hard coded JS/ajax before which is not targeting this code part.
I did copy ajax layout in th webroot/view folder.

I can see the AJAX code displayed in formatted source code

```<code><div class="submit"><input id="submit-1697561504" type="submit" value="Modify" /></div>     </form><script type="text/javascript">
//<![CDATA[
$(document).ready(function () {$("#submit-1697561504").bind("click", function (event)     {$.ajax({data:$("#submit-1697561504").closest("form").serialize(), dataType:"html",    success:function (data, textStatus) {$("#error_message").html(data);}, type:"post", url:"\/Webmastering\/form1C\/frame\/orders\/ajax_edit\/1"});
return false;});});
//]]>
</script>
</code>```

BTW, I start getting bored of the lack of doc in cakephp and its non efficacity to realize task more complicated than just posting a post in a blog. So thank you for your help before I start destroying my computer ;)

ContentLicense: CC BY-SA 2.5

Body:
I'm using CakePHP 1.3, and trying to make a simple message posting board with ajax. I'm trying to use the Js helper to submit a form on the index page, then refresh the message board's div to include the new message. This is all on a single page.

I have previously posted on this, but I wanted to rephrase the question and include some updates. The previous question can be seen here How to use Js->submit() in CakePHP?

When I came back to this project after a couple days, I immediately tested and the form worked (sort of). Submitting the form added a message to the database (it didn't display the message, but I haven't attacked that part yet). It worked 2 times, adding 2 messages. Then I opened the controller file and commented out some debug code, and it stopped working. It appears the action is not being called.

Here is my messages_controller.php:

<?php

class MessagesController extends AppController {

 function index() {
  $messages = $this->Message->find('all');
  $this->set('messages',$messages);
 }

 function add() {

  $this->autoRender = false;
  $this->Session->setFlash('Add action called');

  if($this->RequestHandler->isAjax()) {

   $this->Session->setFlash('Ajax request made');
   $this->layout = 'ajax';

   if(!empty($this->data)) {

    if($this->Message->save($this->data)) {

     $this->Session->setFlash('Your Message has been posted');
    }
   }
  }
 }

}

?>

Here is the index.ctp for my Message class

Sign our Guestbook

 <?php

 echo $this->Form->create('Message');
 echo $this->Form->input('name', array('label' => 'From:'));
 echo $this->Form->input('text', array('label' => 'Message:'));
 echo $this->Js->submit('Post Your Message', array(
  'url' => array(
   'controller' => 'messages',
   'action' => 'add'
  ),
  'update' => '#message_board'
 ));
 echo $this->Form->end();

 echo $this->Js->writeBuffer(array('inline' => 'true'));
 ?>

  <?php foreach($messages as $message) { ?>

     <?php echo $message['Message']['text']; ?>

      <?php echo $message['Message']['name']; ?>

       <?php echo $message['Message']['date']; ?>

  <?php } ?>

When the submit button is clicked, I can see in the console that a POST is made to http://localhost/messages/add with the correct data. But there doesn't appear to be a response. The flash message "Add action called" is NOT set from the controller (or any of the flash messages, for that matter) and the contents of #message_board are emptied.

If I refresh the page at this point, the SECOND flash message appears ("Ajax request made"), and the contents of the #message_board are restored. However the new message was not saved, its the same 2 messages from before.

I'm stumped. I have a feeling maybe there are bigger issues causing my problem, but I can't see it. Any help would be appreciated.

Body:
I tried to use the same solution as you used but it's not working. Ajax is ok when I access it directly in the URL, and I have the impression that the click is doing nothing. When I use

   <fieldset><legend><?php __(' Run 1');?></legend>
<div id="formUpdateID"><div id="#error-message"></div>
<?php
$orders=array_merge($emptyarray,$orders['r1']['Order']);
   echo $this->Form->create('Order');
   echo $this->Form->input('id', array('value'=>$orders['id'],'type' =>'hidden'));
    echo $this->Form->input('race_id', array('value'=> $orders['race_id'],'type' =>'hidden'));
    echo $this->Form->input('driver_id', array('value'=>$session->read('Auth.User.driver_id'),'type' =>'hidden'));

    echo $this->Form->input('run', array('value'=>$run,'type' =>'hidden'));
    echo $this->Form->input('pm', array('value'=>$orders['pm'],'error'=>$err[$run]));
    echo $this->Form->input('pr', array('value'=>$orders['pr'],'error'=>$err[$run]));
    echo $this->Form->input('fuel', array('value'=>$orders['fuel'],'error'=>$err[$run]));
    echo $this->Form->input('pit', array('value'=>$orders['pit'],'label' => __('Pit on lap '),'error'=>$err[$run]));
    echo $this->Form->input('tyre_type', array('value'=>$orders['tyre_type'],'error'=>$err[$run]));
echo $this->Js->submit('Modify', array(
'url' => array(
    'controller' => 'orders',
    'action' => 'ajax_edit'
),
'update' => '#error_message'
));
echo $this->Form->end();

     ?>
     <?php pr($this->validationErrors); ?>
     </div></fieldset>

in view and in controller "orders":

   function ajax_edit($id=null){

        $this->autoRender = false;

       if($this->RequestHandler->isAjax()) {
    die(debug('In Ajax'));

        $this->layout = 'ajax';

    debug('didn\'t validate logic');
    }
    echo 'hi';
}

None of the messages are displayed.

I have some hard coded JS/ajax before which is not targeting this code part.
I did copy ajax layout in th webroot/view folder.

I can see the AJAX code displayed in formatted source code

<div class="submit"><input id="submit-1697561504" type="submit" value="Modify" /></div>     </form><script type="text/javascript">
//<![CDATA[
$(document).ready(function () {$("#submit-1697561504").bind("click", function (event)     {$.ajax({data:$("#submit-1697561504").closest("form").serialize(), dataType:"html",    success:function (data, textStatus) {$("#error_message").html(data);}, type:"post", url:"\/Webmastering\/form1C\/frame\/orders\/ajax_edit\/1"});
return false;});});
//]]>
</script>

BTW, I start getting bored of the lack of doc in cakephp and its non efficacity to realize task more complicated than just posting a post in a blog. So thank you for your help before I start destroying my computer ;)


问:
TypeError: only integer scalar arrays can be converted to a scalar index when i want to use matplotlib
my code for create a plot of the pendulum period vs. length for pendulums with string lengths of 10 cm to 2 m.
anyone could solve this problem?!
i wrote this code but it's not work and has type error

```<code>import matplotlib.pyplot as plt
import math
import numpy as np

g = 9.8
L1 = np.arange (10, 201)
print (L1)

for t in range (L1):
    Length = L1/100
    t = (math.sqrt(Length/9.8)) * 2* 3.14
    print (t)
    plt.plot (Length, t)
</code>```

TypeError: only integer scalar arrays can be converted to a scalar index

答:
```<code>import matplotlib.pyplot as plt
import numpy as np

g = 9.8
L1 = np.arange (10, 201)

for t in L1:
    Length = L1/100
    a = (np.sqrt(Length/9.8)) * 2* 3.14
    plt.plot (Length, a)
</code>```

Body:
my code for create a plot of the pendulum period vs. length for pendulums with string lengths of 10 cm to 2 m.
anyone could solve this problem?!
i wrote this code but it's not work and has type error

import matplotlib.pyplot as plt
import math
import numpy as np

g = 9.8
L1 = np.arange (10, 201)
print (L1)

for t in range (L1):
    Length = L1/100
    t = (math.sqrt(Length/9.8)) * 2* 3.14
    print (t)
    plt.plot (Length, t)

TypeError: only integer scalar arrays can be converted to a scalar index


问:
Getting Object is possibly 'null' even after null checking
```<code>export async function getSingleUserQA(command: Command, period?: string[]) {
  let slackUserID;

  if (command && command.text) {
    slackUserID = command.text.match("/(?<=@)(.*?)(?=|)/g")[0];
  }
}
</code>```

I am being flagged that 'command' is possibly 'null' or 'undefined'. How come if I am making sure that command exists and command.text exists?

答:
Look closely at the warning. It's not saying that command might not exist, but that this whole expression:

```<code>command.text.match("/(?<=@)(.*?)(?=|)/g")
</code>```

might not.

What do you want to do if the regular expression has no match? Figure that out, and guard it appropriately.

```<code>if (command && command.text) {
    const match = command.text.match("/(?<=@)(.*?)(?=|)/g");
    if (match) {
        slackUserID = match[0];
    } else {
        // handle badly formatted command
    }
}
</code>```

You should also probably do

```<code>let slackUserID: string;
</code>```

or only use the result inside the conditional.

Body:
export async function getSingleUserQA(command: Command, period?: string[]) {
  let slackUserID;

  if (command && command.text) {
    slackUserID = command.text.match("/(?<=@)(.*?)(?=|)/g")[0];
  }
}

I am being flagged that 'command' is possibly 'null' or 'undefined'. How come if I am making sure that command exists and command.text exists?

Body:
Look closely at the warning. It's not saying that command might not exist, but that this whole expression:

command.text.match("/(?<=@)(.*?)(?=|)/g")

might not.

What do you want to do if the regular expression has no match? Figure that out, and guard it appropriately.

if (command && command.text) {
    const match = command.text.match("/(?<=@)(.*?)(?=|)/g");
    if (match) {
        slackUserID = match[0];
    } else {
        // handle badly formatted command
    }
}

You should also probably do

let slackUserID: string;

or only use the result inside the conditional.


问:
Nextcord is there a way to make a cog but make it disabled by default
Basically I'm trying to make a cog where I added some pranks but I want to make it disabled(unloaded) by default is there any way to do that?</p>

答:
Yes. You can change the cog's name to something like:

_cogname.py

And when you load your cogs, do the following:

```<code>for filename in os.listdir('./cogs'):
    if filename.endswith('.py') and not filename.startswith('_'):
        bot.load_extension(f'cogs.{filename[:-3]}')
</code>```

Make sure you do:
import os
at the start of your code

Body:
Yes. You can change the cog's name to something like:

_cogname.py

And when you load your cogs, do the following:

for filename in os.listdir('./cogs'):
    if filename.endswith('.py') and not filename.startswith('_'):
        bot.load_extension(f'cogs.{filename[:-3]}')

Make sure you do:
import os
at the start of your code


问:
Jest, ES6 modules "does not provide export named"
I have an express app with a CRUD API (with sequelize) and I want to test it with Jest. I'm pretty new in unit-testing so I follow this guide, recommended by Jest's website.

The problem I have is that my app is built with ES6 modules and Jest ES6 modules is experimental and it seems that it doesn't "import" packages.

I have this test (took from the guide)

import request from 'supertest';
import app from '../app';

describe('Test the root path', () => {
    test('It should response the GET method', done => {
        request(app)
            .get('/')
            .then(response => {
                expect(response.statusCode).toBe(404);
                done();
            });
    });
});
```
<p>And when I launched it (with <code>NODE_OPTIONS=--experimental-vm-modules npx jest</code> I had to follow this jest wiki page), It says that</p>
<p><code>'sequelize' does not provide an export named 'DataTypes'</code> and when I launch my app normally (like with <code>npm start</code>) it works fine, without any problems.</p>
<p><em>(the complete error log):</em></p>
```(node:49576) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  __tests__/app_test.js
  ● Test suite failed to run

    SyntaxError: The requested module 'sequelize' does not provide an export named 'DataTypes'

      at Runtime.linkAndEvaluateModule (node_modules/jest-runtime/build/index.js:779:5)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)
```
<p><em>(and my Jest config)</em></p>
```// Sync object
/** @type {import('@jest/types').Config.InitialOptions} */

export default async () => {
    return {
        verbose: true,
        transform: {},
    };
};
```

Am I doing something wrong ? Should I change to commonJS instead of ES6

Thank you.

答:
This is a known problem in Jest: #9771. It is said to be fixed in jest@28.0.0-alpha.0.

An interesting hack to work around this problem is to remove the main field from the package.json of the imported project.

Body:
I have an express app with a CRUD API (with sequelize) and I want to test it with Jest. I'm pretty new in unit-testing so I follow this guide, recommended by Jest's website.

The problem I have is that my app is built with ES6 modules and Jest ES6 modules is experimental and it seems that it doesn't "import" packages.

I have this test (took from the guide)

import request from 'supertest';
import app from '../app';

describe('Test the root path', () => {
    test('It should response the GET method', done => {
        request(app)
            .get('/')
            .then(response => {
                expect(response.statusCode).toBe(404);
                done();
            });
    });
});

And when I launched it (with NODE_OPTIONS=--experimental-vm-modules npx jest I had to follow this jest wiki page), It says that

'sequelize' does not provide an export named 'DataTypes' and when I launch my app normally (like with npm start) it works fine, without any problems.

(the complete error log):

(node:49576) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  __tests__/app_test.js
  ● Test suite failed to run

    SyntaxError: The requested module 'sequelize' does not provide an export named 'DataTypes'

      at Runtime.linkAndEvaluateModule (node_modules/jest-runtime/build/index.js:779:5)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)

(and my Jest config)

// Sync object
/** @type {import('@jest/types').Config.InitialOptions} */

export default async () => {
    return {
        verbose: true,
        transform: {},
    };
};

Am I doing something wrong ? Should I change to commonJS instead of ES6

Thank you.


问:
M2M relation ship : Can't save to the through model
i have a an order model which is in m2m relationship with a product model, when i create an order, and after checking my DB, i can see the order saved but not in the through model

models.py

```<code>from inventory.models import Product
from user.models import User

class Order(models.Model):
    product = models.ManyToManyField(Product, through='OrderItems' )
    vendeur = models.ForeignKey(User, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()

class Customer(models.Model):
    full_name = models.CharField(max_length=60, verbose_name='full name')
    address = models.CharField(max_length=255)
    phone = models.CharField(max_length=20)
    city = models.CharField(max_length=30)

class OrderItems(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order,on_delete=models.CASCADE)
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
</code>```

views.py

```<code>@login_required
def add_order(request):
    if request.method == 'POST':
        form = NewOrderForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            order.vendeur = request.user
            order.save()
            return redirect('dashboard-index', )
    else :
        form = NewOrderForm()
    return render(request, 'dashboard/add_order.html', {'form': form})
</code>```

forms.py

```<code>class NewOrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('product','quantity')
</code>```

答:
if you use save(commit=False), Calling save_m2m() is  required.
because your form has a m2m field

refer to documentions

```<code>@login_required
    def add_order(request):
        if request.method == 'POST':
            form = NewOrderForm(request.POST)
            if form.is_valid():
                order = form.save(commit=False)
                order.vendeur = request.user
                order.save()
                form.save_m2m()
                return redirect('dashboard-index', )
        else :
            form = NewOrderForm()
        return render(request, 'dashboard/add_order.html', {'form': form})
</code>```

Body:
i have a an order model which is in m2m relationship with a product model, when i create an order, and after checking my DB, i can see the order saved but not in the through model

models.py

from inventory.models import Product
from user.models import User

class Order(models.Model):
    product = models.ManyToManyField(Product, through='OrderItems' )
    vendeur = models.ForeignKey(User, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()

class Customer(models.Model):
    full_name = models.CharField(max_length=60, verbose_name='full name')
    address = models.CharField(max_length=255)
    phone = models.CharField(max_length=20)
    city = models.CharField(max_length=30)

class OrderItems(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order,on_delete=models.CASCADE)
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)

views.py

@login_required
def add_order(request):
    if request.method == 'POST':
        form = NewOrderForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            order.vendeur = request.user
            order.save()
            return redirect('dashboard-index', )
    else :
        form = NewOrderForm()
    return render(request, 'dashboard/add_order.html', {'form': form})

forms.py

class NewOrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('product','quantity')

Body:
if you use save(commit=False), Calling save_m2m() is  required.
because your form has a m2m field

refer to documentions

@login_required
    def add_order(request):
        if request.method == 'POST':
            form = NewOrderForm(request.POST)
            if form.is_valid():
                order = form.save(commit=False)
                order.vendeur = request.user
                order.save()
                form.save_m2m()
                return redirect('dashboard-index', )
        else :
            form = NewOrderForm()
        return render(request, 'dashboard/add_order.html', {'form': form})


问:
Error when trying to create and array from an object
I have written a sql query which returns an object. Having used the object in my view file, I now need to convert it to an array so that I can remove the duplicate entries.

To covert the object to an array, I am using,

```<code> $arr = (array)$object_name;
</code>```

Here is the result.

```<code>Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [body_parts_id] => 2
            [conditions_id] => 1
            [priorities_id] => 1
            [name_of_body_part] => Lungs and airways
            [name_of_condition] => Unconscious, not breathing or responding.
            [priority_title] => Priority One
        )

    [1] => stdClass Object
        (
            [id] => 1
            [body_parts_id] => 1
            [conditions_id] => 1
            [priorities_id] => 1
            [name_of_body_part] => Heart and blood vessels
            [name_of_condition] => Unconscious, not breathing or responding.
            [priority_title] => Priority One
        )

    [2] => stdClass Object
        (
            [id] => 1
            [body_parts_id] => 1
            [conditions_id] => 2
            [priorities_id] => 1
            [name_of_body_part] => Heart and blood vessels
            [name_of_condition] => Signs of a heart attack
            [priority_title] => Priority One
        )

    [3] => stdClass Object
        (
            [id] => 1
            [body_parts_id] => 1
            [conditions_id] => 3
            [priorities_id] => 1
            [name_of_body_part] => Heart and blood vessels
            [name_of_condition] => Heavy bleeding that won't stop
            [priority_title] => Priority One
        )

    [4] => stdClass Object
        (
            [id] => 2
            [body_parts_id] => 3
            [conditions_id] => 4
            [priorities_id] => 2
            [name_of_body_part] => Muscle, bone and joint
            [name_of_condition] => Condition test 1
            [priority_title] => Priority Two
        )

)
</code>```

The problem comes when I try and now loop through the array to remove any duplication. I get the message.

Cannot use object of type stdClass as array

Clearly I am not converting the Object to an Array correctly.

Can someone help please - thank you.

答:
To covert the object to an array you should change

```<code>$arr = (array)$object_name;
</code>```

To this instead

```<code>$arr = json_decode($object_name, true);
</code>```

Read more https://www.php.net/manual/en/function.json-decode.php

Body:
I have written a sql query which returns an object. Having used the object in my view file, I now need to convert it to an array so that I can remove the duplicate entries.

To covert the object to an array, I am using,

 $arr = (array)$object_name;

Here is the result.

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [body_parts_id] => 2
            [conditions_id] => 1
            [priorities_id] => 1
            [name_of_body_part] => Lungs and airways
            [name_of_condition] => Unconscious, not breathing or responding.
            [priority_title] => Priority One
        )

    [1] => stdClass Object
        (
            [id] => 1
            [body_parts_id] => 1
            [conditions_id] => 1
            [priorities_id] => 1
            [name_of_body_part] => Heart and blood vessels
            [name_of_condition] => Unconscious, not breathing or responding.
            [priority_title] => Priority One
        )

    [2] => stdClass Object
        (
            [id] => 1
            [body_parts_id] => 1
            [conditions_id] => 2
            [priorities_id] => 1
            [name_of_body_part] => Heart and blood vessels
            [name_of_condition] => Signs of a heart attack
            [priority_title] => Priority One
        )

    [3] => stdClass Object
        (
            [id] => 1
            [body_parts_id] => 1
            [conditions_id] => 3
            [priorities_id] => 1
            [name_of_body_part] => Heart and blood vessels
            [name_of_condition] => Heavy bleeding that won't stop
            [priority_title] => Priority One
        )

    [4] => stdClass Object
        (
            [id] => 2
            [body_parts_id] => 3
            [conditions_id] => 4
            [priorities_id] => 2
            [name_of_body_part] => Muscle, bone and joint
            [name_of_condition] => Condition test 1
            [priority_title] => Priority Two
        )

)

The problem comes when I try and now loop through the array to remove any duplication. I get the message.

Cannot use object of type stdClass as array

Clearly I am not converting the Object to an Array correctly.

Can someone help please - thank you.

Body:
To covert the object to an array you should change

$arr = (array)$object_name;

To this instead

$arr = json_decode($object_name, true);

Read more https://www.php.net/manual/en/function.json-decode.php


问:
Callback function on a JTextField
I have a presenter class and several text fields in my view.

I want my presenter to say "every textfields that are listening to me, please do something now".

BUT I don't want to use Observabe/Observer, since I already use it and I don't want to get confused.

To be a bit more specific, I want the textfields to update a Map in the presenter :

Presenter.java :

```<code>public class Presenter  {

   private HashMap<String,MyObject> map;

   theMethod(){
     //to all text fields, please update the map
</code>```

Then a textfield in a panel :

```<code>JTextField tf = new JTextField("tf 1");
tf.//add something to listen to the presenter
</code>```

The beginning of the process is the method in the presenter :

theMethod() is called (not by the view)

theMethod() triggers a method linked to the TextFields

Every methods called in every TextFields are doing something

答:
How about, instead of letting JTextFields listen to Presenter , Presenter will listen to them?

```<code>public class Presenter  {

   private HashMap<String,MyObject> map;
   private List<MyTextField> listeners = new ArrayList<MyTextField>();

   private void theMethod() {
       for (MyTextField mtf : listeners) {
           mtf.updateMap();
       }
   }

   private void addMyTextFieldListener(MyTextField listener) {
        listeners.add(listener);
   }
}
</code>```

Title: Callback function on a JTextField

Body:
I have a presenter class and several text fields in my view.

I want my presenter to say "every textfields that are listening to me, please do something now".

BUT I don't want to use Observabe/Observer, since I already use it and I don't want to get confused.

To be a bit more specific, I want the textfields to update a Map in the presenter :

Presenter.java :

public class Presenter  {

   private HashMap<String,MyObject> map;

   theMethod(){
     //to all text fields, please update the map

Then a textfield in a panel :

JTextField tf = new JTextField("tf 1");
tf.//add something to listen to the presenter

The beginning of the process is the method in the presenter :

theMethod() is called (not by the view)

theMethod() triggers a method linked to the TextFields

Every methods called in every TextFields are doing something

Body:
How about, instead of letting JTextFields listen to Presenter , Presenter will listen to them?

public class Presenter  {

   private HashMap<String,MyObject> map;
   private List<MyTextField> listeners = new ArrayList<MyTextField>();

   private void theMethod() {
       for (MyTextField mtf : listeners) {
           mtf.updateMap();
       }
   }

   private void addMyTextFieldListener(MyTextField listener) {
        listeners.add(listener);
   }
}


问:
SQLite compare dates between two consecutive rows
I have a table of media files:

```<code>id title date
</code>```

The date is in epoch format, and for example, I have 3 photos:

```<code>1  xxxxx 1644777107349(6:31:47.349)
2  wwwww 1644777110138(6:31:50.138)
3  zzzzz 1644777117453(6:31:57.453)
</code>```

I want to get the count of photos that were taken with a gap of 5 to 30 seconds, for example:
2 and 3 were taken with a gap of 7 seconds so I want to get 2. I want to compare every row with the consecutive row.

This is the SQL query:

```<code>SELECT Count(*)
FROM   (SELECT A._id
    FROM   media_files A
        INNER JOIN media_files B
            ON( Abs(A.added_time - B.added_time) >= 5000 )
                 AND A._id != B._id
                 AND A.type = 'image'
                 AND B.type = 'image'
    WHERE  Abs(A.added_time - B.added_time) <= 30000
    GROUP  BY A._id)
</code>```

And for the above example, I always get 3 instead of 2, any idea what is the problem?

答:
Here is a test setup and a query which returns only the images taken between 5 and 30 seconds after the previous one.NB I'm working on mySQL so where I have put 5 and 30 seconds it may be that in SQLlite you need to put 5000 and 30000.

```<code>CREATE TABLE media_files (
  id INT,
  title VARCHAR(25),
  added_date DATETIME,
  type VARCHAR(25)
  );
INSERT INTO media_files VALUES ( 1,  'xxxxx', '2022-02-13 6:30:47.349','image');
INSERT INTO media_files VALUES ( 1,  'xxxxx', '2022-02-13 6:31:27.349','image');
INSERT INTO media_files VALUES ( 1,  'xxxxx', '2022-02-13 6:31:47.349','image');
INSERT INTO media_files VALUES ( 2,  'wwwww', '2022-02-13 6:31:50.138','image');
INSERT INTO media_files VALUES ( 3,  'zzzzz', '2022-02-13 6:31:57.453','image');
</code>```
```
</blockquote>

<blockquote>
```SELECT    id,
          added_date ad,
          added_date -
        ( SELECT MAX(added_date)
          FROM media_files m
           WHERE m.added_date < mf.added_date ) DIF
FROM  media_files mf
WHERE (          added_date -
        ( SELECT MAX(added_date)
          FROM media_files m
          WHERE m.added_date < mf.added_date )) > 5
AND   (          added_date -
        ( SELECT MAX(added_date)
          FROM media_files m
          WHERE m.added_date < mf.added_date )) < 30;
```

id | ad                  | DIF
-: | :------------------ | --:
 1 | 2022-02-13 06:31:47 |  20
 3 | 2022-02-13 06:31:57 |   7
```

Body:
I have a table of media files:

id title date

The date is in epoch format, and for example, I have 3 photos:

1  xxxxx 1644777107349(6:31:47.349)
2  wwwww 1644777110138(6:31:50.138)
3  zzzzz 1644777117453(6:31:57.453)

I want to get the count of photos that were taken with a gap of 5 to 30 seconds, for example:
2 and 3 were taken with a gap of 7 seconds so I want to get 2. I want to compare every row with the consecutive row.

This is the SQL query:

SELECT Count(*)
FROM   (SELECT A._id
    FROM   media_files A
        INNER JOIN media_files B
            ON( Abs(A.added_time - B.added_time) >= 5000 )
                 AND A._id != B._id
                 AND A.type = 'image'
                 AND B.type = 'image'
    WHERE  Abs(A.added_time - B.added_time) <= 30000
    GROUP  BY A._id)

And for the above example, I always get 3 instead of 2, any idea what is the problem?

Body:
Here is a test setup and a query which returns only the images taken between 5 and 30 seconds after the previous one.NB I'm working on mySQL so where I have put 5 and 30 seconds it may be that in SQLlite you need to put 5000 and 30000.

CREATE TABLE media_files (
  id INT,
  title VARCHAR(25),
  added_date DATETIME,
  type VARCHAR(25)
  );
INSERT INTO media_files VALUES ( 1,  'xxxxx', '2022-02-13 6:30:47.349','image');
INSERT INTO media_files VALUES ( 1,  'xxxxx', '2022-02-13 6:31:27.349','image');
INSERT INTO media_files VALUES ( 1,  'xxxxx', '2022-02-13 6:31:47.349','image');
INSERT INTO media_files VALUES ( 2,  'wwwww', '2022-02-13 6:31:50.138','image');
INSERT INTO media_files VALUES ( 3,  'zzzzz', '2022-02-13 6:31:57.453','image');

SELECT    id,
          added_date ad,
          added_date -
        ( SELECT MAX(added_date)
          FROM media_files m
           WHERE m.added_date < mf.added_date ) DIF
FROM  media_files mf
WHERE (          added_date -
        ( SELECT MAX(added_date)
          FROM media_files m
          WHERE m.added_date < mf.added_date )) > 5
AND   (          added_date -
        ( SELECT MAX(added_date)
          FROM media_files m
          WHERE m.added_date < mf.added_date )) < 30;

id | ad                  | DIF
-: | :------------------ | --:
 1 | 2022-02-13 06:31:47 |  20
 3 | 2022-02-13 06:31:57 |   7


问:
How to resubmit the request after refreshing the token?
The situation: I send a request to receive some data and receive a response that the token has expired. Next, I have to update the token and resend the request that I sent at the beginning. How to do it using redux-toolkit and middleware?

Middleware for catching errors:

```<code>import { doRefreshToken } from "../reducers/user";

const TOKEN_EXPIRED_ERROR = "tokenExpiredException";

const tokenMiddleware = (api) => (next) => (action) => {
    const result = next(action);

    if (action.type === TOKEN_EXPIRED_ERROR) {
        const refreshToken = localStorage.getItem("refreshToken");
        api.dispatch(doRefreshToken({ refreshToken })).then(() => {
            // dispatch new action
        });
    }

    return result;
};

export default tokenMiddleware;
</code>```

The request to send after refreshing the token:

```<code>const getSmth = createAsyncThunk("user/getSmth ", async (_, { rejectWithValue }) => {
    try {
        const response = await api.get("/smth");
        return response;
    } catch (error) {
        return rejectWithValue(error.response);
    }
});
</code>```

Important: to be able to send not only a getSmth request, but also any other one, and you also need to do this in the middleware

答:
You can give the dispatch like argument on your calling middleware and dispatch an new action directly inside :

origin call :

```<code>dispatch(tokenMiddleware(dispatch, ...otherArgument...))
</code>```

in middleware :

```<code>.then(() => dispatch(getSmth())
</code>```

Body:
The situation: I send a request to receive some data and receive a response that the token has expired. Next, I have to update the token and resend the request that I sent at the beginning. How to do it using redux-toolkit and middleware?

Middleware for catching errors:

import { doRefreshToken } from "../reducers/user";

const TOKEN_EXPIRED_ERROR = "tokenExpiredException";

const tokenMiddleware = (api) => (next) => (action) => {
    const result = next(action);

    if (action.type === TOKEN_EXPIRED_ERROR) {
        const refreshToken = localStorage.getItem("refreshToken");
        api.dispatch(doRefreshToken({ refreshToken })).then(() => {
            // dispatch new action
        });
    }

    return result;
};

export default tokenMiddleware;

The request to send after refreshing the token:

const getSmth = createAsyncThunk("user/getSmth ", async (_, { rejectWithValue }) => {
    try {
        const response = await api.get("/smth");
        return response;
    } catch (error) {
        return rejectWithValue(error.response);
    }
});

Important: to be able to send not only a getSmth request, but also any other one, and you also need to do this in the middleware

Body:
You can give the dispatch like argument on your calling middleware and dispatch an new action directly inside :

origin call :

dispatch(tokenMiddleware(dispatch, ...otherArgument...))

in middleware :

.then(() => dispatch(getSmth())


问:
How to change TabView color for each icon?
I've tried this to try to change the color of the tab icons individually, but for some reason, the color will modify it correctly and then after tapping back to the icon, it will not display the customized color.

How would I go about changing the tab items icons for each individual tab (different colors for each)?

Here's the code for the view holding the TabView that I'm trying to modify.

struct MainView: View {
    @AppStorage("PendingOnboarding") var pendingOnboarding = true

    init() {
        UIPageControl.appearance().currentPageIndicatorTintColor = UIColor(Color.recyclepediaGreen)
    }

    var body: some View {
        NavigationView {
            ZStack {
                TabView {
                    CurbsideView()
                        .tabItem {
                            Label("Curbside", systemImage: "car.fill")
                        }
                    ItemsView()
                        .tabItem {
                            Label("Items", systemImage: "archivebox.fill")
                        }
                    LearnView()
                        .tabItem {
                            Label("Learn", systemImage: "info.circle.fill")
                        }
                    ContactUsView()
                        .tabItem {
                            Label("Contact Us", systemImage: "phone.fill.connection")
                        }
                }
                .accentColor(Color.recyclepediaBlue)
                .toolbar {
                    ToolbarItem(placement: .principal) {
                        Image("Recyclepedia")
                            .resizable()
                            .scaledToFit()
                            .padding(.top, 5)
                            .padding(.bottom, 5)
                    }
                }
            }
            .popup(isPresented: $pendingOnboarding, dragToDismiss: false, closeOnTap: false, backgroundColor: Color.white) {
                OnboardingView(pendingOnboarding: $pendingOnboarding)
            }
        }
    }
}
```

答:
The easiest solution is to use an enum that returns a Color. Like this:

```<code>struct TestTabviewIconColor: View {

    @State var pageIndex: TabColor = .red

    var body: some View {
        VStack {
            Text("Current page is \(pageIndex.rawValue)")
            TabView(selection: $pageIndex) { // Use the Tabview(selection:) init
                Text("The First Tab: \(pageIndex.color().description)")
                    .tabItem {
                        Image(systemName: "1.square.fill")
                        Text("First")
                    }
                    .tag(TabColor.red)

                Text("Another Tab: \(pageIndex.color().description)")
                    .tabItem {
                        Image(systemName: "2.square.fill")
                        Text("Second")
                    }
                    .tag(TabColor.green)

                Text("The Last Tab: \(pageIndex.color().description)")
                    .tabItem {
                        Image(systemName: "3.square.fill")
                        Text("Third")
                    }
                    .tag(TabColor.teal)
            }
            .accentColor(pageIndex.color())
            .font(.headline)
        }
    }
}

// Define your enum here
enum TabColor: Int {
    case red = 0
    case green = 1
    case teal = 2

    func color() -> Color {
        switch self {
        case .red:
            return .red
        case .green:
            return .green
        case .teal:
            return .teal
        }
    }
}
</code>```

As a bonus, you can select your tab by using it's color simply by calling:

```<code>pageIndex = .green
</code>```

Body:
The easiest solution is to use an enum that returns a Color. Like this:

struct TestTabviewIconColor: View {

    @State var pageIndex: TabColor = .red

    var body: some View {
        VStack {
            Text("Current page is \(pageIndex.rawValue)")
            TabView(selection: $pageIndex) { // Use the Tabview(selection:) init
                Text("The First Tab: \(pageIndex.color().description)")
                    .tabItem {
                        Image(systemName: "1.square.fill")
                        Text("First")
                    }
                    .tag(TabColor.red)

                Text("Another Tab: \(pageIndex.color().description)")
                    .tabItem {
                        Image(systemName: "2.square.fill")
                        Text("Second")
                    }
                    .tag(TabColor.green)

                Text("The Last Tab: \(pageIndex.color().description)")
                    .tabItem {
                        Image(systemName: "3.square.fill")
                        Text("Third")
                    }
                    .tag(TabColor.teal)
            }
            .accentColor(pageIndex.color())
            .font(.headline)
        }
    }
}

// Define your enum here
enum TabColor: Int {
    case red = 0
    case green = 1
    case teal = 2

    func color() -> Color {
        switch self {
        case .red:
            return .red
        case .green:
            return .green
        case .teal:
            return .teal
        }
    }
}

As a bonus, you can select your tab by using it's color simply by calling:

pageIndex = .green


问:
Problem with PyInstaller and local packages
My project is structured as follows:

example3/

window/

__init__.py

...

__init__.py

__main__.py

setup.py

example.py

in the main file:

```<code>import sys
from PySide2.QtWidgets import QApplication
import window

def main():
    app = QApplication(sys.argv)
    main_window = window.Main()
    main_window.show()
    app.exec_()

if __name__ == '__main__':
    main()
</code>```

The build script example.py for PyInstaller:

```<code>from example3.__main__ import main

if __name__ == '__main__':
    main()
</code>```

How do I get PyInstaller to recognize my project's packages or the modules in them? PyInstaller only sees the packages installed using pip. I had read something about hook files but didn't really understand how to do it.

I created the executable with the command:

```<code>> pyinstaller example.py --onefile
</code>```

When I try to run the application I get the error message:

```<code>> ./dist/example
Traceback (most recent call last):
  File "example.py", line 3, in <module>
  File "PyInstaller/loader/pyimod03_importers.py", line 495, in exec_module
  File "example3/__main__.py", line 7, in <module>
  File "/tmp/embedded.xpuoquuw.zip/shibokensupport/__feature__.py", line 146, in _import
ModuleNotFoundError: No module named 'window'
[127129] Failed to execute script 'example' due to unhandled exception!
</code>```

答:
The problem could be solved by telling PyInstaller the search path for my project's modules and packages:</p>
```<code>pyinstaller --onefile example.py --paths ./example3/
</code>```

Body:
My project is structured as follows:

example3/

window/

__init__.py

...

__init__.py

__main__.py

setup.py

example.py

in the main file:

import sys
from PySide2.QtWidgets import QApplication
import window

def main():
    app = QApplication(sys.argv)
    main_window = window.Main()
    main_window.show()
    app.exec_()

if __name__ == '__main__':
    main()

The build script example.py for PyInstaller:

from example3.__main__ import main

if __name__ == '__main__':
    main()

How do I get PyInstaller to recognize my project's packages or the modules in them? PyInstaller only sees the packages installed using pip. I had read something about hook files but didn't really understand how to do it.

I created the executable with the command:

> pyinstaller example.py --onefile

When I try to run the application I get the error message:

> ./dist/example
Traceback (most recent call last):
  File "example.py", line 3, in <module>
  File "PyInstaller/loader/pyimod03_importers.py", line 495, in exec_module
  File "example3/__main__.py", line 7, in <module>
  File "/tmp/embedded.xpuoquuw.zip/shibokensupport/__feature__.py", line 146, in _import
ModuleNotFoundError: No module named 'window'
[127129] Failed to execute script 'example' due to unhandled exception!

Body:
The problem could be solved by telling PyInstaller the search path for my project's modules and packages:

pyinstaller --onefile example.py --paths ./example3/


问:
Convert hex value to decimal in C but keep getting incorrect value, plus too few argument error when calling func
Hello I am trying to convert a hex value into the decimal form but for some reason the result I'm getting each time is negative and completely incorrect. Additionally I would like to take that decimal number and then convert it into it binary value. I have created func's for both but have run into the problem of "too few arguments" when calling my bin() func. If somebody could point me in the right direction and explain what I am doing wrong I would sincerely appreciate it.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define arraysize 20

int decimal() {

    int i = 0, val, len;
    char hex1[arraysize];
    long long dec = 0, base = 1;

    len = strlen(hex1);

    for (i = len--;i >= 0; i--) {
        if (hex1[1] >= '0' && hex1[i] <= '9') {
            dec += (hex1[i] - 48) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'A' && hex1[i] <= 'F') {
            dec += (hex1[i] - 55) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'a' && hex1[i] <= 'f') {
            dec += (hex1[i] - 87) * base;
            base *= 16;
        }
    }
    printf("Your decimal value is: %lld\n",dec);
    return 0;
}

int bin(long long dec) {

    int a[10], i;

    for (i = 0; dec > 0; i++) {
        a[i] = dec % 2;
        dec = dec / 2;
    }
    printf("\nThe binary value is: ");
    for (i = i - 1; i >= 0; i--) {
        printf("%d", a[i]);
    }
    return 0;
}

int main() {

    char hex1[arraysize];

    printf("Enter your HEX value: ");
    fflush(stdin);
    fgets(hex1, arraysize, stdin);

    decimal(hex1);
    bin();
}
</code>```

答:
Try this and replace char hex1[arraysize]="FFFFFFFFFFFFFFFF"; as needed:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define arraysize 20
#define bin_arraysize 64

unsigned long long decimal(char* hex1) {

        long long dec = 0, base = 1;
        int len = strlen(hex1);
        for(int i = len-1;i >=0; i--) {
               if(hex1[i] >= '0' && hex1[i] <= '9') {
                        dec += (hex1[i] - 48) * base;
                        base *= 16;
               }
                else if(hex1[i] >= 'A' && hex1[i] <= 'F') {
                        dec += (hex1[i] - 55) * base;
                        base *= 16;
                }
               else if(hex1[i] >= 'a' && hex1[i] <= 'f') {
                       dec += (hex1[i] - 87) * base;
                       base *= 16;
               }
        }
        printf("Your decimal value is: %llu\n",dec);
        return dec;
}

void bin(unsigned long long dec) {

        int a[bin_arraysize], i;

        for(i = 0; dec > 0; i++) {
                a[i] = dec%2;
                dec = dec/2;
        }
        printf("\nThe binary value is: ");
        for(i = i - 1; i >= 0; i--) {
                printf("%d", a[i]);
                }
        return;
}

int main() {

        char hex1[arraysize]="FFFFFFFFFFFFFFFF";
        unsigned long long dec=decimal(hex1);
        bin(dec);
}
</code>```

Body:
Hello I am trying to convert a hex value into the decimal form but for some reason the result I'm getting each time is negative and completely incorrect. Additionally I would like to take that decimal number and then convert it into it binary value. I have created func's for both but have run into the problem of "too few arguments" when calling my bin() func. If somebody could point me in the right direction and explain what I am doing wrong I would sincerely appreciate it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define arraysize 20

int decimal() {

    int i = 0, val, len;
    char hex1[arraysize];
    long long dec = 0, base = 1;

    len = strlen(hex1);

    for (i = len--;i >= 0; i--) {
        if (hex1[1] >= '0' && hex1[i] <= '9') {
            dec += (hex1[i] - 48) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'A' && hex1[i] <= 'F') {
            dec += (hex1[i] - 55) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'a' && hex1[i] <= 'f') {
            dec += (hex1[i] - 87) * base;
            base *= 16;
        }
    }
    printf("Your decimal value is: %lld\n",dec);
    return 0;
}

int bin(long long dec) {

    int a[10], i;

    for (i = 0; dec > 0; i++) {
        a[i] = dec % 2;
        dec = dec / 2;
    }
    printf("\nThe binary value is: ");
    for (i = i - 1; i >= 0; i--) {
        printf("%d", a[i]);
    }
    return 0;
}

int main() {

    char hex1[arraysize];

    printf("Enter your HEX value: ");
    fflush(stdin);
    fgets(hex1, arraysize, stdin);

    decimal(hex1);
    bin();
}

Body:
Try this and replace char hex1[arraysize]="FFFFFFFFFFFFFFFF"; as needed:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define arraysize 20
#define bin_arraysize 64

unsigned long long decimal(char* hex1) {

        long long dec = 0, base = 1;
        int len = strlen(hex1);
        for(int i = len-1;i >=0; i--) {
               if(hex1[i] >= '0' && hex1[i] <= '9') {
                        dec += (hex1[i] - 48) * base;
                        base *= 16;
               }
                else if(hex1[i] >= 'A' && hex1[i] <= 'F') {
                        dec += (hex1[i] - 55) * base;
                        base *= 16;
                }
               else if(hex1[i] >= 'a' && hex1[i] <= 'f') {
                       dec += (hex1[i] - 87) * base;
                       base *= 16;
               }
        }
        printf("Your decimal value is: %llu\n",dec);
        return dec;
}

void bin(unsigned long long dec) {

        int a[bin_arraysize], i;

        for(i = 0; dec > 0; i++) {
                a[i] = dec%2;
                dec = dec/2;
        }
        printf("\nThe binary value is: ");
        for(i = i - 1; i >= 0; i--) {
                printf("%d", a[i]);
                }
        return;
}

int main() {

        char hex1[arraysize]="FFFFFFFFFFFFFFFF";
        unsigned long long dec=decimal(hex1);
        bin(dec);
}


问:
Should domain objects be allowed to be temporarily invalid, and how does that decision affect validation techniques?
I'm writing a VB.NET Winforms project based on MVVM (using Winforms binding).  My instinct is to never allow a domain entity be in an invalid state.  This requires that I do validation checks in the constructor for new entities and in each setter for existing entities:

```<code>Public Class Product

    Public Sub New(ProductID as Integer, Name as String)

        If ProductID > 0 AndAlso Name.Length > 5 Then

            _ProductID = ProductID
            _Name = Name

        Else
            Throw New InvalidProductException
        End If
    End Sub

    Private _ProductID as Integer
    Public Property ProductID as Integer

        Set(value as String)

            If value > 0 then
                _ProductID = value
            Else
                Throw New InvalidProductException
            End If

        End Set

    End Property

    'Same principle as above for Name setter.

End Class
</code>```

Then I ran across Data Annotations, which seemed pretty slick.  I noticed that most people using Data Annotations allow the domain entity to become invalid temporarily, and then validate the entity at some later point with a call to Validate.ValidateObject.  By this point the entity is invalid and the original state has been lost unless you have some other mechanism to roll it back.

Two Questions:

1) Do you allow domain entities to become temporarily invalid?

2) Based on your answer to #1, what techniques do you use to validate the entity?

答:
Firstly, no, domain objects should never exist in an invalid state.

I think the confusion you are having stems from the fact you are trying to power your UI screens from domain objects (and you are definitely not the only one), i.e. binding to your domain objects properties. You shouldn't. Your UI should get it's data from the properties of a view model; a purpose built UI object, which is allowed to be in an invalid state, and can make use of any cool UI validation frameworks.

Domain objects should only come into play in the context of a command/transaction. i.e. the user has selected a view model object from a list on the screen and wishes to perform an action on it. Typically the UI will then call an application/command service method for the action they wish to perform, passing the ID from the view model the user has selected. This will then retrieve the domain object from it's repository and invoke the appropriate method.

In terms of where the view model object comes from: I have a separate query service that the UI calls. This provides 'flat' (de-normalised aggregated data) DTO's which can be used to populate view model objects or act as the view models themselves. This service is unaware of any domain model and simply returns projections from the data that the domain objects conduct transactions over.

I can't recommend enough reading up on CQRS, even if you only take up certain aspects of it. Not only does it help make practical sense of DDD, but if implemented well it can really help with the performance aspect of getting the data to your UI screens.

Body:
I'm writing a VB.NET Winforms project based on MVVM (using Winforms binding).  My instinct is to never allow a domain entity be in an invalid state.  This requires that I do validation checks in the constructor for new entities and in each setter for existing entities:

Public Class Product

    Public Sub New(ProductID as Integer, Name as String)

        If ProductID > 0 AndAlso Name.Length > 5 Then

            _ProductID = ProductID
            _Name = Name

        Else
            Throw New InvalidProductException
        End If
    End Sub

    Private _ProductID as Integer
    Public Property ProductID as Integer

        Set(value as String)

            If value > 0 then
                _ProductID = value
            Else
                Throw New InvalidProductException
            End If

        End Set

    End Property

    'Same principle as above for Name setter.

End Class

Then I ran across Data Annotations, which seemed pretty slick.  I noticed that most people using Data Annotations allow the domain entity to become invalid temporarily, and then validate the entity at some later point with a call to Validate.ValidateObject.  By this point the entity is invalid and the original state has been lost unless you have some other mechanism to roll it back.

Two Questions:

1) Do you allow domain entities to become temporarily invalid?

2) Based on your answer to #1, what techniques do you use to validate the entity?


问:
How to get dimensions of window when using @react-navigation/native-stack and presentation: 'modal'?
I am trying to use @react-navigation/native-stack and presentation: 'modal' to get more native feel on tablets. My problem is I did not find any way how to get dimensions of modal window. I tried both useWindowDimensions() and Dimensions.get('window/screen') but I always get size of whole app window, not just the modal window size.

Is there any way how to do that?

答:
if u cant find something u can always use "onLayout", juts put t on wrapper View in modal</p>
```<code><View style={{flex:1}} onLayout={(event: LayoutChangeEvent) => {
  // event.nativeEvent.layout.width
  // event.nativeEvent.layout.height
}}>
</View>
</code>```

Body:
if u cant find something u can always use "onLayout", juts put t on wrapper View in modal

<View style={{flex:1}} onLayout={(event: LayoutChangeEvent) => {
  // event.nativeEvent.layout.width
  // event.nativeEvent.layout.height
}}>
</View>