问:
Use this. in a function inside a function
I'm trying to get a String from my data in Vue 2, but I don't know how to get it from a function inside a function. Does anyone know how to? I'm using a library, iziToast library. See the comments, that's the part where I'm stucked.

```<code>data: () => ({
    myString: "Example string",
  }),

methods: {
showAlert() {
     iziToast.show({
        title: user.name,
        message: "¿Permitir que entre?",
        position: "bottomCenter",
        buttons: [
          ["<button>Yes</button>", function(instance, toast) {
            // Function if Yes button is pressed
            alert(this.myString); // This won't work
            }, true],
          [
            "<button>No</button>",
            function(instance, toast) {
              instance.hide(
                {
                  transitionOut: "fadeOutUp",
                  onClosing: function(instance, toast, closedBy) {
                    console.info("closedBy: " + closedBy);
                  }
                },
                toast,
                "buttonName"
              );
            }
          ]
        ]
      });
    },
}
</code>```

答:
Change the function signature as below & you'll have access to this.myString

function(instance, toast) { to (instance, toast) => {

Body:
I'm trying to get a String from my data in Vue 2, but I don't know how to get it from a function inside a function. Does anyone know how to? I'm using a library, iziToast library. See the comments, that's the part where I'm stucked.

data: () => ({
    myString: "Example string",
  }),

methods: {
showAlert() {
     iziToast.show({
        title: user.name,
        message: "¿Permitir que entre?",
        position: "bottomCenter",
        buttons: [
          ["<button>Yes</button>", function(instance, toast) {
            // Function if Yes button is pressed
            alert(this.myString); // This won't work
            }, true],
          [
            "<button>No</button>",
            function(instance, toast) {
              instance.hide(
                {
                  transitionOut: "fadeOutUp",
                  onClosing: function(instance, toast, closedBy) {
                    console.info("closedBy: " + closedBy);
                  }
                },
                toast,
                "buttonName"
              );
            }
          ]
        ]
      });
    },
}


来源: stackexchange

问:
Error in POM file while creating Spring Starter Project
I have just created a new Spring Starter Project in STS. After creating, seen it is not getting fully loaded as MAVEN project. Seen the below error in POM file.

Project build error: Non-parseable POM C:\Users\salim.m2\repository\org\springframework\boot\spring-boot-starter-
 parent\2.3.0.RELEASE\spring-boot-starter-parent-2.3.0.RELEASE.pom: unexpected markup \n

Not sure what is happening. Please help me with this.

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.3.0.RELEASE

    com.vishnu.ws.soap
    hellowebservice
    0.0.1-SNAPSHOT
    hellowebservice
    Hello SOAP Service

```<code><properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

答:
I don't know if you posted your pom correctly, but it seems to be incorrect, therefore giving the parse error. It's missing some tags apprentely. IT should be something like this for your case:</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
    </parent>
    <groupId>com.vishnu.ws.soap</groupId>
    <artifactId>hellowebservice</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hellowebservice</name>
    <description>SOAP Service</description>

   <!-- additional lines as you have it now -->

 </project>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have just created a new Spring Starter Project in STS. After creating, seen it is not getting fully loaded as MAVEN project. Seen the below error in POM file.

Project build error: Non-parseable POM C:\Users\salim.m2\repository\org\springframework\boot\spring-boot-starter-
 parent\2.3.0.RELEASE\spring-boot-starter-parent-2.3.0.RELEASE.pom: unexpected markup \n

Not sure what is happening. Please help me with this.

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.3.0.RELEASE

    com.vishnu.ws.soap
    hellowebservice
    0.0.1-SNAPSHOT
    hellowebservice
    Hello SOAP Service

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Body:
I don't know if you posted your pom correctly, but it seems to be incorrect, therefore giving the parse error. It's missing some tags apprentely. IT should be something like this for your case:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
    </parent>
    <groupId>com.vishnu.ws.soap</groupId>
    <artifactId>hellowebservice</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hellowebservice</name>
    <description>SOAP Service</description>

   <!-- additional lines as you have it now -->

 </project>


问:
SpringBoot with MariaDB: The driver has not received any packets from the server
I have a MariaDB, when connecting with sequel Pro I use this credentials and I can connect

with SpringBoot I use

```<code>spring.datasource.url=jdbc:mysql://172.105.50.55:3306/pradera_db
spring.datasource.username=pradera_usr
spring.datasource.password=Mddejh847h$#@
</code>```

but I have this error:

```<code>Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:400)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:243)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:225)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:402)
    at java.base/java.net.Socket.connect(Socket.java:591)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
    ... 81 common frames omitted
2020-05-31 12:30  [restartedMain] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
2020-05-31 12:30  [restartedMain] ERROR com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Exception during pool initialization.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
</code>```

this is the dependency in the pom.xml:

```<code><dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
</code>```

答:
Try this as connection string :

spring.datasource.url=jdbc:mysql://172.105.50.55:3306/pradera_db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

pom.xml :

```<code><dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
</code>```

Body:
I have a MariaDB, when connecting with sequel Pro I use this credentials and I can connect

with SpringBoot I use

spring.datasource.url=jdbc:mysql://172.105.50.55:3306/pradera_db
spring.datasource.username=pradera_usr
spring.datasource.password=Mddejh847h$#@

but I have this error:

Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:400)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:243)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:225)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:402)
    at java.base/java.net.Socket.connect(Socket.java:591)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
    ... 81 common frames omitted
2020-05-31 12:30  [restartedMain] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
2020-05-31 12:30  [restartedMain] ERROR com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Exception during pool initialization.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

this is the dependency in the pom.xml:

<dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

Body:
Try this as connection string :

spring.datasource.url=jdbc:mysql://172.105.50.55:3306/pradera_db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

pom.xml :

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>


问:
Button inside clickable row is activating the row highlight
I have a Bootstrap table that is just a clickable row. I put a button in that row which is going to be a href to another location. When I click on the button, the row is activated and gets highlighted.

I am reading that I need to stop pagination use jQuery however I am not sure how to do that. This is my current jQuery that is used to toggle the clickable row.

```<code>$(document).ready(function() {
            $('.myTable').on('click', '.clickable-row', function(event) {
                $(this).toggleClass('table-warning');
            });
        });
</code>```

I am not sure what needs to be added so that my row does not get highlighted when click on the button

EDIT:

```<code><table class="table table-hover" id="myTable">
  <thead>
    <tr class="clickable-row">
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr class="clickable-row">
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr class="clickable-row">
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr class="clickable-row">
      <th scope="row">3</th>
      <td colspan="2">Larry the Bird</td>
      <td><a class="btn btn-primary" href="#" target="_blank" role="button">Link</a></td>
    </tr>
  </tbody>
</code>```

答:
You may have read that you need to stop propagation, not pagination. To stop propagation means to prevent further propagation of the current event in the capturing and bubbling phases. Applied to your example, it means that a click on the button in the table won't be also counted as click on the row. More info on stopPropagation(). Note that I've also added event.preventDefault(); in the example as it would result in opening a broken link. Omit this in your real code when you add a link address to the button.

$(document).ready(function() {
  $('#myTable').on('click', '.clickable-row', function(event) {
    $(this).toggleClass('table-warning');
  });

  $('#myTable').on('click', '.btn', function(event) {
  event.preventDefault();
  event.stopPropagation();
  $(this).parent("td").toggleClass("clicked");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table-warning {
  background-color: yellow;
}
.clicked {
  background-color:red;
}</code>```

      #
      First
      Last
      Handle

      1
      Mark
      Otto
      @mdo

      2
      Jacob
      Thornton
      @fat

      3
      Larry the Bird
      Link

```

Body:
I have a Bootstrap table that is just a clickable row. I put a button in that row which is going to be a href to another location. When I click on the button, the row is activated and gets highlighted.

I am reading that I need to stop pagination use jQuery however I am not sure how to do that. This is my current jQuery that is used to toggle the clickable row.

$(document).ready(function() {
            $('.myTable').on('click', '.clickable-row', function(event) {
                $(this).toggleClass('table-warning');
            });
        });

I am not sure what needs to be added so that my row does not get highlighted when click on the button

EDIT:

      #
      First
      Last
      Handle

      1
      Mark
      Otto
      @mdo

      2
      Jacob
      Thornton
      @fat

      3
      Larry the Bird
      Link

Body:
You may have read that you need to stop propagation, not pagination. To stop propagation means to prevent further propagation of the current event in the capturing and bubbling phases. Applied to your example, it means that a click on the button in the table won't be also counted as click on the row. More info on stopPropagation(). Note that I've also added event.preventDefault(); in the example as it would result in opening a broken link. Omit this in your real code when you add a link address to the button.

$(document).ready(function() {
  $('#myTable').on('click', '.clickable-row', function(event) {
    $(this).toggleClass('table-warning');
  });

  $('#myTable').on('click', '.btn', function(event) {
  event.preventDefault();
  event.stopPropagation();
  $(this).parent("td").toggleClass("clicked");
  });
});

.table-warning {
  background-color: yellow;
}
.clicked {
  background-color:red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover" id="myTable">
  <thead>
    <tr class="clickable-row">
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr class="clickable-row">
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr class="clickable-row">
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr class="clickable-row">
      <th scope="row">3</th>
      <td colspan="2">Larry the Bird</td>
      <td><a class="btn btn-primary" href="#" target="_blank" role="button">Link</a></td>
    </tr>
  </tbody>
  </table>


问:
Prolog performance and recursion type
I was playing with permutation in a couple of programs and stumbled upon this little experiment:

Permutation method 1:

```<code>permute([], []).
permute([X|Rest], L) :-
    permute(Rest, L1),
    select(X, L, L1).
</code>```

Permutation method 2:

```<code>permute([], []).
permute(L, [P | P1]) :-
    select(P, L, L1),
    permute(L1, P1).
</code>```

Permutation method 3 (use the built-in):

```<code>permute(L, P) :- permutation(L, P).
</code>```

I understand that it's good practice to use tail recursion, and generally using built-ins is supposed to be efficient. But when I run the following:

```<code>time(findall(P, permute([1,2,3,4,5,6,7,8,9], P), L)).
</code>```

I got the following results, which are relatively consistent across several runs:

Method 1:

```<code>% 772,064 inferences, 1.112 CPU in 2.378 seconds (47% CPU, 694451 Lips)
</code>```

Method 2:

```<code>% 3,322,118 inferences, 2.126 CPU in 4.660 seconds (46% CPU, 1562923 Lips)
</code>```

Method 3:

```<code>% 2,959,245 inferences, 1.967 CPU in 4.217 seconds (47% CPU, 1504539 Lips)
</code>```

So the non-tail recursive method is quite significantly more real-time efficient.

Is a particular recursion type generally more real time efficient, all other things being equal (I know that's not always a simple premise)? What this experiment tells me is that I may not want to be always striving for tail recursion, but I may need to do a performance analysis first, then weigh performance benefit against other benefits that tail recursion does have.

答:
Nice example. But I would rather use,
it doesn't leave a choice point in permute([], []):

```<code>permute3([], []).
permute3([H|T], [P|P1]) :-
    select(P, [H|T], L1),
    permute3(L1, P1).
</code>```

Its tail recursive and like 20% faster than
permute2/2, but still not as fast as permute1/2.

```<code>?- time((permute2([1,2,3,4,5,6,7,8,9,0],_), fail; true)).
% 29,592,302 inferences, 1.653 CPU in 1.667 seconds (99% CPU, 17896885 Lips)
true.

?- time((permute3([1,2,3,4,5,6,7,8,9,0],_), fail; true)).
% 25,963,501 inferences, 1.470 CPU in 1.480 seconds (99% CPU, 17662390 Lips)
true.
</code>```

But I am not sure whether the explanation by mat is correct.
It could be also the case that permute1/2 does less often
perform LCO than permute3/2 does.

Namely of n! results of the sub call permute1/2, only the
last redo doesn't leave a choice point. On the other hand in
permute3/2 every select/3 call has n results and doesn't

leave a choice point in the last redo. I did a little test,
write a period for each LCO:

```<code>?- permute1([1,2,3],_), fail; nl.
...
?- permute3([1,2,3],_), fail; nl.
..........
</code>```

LCO has not an extreme benefit in a fail loop. But the Prolog
system doesn't know about it. So I guess thats where unnecessary
time is spent, to a larger amount in permute3/2.

ContentLicense: CC BY-SA 3.0

Title: Prolog performance and recursion type

Body:
I was playing with permutation in a couple of programs and stumbled upon this little experiment:

Permutation method 1:

permute([], []).
permute([X|Rest], L) :-
    permute(Rest, L1),
    select(X, L, L1).

Permutation method 2:

permute([], []).
permute(L, [P | P1]) :-
    select(P, L, L1),
    permute(L1, P1).

Permutation method 3 (use the built-in):

permute(L, P) :- permutation(L, P).

I understand that it's good practice to use tail recursion, and generally using built-ins is supposed to be efficient. But when I run the following:

time(findall(P, permute([1,2,3,4,5,6,7,8,9], P), L)).

I got the following results, which are relatively consistent across several runs:

Method 1:

% 772,064 inferences, 1.112 CPU in 2.378 seconds (47% CPU, 694451 Lips)

Method 2:

% 3,322,118 inferences, 2.126 CPU in 4.660 seconds (46% CPU, 1562923 Lips)

Method 3:

% 2,959,245 inferences, 1.967 CPU in 4.217 seconds (47% CPU, 1504539 Lips)

So the non-tail recursive method is quite significantly more real-time efficient.

Is a particular recursion type generally more real time efficient, all other things being equal (I know that's not always a simple premise)? What this experiment tells me is that I may not want to be always striving for tail recursion, but I may need to do a performance analysis first, then weigh performance benefit against other benefits that tail recursion does have.

Body:
Nice example. But I would rather use,
it doesn't leave a choice point in permute([], []):

permute3([], []).
permute3([H|T], [P|P1]) :-
    select(P, [H|T], L1),
    permute3(L1, P1).

Its tail recursive and like 20% faster than
permute2/2, but still not as fast as permute1/2.

?- time((permute2([1,2,3,4,5,6,7,8,9,0],_), fail; true)).
% 29,592,302 inferences, 1.653 CPU in 1.667 seconds (99% CPU, 17896885 Lips)
true.

?- time((permute3([1,2,3,4,5,6,7,8,9,0],_), fail; true)).
% 25,963,501 inferences, 1.470 CPU in 1.480 seconds (99% CPU, 17662390 Lips)
true.

But I am not sure whether the explanation by mat is correct.
It could be also the case that permute1/2 does less often
perform LCO than permute3/2 does.

Namely of n! results of the sub call permute1/2, only the
last redo doesn't leave a choice point. On the other hand in
permute3/2 every select/3 call has n results and doesn't

leave a choice point in the last redo. I did a little test,
write a period for each LCO:

?- permute1([1,2,3],_), fail; nl.
...
?- permute3([1,2,3],_), fail; nl.
..........

LCO has not an extreme benefit in a fail loop. But the Prolog
system doesn't know about it. So I guess thats where unnecessary
time is spent, to a larger amount in permute3/2.


问:
Dialogflow getting username from Gmail account in inline editor
I have a Dialogflow inline, where when welcome intent is executed I need to call agent.add() so it replies with something like

Hello (username)!

This username is not that the user writes but it's the profile name that he has logged in to the device

答:
In order to get the user's name, you need to request permission from the user. So it usually isn't available as part of the welcoming Intent (at least not the first time they talk to your Action). You need to do one of two things:

Request user information which includes the user name. Once you have requested this information, you can save it so you'll get it the next time the user connects.

Ask the user to sign in. Once they have done so, you'll get an identity token with each request that includes the user's information


问:
Convert date issue in c#
I have dateformat issue where I need to convert the date from DB to different formats according to the login

Like I have 3 different format

DD/MM/YY,MM/DD/YY,DD/MMM/YY
I tried to convert using the following methods but no luck.

```<code>DateTime.TryParseExact(drtemp["StartDate"].ToString(),dateFormat,null,
   System.Globalization.DateTimeStyles.None,out startDate);
orderDate =DateTime.ParseExact(drtemp["StartDate"].ToString(), dateFormat, null);
</code>```

Any help is highly apprenticed
Thanks,
Magz

答:
Try

```<code>string date = DateTime.Now.ToString("dd/MM/yy");
string date1 = DateTime.Now.ToString("MM/dd/yy");
string date2 = DateTime.Now.ToString("dd/MMM/yy");
</code>```

In your case you could do

```<code>string formattedDate = drtemp["StartDate"].ToString("dd/MM/yy");
</code>```

Title: Convert date issue in c#

Body:
I have dateformat issue where I need to convert the date from DB to different formats according to the login

Like I have 3 different format

DD/MM/YY,MM/DD/YY,DD/MMM/YY
I tried to convert using the following methods but no luck.

DateTime.TryParseExact(drtemp["StartDate"].ToString(),dateFormat,null,
   System.Globalization.DateTimeStyles.None,out startDate);
orderDate =DateTime.ParseExact(drtemp["StartDate"].ToString(), dateFormat, null);

Any help is highly apprenticed
Thanks,
Magz

Body:
Try

string date = DateTime.Now.ToString("dd/MM/yy");
string date1 = DateTime.Now.ToString("MM/dd/yy");
string date2 = DateTime.Now.ToString("dd/MMM/yy");

In your case you could do

string formattedDate = drtemp["StartDate"].ToString("dd/MM/yy");


问:
Problems with images
I'm working on a script that is going to analize an image, I have a test image and the output image, the dimensions are 960x540 but I want to use this program on 4K images.

Basically my program is going to open the test image and convert it in a numpy array (as numpy.uint8) and using some for loops iterate over every single pixel and get the RGB values, sum them and if the sum is greater or equal then  765 ( (255+255+255)/2 ) make that pixel all white, and if the sum is less than 765 make that pixel black.

The script that I wrote is the following:

from PIL import Image
import numpy

img = Image.open('test.bmp')
img = numpy.array(img, numpy.uint8)

for il, line in enumerate(img):
    for ip, pixels in enumerate(line):
        if int(pixels[0]) + int(pixels[1]) + int(pixels[2]) >= 765:
            img[il][ip] = 255, 255, 255
        else:
            img[il][ip] = 0, 0, 0

img = Image.fromarray(img.astype('uint8'))
img.save('test_new.bmp')
```

I know that other peoples alredy responded to this in their threads but I want to understand why my script failed and generated that wrong output image (see links above).

Thanks

EDIT:
Thanks to an user I found out why my script wan't working perfectly, I still don't know why, but i included the results.

Result compared

答:
It seems you need a lower threshold, e.g:</p>

```<code>int(pixels[0]) + int(pixels[1]) + int(pixels[2]) >= 600
</code>```

Title: Problems with images

Body:
I'm working on a script that is going to analize an image, I have a test image and the output image, the dimensions are 960x540 but I want to use this program on 4K images.

Basically my program is going to open the test image and convert it in a numpy array (as numpy.uint8) and using some for loops iterate over every single pixel and get the RGB values, sum them and if the sum is greater or equal then  765 ( (255+255+255)/2 ) make that pixel all white, and if the sum is less than 765 make that pixel black.

The script that I wrote is the following:

from PIL import Image
import numpy

img = Image.open('test.bmp')
img = numpy.array(img, numpy.uint8)

for il, line in enumerate(img):
    for ip, pixels in enumerate(line):
        if int(pixels[0]) + int(pixels[1]) + int(pixels[2]) >= 765:
            img[il][ip] = 255, 255, 255
        else:
            img[il][ip] = 0, 0, 0

img = Image.fromarray(img.astype('uint8'))
img.save('test_new.bmp')

I know that other peoples alredy responded to this in their threads but I want to understand why my script failed and generated that wrong output image (see links above).

Thanks

EDIT:
Thanks to an user I found out why my script wan't working perfectly, I still don't know why, but i included the results.

Result compared

Body:
It seems you need a lower threshold, e.g:

int(pixels[0]) + int(pixels[1]) + int(pixels[2]) >= 600


问:
Why doesnt jsch execute the scp command?
I am trying to transfer a file from local to remote with scp. Local is windows(OpenSSH is running as service) and remote is FreeBSD(rsa key are setup).
For this i am using Jsch library.

```<code>try {
        if (ses == null) ses = fsaTo.getSession();
        channel = ses.openChannel("exec");
        String cmd = "scp "+ UserHostIdentity.getTransferUser(fsaFrom.getSystem()) + "@"
                + UserHostIdentity.getTransferHost(fsaFrom.getSystem()) + ":"
                + from + " "
                + to;
        ((ChannelExec)channel).setCommand(cmd);
        ((ChannelExec)channel).setErrStream(System.err);
        channel.connect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

The command cmd I tested it manually executing it and it worked. This is how I start up the session:

```<code>JSch jsch = new JSch();
    try {
        sshSession = jsch.getSession(UserHostIdentity.getTransferUser(fs), UserHostIdentity.getTransferHost(fs),22);
        UserInfo lui = UserHostIdentity.getTransferUserInfo(fs);
        sshSession.setUserInfo(lui);
        sshSession.setConfig("StrictHostKeyChecking", "no");
        sshSession.connect();
    } catch (JSchException e) {
        logger.error("Could not access fileserver.");
        throw new RuntimeException(e);
    }
</code>```

The issue is after calling channel.connect() nothing happens, no error, nothing.
In the same context the following code executes "sha256 -q " + filePath and returns correct results:

```<code>public String doCommand(String cmd) {
    if (sshSession == null) {
        initiateConnection();
    }

    Channel channel;
    String result = "";
    try {
        channel = sshSession.openChannel("exec");
        ((ChannelExec)channel).setCommand(cmd);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream input = channel.getInputStream();
        channel.connect();
        InputStreamReader inputReader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(inputReader);
        String line = null;

        while((line = bufferedReader.readLine()) != null){
            result = line;
        }
        bufferedReader.close();
        inputReader.close();
        channel.disconnect();
    } catch (JSchException e) {
        logger.error("Problem with communication to Fileserver.");
        throw new RuntimeException(e);
    } catch (IOException e) {
        logger.error("Problem with command stream.");
        throw new RuntimeException(e);
    }
    return result;
}
</code>```

My question is, why doesnt it work with the scp command.

答:
OK, so what your code is doing is:

Using SSH to connecting to <fsaTo>.

On <fsaTo> run the command "scp @:/ ".

The scp command will be trying to open another SSH connection back to <fsaFrom> ... which is presumable this host ... and pull the file back over that connection

This could work, but will only work if:

<fsaFrom> is listening for incoming SSH connections

the <fsaTo> account that you are using has an SSH private key (without a passphrase) that corresponds to one of the public keys registered for logging in to <fsaFrom> as <user>.

There is a better way that doesn't have any preconditions.  There are some undocumented command line switches for the scp command that are used on the remote system when you run the scp command as a normal command.

scp -f <remote-file> reads from <remote-file> and sending it to the ssh output stream.

scp -t <remote-file> reads from the ssh input stream and outputs to <remote-file>.

For more details, see SSH: The Secure Shell, the definitive guide section 3.8.

Or if you just want an example, the JSch ScpTo.java example shows how to do what you are trying to do.

Body:
I am trying to transfer a file from local to remote with scp. Local is windows(OpenSSH is running as service) and remote is FreeBSD(rsa key are setup).
For this i am using Jsch library.

try {
        if (ses == null) ses = fsaTo.getSession();
        channel = ses.openChannel("exec");
        String cmd = "scp "+ UserHostIdentity.getTransferUser(fsaFrom.getSystem()) + "@"
                + UserHostIdentity.getTransferHost(fsaFrom.getSystem()) + ":"
                + from + " "
                + to;
        ((ChannelExec)channel).setCommand(cmd);
        ((ChannelExec)channel).setErrStream(System.err);
        channel.connect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

The command cmd I tested it manually executing it and it worked. This is how I start up the session:

JSch jsch = new JSch();
    try {
        sshSession = jsch.getSession(UserHostIdentity.getTransferUser(fs), UserHostIdentity.getTransferHost(fs),22);
        UserInfo lui = UserHostIdentity.getTransferUserInfo(fs);
        sshSession.setUserInfo(lui);
        sshSession.setConfig("StrictHostKeyChecking", "no");
        sshSession.connect();
    } catch (JSchException e) {
        logger.error("Could not access fileserver.");
        throw new RuntimeException(e);
    }

The issue is after calling channel.connect() nothing happens, no error, nothing.
In the same context the following code executes "sha256 -q " + filePath and returns correct results:

public String doCommand(String cmd) {
    if (sshSession == null) {
        initiateConnection();
    }

    Channel channel;
    String result = "";
    try {
        channel = sshSession.openChannel("exec");
        ((ChannelExec)channel).setCommand(cmd);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream input = channel.getInputStream();
        channel.connect();
        InputStreamReader inputReader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(inputReader);
        String line = null;

        while((line = bufferedReader.readLine()) != null){
            result = line;
        }
        bufferedReader.close();
        inputReader.close();
        channel.disconnect();
    } catch (JSchException e) {
        logger.error("Problem with communication to Fileserver.");
        throw new RuntimeException(e);
    } catch (IOException e) {
        logger.error("Problem with command stream.");
        throw new RuntimeException(e);
    }
    return result;
}

My question is, why doesnt it work with the scp command.


问:
TypeScript - How to ensure value is a certain string?
I have the following;

```<code>type AppDisplay = "MainMenu" | "Game" | "GameOver";

interface AppState {
  appDisplay: AppDisplay
}

const initialAppState : AppState = {
  appDisplay: "MainMenu"
}

type ActionType = {
  type: "DisplayMenu" | "DisplayGame" | "DisplayGameOver";
}

const appStateReducer = (state : AppState, action : ActionType) => {
  switch (action.type) {
    case "DisplayMenu":
      return {
        appDisplay: "MainMenu"
      }
    case "DisplayGame":
      return {
        appDisplay: "Game"
      }
    case "DisplayGameOver":
      return {
        appDisplay: "GameOver"
      }
  }
}
</code>```

The above code doesn't work, because the assignments in appStateReducer are of type String, and TS doesn't recognise them as being of type AppDisplay. How can I ensure that appDisplay can only be assigned as "Game", "GameOver" or "MainMenu"?

答:
As Oles mentioned, you can specify the return type of your function, but you can also simplify some aspects of your code:

You can define an enum with your desired values:

```<code>enum AppDisplay {
    MAIN_MENU,
    GAME,
    GAME_OVER
}
</code>```

You can use this enum when defining the AppState interface:

```<code>interface AppState {
    appState: AppDisplay
}
</code>```

The same idea can be applied to ActionType:

```<code>enum ActionType {
    DIPLAY_MENU,
    DISPLAY_GAME,
    DISPLAY_GAME_OVER
}
</code>```

Using enums allows you do define specific values, without caring about the actual value type (string, number etc.).

Finally, your reducer function can look something like this (small remark - the state parameter doesn't seem to be used in your code):

```<code>const appStateReducer = (action: ActionType): AppDisplay => {
    switch(action) {
        case ActionType.DISPLAY_MENU:
            return AppDisplay.MAIN_MENU;

        case ActionType.DISPLAY_GAME:
            return AppDisplay.GAME;

        case ActionType.GAME_OVER:
            return AppDisplay.DISPLAY_GAME_OVER;

    }
}
</code>```

Hope you've found this helpful. Cheers.

Body:
I have the following;

type AppDisplay = "MainMenu" | "Game" | "GameOver";

interface AppState {
  appDisplay: AppDisplay
}

const initialAppState : AppState = {
  appDisplay: "MainMenu"
}

type ActionType = {
  type: "DisplayMenu" | "DisplayGame" | "DisplayGameOver";
}

const appStateReducer = (state : AppState, action : ActionType) => {
  switch (action.type) {
    case "DisplayMenu":
      return {
        appDisplay: "MainMenu"
      }
    case "DisplayGame":
      return {
        appDisplay: "Game"
      }
    case "DisplayGameOver":
      return {
        appDisplay: "GameOver"
      }
  }
}

The above code doesn't work, because the assignments in appStateReducer are of type String, and TS doesn't recognise them as being of type AppDisplay. How can I ensure that appDisplay can only be assigned as "Game", "GameOver" or "MainMenu"?

Body:
As Oles mentioned, you can specify the return type of your function, but you can also simplify some aspects of your code:

You can define an enum with your desired values:

enum AppDisplay {
    MAIN_MENU,
    GAME,
    GAME_OVER
}

You can use this enum when defining the AppState interface:

interface AppState {
    appState: AppDisplay
}

The same idea can be applied to ActionType:

enum ActionType {
    DIPLAY_MENU,
    DISPLAY_GAME,
    DISPLAY_GAME_OVER
}

Using enums allows you do define specific values, without caring about the actual value type (string, number etc.).

Finally, your reducer function can look something like this (small remark - the state parameter doesn't seem to be used in your code):

const appStateReducer = (action: ActionType): AppDisplay => {
    switch(action) {
        case ActionType.DISPLAY_MENU:
            return AppDisplay.MAIN_MENU;

        case ActionType.DISPLAY_GAME:
            return AppDisplay.GAME;

        case ActionType.GAME_OVER:
            return AppDisplay.DISPLAY_GAME_OVER;

    }
}

Hope you've found this helpful. Cheers.


问:
Overlay three curves in the same y axis
I want to overlay three curves of the normal distribution with three different sigma values. I have done this:

```<code>curve(dnorm(x, mean(x), sd(x)), col = 2, lwd = 2)
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)/2), col = 3, lwd = 2)
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)*2), col = 4, lwd = 2)
</code>```

And the result is
But I want to use only one y axis scale, so the three plots are one under the other and not on the same y scale. Also I want to expand the range of the x axis, to be from -3 to 3 for example

答:
You can use yaxt and xaxt to remove the y axis from the graph.

```<code>curve(dnorm(x, mean(x), sd(x)), col = 2, lwd = 2,ylab="My y axis name")
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)/2), col = 3, lwd = 2,yaxt='n',xaxt='n',ylab="")
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)*2), col = 4, lwd = 2,yaxt='n',xaxt='n',ylab="")
</code>```

gives,

Title: Overlay three curves in the same y axis

Body:
I want to overlay three curves of the normal distribution with three different sigma values. I have done this:

curve(dnorm(x, mean(x), sd(x)), col = 2, lwd = 2)
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)/2), col = 3, lwd = 2)
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)*2), col = 4, lwd = 2)

And the result is
But I want to use only one y axis scale, so the three plots are one under the other and not on the same y scale. Also I want to expand the range of the x axis, to be from -3 to 3 for example

Body:
You can use yaxt and xaxt to remove the y axis from the graph.

curve(dnorm(x, mean(x), sd(x)), col = 2, lwd = 2,ylab="My y axis name")
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)/2), col = 3, lwd = 2,yaxt='n',xaxt='n',ylab="")
par(new = TRUE)
curve(dnorm(x, mean(x), sd(x)*2), col = 4, lwd = 2,yaxt='n',xaxt='n',ylab="")

gives,


问:
Multiclass image recognition with Keras
i’m trying to build a network that recognize 21 classes.

The Data are in the Uc-merced.zip

This is the code:

```<code># import

import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Model
from keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense, GlobalAveragePooling2D
from keras import backend as K
from keras import applications
from keras import optimizers
from keras import utils
</code>```

I’m using Google Colab

```<code>%cd /content/drive/My Drive/
! unzip -q -n UCMerced_LandUse.zip
! echo 'Training folder content'
! ls -l ./UCMerced_LandUse/train/
! echo 'Validation folder content'
! ls -l ./UCMerced_LandUse/validation/

train_data_dir = 'UCMerced_LandUse/train/'
val_data_dir = 'UCMerced_LandUse/validation/'

### DATA GENERATOR
# get data from the folder, perform the preprocessing and the data augmentation,
# and arranges them in batches

# dimensions of our images
img_width, img_height = 256, 256

batch_size = 5

nb_train_samples = 1493
nb_val_samples = 622

# this is the preprocessing configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,     # rescale
    shear_range=0.2,      # on-th-fly data augmentation
    zoom_range=0.2,       # on-th-fly data augmentation
    horizontal_flip=True) # on-th-fly data augmentation

# this is the preprocessing configuration we will use for validation:
# rescaling only
val_datagen = ImageDataGenerator(rescale=1. / 255)

print('Training set generator:')
train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical'
   )

print('Validation set generator:')
val_generator = val_datagen.flow_from_directory(
    val_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

</code>```

This is the output:

```<code>Training set generator:
Found 1493 images belonging to 21 classes.
Validation set generator:
Found 622 images belonging to 21 classes.
</code>```

```<code># Inception V3 with pre-trained weights
base_model = applications.InceptionV3(weights='imagenet', include_top=False,input_shape=(256,256,3),classes=21)
train_after_layer =50 #

### CHANGE THE TOP MODEL BLOCK

x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(21, activation='softmax')(x)

model = Model(inputs=base_model.input, outputs=x)

# set the first K layers (up to the last conv block)
# to non-trainable (weights will not change during training)
for layer in model.layers[:train_after_layer]:
    layer.trainable = False

# compile the model with a SGD/momentum optimizer
# and a very slow learning rate.
model.compile(loss='categorical_crossentropy',
              optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
              metrics=['accuracy'])

epochs_fine = 50

history=model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs_fine,
    validation_data=val_generator,
    validation_steps=nb_val_samples // batch_size)

model.save_weights('prova.h5')

</code>```

The results seems to be pretty god, at the end of 50epoch this is the result:

loss: 0.0866 - accuracy: 0.9845 - val_loss: 0.6575 - val_accuracy: 0.9028

```<code>
from keras.preprocessing import image
import os

model.load_weights('prova.h5')

path = '/content/drive/My Drive/UCMerced_LandUse/validation/airplane'
dirs = os.listdir( path )

print(train_generator.class_indices)

for file in dirs:
  print(file)
  string=os.path.join(path,file)
  img_pred=image.load_img(string,target_size=(256,256,3))
  img_pred=image.img_to_array(img_pred)
  img_pred=np.expand_dims(img_pred,axis=0)
  array=model.predict(img_pred)
  y_classes = array.argmax(axis=-1)
  print(y_classes)

</code>```

This is the output:

```<code>{'agricultural': 0, 'airplane': 1, 'baseballdiamond': 2, 'beach': 3, 'buildings': 4, 'chaparral': 5, 'denseresidential': 6, 'forest': 7, 'freeway': 8, 'golfcourse': 9, 'harbor': 10, 'intersection': 11, 'mediumresidential': 12, 'mobilehomepark': 13, 'overpass': 14, 'parkinglot': 15, 'river': 16, 'runway': 17, 'sparseresidential': 18, 'storagetanks': 19, 'tenniscourt': 20}

airplane71.tif
[3]
airplane72.tif
[16]
airplane73.tif
[2]
airplane74.tif
[16]
airplane75.tif
[2]
airplane76.tif
[2]
airplane77.tif
[16]
airplane78.tif
[2]
airplane79.tif
[2]
airplane80.tif
</code>```

The val_accuracy is 90% but no one predict is correct.
This is the same for each class.

答: You forgot to rescale your image to be in range [0,1] at prediction time. Divide your images by 255 at test time. You have to do that because you specified rescale=1. / 255, in the ImageDataGenerator.

Title: Multiclass image recognition with Keras

Body:
i’m trying to build a network that recognize 21 classes.

The Data are in the Uc-merced.zip

This is the code:

# import

import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Model
from keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense, GlobalAveragePooling2D
from keras import backend as K
from keras import applications
from keras import optimizers
from keras import utils

I’m using Google Colab

%cd /content/drive/My Drive/
! unzip -q -n UCMerced_LandUse.zip
! echo 'Training folder content'
! ls -l ./UCMerced_LandUse/train/
! echo 'Validation folder content'
! ls -l ./UCMerced_LandUse/validation/

train_data_dir = 'UCMerced_LandUse/train/'
val_data_dir = 'UCMerced_LandUse/validation/'

### DATA GENERATOR
# get data from the folder, perform the preprocessing and the data augmentation,
# and arranges them in batches

# dimensions of our images
img_width, img_height = 256, 256

batch_size = 5

nb_train_samples = 1493
nb_val_samples = 622

# this is the preprocessing configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,     # rescale
    shear_range=0.2,      # on-th-fly data augmentation
    zoom_range=0.2,       # on-th-fly data augmentation
    horizontal_flip=True) # on-th-fly data augmentation

# this is the preprocessing configuration we will use for validation:
# rescaling only
val_datagen = ImageDataGenerator(rescale=1. / 255)

print('Training set generator:')
train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical'
   )

print('Validation set generator:')
val_generator = val_datagen.flow_from_directory(
    val_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

This is the output:

Training set generator:
Found 1493 images belonging to 21 classes.
Validation set generator:
Found 622 images belonging to 21 classes.

# Inception V3 with pre-trained weights
base_model = applications.InceptionV3(weights='imagenet', include_top=False,input_shape=(256,256,3),classes=21)
train_after_layer =50 #

### CHANGE THE TOP MODEL BLOCK

x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(21, activation='softmax')(x)

model = Model(inputs=base_model.input, outputs=x)

# set the first K layers (up to the last conv block)
# to non-trainable (weights will not change during training)
for layer in model.layers[:train_after_layer]:
    layer.trainable = False

# compile the model with a SGD/momentum optimizer
# and a very slow learning rate.
model.compile(loss='categorical_crossentropy',
              optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
              metrics=['accuracy'])

epochs_fine = 50

history=model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs_fine,
    validation_data=val_generator,
    validation_steps=nb_val_samples // batch_size)

model.save_weights('prova.h5')

The results seems to be pretty god, at the end of 50epoch this is the result:

loss: 0.0866 - accuracy: 0.9845 - val_loss: 0.6575 - val_accuracy: 0.9028

from keras.preprocessing import image
import os

model.load_weights('prova.h5')

path = '/content/drive/My Drive/UCMerced_LandUse/validation/airplane'
dirs = os.listdir( path )

print(train_generator.class_indices)

for file in dirs:
  print(file)
  string=os.path.join(path,file)
  img_pred=image.load_img(string,target_size=(256,256,3))
  img_pred=image.img_to_array(img_pred)
  img_pred=np.expand_dims(img_pred,axis=0)
  array=model.predict(img_pred)
  y_classes = array.argmax(axis=-1)
  print(y_classes)

This is the output:

{'agricultural': 0, 'airplane': 1, 'baseballdiamond': 2, 'beach': 3, 'buildings': 4, 'chaparral': 5, 'denseresidential': 6, 'forest': 7, 'freeway': 8, 'golfcourse': 9, 'harbor': 10, 'intersection': 11, 'mediumresidential': 12, 'mobilehomepark': 13, 'overpass': 14, 'parkinglot': 15, 'river': 16, 'runway': 17, 'sparseresidential': 18, 'storagetanks': 19, 'tenniscourt': 20}

airplane71.tif
[3]
airplane72.tif
[16]
airplane73.tif
[2]
airplane74.tif
[16]
airplane75.tif
[2]
airplane76.tif
[2]
airplane77.tif
[16]
airplane78.tif
[2]
airplane79.tif
[2]
airplane80.tif

The val_accuracy is 90% but no one predict is correct.
This is the same for each class.


问:
Django model's save method is not called when creating objects in test
I am trying to test one of my application's model Book that has a slug field. I have a custom save function for it, like below.

models.py

class Book(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(self.title, allow_unicode=True)

        return super(Book, self).save(*args, **kwargs)

```

<p>To test this, I created the following <strong>test.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class BookModelTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        Book.objects.create(title="Book One")

    def test_get_absolute_url(self):
        book = Book.objects.get(pk=1)
        self.assertEquals(book.get_absolute_url(), '/books/book-one/')
</code>```

But when I run the test, it fails with django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$'].

Traceback

```<code>Traceback (most recent call last):
  File "Bookman/bookman/bms/tests/test_models.py", line 14, in test_get_absolute_url
    self.assertEquals(book.get_absolute_url(), '/books/book-one/')
  File "Bookman/bookman/bms/models.py", line 26, in get_absolute_url
    return reverse('book-detail', args=[str(self.slug)])
  File "Bookman/venv/lib/python3.8/site-packages/django/urls/base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "Bookman/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 677, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$']
</code>```

Why is slug empty? Why is the save method not called? What am I missing?

答:
Unintended mistake in your save method. You should use self.slug to assign the value to the object's slug like:

```<code>def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(self.title, allow_unicode=True)

    return super(Book, self).save(*args, **kwargs)
</code>```

Body:
I am trying to test one of my application's model Book that has a slug field. I have a custom save function for it, like below.

models.py

class Book(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(self.title, allow_unicode=True)

        return super(Book, self).save(*args, **kwargs)

To test this, I created the following test.py

class BookModelTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        Book.objects.create(title="Book One")

    def test_get_absolute_url(self):
        book = Book.objects.get(pk=1)
        self.assertEquals(book.get_absolute_url(), '/books/book-one/')

But when I run the test, it fails with django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$'].

Traceback

Traceback (most recent call last):
  File "Bookman/bookman/bms/tests/test_models.py", line 14, in test_get_absolute_url
    self.assertEquals(book.get_absolute_url(), '/books/book-one/')
  File "Bookman/bookman/bms/models.py", line 26, in get_absolute_url
    return reverse('book-detail', args=[str(self.slug)])
  File "Bookman/venv/lib/python3.8/site-packages/django/urls/base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "Bookman/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 677, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$']

Why is slug empty? Why is the save method not called? What am I missing?

Body:
Unintended mistake in your save method. You should use self.slug to assign the value to the object's slug like:

def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(self.title, allow_unicode=True)

    return super(Book, self).save(*args, **kwargs)


问:
Handling null in ReactJS
I have table, filling from Web - Api.

When I am deleting department, linked to some user. Department object getting null. And I have crash of my react app with such error: TypeError: Cannot read property 'name' of null

I've tried ternary like that, but it didn't help

```<code>(typeof user !=='undefined' && typeof user.department.name !=='undefined') ? user.department.name : ''
</code>```

  refreshList()
    {
       fetch("https://localhost:5001/api/users")
       .then(response=> response.json())
       .then(data=> {
        this.setState({users:data});
       });
    }

render(){
        const {users, userid, username, userfullname, department} = this.state;
        return(

           {users.map(user=>

               {user.id}
               {user.userName}
               {user.fullName}
               {user.department.name}	  <---- here i am getting crash when department is null

               ....
               )```

答:
You need to just validate is the property of the object is undefined or not.</p>

```<code><td>
    {user.department ? user.department.name ? user.department.name :null :null}
</td>
</code>```

Title: Handling null in ReactJS

Body:
I have table, filling from Web - Api.

When I am deleting department, linked to some user. Department object getting null. And I have crash of my react app with such error: TypeError: Cannot read property 'name' of null

I've tried ternary like that, but it didn't help

(typeof user !=='undefined' && typeof user.department.name !=='undefined') ? user.department.name : ''

  refreshList()
    {
       fetch("https://localhost:5001/api/users")
       .then(response=> response.json())
       .then(data=> {
        this.setState({users:data});
       });
    }

render(){
        const {users, userid, username, userfullname, department} = this.state;
        return(

           {users.map(user=>

               {user.id}
               {user.userName}
               {user.fullName}
               {user.department.name}	  <---- here i am getting crash when department is null

               ....
               )

Body:
You need to just validate is the property of the object is undefined or not.

<td>
    {user.department ? user.department.name ? user.department.name :null :null}
</td>


问:
Loading data to a String Array from a String holding the array data in java Android Studio
I actually have a String that contains the format of String array. And I want to load that string data into the array.

```<code>String data = "{"Sam" , "14","USA","7th"}";
</code>```

and the String Array

```<code>String loaded_data[][];
</code>```

Thanks in advance...

答:
I think this is what you wanted.

Using String.split() splits the string into an string array with , regex.

```<code>    public void something() {
        String data = "{'Sam' , '14','USA','7th'}";

        data = data.substring(1, data.length() - 1); //Ignores curly brackets
        data = data.replaceAll("'", ""); //Removes apostrophes
        data = data.replaceAll(" ", ""); //Removes whitespace

        String[] loadedData = data.split(","); //Splits string -> string[]

        System.out.println(Arrays.toString(loadedData));
    }
</code>```

println:

```<code>[Sam, 14, USA, 7th]
</code>```

Body:
I actually have a String that contains the format of String array. And I want to load that string data into the array.

String data = "{"Sam" , "14","USA","7th"}";

and the String Array

String loaded_data[][];

Thanks in advance...

Body:
I think this is what you wanted.

Using String.split() splits the string into an string array with , regex.

    public void something() {
        String data = "{'Sam' , '14','USA','7th'}";

        data = data.substring(1, data.length() - 1); //Ignores curly brackets
        data = data.replaceAll("'", ""); //Removes apostrophes
        data = data.replaceAll(" ", ""); //Removes whitespace

        String[] loadedData = data.split(","); //Splits string -> string[]

        System.out.println(Arrays.toString(loadedData));
    }

println:

[Sam, 14, USA, 7th]


问:
Error: Client network socket disconnected before secure TLS connection was established
```<code>Error
Client network socket disconnected before secure TLS connection was established
ECONNRESET
</code>```

I keep running in to this error while using TLS.connect().
I am able to connect using a browser.
Using Node.js v14

答:
I had failed to notice that the server is using Server Name Indication (SNI).

To fix this I needed to specify the servername option.

Body:
Error
Client network socket disconnected before secure TLS connection was established
ECONNRESET

I keep running in to this error while using TLS.connect().
I am able to connect using a browser.
Using Node.js v14


问:
Boolean statement logic not correct
I have the following code:

```<code>if (date.datetime.today().weekday == 5) or (date.datetime.today().weekday == 6):
     print('True')
</code>```

What i am trying to do here is that the if statement should be true if today is saturday or sunday.
The output is false even though today is Sunday. Why is this not True?

答:
A quick working example, weekday is a method, you have to call it.</p>

```<code>from datetime import date

if (date.today().weekday() == 5) or (date.today().weekday() == 6):
     print('True')
</code>```

Title: Boolean statement logic not correct

Body:
I have the following code:

if (date.datetime.today().weekday == 5) or (date.datetime.today().weekday == 6):
     print('True')

What i am trying to do here is that the if statement should be true if today is saturday or sunday.
The output is false even though today is Sunday. Why is this not True?

Body:
A quick working example, weekday is a method, you have to call it.

from datetime import date

if (date.today().weekday() == 5) or (date.today().weekday() == 6):
     print('True')


问:
C# - pass on variable amount of parameters to other method within a method
I know the title is a little bit tricky to understand, but the following example should clarify what I mean:

Imagine you have a method with 2 overloads:

```<code>void Method(int i)
{
    Console.WriteLine("Method(int) called");
}

void Method(int i, string s)
{
    Console.WriteLine("Method(int, string) called");
}
</code>```

Then you have another method that takes a variable amount of parameters:

```<code>void MethodOverload(params dynamic[] parameters)
{
    Method(parameters); // Call one of the overloading methods depending on the parameter amount and their type
}
</code>```

The method above accepts any amount of parameters with any type. I want to call one of the overloading methods depending on the amount of passed parameters and their type.

For example:

```<code>void Run()
{
    TestFuncOverload(5);                 // Output: "testFunc(int) called"
    TestFuncOverload(5, "some text");    // Output: "testFunc(int, string) called"

    TestFuncOverload(5, 5);              //Error
}
</code>```

How does one achieve this in C#?

答: You'll need to use Reflection and call the method by Invoke. </p>

Body:
I know the title is a little bit tricky to understand, but the following example should clarify what I mean:

Imagine you have a method with 2 overloads:

void Method(int i)
{
    Console.WriteLine("Method(int) called");
}

void Method(int i, string s)
{
    Console.WriteLine("Method(int, string) called");
}

Then you have another method that takes a variable amount of parameters:

void MethodOverload(params dynamic[] parameters)
{
    Method(parameters); // Call one of the overloading methods depending on the parameter amount and their type
}

The method above accepts any amount of parameters with any type. I want to call one of the overloading methods depending on the amount of passed parameters and their type.

For example:

void Run()
{
    TestFuncOverload(5);                 // Output: "testFunc(int) called"
    TestFuncOverload(5, "some text");    // Output: "testFunc(int, string) called"

    TestFuncOverload(5, 5);              //Error
}

How does one achieve this in C#?


问:
Why cant Routing Information Protocol RIP (distance-vector routing protocol) use Dijkstra instead of bellman ford?
Hello I am learning networking and am confused about why both the interior routing protocols (RIP and OSPF) use the same algorithm to calculate the shortest path? I think I understand how they differ (RIP and OSPF) but am not clear on using a different algorithm for calculating the shortest path?</p>

答:
RIP was invented a long time before OSPF and for that reason it uses a much simpler algorithm (distance vector) than OSPF (Dijkstra).

Distance vector is much simpler than Dijkstra because it only needs local information from the direct neighbors, whereas Dijkstra requires knowledge of the topology of the entire network.


问:
how should I set "scopes" when creating ServiceAccountCredential FromServiceAccountData
I need to set the credentials scope to access some APIs
my code is like that

```<code>ServiceAccountCredential saCredential;
        using (var fs = new FileStream(@"C:\work\ConsoleApp2\google_credentials\foo.json", FileMode.Open, FileAccess.Read))
        {
            saCredential = ServiceAccountCredential.FromServiceAccountData(fs);

        }

        //saCredential.Scopes = new List<string> { "" };
        var accessToken = saCredential.GetAccessTokenForRequestAsync().Result;
</code>```

how can I set the scopes? now I get

TokenResponseException: Error:"invalid_scope", Description:"Invalid OAuth scope or ID token audience provided.",

the Scopes property is read-only

答:
I succeeded to do it like that</p>

```<code>GoogleCredential credential = GoogleCredential.GetApplicationDefault();
        credential = credential.CreateScoped(new List<string>() { "https://www.googleapis.com/auth/compute" });
        var dataflowService = new DataflowService(new Google.Apis.Services.BaseClientService.Initializer()
        {
            HttpClientInitializer = credential
        });
</code>```

Body:
I need to set the credentials scope to access some APIs
my code is like that

ServiceAccountCredential saCredential;
        using (var fs = new FileStream(@"C:\work\ConsoleApp2\google_credentials\foo.json", FileMode.Open, FileAccess.Read))
        {
            saCredential = ServiceAccountCredential.FromServiceAccountData(fs);

        }

        //saCredential.Scopes = new List<string> { "" };
        var accessToken = saCredential.GetAccessTokenForRequestAsync().Result;

how can I set the scopes? now I get

TokenResponseException: Error:"invalid_scope", Description:"Invalid OAuth scope or ID token audience provided.",

the Scopes property is read-only

Body:
I succeeded to do it like that

GoogleCredential credential = GoogleCredential.GetApplicationDefault();
        credential = credential.CreateScoped(new List<string>() { "https://www.googleapis.com/auth/compute" });
        var dataflowService = new DataflowService(new Google.Apis.Services.BaseClientService.Initializer()
        {
            HttpClientInitializer = credential
        });


答:
The weekday must be followed by (), otherwise you are making a built in method object.

```<code>if (date.datetime.today().weekday() == 5) or (date.datetime.today().weekday() == 6):
     print('True')
</code>```

Title: Boolean statement logic not correct

Body:
The weekday must be followed by (), otherwise you are making a built in method object.

if (date.datetime.today().weekday() == 5) or (date.datetime.today().weekday() == 6):
     print('True')


问:
How can I create a column with incremented values from a column with cumulated values in MySQL?
Table1 contains a column with cumulated values (all positive integers):

```<code>id ValuesCum
1  5
2  8
3  20
</code>```

I would like to write a statement that returns an extra column with the incremented values for each row. The output should read something like:

```<code>id ValuesCum ValuesInc
1  5         (5)
2  8         3
3  20        12
</code>```

Does anyone have a solution for this?

答:
If you are running MySQL 8.0, you can use window function lag() for this:

```<code>select
    t.*,
    ValuesCum - lag(ValuesCum, 1, 0) over(order by id) ValuesInc
from mytable t
</code>```

In earlier versions, an alternative is a correlated subquery:

```<code>select
    t.*,
    ValuesCum - (
        select coalesce(max(t1.ValuesCum), 0)
        from mytable t1
        where t1.id < t.id
    ) ValuesInc

from mytable t
</code>```

Body:
Table1 contains a column with cumulated values (all positive integers):

id ValuesCum
1  5
2  8
3  20

I would like to write a statement that returns an extra column with the incremented values for each row. The output should read something like:

id ValuesCum ValuesInc
1  5         (5)
2  8         3
3  20        12

Does anyone have a solution for this?

Body:
If you are running MySQL 8.0, you can use window function lag() for this:

select
    t.*,
    ValuesCum - lag(ValuesCum, 1, 0) over(order by id) ValuesInc
from mytable t

In earlier versions, an alternative is a correlated subquery:

select
    t.*,
    ValuesCum - (
        select coalesce(max(t1.ValuesCum), 0)
        from mytable t1
        where t1.id < t.id
    ) ValuesInc

from mytable t


问:
Mongoose: how to automatically remove old entries form an array?
I have a messaging app, that can display messages threads. In order not to bother with pagination, endless api calls and performance issues, I would like to automatically delete messages older than x days in an array in order to keep a small a amount of data.

How to do it? If it is not possible, how to automatically remove the oldest element from an array if it already has 50 elements while trying to push a new message? I could do it with native javascript, but maybe there is a cleaner way?

const mongoose = require("mongoose");

const conversationSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, unique: true },
    messages: [{ message: { type: String }, authorId: { type: String } }],
    lastMessage: {
      authorId: { type: String },
      snippet: { type: String },
      read: { type: Boolean },
    },
  },
  { timestamps: true }
);

conversationSchema.index({ name: 1 });

module.exports = mongoose.model("Conversation", conversationSchema);```

答:
The $slice operator allows $pushing to an array and then limiting that array's length:

```<code>db.messageChannels.update(
   { _id: myMessageChannelId },
   {
     $push: {
       messages: {
         $each: [ "Hello world!" ],
         $slice: -50
       }
     }
   }
)

</code>```

Similarly, on an update, you can use $pull to remove any messages that match a criteria (in this case, the criteria would be being older than X days). This won't automatically expire these messages if nobody is using the channel (which you could automatically handle by deleting the whole channel if you track a lastMessageDate on your whole channel using a TTL index).

```<code>db.messageChannels.updateOne(
    { _id: myMessageChannelId },
    { $pull: { messages: { sentAt: {$lte: expirationDate} }, $push: {messages: "Hello world!"} },
)
</code>```

To expire all, you can run a query like the below on a cron:

```<code>db.messageChannels.update(
    { },
    { $pull: { messages: { sentAt: {$lte: expirationDate} } },
    { multi: true }
)
</code>```

TTL indexes apply to the whole document so aren't workable, unless you group your messages by day or something similar.

Body:
The $slice operator allows $pushing to an array and then limiting that array's length:

db.messageChannels.update(
   { _id: myMessageChannelId },
   {
     $push: {
       messages: {
         $each: [ "Hello world!" ],
         $slice: -50
       }
     }
   }
)

Similarly, on an update, you can use $pull to remove any messages that match a criteria (in this case, the criteria would be being older than X days). This won't automatically expire these messages if nobody is using the channel (which you could automatically handle by deleting the whole channel if you track a lastMessageDate on your whole channel using a TTL index).

db.messageChannels.updateOne(
    { _id: myMessageChannelId },
    { $pull: { messages: { sentAt: {$lte: expirationDate} }, $push: {messages: "Hello world!"} },
)

To expire all, you can run a query like the below on a cron:

db.messageChannels.update(
    { },
    { $pull: { messages: { sentAt: {$lte: expirationDate} } },
    { multi: true }
)

TTL indexes apply to the whole document so aren't workable, unless you group your messages by day or something similar.


问:
Can't make Stack of Widgets clickable after exporting Widget from Adobe XD
I want to add one widget I've exported from Adobe XD to ListView.separated and in that widget I want two places to be clickable, however I cannot completely understand where should I put InkWell() or GestureDetector() or maybe another widget to make two places clickable
Here is the code:

```<code>import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          margin: EdgeInsets.only(
            top: 30.0,
          ),
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    SizedBox(
                      width: 100.0,
                      child: Text(
                        'Logout',
                        textAlign: TextAlign.center,
                        textScaleFactor: 1.0,
                        style: TextStyle(
                          color: Colors.blueGrey,
                          fontSize: 22.0,
                          fontWeight: FontWeight.w300,
                        ),
                      ),
                    ),
                    Image.asset(
                      'assets/call_info_logo.png',
                      width: 60.0,
                    ),
                    Row(
                      children: <Widget>[
                        SizedBox(
                          width: 100.0,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Image.asset(
                                'assets/support.png',
                                width: 55.0,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Flexible(
                child: Container(
                  margin: EdgeInsets.only(top: 55.0),
                  child: ListView.separated(
                    padding: EdgeInsets.only(
                      left: 30.0,
                      right: 30.0,
                      bottom: 30.0,
                    ),
                    itemCount: 6,
                    separatorBuilder: (context, index) => SizedBox(
                      height: 40.0,
                    ),
                    itemBuilder: (context, index) => Stack(
                      children: <Widget>[
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(85.0, 259.0),
                                child: SvgPicture.string(
                                  _svg_chij22,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                              Transform.translate(
                                offset: Offset(-7.0, 139.0),
                                child: Stack(
                                  children: <Widget>[
                                    Transform.translate(
                                      offset: Offset(102.0, 132.0),
                                      child: SizedBox(
                                        width: 171.0,
                                        height: 57.0,
                                        child: SingleChildScrollView(
                                            child: Text(
                                          'г. Нур-Султан, ул.  Кордай, д.2, под.4 ',
                                          style: TextStyle(
                                            fontFamily: 'Bahnschrift',
                                            fontSize: 18,
                                            color: const Color(0xffffffff),
                                          ),
                                          textAlign: TextAlign.center,
                                        )),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(281.0, 259.0),
                                child: SvgPicture.string(
                                  _svg_fep8be,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(21.0, 259.0),
                                child: Container(
                                  width: 61.0,
                                  height: 80.0,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(25.0),
                                      bottomLeft: Radius.circular(25.0),
                                    ),
                                    color: const Color(0xffcfdb24),
                                  ),
                                ),
                              ),
                              Transform.translate(
                                offset: Offset(37.0, 280.0),
                                child:
                                    // Adobe XD layer: 'Icon awesome-file-v…' (shape)
                                    SvgPicture.string(
                                  _svg_xqnie9,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

const String _svg_chij22 =
    '<svg viewBox="85.0 259.0 193.0 80.0" ><path transform="translate(85.0, 259.0)" d="M 0 0 L 193 0 L 193 80 L 0 80 L 0 0 Z" fill="#2a7ac6" fill-opacity="0.85" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_fep8be =
    '<svg viewBox="281.0 259.0 61.0 80.0" ><path transform="matrix(-1.0, 0.0, 0.0, -1.0, 342.0, 339.0)" d="M 25 0 L 60 0 C 60.55228424072266 0 61 0.4477152228355408 61 1 L 61 79 C 61 79.55228424072266 60.55228424072266 80 60 80 L 25 80 C 11.19288063049316 80 0 68.80712127685547 0 55 L 0 25 C 0 11.19288063049316 11.19288063049316 0 25 0 Z" fill="#16cf2f" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(295.0, 276.0)" d="M 29.01785659790039 20.07470893859863 L 11.0267858505249 20.07470893859863 L 11.0267858505249 11.98993682861328 C 11.0267858505249 8.884631156921387 13.32645130157471 6.304718494415283 16.19921875 6.273351669311523 C 19.10100364685059 6.241985321044922 21.47321510314941 8.790531158447266 21.47321510314941 11.91936206817627 L 21.47321510314941 13.17403030395508 C 21.47321510314941 14.21697330474854 22.24944305419922 15.05603408813477 23.21428489685059 15.05603408813477 L 25.53571510314941 15.05603408813477 C 26.50055694580078 15.05603408813477 27.27678489685059 14.21697330474854 27.27678489685059 13.17403030395508 L 27.27678489685059 11.91936206817627 C 27.27678489685059 5.332350254058838 22.3074779510498 -0.02351734600961208 16.2137279510498 7.694517080381047e-06 C 10.1199779510498 0.02353273518383503 5.223214149475098 5.449975490570068 5.223214149475098 12.0369873046875 L 5.223214149475098 20.07470893859863 L 3.482142925262451 20.07470893859863 C 1.559709787368774 20.07470893859863 0 21.76066970825195 0 23.83871650695801 L 0 36.38540267944336 C 0 38.46344757080078 1.559709787368774 40.14941024780273 3.482142925262451 40.14941024780273 L 29.01785659790039 40.14941024780273 C 30.9402904510498 40.14941024780273 32.5 38.46344757080078 32.5 36.38540267944336 L 32.5 23.83871650695801 C 32.5 21.76066970825195 30.9402904510498 20.07470893859863 29.01785659790039 20.07470893859863 Z" fill="#ffffff" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_xqnie9 =
    '<svg viewBox="37.0 280.0 30.0 39.0" ><path transform="translate(37.0, 280.0)" d="M 29.99999809265137 9.288474082946777 L 29.99999809265137 9.75 L 19.99999809265137 9.75 L 19.99999809265137 0 L 20.47335815429688 0 C 20.97062301635742 0 21.44757461547852 0.1926386654376984 21.79921913146973 0.535412073135376 L 29.45085716247559 7.995761394500732 C 29.80244445800781 8.338640213012695 29.99996948242188 8.803627014160156 29.9999942779541 9.288474082946777 Z M 17.49999618530273 10.359375 L 17.49999618530273 0 L 1.87499988079071 0 C 0.8394531011581421 0 0 0.8184667825698853 0 1.828125 L 0 37.171875 C 0 38.18153381347656 0.8394531011581421 39 1.87499988079071 39 L 28.12499809265137 39 C 29.16054344177246 39 29.99999809265137 38.18153381347656 29.99999809265137 37.171875 L 29.99999809265137 12.1875 L 19.37499618530273 12.1875 C 18.34374809265137 12.1875 17.49999618530273 11.36484432220459 17.49999618530273 10.359375 Z M 24.99999618530273 21.329345703125 L 24.99999618530273 29.8577766418457 C 24.99999618530273 31.49127960205078 22.97320175170898 32.29512405395508 21.79913711547852 31.15048980712891 L 17.49999618530273 26.96035003662109 L 17.49999618530273 29.859375 C 17.49999618530273 30.86903190612793 16.66054725646973 31.6875 15.62499904632568 31.6875 L 6.874999523162842 31.6875 C 5.839452743530273 31.6875 4.999999523162842 30.86903190612793 4.999999523162842 29.859375 L 4.999999523162842 21.328125 C 4.999999523162842 20.31846809387207 5.839452743530273 19.5 6.874999523162842 19.5 L 15.62499904632568 19.5 C 16.66054725646973 19.5 17.49999618530273 20.31846809387207 17.49999618530273 21.328125 L 17.49999618530273 24.22715187072754 L 21.79913711547852 20.03670692443848 C 22.97187042236328 18.89336776733398 24.99999618530273 19.69462013244629 24.99999618530273 21.329345703125 Z" fill="#ffffff" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
</code>```

I want to make these two buttons clickable

答:
just wrap the widget either with GestureDetector or InkWell which needs to accept user's tap.

e.g. you can wrap your widget with GestureDetector it will provide you a onTap delegate.

```<code>                  GestureDetector(
                  onTap: () {print('Hi') }
                      child:
                        SizedBox(
                          width: 100.0,
                          child: Text(
                            'Logout',
                            textAlign: TextAlign.center,
                            textScaleFactor: 1.0,
                             style: TextStyle(
                              color: Colors.blueGrey,
                              fontSize: 22.0,
                              fontWeight: FontWeight.w300,
                            ),
                          ),
                        ),)
</code>```

Body:
I want to add one widget I've exported from Adobe XD to ListView.separated and in that widget I want two places to be clickable, however I cannot completely understand where should I put InkWell() or GestureDetector() or maybe another widget to make two places clickable
Here is the code:

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          margin: EdgeInsets.only(
            top: 30.0,
          ),
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    SizedBox(
                      width: 100.0,
                      child: Text(
                        'Logout',
                        textAlign: TextAlign.center,
                        textScaleFactor: 1.0,
                        style: TextStyle(
                          color: Colors.blueGrey,
                          fontSize: 22.0,
                          fontWeight: FontWeight.w300,
                        ),
                      ),
                    ),
                    Image.asset(
                      'assets/call_info_logo.png',
                      width: 60.0,
                    ),
                    Row(
                      children: <Widget>[
                        SizedBox(
                          width: 100.0,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Image.asset(
                                'assets/support.png',
                                width: 55.0,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Flexible(
                child: Container(
                  margin: EdgeInsets.only(top: 55.0),
                  child: ListView.separated(
                    padding: EdgeInsets.only(
                      left: 30.0,
                      right: 30.0,
                      bottom: 30.0,
                    ),
                    itemCount: 6,
                    separatorBuilder: (context, index) => SizedBox(
                      height: 40.0,
                    ),
                    itemBuilder: (context, index) => Stack(
                      children: <Widget>[
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(85.0, 259.0),
                                child: SvgPicture.string(
                                  _svg_chij22,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                              Transform.translate(
                                offset: Offset(-7.0, 139.0),
                                child: Stack(
                                  children: <Widget>[
                                    Transform.translate(
                                      offset: Offset(102.0, 132.0),
                                      child: SizedBox(
                                        width: 171.0,
                                        height: 57.0,
                                        child: SingleChildScrollView(
                                            child: Text(
                                          'г. Нур-Султан, ул.  Кордай, д.2, под.4 ',
                                          style: TextStyle(
                                            fontFamily: 'Bahnschrift',
                                            fontSize: 18,
                                            color: const Color(0xffffffff),
                                          ),
                                          textAlign: TextAlign.center,
                                        )),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(281.0, 259.0),
                                child: SvgPicture.string(
                                  _svg_fep8be,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Transform.translate(
                          offset: Offset(-21.0, -259.0),
                          child: Stack(
                            children: <Widget>[
                              Transform.translate(
                                offset: Offset(21.0, 259.0),
                                child: Container(
                                  width: 61.0,
                                  height: 80.0,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(25.0),
                                      bottomLeft: Radius.circular(25.0),
                                    ),
                                    color: const Color(0xffcfdb24),
                                  ),
                                ),
                              ),
                              Transform.translate(
                                offset: Offset(37.0, 280.0),
                                child:
                                    // Adobe XD layer: 'Icon awesome-file-v…' (shape)
                                    SvgPicture.string(
                                  _svg_xqnie9,
                                  allowDrawingOutsideViewBox: true,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

const String _svg_chij22 =
    '<svg viewBox="85.0 259.0 193.0 80.0" ><path transform="translate(85.0, 259.0)" d="M 0 0 L 193 0 L 193 80 L 0 80 L 0 0 Z" fill="#2a7ac6" fill-opacity="0.85" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_fep8be =
    '<svg viewBox="281.0 259.0 61.0 80.0" ><path transform="matrix(-1.0, 0.0, 0.0, -1.0, 342.0, 339.0)" d="M 25 0 L 60 0 C 60.55228424072266 0 61 0.4477152228355408 61 1 L 61 79 C 61 79.55228424072266 60.55228424072266 80 60 80 L 25 80 C 11.19288063049316 80 0 68.80712127685547 0 55 L 0 25 C 0 11.19288063049316 11.19288063049316 0 25 0 Z" fill="#16cf2f" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(295.0, 276.0)" d="M 29.01785659790039 20.07470893859863 L 11.0267858505249 20.07470893859863 L 11.0267858505249 11.98993682861328 C 11.0267858505249 8.884631156921387 13.32645130157471 6.304718494415283 16.19921875 6.273351669311523 C 19.10100364685059 6.241985321044922 21.47321510314941 8.790531158447266 21.47321510314941 11.91936206817627 L 21.47321510314941 13.17403030395508 C 21.47321510314941 14.21697330474854 22.24944305419922 15.05603408813477 23.21428489685059 15.05603408813477 L 25.53571510314941 15.05603408813477 C 26.50055694580078 15.05603408813477 27.27678489685059 14.21697330474854 27.27678489685059 13.17403030395508 L 27.27678489685059 11.91936206817627 C 27.27678489685059 5.332350254058838 22.3074779510498 -0.02351734600961208 16.2137279510498 7.694517080381047e-06 C 10.1199779510498 0.02353273518383503 5.223214149475098 5.449975490570068 5.223214149475098 12.0369873046875 L 5.223214149475098 20.07470893859863 L 3.482142925262451 20.07470893859863 C 1.559709787368774 20.07470893859863 0 21.76066970825195 0 23.83871650695801 L 0 36.38540267944336 C 0 38.46344757080078 1.559709787368774 40.14941024780273 3.482142925262451 40.14941024780273 L 29.01785659790039 40.14941024780273 C 30.9402904510498 40.14941024780273 32.5 38.46344757080078 32.5 36.38540267944336 L 32.5 23.83871650695801 C 32.5 21.76066970825195 30.9402904510498 20.07470893859863 29.01785659790039 20.07470893859863 Z" fill="#ffffff" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';
const String _svg_xqnie9 =
    '<svg viewBox="37.0 280.0 30.0 39.0" ><path transform="translate(37.0, 280.0)" d="M 29.99999809265137 9.288474082946777 L 29.99999809265137 9.75 L 19.99999809265137 9.75 L 19.99999809265137 0 L 20.47335815429688 0 C 20.97062301635742 0 21.44757461547852 0.1926386654376984 21.79921913146973 0.535412073135376 L 29.45085716247559 7.995761394500732 C 29.80244445800781 8.338640213012695 29.99996948242188 8.803627014160156 29.9999942779541 9.288474082946777 Z M 17.49999618530273 10.359375 L 17.49999618530273 0 L 1.87499988079071 0 C 0.8394531011581421 0 0 0.8184667825698853 0 1.828125 L 0 37.171875 C 0 38.18153381347656 0.8394531011581421 39 1.87499988079071 39 L 28.12499809265137 39 C 29.16054344177246 39 29.99999809265137 38.18153381347656 29.99999809265137 37.171875 L 29.99999809265137 12.1875 L 19.37499618530273 12.1875 C 18.34374809265137 12.1875 17.49999618530273 11.36484432220459 17.49999618530273 10.359375 Z M 24.99999618530273 21.329345703125 L 24.99999618530273 29.8577766418457 C 24.99999618530273 31.49127960205078 22.97320175170898 32.29512405395508 21.79913711547852 31.15048980712891 L 17.49999618530273 26.96035003662109 L 17.49999618530273 29.859375 C 17.49999618530273 30.86903190612793 16.66054725646973 31.6875 15.62499904632568 31.6875 L 6.874999523162842 31.6875 C 5.839452743530273 31.6875 4.999999523162842 30.86903190612793 4.999999523162842 29.859375 L 4.999999523162842 21.328125 C 4.999999523162842 20.31846809387207 5.839452743530273 19.5 6.874999523162842 19.5 L 15.62499904632568 19.5 C 16.66054725646973 19.5 17.49999618530273 20.31846809387207 17.49999618530273 21.328125 L 17.49999618530273 24.22715187072754 L 21.79913711547852 20.03670692443848 C 22.97187042236328 18.89336776733398 24.99999618530273 19.69462013244629 24.99999618530273 21.329345703125 Z" fill="#ffffff" stroke="none" stroke-width="1" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';

I want to make these two buttons clickable

Body:
just wrap the widget either with GestureDetector or InkWell which needs to accept user's tap.

e.g. you can wrap your widget with GestureDetector it will provide you a onTap delegate.

                  GestureDetector(
                  onTap: () {print('Hi') }
                      child:
                        SizedBox(
                          width: 100.0,
                          child: Text(
                            'Logout',
                            textAlign: TextAlign.center,
                            textScaleFactor: 1.0,
                             style: TextStyle(
                              color: Colors.blueGrey,
                              fontSize: 22.0,
                              fontWeight: FontWeight.w300,
                            ),
                          ),
                        ),)