问:
How to Include JS File To Component in Angular
I have many components and i want to include js files each. I have to use 3rd party js files and this js files are specific for any component. I mean that these js files are not global, they are component specific. So, i want to include a js file to component.

How to i include js files to components ?

index.html ( main html in project )

```<code><!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <base href="/">

  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body class="fixed-navbar">
  <div class="site">

    <app-root></app-root>

  </div>

  <script src="assets/plugins/jquery/jquery.min.js"></script>
  <script src="assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script></script>

  <!-- Component Specific JS Files Have To Come Here -->
  <!-- Component Specific JS Files Have To Come Here -->
  <!-- Component Specific JS Files Have To Come Here -->
  <!-- Component Specific JS Files Have To Come Here -->
  <!-- Component Specific JS Files Have To Come Here -->

</body>

</html>
</code>```

post.component.html ( component html )

```<code><p> Post 1</p>
<p> Post 2 </p>
<p> Post Bla bla bla </p>

<!-- This scripts is only for this component -->
<!-- This js section has to go to specific place in index.html where i type -->

<script src="/assets/plugins/parallax/parallax.min.js"></script>
<script src="/assets/plugins/easypiechart/jquery.easypiechart.min.js"></script>
<script>
  $(function () {
    $('.easypiechart').easyPieChart();
  });
</script>

<!-- Angular doesn't include these scripts to page -->
</code>```

user.component.html ( component html )

```<code><p> User 1 </p>
<p> User2 </p>
<p> User Bla bla bla </p>

<!-- This scripts is only for this component -->
<!-- This js section has to go to specific place in index.html where i type -->

<script src="/assets/plugins/anotherjs/anotherjs.min.js"></script>
<script src="/assets/plugins/chart2/jquery.chart2.min.js"></script>

<!-- Angular doesn't include these scripts to page -->
</code>```

I can't add js files by using "

答:
In case, if anyone is still struggling in 2022, and he/she wants to add JS file in any one component. This is how I did:

In component.ts file:

```<code>  ngOnInit(): void {
    let node = document.createElement('script');
    node.src = "https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js";//Change to your js file
    node.type = 'text/javascript';
    node.async = true;
    node.charset = 'utf-8';
    document.getElementsByTagName('head')[0].appendChild(node);
 }
</code>```

Body:
I have many components and i want to include js files each. I have to use 3rd party js files and this js files are specific for any component. I mean that these js files are not global, they are component specific. So, i want to include a js file to component.

How to i include js files to components ?

index.html ( main html in project )

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <base href="/">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

    <app-root></app-root>

  </script>

post.component.html ( component html )

 Post 1

 Post 2

 Post Bla bla bla

user.component.html ( component html )

 User 1

 User2

 User Bla bla bla

I can't add js files by using "

Body:
In case, if anyone is still struggling in 2022, and he/she wants to add JS file in any one component. This is how I did:

In component.ts file:

  ngOnInit(): void {
    let node = document.createElement('script');
    node.src = "https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js";//Change to your js file
    node.type = 'text/javascript';
    node.async = true;
    node.charset = 'utf-8';
    document.getElementsByTagName('head')[0].appendChild(node);
 }


来源: stackexchange

问:
Change CircleAvatar size in ListTile
I want to increase the size of an CircleAvatar as Leading of a Listtile. But if i increase the Radius the Circle doesnt keep its ratio and becomes an ellipse.

Here is my Code:

```<code>ListView.builder(
itemCount: friendlist.length,
itemBuilder: (BuildContext context, int index) {
print(friendlist[index]);
return ListTile(
        title: Text(friendlist[index]["nickname"],
                style: TextStyle(fontSize: 20)),
        leading: CircleAvatar(
            radius: 50,
            backgroundColor: Colors.transparent,
            backgroundImage: CachedNetworkImageProvider(core.url + "profiles/" + friendlist[index]["avatar_id"]),
          ),
        subtitle:
        Text(friendlist[index]["lost_last"])
    );
}));
</code>```

What I tried:

Nesting the Circle Avatar into a Container with fixed Width and Height -> Circle is still an ellipse

Changing the ItemExtent of the ListView.builder -> The Circle still cant use all of the empty space and becomes an ellipse.

Thanks

答:
There is a way to change the CircleAvatar actually , There are two properties related to size: minRadius and maxRadius. The are used to set the minimum and maximum radius respectively. If you already use radius, you are not allowed to use minRadius and/or maxRadius. On the contrary, if either minRadius or maxRadius is set, you are not allowed to use radius :

```<code>CircleAvatar(
    backgroundImage: NetworkImage('https://www.woolha.com/media/2020/03/eevee.png'),
    minRadius: 50,
    maxRadius: 75,
  )
</code>```

ContentLicense: CC BY-SA 4.0

Title: Change CircleAvatar size in ListTile

Body:
I want to increase the size of an CircleAvatar as Leading of a Listtile. But if i increase the Radius the Circle doesnt keep its ratio and becomes an ellipse.

Here is my Code:

ListView.builder(
itemCount: friendlist.length,
itemBuilder: (BuildContext context, int index) {
print(friendlist[index]);
return ListTile(
        title: Text(friendlist[index]["nickname"],
                style: TextStyle(fontSize: 20)),
        leading: CircleAvatar(
            radius: 50,
            backgroundColor: Colors.transparent,
            backgroundImage: CachedNetworkImageProvider(core.url + "profiles/" + friendlist[index]["avatar_id"]),
          ),
        subtitle:
        Text(friendlist[index]["lost_last"])
    );
}));

What I tried:

Nesting the Circle Avatar into a Container with fixed Width and Height -> Circle is still an ellipse

Changing the ItemExtent of the ListView.builder -> The Circle still cant use all of the empty space and becomes an ellipse.

Thanks

Body:
There is a way to change the CircleAvatar actually , There are two properties related to size: minRadius and maxRadius. The are used to set the minimum and maximum radius respectively. If you already use radius, you are not allowed to use minRadius and/or maxRadius. On the contrary, if either minRadius or maxRadius is set, you are not allowed to use radius :

CircleAvatar(
    backgroundImage: NetworkImage('https://www.woolha.com/media/2020/03/eevee.png'),
    minRadius: 50,
    maxRadius: 75,
  )


问:
Streaming pipeline using result in next step
I'm using the streaming package.
I want to use result of one step defined by the S.store as a parameter to a following step in the pipeline by preserving the constant memory. The myStream is loaded and parsed from a file.

I have a following example that typechecks:

import qualified Streaming.Prelude as S
import qualified Data.Map.Strict as M

data A = MkA deriving (Show)

insertA :: MonadIO m => S.Stream (S.Of A) m r -> m (M.Map String Int)
insertA = undefined

insertB :: MonadIO m => M.Map String Int -> S.Stream (S.Of A) m r -> m Int
insertB = undefined

myStream :: S.Stream (S.Of A) IO r
myStream = undefined

run :: IO ()
run =
  myStream
    & S.store insertA
    & insertB M.empty
    & print
```
<p>However, the line <code>& insertB M.empty</code> is taking an empty map but I want to use the map from the previous step, from the <code>insertA</code> function.
The <code>insertB</code> function then uses this Map for a lookup.</p>
<p>The solution I can think of is the following:</p>
<pre class="lang-hs prettyprint-override"><code>run :: IO ()
run =
  myStream
    & S.store insertA
    & ( \e -> do
          resultMap <- S.effects e
          insertB resultMap e
      )
    & print
</code>```

Questions

Does this preserve streaming benefits like running in constant memory?
How does it solve this in the background, since the stream needs to be processed as a whole to get the Map? It passes the same stream multiple times - loads it from a file 2 times to preserve the constant memory?

In case this would be the case (loads the file 2 times), what if the source of the stream was not from parsing a file but from some data stream that can be read only once?

Is there any other elegant solution to this problem that also holds the benefits of streaming where the next step in a pipeline needs to use the result of the previous one?

答:
There's a problem with the proposed code here:

```<code>  resultMap <- S.effects e
  insertB resultMap e
</code>```

The problem is that you are "running" the same stream twice, and that is usually problematic for IO-based streams.

For example, imagine myStream reads from a file handle. By the time we invoke insertB for the second pass, effects will have already reached end-of-file!  Any further reads from the handle won't return any data.

Of course, we could read the same file twice with two different streams. That preserves streaming, but requires two passes.

It should be noted though that for certain base monads that have built-in resource management, like resourcet, you can run the same Stream value twice, because the stream code is "smart" enough to allocate and deallocate the underlying resources each time the stream is run.

For example, the version of the Stream type present in linear-base supports the function readFile:

```<code>readFile :: FilePath -> Stream (Of Text) RIO ()
</code>```

Which returns a Stream working in a resource-aware IO.

That said, I'm not a fan of hiding such repeated reads of a file in a streaming pipeline, it seems confusing to me.

Body:
I'm using the streaming package.
I want to use result of one step defined by the S.store as a parameter to a following step in the pipeline by preserving the constant memory. The myStream is loaded and parsed from a file.

I have a following example that typechecks:

import qualified Streaming.Prelude as S
import qualified Data.Map.Strict as M

data A = MkA deriving (Show)

insertA :: MonadIO m => S.Stream (S.Of A) m r -> m (M.Map String Int)
insertA = undefined

insertB :: MonadIO m => M.Map String Int -> S.Stream (S.Of A) m r -> m Int
insertB = undefined

myStream :: S.Stream (S.Of A) IO r
myStream = undefined

run :: IO ()
run =
  myStream
    & S.store insertA
    & insertB M.empty
    & print

However, the line & insertB M.empty is taking an empty map but I want to use the map from the previous step, from the insertA function.
The insertB function then uses this Map for a lookup.

The solution I can think of is the following:

run :: IO ()
run =
  myStream
    & S.store insertA
    & ( \e -> do
          resultMap <- S.effects e
          insertB resultMap e
      )
    & print

Questions

Does this preserve streaming benefits like running in constant memory?
How does it solve this in the background, since the stream needs to be processed as a whole to get the Map? It passes the same stream multiple times - loads it from a file 2 times to preserve the constant memory?

In case this would be the case (loads the file 2 times), what if the source of the stream was not from parsing a file but from some data stream that can be read only once?

Is there any other elegant solution to this problem that also holds the benefits of streaming where the next step in a pipeline needs to use the result of the previous one?

Body:
There's a problem with the proposed code here:

  resultMap <- S.effects e
  insertB resultMap e

The problem is that you are "running" the same stream twice, and that is usually problematic for IO-based streams.

For example, imagine myStream reads from a file handle. By the time we invoke insertB for the second pass, effects will have already reached end-of-file!  Any further reads from the handle won't return any data.

Of course, we could read the same file twice with two different streams. That preserves streaming, but requires two passes.

It should be noted though that for certain base monads that have built-in resource management, like resourcet, you can run the same Stream value twice, because the stream code is "smart" enough to allocate and deallocate the underlying resources each time the stream is run.

For example, the version of the Stream type present in linear-base supports the function readFile:

readFile :: FilePath -> Stream (Of Text) RIO ()

Which returns a Stream working in a resource-aware IO.

That said, I'm not a fan of hiding such repeated reads of a file in a streaming pipeline, it seems confusing to me.


问:
Cannot change default port in NX JS project in React app
I try to change NX JS default port from 4200 to any different value.
I tried some commands which I understood from documentation that need to be placed into terminal and it didn't work:

```<code>yarn nx serve --port:3000
yarn nx serve myapp port:3000
nx serve myapp port:3000
</code>```

what I do wrong ?

thanks

答: Try using nx serve myapp --port 3000

Body:
I try to change NX JS default port from 4200 to any different value.
I tried some commands which I understood from documentation that need to be placed into terminal and it didn't work:

yarn nx serve --port:3000
yarn nx serve myapp port:3000
nx serve myapp port:3000

what I do wrong ?

thanks

Body: Try using nx serve myapp --port 3000


问:
Chronicle: How to optimize memory-mapped files for low-latency?
I'm using Chronicle to transfer vast amounts of data from one JVM to another. Problem is that I notice a lot of jitter on my benchmarks. My knowledge of memory-mapped files is somewhat limited, but I do know that the OS swaps pages back and forth from memory to disk.

How do I configure those pages for maximum performance, in my case, for less jitter and the lowest possible latency, when using Chronicle? Do they need to be big or small? Do they need to be many or few?

Here is what I currently have on my Ubuntu box:

```<code>$ cat /proc/meminfo | grep Huge
AnonHugePages:      2048 kB
ShmemHugePages:        0 kB
HugePages_Total:       1
HugePages_Free:        1
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:    1048576 kB
</code>```

答:
Assuming you have Linux, you can enable sparse files with useSparseFiles(true) on the builder.

You can also use a faster drive to reduce outliers or /dev/shm.

There is an asynchronous mode in the closed source version, however, you can get most outliers well below 80 microseconds without it.

Chronicle Queue doesn't use Huge pages.

Here is a chart I created when I was comparing it to Kafka, writing to a Corsair MP600 Pro XT.

http://blog.vanillajava.blog/2022/01/benchmarking-kafka-vs-chronicle-for.html

NOTE: This is the latency for two hops writing and reading an object of around 220 bytes (with serialization)

Body:
I'm using Chronicle to transfer vast amounts of data from one JVM to another. Problem is that I notice a lot of jitter on my benchmarks. My knowledge of memory-mapped files is somewhat limited, but I do know that the OS swaps pages back and forth from memory to disk.

How do I configure those pages for maximum performance, in my case, for less jitter and the lowest possible latency, when using Chronicle? Do they need to be big or small? Do they need to be many or few?

Here is what I currently have on my Ubuntu box:

$ cat /proc/meminfo | grep Huge
AnonHugePages:      2048 kB
ShmemHugePages:        0 kB
HugePages_Total:       1
HugePages_Free:        1
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:    1048576 kB


问:
Building a Singleton Trait with PHP 5.4
We recently had a discussion if it was possible to build a trait Singleton PHP Traits and we played around with it a possible Implementation but ran into issues with building one.

This is an academic exercise. I know that Singletons have very little - if not to say no - use in PHP and that one should 'just create one' but just for exploring the possibilities of traits:

```<code><?php
trait Singleton
{
    protected static $instance;
    final public static function getInstance()
    {
        return isset(static::$instance)
            ? static::$instance
            : static::$instance = new static;
    }
    final private function __construct() {
        static::init();
    }
    protected function init() {}
    final private function __wakeup() {}
    final private function __clone() {}
}

class A  {
    use Singleton;
    public function __construct() {
        echo "Doesn't work out!";
    }
}

$a = new A(); // Works fine
</code>```

reproduce: http://codepad.viper-7.com/NmP0nZ

The question is: It is possible to create a Singleton Trait in PHP?

答:
Quick solution we've found (thanks chat!):

If a trait and a class both define the same method, the one of class if used

So the Singleton trait only works if the class that uses it doesn't define a __construct()

Trait:

```<code><?php
trait Singleton
{
    protected static $instance;
    final public static function getInstance()
    {
        return isset(static::$instance)
            ? static::$instance
            : static::$instance = new static;
    }
    final private function __construct() {
        $this->init();
    }
    protected function init() {}
    final private function __wakeup() {}
    final private function __clone() {}
}
</code>```

Example for a consuming class:

```<code><?php
class A  {
    use Singleton;

    protected function init() {
        $this->foo = 1;
        echo "Hi!\n";
    }
}

var_dump(A::getInstance());

new A();
</code>```

The var_dump now produces the expected output:

```<code>Hi!
object(A)#1 (1) {
  ["foo"]=>
  int(1)
}
</code>```

and the new fails:

```<code>Fatal error: Call to private A::__construct() from invalid context in ...
</code>```

Demo

ContentLicense: CC BY-SA 3.0

Title: Building a Singleton Trait with PHP 5.4

Body:
We recently had a discussion if it was possible to build a trait Singleton PHP Traits and we played around with it a possible Implementation but ran into issues with building one.

This is an academic exercise. I know that Singletons have very little - if not to say no - use in PHP and that one should 'just create one' but just for exploring the possibilities of traits:

<?php
trait Singleton
{
    protected static $instance;
    final public static function getInstance()
    {
        return isset(static::$instance)
            ? static::$instance
            : static::$instance = new static;
    }
    final private function __construct() {
        static::init();
    }
    protected function init() {}
    final private function __wakeup() {}
    final private function __clone() {}
}

class A  {
    use Singleton;
    public function __construct() {
        echo "Doesn't work out!";
    }
}

$a = new A(); // Works fine

reproduce: http://codepad.viper-7.com/NmP0nZ

The question is: It is possible to create a Singleton Trait in PHP?

Body:
Quick solution we've found (thanks chat!):

If a trait and a class both define the same method, the one of class if used

So the Singleton trait only works if the class that uses it doesn't define a __construct()

Trait:

<?php
trait Singleton
{
    protected static $instance;
    final public static function getInstance()
    {
        return isset(static::$instance)
            ? static::$instance
            : static::$instance = new static;
    }
    final private function __construct() {
        $this->init();
    }
    protected function init() {}
    final private function __wakeup() {}
    final private function __clone() {}
}

Example for a consuming class:

<?php
class A  {
    use Singleton;

    protected function init() {
        $this->foo = 1;
        echo "Hi!\n";
    }
}

var_dump(A::getInstance());

new A();

The var_dump now produces the expected output:

Hi!
object(A)#1 (1) {
  ["foo"]=>
  int(1)
}

and the new fails:

Fatal error: Call to private A::__construct() from invalid context in ...

Demo


问:
Download response file using Newman
We can use "send and download" option in Postman to download a response file. Do we have any option or command to download a file(eg excel) using Newman command in newman's current working directory?</p>

答:
Looks like it is not there as of this comment

https://github.com/postmanlabs/newman/issues/413

A workaround is available in this bug, that might be useful !

Title: Download response file using Newman


问:
CSS welcome animation overflow
I have this snippet.
The welcome div is for a welcome animation on the page that lasts 3.5 seconds and then disappears.

The problem is that the overflow is visible, being able to see the elements that I would like to be visible only after the welcome animation is finished.
As a solution to this problem, I thought of javascript, inserting another function for setTimeOut for body with hidden overflow

setTimeout (function () {
document.querySelector ('. body'). style.overflow = 'hidden';

}, 3500);

But it does not work.
I want the animation to last x seconds and then all the elements of the page to be visible, not during the animation.
Do you have solutions?
Is this method as effective for a beginning animation as other modern sites have?

 setTimeout(function() {
  document.querySelector('.welcome').style.display ='none' ;

},3500) ; ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
  margin:0;
  padding:0;
  box-sizing:border-box;

}

.welcome{
background:black;

height:100vh;
display:flex;
align-items:center;
justify-content:center;

}</code>```

Developed

Developed

```

答:
Just wrap the content you want to appear after, inside a div or section (say, with an id #mainContent) and initially set its's display to none. When you change the display of .welcome to none, you can also change the display of #mainContent to block like this:

setTimeout(function() {
  document.querySelector('.welcome').style.display ='none';
  document.querySelector('#mainContent').style.display ='block' ;

},3500) ;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
  margin:0;
  padding:0;
  box-sizing:border-box;

}
.welcome{
background:black;
height:50vh;
display:flex;
align-items:center;
justify-content:center;
color: #FFF;
}
#mainContent {display: none;}</code>```

Welcome

Header

Body content and other text here

Body content and other text here

Body content and other text here

Body content and other text here

Footer

```

Title: CSS welcome animation overflow

Body:
I have this snippet.
The welcome div is for a welcome animation on the page that lasts 3.5 seconds and then disappears.

The problem is that the overflow is visible, being able to see the elements that I would like to be visible only after the welcome animation is finished.
As a solution to this problem, I thought of javascript, inserting another function for setTimeOut for body with hidden overflow

setTimeout (function () {
document.querySelector ('. body'). style.overflow = 'hidden';

}, 3500);

But it does not work.
I want the animation to last x seconds and then all the elements of the page to be visible, not during the animation.
Do you have solutions?
Is this method as effective for a beginning animation as other modern sites have?

 setTimeout(function() {
  document.querySelector('.welcome').style.display ='none' ;

},3500) ;

*{
  margin:0;
  padding:0;
  box-sizing:border-box;

}

.welcome{
background:black;

height:100vh;
display:flex;
align-items:center;
justify-content:center;

}

Developed

Developed

Body:
Just wrap the content you want to appear after, inside a div or section (say, with an id #mainContent) and initially set its's display to none. When you change the display of .welcome to none, you can also change the display of #mainContent to block like this:

setTimeout(function() {
  document.querySelector('.welcome').style.display ='none';
  document.querySelector('#mainContent').style.display ='block' ;

},3500) ;

*{
  margin:0;
  padding:0;
  box-sizing:border-box;

}
.welcome{
background:black;
height:50vh;
display:flex;
align-items:center;
justify-content:center;
color: #FFF;
}
#mainContent {display: none;}

<div class="welcome">
  <h1>Welcome</h1>
</div>

<div id="mainContent">
  <div class="header">
    <div class= "developedbar">
      <h2 class="developed1">Header</h2>
    </div>
  </div>
  <div class="body">
    <p>Body content and other text here</p>
    <p>Body content and other text here</p>
    <p>Body content and other text here</p>
    <p>Body content and other text here</p>
  </div>
  <div class="footer">
    <h2 class="developed1">Footer</h2>
  </div>
</div>


问:
Overreaching FDS max limit, but where?
I have this piece of code that just downloads files from WebDav server.

_download(self) is a thread function, it is handled by multi_download(self) controller, that keeps the Thread count under 24 and it works fine. It should ensure that no more than 24 sockets are used. It is very straightforward, I am not even going to post the method here. Maybe relevant is that I am using Threads, not ThreadPoolExecutor - i am not a fan of Pool so much - handling the max ThreadCount manually.

Problem is when e.g. VPN drops and i cannot connect, or some other unhandled network problems. I could handle that ofc, but thats not the point here.

The unexpected behaviour is HERE:

After a while of running retrials and logging exceptions , the file descriptor count seems to overreach the limit because it starts throwing this Error. It never happened when there was no errors/retrials in the whole process.:
NOTE: webdav.download() library method uses with open(file, 'wb') to download data, so there should be no hanging FDs either.

```<code>2022-02-09 10:36:53,898 - DEBUG - 2294-1644212940.tdms thrd - Retried download successfull on 25 attempt         [webdav.py:_download:183]
2022-02-09 10:36:53,904 - DEBUG - 2294-1644212940.tdms thrd - downloaded 900 files                               [webdav.py:add_download_counter:67]#just a log
2022-02-09 10:36:59,801 - DEBUG - 2294-1644219643.tdms thrd - Retried download successfull on 25 attempt         [webdav.py:_download:183]
2022-02-09 10:36:59,856 - DEBUG - 2294-1644213248.tdms thrd - Retried download successfull on 25 attempt         [webdav.py:_download:183]
2022-02-09 10:36:59,905 - WARNING - 2294-1643646904.tdms thrd - WebDav cannot connect: HTTPConnectionPool(host='123.16.456.123', port=987):
Max retries exceeded with url:/path/to/webdav/file (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f7b3377d898>:
Failed to establish a new connection: [Errno 24] Too many open files'))

# Marked in code where this is thrown !
</code>```

I assume that it means i am opening too many sockets, but I tried to clean after myself, in code you can see me closing the session and even deleting the reference to client to make it more neat. BUT after a while of debugging it, I cannot seem to get hold of WHERE I am forgetting something and where are the hanging sockets. I try ask for help before I start counting FDs and subclassing easywebdav2 classes :) Thanks, Q.

# Python 3.7.3

from easywebdav2 import Client as WebDavClient
# WebDav source:
# https://github.com/zabuldon/easywebdav/blob/master/easywebdav2/client.py

def clean_webdav(self, webdav):
"""Closing sockets after"""
  try:
    webdav.session.close()
  except Exception as err:
    logger.error(f'Err closing session: {err}')
  finally:
    del webdav

def _download(self, local, remote, *, retry=0):
"""This is a thread function, therefore raising SystemExit."""
  try:
    webdav = WebDavClient(**kw)
  except Exception as err:
    logger.error(f'There is an err creating client: {err}')
    raise SystemExit

  try:
    webdav.download(remote, local)   # < --------------- HERE THROWS
    if retry != 0:
      logger.info(f'Retry number {retry} was successfull')
  except(ConnectionError, requests.exceptions.ConnectionError) as err:
    if retry >= MAX_RETRY:
      logger.exception(f'There was err: {err}')
      return
    retry += 1
    self.clean_webdav(webdav)
    self._download(local, remote, retry=retry)
  except Exception as err:
    logger.error(f'Unhandled Exception: {err}')
  finally:
    self.clean_webdav(webdav)
    raise SystemExit
```

EDIT: Since one answer contained reference to WebDav being HTTP protocol expansion(which it is) - HTTP keep-alive should not play a role here if I am specifically closing the requests session by webdav.session.close() which is indeed THE requests session made by webdav. There should be no keep-alive after specifically closing right?

答:
I'm not specifically familiar with the WebDAV client package you're using, but any WebDAV client would usually support HTTP Keep-Alive, which means that after you release a connection, it will keep it alive in a pool for a while in case you need it again.

The way you use a client like that would be to construct one WebDavClient for your application, and use that one client for all requests.  Of course, you need to know that it's thread safe if you're going to call it from multiple download threads.

Since you are creating a WebDavClient in each thread, there's a good chance that total number of connections being kept alive across all of their pools exceeds your file handle limit.

--

EDIT: A quick look on the Web indicates that each WebDavClient creates a session of object from requests, which does indeed have a connection pool, but unfortunately isn't thread-safe.  You should create a WebDavClient per thread and use it for all of the downloads that that thread does.  That will probably require a little refactoring.

Title: Overreaching FDS max limit, but where?

Body:
I have this piece of code that just downloads files from WebDav server.

_download(self) is a thread function, it is handled by multi_download(self) controller, that keeps the Thread count under 24 and it works fine. It should ensure that no more than 24 sockets are used. It is very straightforward, I am not even going to post the method here. Maybe relevant is that I am using Threads, not ThreadPoolExecutor - i am not a fan of Pool so much - handling the max ThreadCount manually.

Problem is when e.g. VPN drops and i cannot connect, or some other unhandled network problems. I could handle that ofc, but thats not the point here.

The unexpected behaviour is HERE:

After a while of running retrials and logging exceptions , the file descriptor count seems to overreach the limit because it starts throwing this Error. It never happened when there was no errors/retrials in the whole process.:
NOTE: webdav.download() library method uses with open(file, 'wb') to download data, so there should be no hanging FDs either.

2022-02-09 10:36:53,898 - DEBUG - 2294-1644212940.tdms thrd - Retried download successfull on 25 attempt         [webdav.py:_download:183]
2022-02-09 10:36:53,904 - DEBUG - 2294-1644212940.tdms thrd - downloaded 900 files                               [webdav.py:add_download_counter:67]#just a log
2022-02-09 10:36:59,801 - DEBUG - 2294-1644219643.tdms thrd - Retried download successfull on 25 attempt         [webdav.py:_download:183]
2022-02-09 10:36:59,856 - DEBUG - 2294-1644213248.tdms thrd - Retried download successfull on 25 attempt         [webdav.py:_download:183]
2022-02-09 10:36:59,905 - WARNING - 2294-1643646904.tdms thrd - WebDav cannot connect: HTTPConnectionPool(host='123.16.456.123', port=987):
Max retries exceeded with url:/path/to/webdav/file (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f7b3377d898>:
Failed to establish a new connection: [Errno 24] Too many open files'))

# Marked in code where this is thrown !

I assume that it means i am opening too many sockets, but I tried to clean after myself, in code you can see me closing the session and even deleting the reference to client to make it more neat. BUT after a while of debugging it, I cannot seem to get hold of WHERE I am forgetting something and where are the hanging sockets. I try ask for help before I start counting FDs and subclassing easywebdav2 classes :) Thanks, Q.

# Python 3.7.3

from easywebdav2 import Client as WebDavClient
# WebDav source:
# https://github.com/zabuldon/easywebdav/blob/master/easywebdav2/client.py

def clean_webdav(self, webdav):
"""Closing sockets after"""
  try:
    webdav.session.close()
  except Exception as err:
    logger.error(f'Err closing session: {err}')
  finally:
    del webdav

def _download(self, local, remote, *, retry=0):
"""This is a thread function, therefore raising SystemExit."""
  try:
    webdav = WebDavClient(**kw)
  except Exception as err:
    logger.error(f'There is an err creating client: {err}')
    raise SystemExit

  try:
    webdav.download(remote, local)   # < --------------- HERE THROWS
    if retry != 0:
      logger.info(f'Retry number {retry} was successfull')
  except(ConnectionError, requests.exceptions.ConnectionError) as err:
    if retry >= MAX_RETRY:
      logger.exception(f'There was err: {err}')
      return
    retry += 1
    self.clean_webdav(webdav)
    self._download(local, remote, retry=retry)
  except Exception as err:
    logger.error(f'Unhandled Exception: {err}')
  finally:
    self.clean_webdav(webdav)
    raise SystemExit

EDIT: Since one answer contained reference to WebDav being HTTP protocol expansion(which it is) - HTTP keep-alive should not play a role here if I am specifically closing the requests session by webdav.session.close() which is indeed THE requests session made by webdav. There should be no keep-alive after specifically closing right?


问:
Error message "The server selected protocol version TLS10 is not accepted by client preferences"
I am trying to run this JNLP file on Windows 10 to connect to a server (actually, I am connecting to a dedicated server via KVM over IPMI (IPKVM) or whatever it is called, so I can install a new operating system).

I am getting error

The server selected protocol version TLS10 is not accepted by client preferences.

Is there something I need to do in Java client to fix the error?

答: You can set it in JRE inside SoapUI (if you are using it): Remove "TLSv1, TLSv1.1" from "jdk.tls.disabledAlgorithms" property in file ${soapui_home}/jre/conf/securityjava.security.


问:
run capital-gains command and get erro: AttributeError: module 'argparse' has no attribute 'BooleanOptionalAction'
I'm trying to use python library capital-gains
I refer https://pypi.org/project/capital-gains/ this python docs.
when I run capital-gains command it throws an error:

AttributeError: module 'argparse' has no attribute
'BooleanOptionalAction'

Traceback (most recent call last):   File
"/home/archana/mantralabs/backend/env/bin/capital-gains", line 8, in

sys.exit(main())   File "/home/archana/mantralabs/backend/env/lib/python3.6/site-packages/capital_gains/capital_gains.py",
line 11, in main
parser = argument_parser.get_parser()   File "/home/archana/mantralabs/backend/env/lib/python3.6/site-packages/capital_gains/argument_parser.py",
line 52, in get_parser
action=argparse.BooleanOptionalAction, AttributeError: module 'argparse' has no attribute 'BooleanOptionalAction'

Python version - 3.8

Can anyone help me? i'm not able to find out solution on google

答:
Actually The argparse.BooleanOptionalAction feature is only available in Python 3.9 and above.
you can try with python 3.9 or above version's


问:
Getting 500 Internal Server Error when calling /mint_nft NEAR REST API
I have cloned this NEAR REST API SERVER repo into my local system and haven't made any changes to its original code. Only added console logs for debugging purpose. Using its API, I have successfully deployed a contract to testnet account and also called that contract.

But when comes to NFT part, its not working.
I'm calling /mint_nft API and getting 500 Internal Server Error.

It's breaking here:

let create_token = await token.ViewNFT(tokenId, contract);

create_token is null.

If I do minting with NEAR CLI, its working fine and I can see that NFT in my testnet wallet..

near call $ID nft_mint '{"token_id": "02", "receiver_id": "'$ID'", "token_metadata": { "title": "Design #2", "description": "Art Design", "media": "https://ipfs.io/ipfs/Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu", "copies": 1}}' --accountId $ID --deposit 0.1

near-api-server.config.json

{
  "server_host": "localhost",
  "server_port": 9000,
  "rpc_node": "https://rpc.testnet.near.org",
  "init_disabled": false,
  "master_account_id": "parimal9.testnet",
  "master_key": "ed25519:2bUSD2v88RiwznraL1ZYtduH2rsJqbrE8K6QT2asnsPnXHc171Qj4khvxFxZqb6AN6zyiZzo4j7f9amooFi7kJX1",
  "nft_contract": "nft.parimal9.testnet"
}```
</div>
</div>
</p>
<hr />
I have also tried this way but still not working.
<p><img src="https://i.stack.imgur.com/O6SbW.png" alt="enter image description here" /></p>
<hr />
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>server.route({
        method: 'POST',
        path: '/mint_nft',
        handler: async (request) => {
            console.log('\n\n\nMINT_NFT_PAYLOAD:', request.payload);
            let {min, max} = request.payload;

            if (!min || !max) min = max = 0;
            let response = [];

            request = processRequest(request);
            for (let i = min; i <= max; i++) {
                const tokenId = request.payload.token_id.replace('{inc}', i);
                console.log('tokenId:', tokenId);

                let {account_id, private_key, metadata, contract} = request.payload;

                const tx = await token.MintNFT(
                    tokenId,
                    metadata,
                    contract,
                    account_id,
                    private_key
                );

                if (tx) {
                    if (min === max) {
                        console.log('tokenId:', tokenId);
                        let create_token = await token.ViewNFT(tokenId, contract);
                        console.log('create_token:', create_token, '\n\n\n');
                        create_token.token_id = tokenId;
                        console.log('create_token.token_id:', tokenId, '\n\n\n');
                        response.push({token: create_token, tx: tx});
                    } else {
                        response.push({tx: tx});
                    }
                } else {
                    response.push({text: 'Error. Check backend logs.'});
                }
            }

            return response;
        },
    });</code>```

答:
There are several issues in the existing repository for /mint_nft.

The REST-API implemented doesn't follow the correct format when minting an NFT.
I have created a PR to address the issue

In short, the function call to mint an NFT is missing one argument, receiver_id, and the format and name of metadata is not correct. It should be token_metadata: {} // type is object, not string.

If we change the postData to

```<code>{
    "token_id": "foo",
    "token_metadata": {
        "media": "https://ipfs.io/ipfs/Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu"
    },
    "account_id": "parimal9.testnet",
    "private_key": "yourPrivateKey",
    "contract": "parimal9.testnet"
}
</code>```

and make a few changes to the server code, which you can see in the PR I made, we should be able to call /mint_nft from the server.

Body:
I have cloned this NEAR REST API SERVER repo into my local system and haven't made any changes to its original code. Only added console logs for debugging purpose. Using its API, I have successfully deployed a contract to testnet account and also called that contract.

But when comes to NFT part, its not working.
I'm calling /mint_nft API and getting 500 Internal Server Error.

It's breaking here:

let create_token = await token.ViewNFT(tokenId, contract);

create_token is null.

If I do minting with NEAR CLI, its working fine and I can see that NFT in my testnet wallet..

near call $ID nft_mint '{"token_id": "02", "receiver_id": "'$ID'", "token_metadata": { "title": "Design #2", "description": "Art Design", "media": "https://ipfs.io/ipfs/Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu", "copies": 1}}' --accountId $ID --deposit 0.1

near-api-server.config.json

{
  "server_host": "localhost",
  "server_port": 9000,
  "rpc_node": "https://rpc.testnet.near.org",
  "init_disabled": false,
  "master_account_id": "parimal9.testnet",
  "master_key": "ed25519:2bUSD2v88RiwznraL1ZYtduH2rsJqbrE8K6QT2asnsPnXHc171Qj4khvxFxZqb6AN6zyiZzo4j7f9amooFi7kJX1",
  "nft_contract": "nft.parimal9.testnet"
}

I have also tried this way but still not working.

server.route({
        method: 'POST',
        path: '/mint_nft',
        handler: async (request) => {
            console.log('\n\n\nMINT_NFT_PAYLOAD:', request.payload);
            let {min, max} = request.payload;

            if (!min || !max) min = max = 0;
            let response = [];

            request = processRequest(request);
            for (let i = min; i <= max; i++) {
                const tokenId = request.payload.token_id.replace('{inc}', i);
                console.log('tokenId:', tokenId);

                let {account_id, private_key, metadata, contract} = request.payload;

                const tx = await token.MintNFT(
                    tokenId,
                    metadata,
                    contract,
                    account_id,
                    private_key
                );

                if (tx) {
                    if (min === max) {
                        console.log('tokenId:', tokenId);
                        let create_token = await token.ViewNFT(tokenId, contract);
                        console.log('create_token:', create_token, '\n\n\n');
                        create_token.token_id = tokenId;
                        console.log('create_token.token_id:', tokenId, '\n\n\n');
                        response.push({token: create_token, tx: tx});
                    } else {
                        response.push({tx: tx});
                    }
                } else {
                    response.push({text: 'Error. Check backend logs.'});
                }
            }

            return response;
        },
    });

Body:
There are several issues in the existing repository for /mint_nft.

The REST-API implemented doesn't follow the correct format when minting an NFT.
I have created a PR to address the issue

In short, the function call to mint an NFT is missing one argument, receiver_id, and the format and name of metadata is not correct. It should be token_metadata: {} // type is object, not string.

If we change the postData to

{
    "token_id": "foo",
    "token_metadata": {
        "media": "https://ipfs.io/ipfs/Qme7ss3ARVgxv6rXqVPiikMJ8u2NLgmgszg13pYrDKEoiu"
    },
    "account_id": "parimal9.testnet",
    "private_key": "yourPrivateKey",
    "contract": "parimal9.testnet"
}

and make a few changes to the server code, which you can see in the PR I made, we should be able to call /mint_nft from the server.


问:
UIImage and UIImageView show/hide problems
I am having an issue with code to show and hide a UIImage and UIImageView for my app. I want the button to capture a photo from the AVCapture session and then make the photo the entire view of the screen on the first press. Then when the user hits the button again it removes the UIImage and UIIamgeView.

Here is the code I have so far

```<code>    extension ViewController: AVCapturePhotoCaptureDelegate {
        func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto
        photo: AVCapturePhoto, error: Error?) {
        guard let data = photo.fileDataRepresentation() else{
               return }

        let image = UIImage(data: data)

        let Photo = UIImageView(image: image)
        if shutterButton.tag == 0 {
           shutterButton.tag = 1
           Photo.contentmode = .scaleAspectFill
           view.insertSubview(Photo, belowSubview: shutterbutton)
           }
        else if shutterButton.tag == 1{
                shutterButton.tag = 0 }
</code>```

I have tried using (below) as a possible fix but that does no resolve my issue

```<code>.isHidden = true
</code>```

What can I do to resolve my problem?

答:
OK - you said in the comments that "The shutter button was added via code", so presumably your code looks something like this:

```<code>class ViewController: UIViewController {

    let shutterButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        // other stuff

        view.addSubview(shutterButton)

        // constraints for shutterButton and other elements

    }

}
</code>```

then, when you get the photo image, you're doing this:

```<code>    let image = UIImage(data: data)

    let Photo = UIImageView(image: image)

    if shutterButton.tag == 0 {
        shutterButton.tag = 1
        Photo.contentMode = .scaleAspectFill
        view.insertSubview(Photo, belowSubview: shutterButton)
    }
    else if shutterButton.tag == 1
    {
        shutterButton.tag = 0
    }
</code>```

which means you're creating a NEW image view and inserting it as a subview every time this is called.

If you want to "add a photo" / "remove the photo" on every-other button tap, you want to have your image view already there, so you can set the image and show or hide the image view instead of creating new ones.

So, add your image view the same way you added the button... but add it before you add the button (so the button will be "on top"), and set it to hidden to start with:

```<code>class ViewController: UIViewController {

    let shutterButton = UIButton()

    let photoImageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // other stuff

        // setup the photo image view
        photoImageView.contentMode = .scaleAspectFill

        // start with it hidden
        photoImageView.isHidden = true

        // add the photo image view to the view hierarchy
        view.addSubview(photoImageView)

        // add the button last
        view.addSubview(shutterButton)

        // constraints for the image view

        // constraints for shutterButton and other elements

    }

}
</code>```

then, when you handle the photo capture:

```<code>extension ViewController: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto
                     photo: AVCapturePhoto, error: Error?) {

        guard let data = photo.fileDataRepresentation() else {
            return
        }

        let image = UIImage(data: data)

        // don't do this
        //let Photo = UIImageView(image: image)

        if shutterButton.tag == 0 {
            shutterButton.tag = 1

            // don't do this
            //Photo.contentMode = .scaleAspectFill
            //view.insertSubview(Photo, belowSubview: shutterButton)

            // instead, do this
            photoImageView.image = image
            photoImageView.isHidden = false

        }
        else if shutterButton.tag == 1
        {
            shutterButton.tag = 0

            // do this to "remove" the image
            photoImageView.image = nil
            photoImageView.isHidden = true
        }
    }
}
</code>```

Body:
I am having an issue with code to show and hide a UIImage and UIImageView for my app. I want the button to capture a photo from the AVCapture session and then make the photo the entire view of the screen on the first press. Then when the user hits the button again it removes the UIImage and UIIamgeView.

Here is the code I have so far

    extension ViewController: AVCapturePhotoCaptureDelegate {
        func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto
        photo: AVCapturePhoto, error: Error?) {
        guard let data = photo.fileDataRepresentation() else{
               return }

        let image = UIImage(data: data)

        let Photo = UIImageView(image: image)
        if shutterButton.tag == 0 {
           shutterButton.tag = 1
           Photo.contentmode = .scaleAspectFill
           view.insertSubview(Photo, belowSubview: shutterbutton)
           }
        else if shutterButton.tag == 1{
                shutterButton.tag = 0 }

I have tried using (below) as a possible fix but that does no resolve my issue

.isHidden = true

What can I do to resolve my problem?

Body:
OK - you said in the comments that "The shutter button was added via code", so presumably your code looks something like this:

class ViewController: UIViewController {

    let shutterButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        // other stuff

        view.addSubview(shutterButton)

        // constraints for shutterButton and other elements

    }

}

then, when you get the photo image, you're doing this:

    let image = UIImage(data: data)

    let Photo = UIImageView(image: image)

    if shutterButton.tag == 0 {
        shutterButton.tag = 1
        Photo.contentMode = .scaleAspectFill
        view.insertSubview(Photo, belowSubview: shutterButton)
    }
    else if shutterButton.tag == 1
    {
        shutterButton.tag = 0
    }

which means you're creating a NEW image view and inserting it as a subview every time this is called.

If you want to "add a photo" / "remove the photo" on every-other button tap, you want to have your image view already there, so you can set the image and show or hide the image view instead of creating new ones.

So, add your image view the same way you added the button... but add it before you add the button (so the button will be "on top"), and set it to hidden to start with:

class ViewController: UIViewController {

    let shutterButton = UIButton()

    let photoImageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // other stuff

        // setup the photo image view
        photoImageView.contentMode = .scaleAspectFill

        // start with it hidden
        photoImageView.isHidden = true

        // add the photo image view to the view hierarchy
        view.addSubview(photoImageView)

        // add the button last
        view.addSubview(shutterButton)

        // constraints for the image view

        // constraints for shutterButton and other elements

    }

}

then, when you handle the photo capture:

extension ViewController: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto
                     photo: AVCapturePhoto, error: Error?) {

        guard let data = photo.fileDataRepresentation() else {
            return
        }

        let image = UIImage(data: data)

        // don't do this
        //let Photo = UIImageView(image: image)

        if shutterButton.tag == 0 {
            shutterButton.tag = 1

            // don't do this
            //Photo.contentMode = .scaleAspectFill
            //view.insertSubview(Photo, belowSubview: shutterButton)

            // instead, do this
            photoImageView.image = image
            photoImageView.isHidden = false

        }
        else if shutterButton.tag == 1
        {
            shutterButton.tag = 0

            // do this to "remove" the image
            photoImageView.image = nil
            photoImageView.isHidden = true
        }
    }
}


问:
How to position footer in my React Router?
I am having problems getting my Footer component to appear at the bottom of the page. And can't seem to see what the issue is.

Here is my App.js:

```<code>import "./App.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Navbar from "./components/layout/Navbar";
import Landing from "./components/layout/Landing";
import Contact from "./components/layout/Contact";
import Footer from "./components/layout/Footer";

function App() {
  return (
    <Router>
      <Navbar />
      <Routes>
        <Route path="/" element={<Landing />} />
        <Route exact path="/contact" element={<Contact />} />
      </Routes>
      <Footer />
    </Router>
  );
}

export default App;
</code>```

Now the navbar appears at the top of the page however the Landing component sits behind it (also advice on how to stop that would be great).

Inside the Landing Component we have two components a such:

```<code>import React from "react";
import LandingInner from "../pages/landing/LandingInner";
import LandingCards from "../pages/landing/LandingCards";

const Landing = () => {
  return (
    <section className="landing">
      <div className=" dark-overlay">
        <LandingInner />
        <LandingCards />
      </div>
    </section>
  );
};

export default Landing;
</code>```

The Footer appears at the bottom of the page upon loading the page (it appears on screen) however I don't want it to appear on the screen unless you scroll down and it should just be the last component on every page that i go to. Like the Navbar is always the first.#

Here is the current css for the Footer:

```<code>.footer {
  border: 5px solid black;
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
}
</code>```

Hope this makes sense. But just to clarify; I want the footer appear at the bottom of every page(not the screen) that I go to on my app.

答:
First of all, if you want the footer to always appear at the bottom no matter what ie. when scroll bar appears and content scrolls and when content is less and there is no scroll bar then the solution is very simple ie. make position fixed of footer and set it to bottom and left 0 with width 100%.

But if you want the footer to go to the bottom when content is less and go to the end of the content when content is large enough to scroll then you need to give your body and HTML height of 100% with a few more tweaks that I can create a sandbox for.

let me know if this fixes the issue, you can ask me if you need more information.

You can try flex I've written code for your reference and also created sandbox

https://codesandbox.io/s/empty-cloud-b6h4c?file=/index.html

body,
html {
  height: 100%;
}

.container {
  display: flex;
  flex-flow: column nowrap;
  height: 100%;
}

main {
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="container">
  <main>
    main content
  </main>
  <footer>Some content </footer>
</section></code>```

Body:
I am having problems getting my Footer component to appear at the bottom of the page. And can't seem to see what the issue is.

Here is my App.js:

import "./App.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Navbar from "./components/layout/Navbar";
import Landing from "./components/layout/Landing";
import Contact from "./components/layout/Contact";
import Footer from "./components/layout/Footer";

function App() {
  return (
    <Router>
      <Navbar />
      <Routes>
        <Route path="/" element={<Landing />} />
        <Route exact path="/contact" element={<Contact />} />
      </Routes>

    </Router>
  );
}

export default App;

Now the navbar appears at the top of the page however the Landing component sits behind it (also advice on how to stop that would be great).

Inside the Landing Component we have two components a such:

import React from "react";
import LandingInner from "../pages/landing/LandingInner";
import LandingCards from "../pages/landing/LandingCards";

const Landing = () => {
  return (

        <LandingInner />
        <LandingCards />

  );
};

export default Landing;

The Footer appears at the bottom of the page upon loading the page (it appears on screen) however I don't want it to appear on the screen unless you scroll down and it should just be the last component on every page that i go to. Like the Navbar is always the first.#

Here is the current css for the Footer:

.footer {
  border: 5px solid black;
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
}

Hope this makes sense. But just to clarify; I want the footer appear at the bottom of every page(not the screen) that I go to on my app.

Body:
First of all, if you want the footer to always appear at the bottom no matter what ie. when scroll bar appears and content scrolls and when content is less and there is no scroll bar then the solution is very simple ie. make position fixed of footer and set it to bottom and left 0 with width 100%.

But if you want the footer to go to the bottom when content is less and go to the end of the content when content is large enough to scroll then you need to give your body and HTML height of 100% with a few more tweaks that I can create a sandbox for.

let me know if this fixes the issue, you can ask me if you need more information.

You can try flex I've written code for your reference and also created sandbox

https://codesandbox.io/s/empty-cloud-b6h4c?file=/index.html

body,
html {
  height: 100%;
}

.container {
  display: flex;
  flex-flow: column nowrap;
  height: 100%;
}

main {
  flex: 1;
}

<section class="container">
  <main>
    main content
  </main>
  <footer>Some content </footer>
</section>


问:
Twilio "Gather input on call" is having pauses
I am using Twilio Studio and in the flow I am using "Gather input on Call" widget, and "Split based on" after that. It works fine, but on one of the keypress I am setting a variable and again using second level of "Gather input on call" widget and "split based on" combination. The second time it works after having a long pause in the speech.

Is it possible to use "Gather input on call" widget twice or many
times in one flow?

Can anyone suggest something to reduce the pause?

答: If you are using digit input (DTMF), if you know the number of expected digits, set that in the widget (Number of digits) so you don’t have to wait for the digit timeout to proceed to the next digit (which is that gap you here).</p>


问:
Determining function time using a wrapper
I'm looking for a generic way of measuring a functions timing like Here, but for c++.

My main goal is to not have cluttered code like this piece everywhere:

```<code>  auto t1 = std::chrono::high_resolution_clock::now();
  function(arg1, arg2);
  auto t2 = std::chrono::high_resolution_clock::now();
  auto tDur = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1);
</code>```

But rather have a nice wrapper around the function.
What I got so far is:

timing.hpp:

```<code>#pragma once

#include <chrono>
#include <functional>

template <typename Tret, typename Tin1, typename Tin2> unsigned int getDuration(std::function<Tret(Tin1, Tin2)> function, Tin1 arg1, Tin2 arg2, Tret& retValue)
{
  auto t1 = std::chrono::high_resolution_clock::now();
  retValue = function(arg1, arg2);
  auto t2 = std::chrono::high_resolution_clock::now();
  auto tDur = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1);
  return tDur.count();
}
</code>```

main.cpp:

```<code>#include "timing.hpp"
#include "matrix.hpp"

constexpr int G_MATRIXSIZE = 2000;

int main(int argc, char** argv)
{
CMatrix<double> myMatrix(G_MATRIXSIZE);

bool ret;
// this call is quite ugly
std::function<bool(int, std::vector<double>)> fillRow = std::bind(&CMatrix<double>::fillRow, &myMatrix, 0, fillVec);
auto duration = getDuration(fillRow, 5, fillVec, ret );
std::cout << "duration(ms): " << duration << std::endl;
}
</code>```

in case sb wants to test the code, matrix.hpp:

```<code>#pragma once

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

template<typename T> class CMatrix {
public:
    // ctor
    CMatrix(int size) :
        m_size(size)
    {
        m_matrixData = new std::vector<std::vector<T>>;
        createUnityMatrix();
    }
    // dtor
    ~CMatrix()
    {
        std::cout << "Destructor of CMatrix called" << std::endl;
        delete m_matrixData;
    }

    // print to std::out
    void printMatrix()
    {
        std::ostringstream oss;
        for (int i = 0; i < m_size; i++)
        {
            for (int j = 0; j < m_size; j++)
            {
                oss << m_matrixData->at(i).at(j) << ";";
            }
            oss << "\n";
        }
        std::cout << oss.str() << std::endl;
    }

    bool fillRow(int index, std::vector<T> row)
    {
        // checks
        if (!indexValid(index))
        {
            return false;
        }

        if (row.size() != m_size)
        {
            return false;
        }

        // data replacement
        for (int j = 0; j < m_size; j++)
        {
            m_matrixData->at(index).at(j) = row.at(j);
        }
        return true;
    }

    bool fillColumn(int index, std::vector<T> column)
    {
        // checks
        if (!indexValid(index))
        {
            return false;
        }

        if (column.size() != m_size)
        {
            return false;
        }

        // data replacement
        for (int j = 0; j < m_size; j++)
        {
            m_matrixData->at(index).at(j) = column.at(j);
        }
        return true;
    }

private:
    // variables
    std::vector<std::vector<T>>* m_matrixData;
    int m_size;

    bool indexValid(int index)
    {
        if (index + 1 > m_size)
        {
            return false;
        }
        return true;
    }

    // functions
    void createUnityMatrix()
    {
        for (int i = 0; i < m_size; i++)
        {
            std::vector<T> _vector;
            for (int j = 0; j < m_size; j++)
            {
                if (i == j)
                {
                    _vector.push_back(1);
                }
                else
                {
                    _vector.push_back(0);
                }
            }
            m_matrixData->push_back(_vector);
        }
    }
};
</code>```

The thing is, this code is still quite ugly due to the std::function usage. Is there a better and/or simpler option ?
(+ also I'm sure I messed sth up with the std::bind, I think I need to use std::placeholders since I want to set the arguments later on.)

// edit, correct use of placeholder in main:

```<code>std::function<bool(int, std::vector<double>)> fillRow = std::bind(&CMatrix<double>::fillRow, &myMatrix, std::placeholders::_1, std::placeholders::_2);
  auto duration = getDuration(fillRow, 18, fillVec, ret );
</code>```

答:
You can utilize RAII to implement a timer that records the execution time of a code block and a template function that wraps the function you would like to execute with the timer.

#include<string>
#include<chrono>
#include <unistd.h>

struct Timer
{
    std::string fn, title;
    std::chrono::time_point<std::chrono::steady_clock> start;
    Timer(std::string fn, std::string title)
        : fn(std::move(fn)), title(std::move(title)), start(std::chrono::steady_clock::now())
    {
    }
    ~Timer()
    {
        const auto elapsed =
            std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
        printf("%s: function=%s; elasepd=%f ms\n", title.c_str(), fn.c_str(), elapsed / 1000.0);
    }
};

#ifndef ENABLE_BENCHMARK
static constexpr inline void dummy_fn() { }
#define START_BENCHMARK_TIMER(...) dummy_fn()
#else
#define START_BENCHMARK_TIMER(title) bench::Timer timer(__FUNCTION__, title)
#endif

template<typename F, typename ...Args>
auto time_fn(F&& fn, Args&&... args) {
  START_BENCHMARK_TIMER("wrapped fn");
  return fn(std::forward<Args>(args)...);
}

int foo(int i) {
  usleep(70000);
  return i;
}

int main()
{
    printf("%d\n", time_fn(foo, 3));
}
```
<p>stdout:</p>
```wrapped fn: function=time_fn; elasepd=71.785000 ms
3
```

General Idea:

time_fn is a simple template function that calls START_BENCHMARK_TIMER and calls fn with the provided arguments

START_BENCHMARK_TIMER then creates a Timer object. It will record the current time in start. Do note that __FUNCTION__ will be replaced with the function that was called.

When the
provided fn returns or throws an exception, the Timer object from (1) will be destroyed and the destructor will be called. The destructor will then calculate the time difference between the current time and the recorded start time and prints it to stdout

Note:

Even though declaring start and end in time_fn instead of the RAII timer will work, having an RAII timer will allow you to cleanly handle the situation when fn throws an exception

If you are on c++11, you will need to change time_fn declaration to typename std::result_of<F &&(Args &&...)>::type  time_fn(F&& fn, Args&&... args).

Edit: Updated the response to include a wrapper function approach.

Body:
I'm looking for a generic way of measuring a functions timing like Here, but for c++.

My main goal is to not have cluttered code like this piece everywhere:

  auto t1 = std::chrono::high_resolution_clock::now();
  function(arg1, arg2);
  auto t2 = std::chrono::high_resolution_clock::now();
  auto tDur = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1);

But rather have a nice wrapper around the function.
What I got so far is:

timing.hpp:

#pragma once

#include <chrono>
#include <functional>

template <typename Tret, typename Tin1, typename Tin2> unsigned int getDuration(std::function<Tret(Tin1, Tin2)> function, Tin1 arg1, Tin2 arg2, Tret& retValue)
{
  auto t1 = std::chrono::high_resolution_clock::now();
  retValue = function(arg1, arg2);
  auto t2 = std::chrono::high_resolution_clock::now();
  auto tDur = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1);
  return tDur.count();
}

main.cpp:

#include "timing.hpp"
#include "matrix.hpp"

constexpr int G_MATRIXSIZE = 2000;

int main(int argc, char** argv)
{
CMatrix<double> myMatrix(G_MATRIXSIZE);

bool ret;
// this call is quite ugly
std::function<bool(int, std::vector<double>)> fillRow = std::bind(&CMatrix<double>::fillRow, &myMatrix, 0, fillVec);
auto duration = getDuration(fillRow, 5, fillVec, ret );
std::cout << "duration(ms): " << duration << std::endl;
}

in case sb wants to test the code, matrix.hpp:

#pragma once

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

template<typename T> class CMatrix {
public:
    // ctor
    CMatrix(int size) :
        m_size(size)
    {
        m_matrixData = new std::vector<std::vector<T>>;
        createUnityMatrix();
    }
    // dtor
    ~CMatrix()
    {
        std::cout << "Destructor of CMatrix called" << std::endl;
        delete m_matrixData;
    }

    // print to std::out
    void printMatrix()
    {
        std::ostringstream oss;
        for (int i = 0; i < m_size; i++)
        {
            for (int j = 0; j < m_size; j++)
            {
                oss << m_matrixData->at(i).at(j) << ";";
            }
            oss << "\n";
        }
        std::cout << oss.str() << std::endl;
    }

    bool fillRow(int index, std::vector<T> row)
    {
        // checks
        if (!indexValid(index))
        {
            return false;
        }

        if (row.size() != m_size)
        {
            return false;
        }

        // data replacement
        for (int j = 0; j < m_size; j++)
        {
            m_matrixData->at(index).at(j) = row.at(j);
        }
        return true;
    }

    bool fillColumn(int index, std::vector<T> column)
    {
        // checks
        if (!indexValid(index))
        {
            return false;
        }

        if (column.size() != m_size)
        {
            return false;
        }

        // data replacement
        for (int j = 0; j < m_size; j++)
        {
            m_matrixData->at(index).at(j) = column.at(j);
        }
        return true;
    }

private:
    // variables
    std::vector<std::vector<T>>* m_matrixData;
    int m_size;

    bool indexValid(int index)
    {
        if (index + 1 > m_size)
        {
            return false;
        }
        return true;
    }

    // functions
    void createUnityMatrix()
    {
        for (int i = 0; i < m_size; i++)
        {
            std::vector<T> _vector;
            for (int j = 0; j < m_size; j++)
            {
                if (i == j)
                {
                    _vector.push_back(1);
                }
                else
                {
                    _vector.push_back(0);
                }
            }
            m_matrixData->push_back(_vector);
        }
    }
};

The thing is, this code is still quite ugly due to the std::function usage. Is there a better and/or simpler option ?
(+ also I'm sure I messed sth up with the std::bind, I think I need to use std::placeholders since I want to set the arguments later on.)

// edit, correct use of placeholder in main:

std::function<bool(int, std::vector<double>)> fillRow = std::bind(&CMatrix<double>::fillRow, &myMatrix, std::placeholders::_1, std::placeholders::_2);
  auto duration = getDuration(fillRow, 18, fillVec, ret );

Body:
You can utilize RAII to implement a timer that records the execution time of a code block and a template function that wraps the function you would like to execute with the timer.

#include<string>
#include<chrono>
#include <unistd.h>

struct Timer
{
    std::string fn, title;
    std::chrono::time_point<std::chrono::steady_clock> start;
    Timer(std::string fn, std::string title)
        : fn(std::move(fn)), title(std::move(title)), start(std::chrono::steady_clock::now())
    {
    }
    ~Timer()
    {
        const auto elapsed =
            std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
        printf("%s: function=%s; elasepd=%f ms\n", title.c_str(), fn.c_str(), elapsed / 1000.0);
    }
};

#ifndef ENABLE_BENCHMARK
static constexpr inline void dummy_fn() { }
#define START_BENCHMARK_TIMER(...) dummy_fn()
#else
#define START_BENCHMARK_TIMER(title) bench::Timer timer(__FUNCTION__, title)
#endif

template<typename F, typename ...Args>
auto time_fn(F&& fn, Args&&... args) {
  START_BENCHMARK_TIMER("wrapped fn");
  return fn(std::forward<Args>(args)...);
}

int foo(int i) {
  usleep(70000);
  return i;
}

int main()
{
    printf("%d\n", time_fn(foo, 3));
}

stdout:

wrapped fn: function=time_fn; elasepd=71.785000 ms
3

General Idea:

time_fn is a simple template function that calls START_BENCHMARK_TIMER and calls fn with the provided arguments

START_BENCHMARK_TIMER then creates a Timer object. It will record the current time in start. Do note that __FUNCTION__ will be replaced with the function that was called.

When the
provided fn returns or throws an exception, the Timer object from (1) will be destroyed and the destructor will be called. The destructor will then calculate the time difference between the current time and the recorded start time and prints it to stdout

Note:

Even though declaring start and end in time_fn instead of the RAII timer will work, having an RAII timer will allow you to cleanly handle the situation when fn throws an exception

If you are on c++11, you will need to change time_fn declaration to typename std::result_of<F &&(Args &&...)>::type  time_fn(F&& fn, Args&&... args).

Edit: Updated the response to include a wrapper function approach.


问:
Google Apps Script Hoisting and ReferenceError
I've been trying to find an answer to this for a few weeks, but couldn't quite do this, so I decided to ask.

I sometimes get this error:

ReferenceError: <SomeObject> is not defined

...whereas I know for sure that it is. The problem is that the object is located in a different file, so if I call the object from that file (or maybe even a third file), the code does work.

I believe this must have to do with how hoisting works, meaning I'm trying to call an object before it's declared.

But then how does it work exactly when you have different files?

Here's an example:

If I have the following code in one file and I run getID(), it works:

const SomeAPI = (function () {
  const _auth = new WeakMap();
  const _url = new WeakMap();

  class SomeAPI {
    constructor(url, user = DEFAULT_USER, pwd = DEFAULT_PWD) {
      _url.set(this, url);
      _auth.set(this, Utilities.base64Encode(`${user}:${pwd}`));
    }

    async fetch() {
      const headers = {
        Authorization: `Basic ${_auth.get(this)}`,
      };

      const options = {
        headers,
      };

      const response = await UrlFetchApp.fetch(_url.get(this), options);
      const data = JSON.parse(response);
      return data;
    }
  }

  return SomeAPI;
})();

const LIST_DATA = (async () => await getListData())();

async function getListData() {
  const response = await new SomeAPI(ALL_SETTINGS['List API URL']).fetch();
  return Array.isArray(response) ? response[0] : response;
}

const getID = async () => {
  const listData = await LIST_DATA;
  const listId = listData.list_id;
  const id = {
    sheetId: SpreadsheetApp.getActive().getId(),
    listId
  };
  console.log(id);
  return id;
};
```

However, if I move LIST_DATA, getListData() and getID() to a different file, I get:

ReferenceError: SomeAPI is not defined

Overall the project is composed of 17 different files.

All help is greatly appreciated!

答: Per the comment by @Cooper to your question, moving the file up works.  I had the same problem with a class I created.  I moved the file with the class to the top and it solved my problem.</p>

Body:
I've been trying to find an answer to this for a few weeks, but couldn't quite do this, so I decided to ask.

I sometimes get this error:

ReferenceError: <SomeObject> is not defined

...whereas I know for sure that it is. The problem is that the object is located in a different file, so if I call the object from that file (or maybe even a third file), the code does work.

I believe this must have to do with how hoisting works, meaning I'm trying to call an object before it's declared.

But then how does it work exactly when you have different files?

Here's an example:

If I have the following code in one file and I run getID(), it works:

const SomeAPI = (function () {
  const _auth = new WeakMap();
  const _url = new WeakMap();

  class SomeAPI {
    constructor(url, user = DEFAULT_USER, pwd = DEFAULT_PWD) {
      _url.set(this, url);
      _auth.set(this, Utilities.base64Encode(`${user}:${pwd}`));
    }

    async fetch() {
      const headers = {
        Authorization: `Basic ${_auth.get(this)}`,
      };

      const options = {
        headers,
      };

      const response = await UrlFetchApp.fetch(_url.get(this), options);
      const data = JSON.parse(response);
      return data;
    }
  }

  return SomeAPI;
})();

const LIST_DATA = (async () => await getListData())();

async function getListData() {
  const response = await new SomeAPI(ALL_SETTINGS['List API URL']).fetch();
  return Array.isArray(response) ? response[0] : response;
}

const getID = async () => {
  const listData = await LIST_DATA;
  const listId = listData.list_id;
  const id = {
    sheetId: SpreadsheetApp.getActive().getId(),
    listId
  };
  console.log(id);
  return id;
};

However, if I move LIST_DATA, getListData() and getID() to a different file, I get:

ReferenceError: SomeAPI is not defined

Overall the project is composed of 17 different files.

All help is greatly appreciated!


问:
Azure Finctions on .NET6 isolated fails to run locally with hostpolicy.dll
I tried following answers: Azure Functions on .net6.0 fail to run locally with hostpolicy.dll error. And a .NET6 function will run but when I make a .NET6 isolated project and try to run I still get following error.</p>
```<code>Failed to load the dll from [C:\Users\mnir\AppData\Local\AzureFunctionsTools\Releases\4.10.1\cli_x64\hostpolicy.dll], HRESULT: 0x800700C1
An error occurred while loading required library hostpolicy.dll from [C:\Users\mnir\AppData\Local\AzureFunctionsTools\Releases\4.10.1\cli_x64\]
</code>```

答:
One of the workarounds is to swap the Environment variables paths of dotnet 32-bit and 64-bit versions i.e..

For more information you can refer Failed to load the dll

Body:
I tried following answers: Azure Functions on .net6.0 fail to run locally with hostpolicy.dll error. And a .NET6 function will run but when I make a .NET6 isolated project and try to run I still get following error.

Failed to load the dll from [C:\Users\mnir\AppData\Local\AzureFunctionsTools\Releases\4.10.1\cli_x64\hostpolicy.dll], HRESULT: 0x800700C1
An error occurred while loading required library hostpolicy.dll from [C:\Users\mnir\AppData\Local\AzureFunctionsTools\Releases\4.10.1\cli_x64\]


问:
How can I dispay the data in django admin panel
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel.

The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name.

As shown in the below image:

models.py

```<code>class Order(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        quantity = models.IntegerField(default=1)
        address = models.CharField(max_length=50, default='', blank=True)
        phone = models.CharField(max_length=50, default='', blank=True)
        price = models.IntegerField()
        date = models.DateField(default=datetime.datetime.today)
        status = models.BooleanField(default=False)
</code>```

admin.py

```<code>class AdminOrders(admin.ModelAdmin):
    list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status']
</code>```

答:
You need to define the __str__ method in the models Product and Customer

Example:

```<code>def __str__(self):
    return self.name
</code>```

Body:
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel.

The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name.

As shown in the below image:

models.py

class Order(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        quantity = models.IntegerField(default=1)
        address = models.CharField(max_length=50, default='', blank=True)
        phone = models.CharField(max_length=50, default='', blank=True)
        price = models.IntegerField()
        date = models.DateField(default=datetime.datetime.today)
        status = models.BooleanField(default=False)

admin.py

class AdminOrders(admin.ModelAdmin):
    list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status']

Body:
You need to define the __str__ method in the models Product and Customer

Example:

def __str__(self):
    return self.name


问:
When to use saveUninitialized and resave in express-session
I am newbie with the MEAN stack. I read the express-session github doc but there are some options which are unclear to me. Those options are saveUninitialized and resave.

Can anyone please explain with examples what are the advatanges of using saveUninitialized and resave, and what will the effect be if we change the boolean values in those options.

Syntax:-

```<code>app.use(session({
  resave: false,
  saveUninitialized: true,
}))
</code>```

答:
Uninitialised = false

It means that Your session is only Stored into your storage, when any of the Property is modified in req.session

Uninitialised = true

It means that Your session will be stored into your storage Everytime for request. It will not depend on the modification of req.session.

resave = true

It means when the modification is performed on the session it will re write the req.session.cookie object.

resave = false

It will not rewrite the req.session.cookie object. the initial req.session.cookie remains as it is.

Body:
I am newbie with the MEAN stack. I read the express-session github doc but there are some options which are unclear to me. Those options are saveUninitialized and resave.

Can anyone please explain with examples what are the advatanges of using saveUninitialized and resave, and what will the effect be if we change the boolean values in those options.

Syntax:-

app.use(session({
  resave: false,
  saveUninitialized: true,
}))


问:
Issue when trying to set one of div as selected in React JS
I have following code.

I'm trying to store a value in my state and every time the user goes to the previous step he can see what he has selected and after that he can change and move on to the next step.

At the first step, everything works good. For example, the user selects the second text and proceeds to the next step, and when he returns to this step, he sees that the second text has already been selected...

The problem is with the second step, I write all the same, but it doesn't work for the second step. When I am clicking on one of the div's in second step nothing was happened. There is no error. Please help me to figure out what's the problem

Here is my code.

App file

```<code>    export default function App() {
     const [selected, setSelected] = useState(1);
     const [term, setTerm] = useState(1);

     const [current, setCurrent] = useState(0);

     const [data, setData] = useState({
       firstName: "bob",
       lastName: "Forest",
       age: 47
     });
      const steps = [
        {
          title: "Package Choose",
          content: (
            <PackageChoose
              setCurrent={setCurrent}
              data={data}
              setData={setData}
              selected={selected}
              setSelected={setSelected}
            />
         ),
          id: 0
        },
        {
          title: "Term",
          content: (
           <Term
            setCurrent={setCurrent}
            data={data}
            selected={term}
            setTerm={setTerm}
            setData={setData}
        />
          ),
          id: 1
        },
        {
          title: "Last step",
          content: <LastStep setCurrent={setCurrent} data={data} />,
          id: 2
        }
      ];
      return (
        <div className="App">
          <div>{steps[current].content}</div>
        </div>
      );
    }
</code>```

first step package choose file

```<code>    const PackageChoose = ({
      setCurrent,
      data,
      setData,
      setSelected,
      selected
    }) => {
      return (
        <div>
          <div
            onClick={() => {
              setData({ ...data, packageType: "choice" });
            }}
          >
            <SelectCard
              id={1}
              selected={selected}
              onSelect={setSelected}
              text="text 1"
            />
          </div>
          <div
            onClick={() => {
              setData({ ...data, packageType: "select" });
            }}
          >
            <SelectCard
              id={2}
              selected={selected}
              onSelect={setSelected}
              text="text 2"
             />
          </div>
          <button onClick={() => setCurrent(1)}>Next</button>
        </div>
      );
   };

</code>```

second step Term file

```<code>   const Term = ({ setCurrent, data, setData, term, setTerm }) => {
      return (
        <div>
          <button onClick={() => setCurrent(0)}>Prev</button>
          <div
            onClick={() => {
              setData({ ...data, termType: "30 day" });
            }}
          >
            <SelectCard
              id={1}
              selected={term}
              onSelect={setTerm}
              text=" term text 1"
            />
         </div>
          <div
            onClick={() => {
              setData({ ...data, termType: "90 day" });
            }}
          >
            <SelectCard
              id={2}
              selected={term}
              onSelect={setTerm}
              text="term text 2"
            />
          </div>
          <button onClick={() => setCurrent(2)}>Next</button>
            </div>
      );
    };
</code>```

SelectCard  file , in this file I am using onSelect

```<code>   const SelectCard = ({ id, selected, onSelect, text }) => {
      const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (
        <div className={classNames(myClassName)} onClick={() => onSelect(id)}>
          <div> {text} </div>
        </div>
      );
     };
</code>```

Please help me to understand how can I fix this problem in my code.

Thanks.

答:
I edited your code.

Your issue in props that you passed.

before: setTerm={setTerm} , now: setSelected={setTerm}

https://codesandbox.io/s/little-leftpad-3owuu

Body:
I have following code.

I'm trying to store a value in my state and every time the user goes to the previous step he can see what he has selected and after that he can change and move on to the next step.

At the first step, everything works good. For example, the user selects the second text and proceeds to the next step, and when he returns to this step, he sees that the second text has already been selected...

The problem is with the second step, I write all the same, but it doesn't work for the second step. When I am clicking on one of the div's in second step nothing was happened. There is no error. Please help me to figure out what's the problem

Here is my code.

App file

    export default function App() {
     const [selected, setSelected] = useState(1);
     const [term, setTerm] = useState(1);

     const [current, setCurrent] = useState(0);

     const [data, setData] = useState({
       firstName: "bob",
       lastName: "Forest",
       age: 47
     });
      const steps = [
        {
          title: "Package Choose",
          content: (
            <PackageChoose
              setCurrent={setCurrent}
              data={data}
              setData={setData}
              selected={selected}
              setSelected={setSelected}
            />
         ),
          id: 0
        },
        {
          title: "Term",
          content: (
           <Term
            setCurrent={setCurrent}
            data={data}
            selected={term}
            setTerm={setTerm}
            setData={setData}
        />
          ),
          id: 1
        },
        {
          title: "Last step",
          content: <LastStep setCurrent={setCurrent} data={data} />,
          id: 2
        }
      ];
      return (

{steps[current].content}

      );
    }

first step package choose file

    const PackageChoose = ({
      setCurrent,
      data,
      setData,
      setSelected,
      selected
    }) => {
      return (

 {
              setData({ ...data, packageType: "choice" });
            }}
          >
            <SelectCard
              id={1}
              selected={selected}
              onSelect={setSelected}
              text="text 1"
            />

 {
              setData({ ...data, packageType: "select" });
            }}
          >
            <SelectCard
              id={2}
              selected={selected}
              onSelect={setSelected}
              text="text 2"
             />

          <button onClick={() => setCurrent(1)}>Next</button>

      );
   };

second step Term file

   const Term = ({ setCurrent, data, setData, term, setTerm }) => {
      return (

          <button onClick={() => setCurrent(0)}>Prev</button>

 {
              setData({ ...data, termType: "30 day" });
            }}
          >
            <SelectCard
              id={1}
              selected={term}
              onSelect={setTerm}
              text=" term text 1"
            />

 {
              setData({ ...data, termType: "90 day" });
            }}
          >
            <SelectCard
              id={2}
              selected={term}
              onSelect={setTerm}
              text="term text 2"
            />

          <button onClick={() => setCurrent(2)}>Next</button>

      );
    };

SelectCard  file , in this file I am using onSelect

   const SelectCard = ({ id, selected, onSelect, text }) => {
      const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (

 onSelect(id)}>

 {text}

      );
     };

Please help me to understand how can I fix this problem in my code.

Thanks.


问:
Adding custom button or a tag to django admin
I want to add some html element (button, "a" tag, etc ) to a django admin page. How can i do it? Please help.</p>

答:
You can create a file under templates/admin called base_site.html
(create the "admin" folder in your app).

add this code:

{% extends "admin/base_site.html" %}
{% load i18n %}

{% block userlinks %}
{% if site_url %}
    {% trans 'View site' %} /
{% endif %}
{% if user.is_active and user.is_staff %}
    {% url 'django-admindocs-docroot' as docsroot %}
    {% if docsroot %}
        {% trans 'Documentation' %} /
    {% endif %}
{% endif %}
{% if user.has_usable_password %}
{% trans 'Change password' %} /
{% endif %}
{% trans 'Log out' %}

    {% trans 'your link 1' %} /
    {% trans 'your link 2' %}

{% endblock %}

```

You can overwrite a lot of the admin html files. Make sure you extends the html you are overwriting, not to loose basic functionality.

See customize-django-admin-python for full admin templates tree you can overwrite.

You can also look at the base_site.html in Django project in Github. You'll find all of the "base_site" blocks you can plant your custom code in.

Body:
You can create a file under templates/admin called base_site.html
(create the "admin" folder in your app).

add this code:

{% extends "admin/base_site.html" %}
{% load i18n %}

{% block userlinks %}
{% if site_url %}
    <a href="{{ site_url }}">{% trans 'View site' %}</a> /
{% endif %}
{% if user.is_active and user.is_staff %}
    {% url 'django-admindocs-docroot' as docsroot %}
    {% if docsroot %}
        <a href="{{ docsroot }}">{% trans 'Documentation' %}</a> /
    {% endif %}
{% endif %}
{% if user.has_usable_password %}
<a href="{% url 'admin:password_change' %}">{% trans 'Change password' %}</a> /
{% endif %}
<a href="{% url 'admin:logout' %}">{% trans 'Log out' %}</a>

<!-- YOUR CUSTOM CODE HERE -->
<div class="your_custom_class">
    <a href="{% url 'your_app:yourlink1' %}">{% trans 'your link 1' %}</a> /
    <a href="{% url 'your_app:yourlink2' %}">{% trans 'your link 2' %}</a>
</div>

{% endblock %}

You can overwrite a lot of the admin html files. Make sure you extends the html you are overwriting, not to loose basic functionality.

See customize-django-admin-python for full admin templates tree you can overwrite.

You can also look at the base_site.html in Django project in Github. You'll find all of the "base_site" blocks you can plant your custom code in.


问:
How to check if an optional workflow_dispatch input is set or not
I have an input defined as

```<code>  workflow_dispatch:
    inputs:
      level:
        description: 'level to process'
        type: number
        required: false
</code>```

I would like to run named actions in the step depending on if the value is set or not but I cannot figure how

This might be working:

```<code>  if: ${{ github.event.inputs.level}}
</code>```

But I cannot find the opposite version, this is invalid:

```<code>  if: !${{ github.event.inputs.level}}
</code>```

答:
I've tested it in this workflow and the correct way to check if an input (or any variable) is empty or not in an IF conditional is by using the following syntax:

```<code>if: "${{ github.event.inputs.<INPUT_NAME> != '' }}"
</code>```

Note: using != "" will break the workflow as the interpreter doesn't accept this symbol in expressions.

Therefore, your workflow would look like this:

```<code>on:
  workflow_dispatch:
    inputs:
      level:
        description: 'level to process'
        type: number
        required: false

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Print variable if not empty
        if: "${{ github.event.inputs.level != '' }}"
        run: echo Level value is ${{ github.event.inputs.level }}

      - name: Print message if empty
        if: "${{ github.event.inputs.level == '' }}"
        run: echo Level value is empty
</code>```

I've made two tests here if you want to check:

workflow run with empty input value

workflow run with not empty input value

Body:
I have an input defined as

  workflow_dispatch:
    inputs:
      level:
        description: 'level to process'
        type: number
        required: false

I would like to run named actions in the step depending on if the value is set or not but I cannot figure how

This might be working:

  if: ${{ github.event.inputs.level}}

But I cannot find the opposite version, this is invalid:

  if: !${{ github.event.inputs.level}}

Body:
I've tested it in this workflow and the correct way to check if an input (or any variable) is empty or not in an IF conditional is by using the following syntax:

if: "${{ github.event.inputs.<INPUT_NAME> != '' }}"

Note: using != "" will break the workflow as the interpreter doesn't accept this symbol in expressions.

Therefore, your workflow would look like this:

on:
  workflow_dispatch:
    inputs:
      level:
        description: 'level to process'
        type: number
        required: false

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Print variable if not empty
        if: "${{ github.event.inputs.level != '' }}"
        run: echo Level value is ${{ github.event.inputs.level }}

      - name: Print message if empty
        if: "${{ github.event.inputs.level == '' }}"
        run: echo Level value is empty

I've made two tests here if you want to check:

workflow run with empty input value

workflow run with not empty input value