问:
How to write multiple variables inside a multiple-line string variable?
I'm trying to make a simple script to be able to print every fonts to a css @font-face

So for every fonts inside a specific directory it should print:

```<code>@font-face {
  font-family: "fontName1", sans-serif;
  src: url("http://localhost/wp-content/themes/theme/fonts/fontName1.ttf");
  font-weight: normal;
}

@font-face {
  font-family: "fontName2", sans-serif;
  src: url("http://localhost/wp-content/themes/theme/fonts/fontName2.ttf");
  font-weight: normal;
}
</code>```

etc...

Now, this is what I tried:

import glob

fontFiles = []

for file in glob.glob("*.ttf"):
    cssRule = """
        @font-face {
            font-family: "{fontName}", sans-serif;
            src: url("http://localhost/wp-content/themes/theme/fonts/{fontFile}");
            font-weight: normal;
        }
    """.format(fontName=file[:-4], fontFile=file)
    print(cssRule)
```

<p>I get the following error when running the script:</p>

```Traceback (most recent call last File ".\script.py", line 6, in <cssRule = KeyError: '\n            font-family'
```

I don't know what I'm doing wrong? Is this because of the format inside my python script? What is the best way to write multiple variables inside a multiple-line string variable?

答:
Enclose in double brace's, this is to espace brace character inside string literal, string_formatting

```<code>for file in glob.glob("*.ttf"):
    cssRule = """
        @font-face {{
            font-family: "{fontName}", sans-serif;
            src: url("http://localhost/wp-content/themes/theme/fonts/{fontFile}");
            font-weight: normal;
        }}
    """.format(fontName=file[:-4], fontFile=file)
    print(cssRule)
</code>```

Body:
I'm trying to make a simple script to be able to print every fonts to a css @font-face

So for every fonts inside a specific directory it should print:

@font-face {
  font-family: "fontName1", sans-serif;
  src: url("http://localhost/wp-content/themes/theme/fonts/fontName1.ttf");
  font-weight: normal;
}

@font-face {
  font-family: "fontName2", sans-serif;
  src: url("http://localhost/wp-content/themes/theme/fonts/fontName2.ttf");
  font-weight: normal;
}

etc...

Now, this is what I tried:

import glob

fontFiles = []

for file in glob.glob("*.ttf"):
    cssRule = """
        @font-face {
            font-family: "{fontName}", sans-serif;
            src: url("http://localhost/wp-content/themes/theme/fonts/{fontFile}");
            font-weight: normal;
        }
    """.format(fontName=file[:-4], fontFile=file)
    print(cssRule)

I get the following error when running the script:

Traceback (most recent call last File ".\script.py", line 6, in <cssRule = KeyError: '\n            font-family'

I don't know what I'm doing wrong? Is this because of the format inside my python script? What is the best way to write multiple variables inside a multiple-line string variable?

Body:
Enclose in double brace's, this is to espace brace character inside string literal, string_formatting

for file in glob.glob("*.ttf"):
    cssRule = """
        @font-face {{
            font-family: "{fontName}", sans-serif;
            src: url("http://localhost/wp-content/themes/theme/fonts/{fontFile}");
            font-weight: normal;
        }}
    """.format(fontName=file[:-4], fontFile=file)
    print(cssRule)


来源: stackexchange

问:
How do I place a Google recaptcha in my website successfully?
I am having real trouble putting a Google recaptcha into my website. There seems to be no easy to follow tutorial. I am brand new to JavaScript, but am building a website which receives a huge amount of spam from the contact form. I'd like a Google recaptcha form, possibly v2 as that seems the 'easiest' but I am still having issues.

I have PHP, JS and HTML and I am not understanding how any of it links, and it is not working. The form submits successfully, however, there is no way of telling the form has submitted, nothing happens on the page. I would like a Bootstrap success alert to take place when I press submit.

Here is the PHP:

```<code><?php

    $Fname = $_POST['Fname'];
    $Lname = $_POST['Lname'];
    $email = $_POST['email'];
    $number = $_POST['number'];
    $company = $_POST['company'];
    $message = $_POST['message'];

    $email_from = "Your website";
    $email_subject = "You have a new submission form from Your website";
    $email_body = "First Name: $Fname.\n".
                    "Last Name: $Lname.\n".
                    "Email Address: $email.\n".
                    "Telephone Number: $number.\n".
                    "Company Name: $company.\n".
                    "Message: $message.\n";

    $to = "howdy@yourwebsite.co.uk";
    $headers = "From: $email_from \r\n";
    $headers .= "Reply-To: $email \r\n";

    $captcha;
    if(isset($_POST['email'])){
        $email=$_POST['email'];
    }
    if(isset($_POST['message'])){
        $message=$_POST['message'];
    }
    if(isset($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
        echo '<h2>Please check the "I am not a robot" checkbox"</h2>';
        exit;
    }
    $secretKey = 'acombinationoflettersandnumbers';
    $ip = $_SERVER['REMOTE_ADDR'];
    // post request to the server
    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
    $response = file_get_contents($url);
    $responseKeys = json_decode($response, true);
    // should return JSON with success as true
    if($responseKeys["success"]) {

        mail($to,$email_subject,$email_body,$headers);

    } else {
        echo '<h2>This has been unsuccessful according to our security checks</h2>';
    }
?>
</code>```

Here is the HTML form:

```<code><form action="contact.php" id="contact-form" method="POST" role="form">
              <div class="messages"></div>
              <div class="row">
                <div class="col">
                  <div class="form-group">
                    <label for="form_name">First Name*</label>
                    <input id="form_name" type="text" class="form-control" name="Fname" placeholder="David" required data-error='Please fill in your first name'>
                    <div class="help-block with-errors"></div>
                  </div>
                </div>
                <div class="col">
                  <div class="form-group">
                    <label for="form_lastname">Last name*</label>
                    <input id="form_lastname" type="text" class="form-control" name="Lname" placeholder="Beckham" required data-error="Please fill in your last name">
                    <div class="help-block with-errors"></div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <div class="form-group">
                    <label for="form_email">Email address*</label>
                    <input id="form_email" type="email" class="form-control" name="email" placeholder="becks@example.com" required data-error="Please provide your email address">
                    <div class="help-block with-errors"></div>
                  </div>
                </div>
                <div class="col">
                  <div class="form-group">
                    <label for="form_number">Contact number*</label>
                    <input id="form_number" type="number" class="form-control" name="number" placeholder="01234567890" required data-error="Please provide a contact number">
                    <div class="help-block with-errors"></div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <div class="form-group">
                    <label for="form_company">Your company name</label>
                    <input id="form_company" type="text" class="form-control" name="company" placeholder="Ex-footballers r us">
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <div class="form-group">
                    <label for="form_message">Your message*</label>
                    <textarea id="form_message" class="form-control" name="message" cols="30" rows="10" placeholder="I need the world's best website...HELP!" required></textarea>
                    <div class="help-block with-errors"></div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <div class="g-recaptcha" data-sitekey="acombinationoflettersandnumbers"></div>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <input type="submit" class="btn btn-outline-brand btn-block" name="submit" value="Send enquiry">
                </div>
              </div>
            </form>
</code>```

Here is the JavaScript:

```<code>var onloadCallback = function() {
        grecaptcha.render('html_element', {
        'sitekey' : 'acombinationoflettersandnumbers'
      });
      };
      onloadCallback();

    $('form').on('submit', function(e) {
      if(grecaptcha.getResponse() == "") {
      e.preventDefault();
      alert("You can't proceed!");
    } else {
      alert("Thank you");
    }
    });
</code>```

I have only got this far by following steps from lots of different tutorials and am not sure if any of it is correct. Hope someone is able to assist with a step by step process that allows me submit a contact form, with a success Bootstrap alert and form refresh once it has been submitted.

Thank you!

答:
You could try something like this:

front-end

```<code><div class="js-form-message form-group" style="text-align: center">
    <div style="display: inline-block;" class="g-recaptcha" data-sitekey="yourkey"></div>
</div>
</code>```

back-end

```<code>$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if ($response->success) {
 // not a robot
} else {
 // robot
}
</code>```

The Recaptcha response will be placed in your g-recaptcha input tag. This value will be sent to the back-end (PHP) of the application. There you can validate the Recaptcha response and show a result based on the outcome of the Recaptcha.

ContentLicense: CC BY-SA 4.0

Body:
I am having real trouble putting a Google recaptcha into my website. There seems to be no easy to follow tutorial. I am brand new to JavaScript, but am building a website which receives a huge amount of spam from the contact form. I'd like a Google recaptcha form, possibly v2 as that seems the 'easiest' but I am still having issues.

I have PHP, JS and HTML and I am not understanding how any of it links, and it is not working. The form submits successfully, however, there is no way of telling the form has submitted, nothing happens on the page. I would like a Bootstrap success alert to take place when I press submit.

Here is the PHP:

<?php

    $Fname = $_POST['Fname'];
    $Lname = $_POST['Lname'];
    $email = $_POST['email'];
    $number = $_POST['number'];
    $company = $_POST['company'];
    $message = $_POST['message'];

    $email_from = "Your website";
    $email_subject = "You have a new submission form from Your website";
    $email_body = "First Name: $Fname.\n".
                    "Last Name: $Lname.\n".
                    "Email Address: $email.\n".
                    "Telephone Number: $number.\n".
                    "Company Name: $company.\n".
                    "Message: $message.\n";

    $to = "howdy@yourwebsite.co.uk";
    $headers = "From: $email_from \r\n";
    $headers .= "Reply-To: $email \r\n";

    $captcha;
    if(isset($_POST['email'])){
        $email=$_POST['email'];
    }
    if(isset($_POST['message'])){
        $message=$_POST['message'];
    }
    if(isset($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
        echo '
Please check the "I am not a robot" checkbox"
';
        exit;
    }
    $secretKey = 'acombinationoflettersandnumbers';
    $ip = $_SERVER['REMOTE_ADDR'];
    // post request to the server
    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
    $response = file_get_contents($url);
    $responseKeys = json_decode($response, true);
    // should return JSON with success as true
    if($responseKeys["success"]) {

        mail($to,$email_subject,$email_body,$headers);

    } else {
        echo '
This has been unsuccessful according to our security checks
';
    }
?>

Here is the HTML form:

<form action="contact.php" id="contact-form" method="POST" role="form">

                    First Name*
                    <input id="form_name" type="text" class="form-control" name="Fname" placeholder="David" required data-error='Please fill in your first name'>

                    Last name*
                    <input id="form_lastname" type="text" class="form-control" name="Lname" placeholder="Beckham" required data-error="Please fill in your last name">

                    Email address*
                    <input id="form_email" type="email" class="form-control" name="email" placeholder="becks@example.com" required data-error="Please provide your email address">

                    Contact number*
                    <input id="form_number" type="number" class="form-control" name="number" placeholder="01234567890" required data-error="Please provide a contact number">

                    Your company name
                    <input id="form_company" type="text" class="form-control" name="company" placeholder="Ex-footballers r us">

                    Your message*
                    <textarea id="form_message" class="form-control" name="message" cols="30" rows="10" placeholder="I need the world's best website...HELP!" required></textarea>

                  <input type="submit" class="btn btn-outline-brand btn-block" name="submit" value="Send enquiry">

            </form>

Here is the JavaScript:

var onloadCallback = function() {
        grecaptcha.render('html_element', {
        'sitekey' : 'acombinationoflettersandnumbers'
      });
      };
      onloadCallback();

    $('form').on('submit', function(e) {
      if(grecaptcha.getResponse() == "") {
      e.preventDefault();
      alert("You can't proceed!");
    } else {
      alert("Thank you");
    }
    });

I have only got this far by following steps from lots of different tutorials and am not sure if any of it is correct. Hope someone is able to assist with a step by step process that allows me submit a contact form, with a success Bootstrap alert and form refresh once it has been submitted.

Thank you!

Body:
You could try something like this:

front-end

<div class="js-form-message form-group" style="text-align: center">
    <div style="display: inline-block;" class="g-recaptcha" data-sitekey="yourkey"></div>
</div>

back-end

$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if ($response->success) {
 // not a robot
} else {
 // robot
}

The Recaptcha response will be placed in your g-recaptcha input tag. This value will be sent to the back-end (PHP) of the application. There you can validate the Recaptcha response and show a result based on the outcome of the Recaptcha.


问:
how to read the response from a web site?
I have a website url which gives corresponding city names by taking zip code as input parameter. Now I want to know how to read the response from the site.

This is the link I am using http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680

答: You need to use HttpWebRequest for receiving content and some tools for parsing html and finding what you need. One of the most popular libs for working with html in c# is HtmlAgilityPack, you can see simple example here: http://www.fairnet.com/post/2010/08/28/Html-screen-scraping-with-HtmlAgilityPack-Library.aspx</p>

ContentLicense: CC BY-SA 3.0


问:
Numpy compute dot product of the inner array of a 3D matrix
I have two arrays that look as follows:

In code that is:

```<code>t = np.random.rand(6, 6, 2)
</code>```

I now want to compute the dot product of the axis 2 arrays (the ones of shape 2), for each of the entries of the axis 0 and 1 arrays.

I can do it with a for loop:

```<code>Q = np.zeros_like(t)
for i in range(6):
    for j in range(6):
        Q[i,j] = t[i,j].dot(t[i,j])
</code>```

How can I do this with numpy functions?

I could not get it to work with .dot, .tensordot or similar methods...

t.dot(t) produces this error ValueError: shapes (6,6,2) and (6,6,2) not aligned: 2 (dim 2) != 6 (dim 1) which is to be expected, however I would like to circumvent it.

答:
Since you're taking the dot product of all rows with themselves, you can simplify to a multiplication of t with itself and adding the result. In order to have the same shape as t, you can use np.broadcast_to:

```<code>np.broadcast_to((t*t).sum(-1)[...,None], t.shape)
</code>```

Update

Based on the comments, it appears that you just need:

```<code>(t*t).sum(-1)
</code>```

Check:

```<code>np.allclose(Q, np.broadcast_to((t*t).sum(-1)[...,None], t.shape))
# True
</code>```

Body:
I have two arrays that look as follows:

In code that is:

t = np.random.rand(6, 6, 2)

I now want to compute the dot product of the axis 2 arrays (the ones of shape 2), for each of the entries of the axis 0 and 1 arrays.

I can do it with a for loop:

Q = np.zeros_like(t)
for i in range(6):
    for j in range(6):
        Q[i,j] = t[i,j].dot(t[i,j])

How can I do this with numpy functions?

I could not get it to work with .dot, .tensordot or similar methods...

t.dot(t) produces this error ValueError: shapes (6,6,2) and (6,6,2) not aligned: 2 (dim 2) != 6 (dim 1) which is to be expected, however I would like to circumvent it.

Body:
Since you're taking the dot product of all rows with themselves, you can simplify to a multiplication of t with itself and adding the result. In order to have the same shape as t, you can use np.broadcast_to:

np.broadcast_to((t*t).sum(-1)[...,None], t.shape)

Update

Based on the comments, it appears that you just need:

(t*t).sum(-1)

Check:

np.allclose(Q, np.broadcast_to((t*t).sum(-1)[...,None], t.shape))
# True


问:
How to read multi-value library with for loop in python
Assume that CSV file has this content:

```<code>Main1,Name1,Name2,Name3,Name4
Main2,NameA,NameB
Main3,Name11,Name12,Name13
</code>```

When I read it as library result is following:

```<code>{'Main1': ['Name1', 'Name2', 'Name3', 'Name4'],
 'Main2': ['NameA', 'NameB'],
 'Main3': ['Name11', 'Name12', 'Name13']}
</code>```

When I turn to particular item/value like a['Main3'][2] I'll get answer 'Name13'.
But the values ('Name's') are unknown number and I would like to read them all individually in e.g. for loop. If I read like this:

```<code>for rows in a:
    print(rows)
</code>```

I will get answer:

```<code>Main1
Main2
Main3
</code>```

But I would like to modify code something like:

```<code>for rows in a:
    print(rows)
    for values in rows:
        print(values)
</code>```

But result is erroneous. I expect to see something like this:

```<code>'Main1'
    'Name1'
    'Name2'
    'Name3'
    'Name4'
'Main2'
    'NameA'
    'NameB'
'Main3'
    'Name11'
    'Name12'
    'Name13'
</code>```

And I cannot figure out how to modify my code. Would you please help me? Thanks!

答:
try this :</p>

```<code>for rows in a:
    print(rows)
    for values in a[rows]:
        print('   ',values)
</code>```

Body:
Assume that CSV file has this content:

Main1,Name1,Name2,Name3,Name4
Main2,NameA,NameB
Main3,Name11,Name12,Name13

When I read it as library result is following:

{'Main1': ['Name1', 'Name2', 'Name3', 'Name4'],
 'Main2': ['NameA', 'NameB'],
 'Main3': ['Name11', 'Name12', 'Name13']}

When I turn to particular item/value like a['Main3'][2] I'll get answer 'Name13'.
But the values ('Name's') are unknown number and I would like to read them all individually in e.g. for loop. If I read like this:

for rows in a:
    print(rows)

I will get answer:

Main1
Main2
Main3

But I would like to modify code something like:

for rows in a:
    print(rows)
    for values in rows:
        print(values)

But result is erroneous. I expect to see something like this:

'Main1'
    'Name1'
    'Name2'
    'Name3'
    'Name4'
'Main2'
    'NameA'
    'NameB'
'Main3'
    'Name11'
    'Name12'
    'Name13'

And I cannot figure out how to modify my code. Would you please help me? Thanks!

Body:
try this :

for rows in a:
    print(rows)
    for values in a[rows]:
        print('   ',values)


答:
Try to do like this.</p>

```<code>for rows in a:
    print(rows)
    for values in a[rows]:
        print(values)
</code>```

Title: How to read multi-value library with for loop in python

Body:
Try to do like this.

for rows in a:
    print(rows)
    for values in a[rows]:
        print(values)


答: you can use a WebClient object, and an easy way to scrape the data is with xpath. </p>

Title: how to read the response from a web site?

Body:
I have a website url which gives corresponding city names by taking zip code as input parameter. Now I want to know how to read the response from the site.

This is the link I am using http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680


问:
robust continuous TCP connection (python socket)
My goal is to establish a continuous and robust TCP connection between one server and exactly one client. If one side fails, the other one should wait until it recovers.

I wrote the following code based on this question (that only asks for continuous, but not robust TCP connections and does not handle keepalive issues), this post and my own experience.

I have two questions:

How can I make the keepalive work? If the server dies, the client only recognizes it after trying to send() - which worked also without the KEEPALIVE option as this results in a connection reset. Is there some way that the socket sends an interrupt for a connection that is dead or some keepalive function that I can check on a regular basis?

Is this a robust way of handling a continous TCP connection? Having a stable, continous TCP connection seems to be a standard problem, however, I couldn't find tutorials covering this in detail. There must be some best-practice.

Note, I could handle keep alive messages on my own at the application level. However, as TCP already implements this at transport level, it is better to rely on this service provided by the lower level.

The server:

```<code>from socket import *
serverPort = 12000

while True:
    # 1. Configure server socket
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serverSocket.bind(('127.0.0.1', serverPort))
    serverSocket.listen(1)
    print("waiting for client connecting...")
    connectionSocket, addr = serverSocket.accept()
    connectionSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE,1)
    print(connectionSocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE))
    print("...connected.")
    serverSocket.close() # Destroy the server socket; we don't need it anymore since we are not accepting any connections beyond this point.

    # 2. communication routine
    while True:
        try:
            sentence = connectionSocket.recv(512).decode()
        except ConnectionResetError as e:
            print("Client connection closed")
            break
        if(len(sentence)==0): # close if client closed connection
            break
        else:
            print("recv: "+str(sentence))

    # 3. proper closure
    connectionSocket.shutdown(SHUT_RDWR)
    connectionSocket.close()
    print("connection closed.")
</code>```

The client:

```<code>from socket import *
import time

while True:
    # 1. configure socket dest.
    serverName = '127.0.0.1'
    serverPort = 12000
    clientSocket = socket(AF_INET, SOCK_STREAM)
    try:
        clientSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE,1)
        clientSocket.connect((serverName, serverPort))
        print(clientSocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE))
    except ConnectionRefusedError as e:
        print("Server refused connection. retrying")
        time.sleep(1)
        continue

    # 2. communication routine
    while(1):
        sentence = input('input sentence: ')
        if(sentence == "close"):
            break
        try:
            clientSocket.send(sentence.encode())
        except ConnectionResetError as e:
            print("Server connection closed")
            break

    # 3. proper closure
    clientSocket.shutdown(SHUT_RDWR)
    clientSocket.close()
</code>```

I tried to hold this example as minimal as possible. But given the requirement of robustness, it is relativley long.

I also tried some socket options as TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT.

Thank you!

答:
How can I make the keepalive work? If the server dies, the client only recognizes it after trying to send() - which worked also without the KEEPALIVE option as this results in a connection reset.

Keepalive is more useful on the server or reading side. And it is a tricky beast. The socket won't notify you at all unless you read/write. You can query its state (even though I'm not sure this is possible with the standard Python) but this still doesn't solve the problem of notification. You need to check the state periodically anyway.

Is there some way that the socket sends an interrupt for a connection that is dead or some keepalive function that I can check on a regular basis?

Have you ever heard about the Two Generals' Problem? There is no reliable way to detect whether one side is dead or not. We can however be close enough with pings and timeouts.

Note, I could handle keep alive messages on my own at the application level. However, as TCP already implements this at transport level, it is better to rely on this service provided by the lower level.

No, it is not better. If, for any reason, there's a proxy between the server and the client, then no TCP feature will help you. Because by design these only control a single connection, while with a proxy you have at least two connections. You should not think about your connection in terms of the underlying transport (TCP). Instead create your own protocol with ping command which the server (or client or both) send periodically together with timeouts. This way you can be sure that the peer is alive up to period interval.

Is this a robust way of handling a continous TCP connection? Having a stable, continous TCP connection seems to be a standard problem, however, I couldn't find tutorials covering this in detail. There must be some best-practice.

You won't find tutorials covering this, because that problem has no solution. Most people simulate "I'm still alive" with the combination of pings and timeouts.

Body:
My goal is to establish a continuous and robust TCP connection between one server and exactly one client. If one side fails, the other one should wait until it recovers.

I wrote the following code based on this question (that only asks for continuous, but not robust TCP connections and does not handle keepalive issues), this post and my own experience.

I have two questions:

How can I make the keepalive work? If the server dies, the client only recognizes it after trying to send() - which worked also without the KEEPALIVE option as this results in a connection reset. Is there some way that the socket sends an interrupt for a connection that is dead or some keepalive function that I can check on a regular basis?

Is this a robust way of handling a continous TCP connection? Having a stable, continous TCP connection seems to be a standard problem, however, I couldn't find tutorials covering this in detail. There must be some best-practice.

Note, I could handle keep alive messages on my own at the application level. However, as TCP already implements this at transport level, it is better to rely on this service provided by the lower level.

The server:

from socket import *
serverPort = 12000

while True:
    # 1. Configure server socket
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serverSocket.bind(('127.0.0.1', serverPort))
    serverSocket.listen(1)
    print("waiting for client connecting...")
    connectionSocket, addr = serverSocket.accept()
    connectionSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE,1)
    print(connectionSocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE))
    print("...connected.")
    serverSocket.close() # Destroy the server socket; we don't need it anymore since we are not accepting any connections beyond this point.

    # 2. communication routine
    while True:
        try:
            sentence = connectionSocket.recv(512).decode()
        except ConnectionResetError as e:
            print("Client connection closed")
            break
        if(len(sentence)==0): # close if client closed connection
            break
        else:
            print("recv: "+str(sentence))

    # 3. proper closure
    connectionSocket.shutdown(SHUT_RDWR)
    connectionSocket.close()
    print("connection closed.")

The client:

from socket import *
import time

while True:
    # 1. configure socket dest.
    serverName = '127.0.0.1'
    serverPort = 12000
    clientSocket = socket(AF_INET, SOCK_STREAM)
    try:
        clientSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE,1)
        clientSocket.connect((serverName, serverPort))
        print(clientSocket.getsockopt(SOL_SOCKET,SO_KEEPALIVE))
    except ConnectionRefusedError as e:
        print("Server refused connection. retrying")
        time.sleep(1)
        continue

    # 2. communication routine
    while(1):
        sentence = input('input sentence: ')
        if(sentence == "close"):
            break
        try:
            clientSocket.send(sentence.encode())
        except ConnectionResetError as e:
            print("Server connection closed")
            break

    # 3. proper closure
    clientSocket.shutdown(SHUT_RDWR)
    clientSocket.close()

I tried to hold this example as minimal as possible. But given the requirement of robustness, it is relativley long.

I also tried some socket options as TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT.

Thank you!


问:
neo4j how to compare two list and return the different items
I am  using  neo4j MATCH and get two list of User: listA,listB,
and listB is part of listA

how can I return users only in listA but not in listB use cipher query

the cipher like :

MATCH listA, listB

  RETURN listA - listB

Here is my previous question: neo4j cypher multi relationship between nodes

Done See solution in the link above

答:
Filter function is removed in the latest Neo4j version 4.0 doc here
instead, use List comprehension </p>

```<code>WITH [1,2,3,4,5,6] as listA, [1,2,3] as listB
RETURN [n IN listA WHERE NOT n IN listB] as listC
</code>```

<p>This results in an output
4, 5, 6 </p>

Body:
Filter function is removed in the latest Neo4j version 4.0 doc here
instead, use List comprehension

WITH [1,2,3,4,5,6] as listA, [1,2,3] as listB
RETURN [n IN listA WHERE NOT n IN listB] as listC

This results in an output
4, 5, 6


问:
Copy and replace part of date from field A to B
I need a simple code that takes date from fixed (always the same) field (B 26 on example below) and copy only the MM.YYYY (from date 19.09.2020  I need the copy only of 09.2020) and this MM.YYYY insert into the date field B2 and replace the old MM.YYYY. Day DD (01 from example) from B2 should stay.

Example:
B26 ->      I need copy of 09.2020
B2 ->       01.08.2020 needs to be raplaced by 09.2020, result should be 01.09.2020.
B3…B25 ->   all lines from B3 to B25 should bet he same, B3 should be 02.09.2020, B4 should be 03.09.2020…

I have an issue probably with wrong format of date.

```<code>Range("B26").Select
Selection.Copy
Range("B2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "8/1/2020"
Range("B2").Select
Selection.AutoFill Destination:=Range("B2:B25"), Type:=xlFillDefault
Range("B2:B25").Select
</code>```

答:
The basic worksheet function you need for this the DATE() function with the syntax =DATE([Year],[Month],[Day]). VBA has an equivalent called DateSerial([Year],[Month],[Day]). Therefore

[B2] = DATE(Year(B26),Month(B26)+1,1)

or, in VBA,

```<code>With Cells(26, "B")
    Cells(2, "B").Value = DateSerial(Year(.Value), Month(.Value) + 1, 1)
End With
</code>```

or, alternatively, using the DateAdd function

```<code>With Cells(2, "B")
    .Value = DateAdd("m", 1, .Value)
End With
</code>```

The latter just adds one month to the date already existing in the cell. Expanding on the idea of using a worksheet function, you can crease a list of numbers from 1 to 24 in B2:B25 using the function =ROW()-1. You might integrate that into the function first above given.

[B2] = DATE(Year(B$26),Month(B$26)+1,ROW()-1)

As you copy this formula down to B25 you get dates from 1 to 25 but from the year and month in B26.

Body:
I need a simple code that takes date from fixed (always the same) field (B 26 on example below) and copy only the MM.YYYY (from date 19.09.2020  I need the copy only of 09.2020) and this MM.YYYY insert into the date field B2 and replace the old MM.YYYY. Day DD (01 from example) from B2 should stay.

Example:
B26 ->      I need copy of 09.2020
B2 ->       01.08.2020 needs to be raplaced by 09.2020, result should be 01.09.2020.
B3…B25 ->   all lines from B3 to B25 should bet he same, B3 should be 02.09.2020, B4 should be 03.09.2020…

I have an issue probably with wrong format of date.

Range("B26").Select
Selection.Copy
Range("B2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "8/1/2020"
Range("B2").Select
Selection.AutoFill Destination:=Range("B2:B25"), Type:=xlFillDefault
Range("B2:B25").Select

Body:
The basic worksheet function you need for this the DATE() function with the syntax =DATE([Year],[Month],[Day]). VBA has an equivalent called DateSerial([Year],[Month],[Day]). Therefore

[B2] = DATE(Year(B26),Month(B26)+1,1)

or, in VBA,

With Cells(26, "B")
    Cells(2, "B").Value = DateSerial(Year(.Value), Month(.Value) + 1, 1)
End With

or, alternatively, using the DateAdd function

With Cells(2, "B")
    .Value = DateAdd("m", 1, .Value)
End With

The latter just adds one month to the date already existing in the cell. Expanding on the idea of using a worksheet function, you can crease a list of numbers from 1 to 24 in B2:B25 using the function =ROW()-1. You might integrate that into the function first above given.

[B2] = DATE(Year(B$26),Month(B$26)+1,ROW()-1)

As you copy this formula down to B25 you get dates from 1 to 25 but from the year and month in B26.


问:
Getting error for Get request in Rest Assured
i am new to RestAssured api testing,i'm getting exception while running my basic code.i have added all the required jars and tried all the suggestions available in the online but still not able to find solution for this. please somebody help me in this
. Thanks in advance.

code

```<code>import java.net.MalformedURLException;
import java.net.URL;

import io.restassured.RestAssured;
import io.restassured.response.Response;

public class Test1 {

    public static void main(String[] args) throws MalformedURLException {
        // TODO Auto-generated method stub
        URL url=new URL("http://dummy.restapiexample.com/");
        Response resp=RestAssured.get(url);
        int status=resp.getStatusCode();
        String respText=resp.getBody().toString();
        System.out.println(respText+"      "+status);
    }

}
</code>```

Exception log

```<code>Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: static io.restassured.internal.http.URIBuilder.convertToURI() is applicable for argument types: (String) values: [http://dummy.restapiexample.com/]
    at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1568)
    at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1554)
    at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:50)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:139)
    at io.restassured.internal.RequestSpecificationImpl.generateRequestUriForLogging(RequestSpecificationImpl.groovy:1103)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:107)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1262)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1029)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:816)
    at io.restassured.internal.RequestSpecificationImpl.invokeMethod(RequestSpecificationImpl.groovy)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.call(PogoInterceptableSite.java:45)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.callCurrent(PogoInterceptableSite.java:55)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:171)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:194)
    at io.restassured.internal.RequestSpecificationImpl.newFilterContext(RequestSpecificationImpl.groovy:1064)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:107)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1262)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1029)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:816)
    at io.restassured.internal.RequestSpecificationImpl.invokeMethod(RequestSpecificationImpl.groovy)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.call(PogoInterceptableSite.java:45)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.callCurrent(PogoInterceptableSite.java:55)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:171)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:203)
    at io.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:1653)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:107)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1262)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1029)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:816)
    at io.restassured.internal.RequestSpecificationImpl.invokeMethod(RequestSpecificationImpl.groovy)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.call(PogoInterceptableSite.java:45)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.callCurrent(PogoInterceptableSite.java:55)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:171)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:203)
    at restAssure.Test1.main(Test1.java:14)
</code>```

Jars Added

答: Mavenise the project worked for me</p>

Body:
i am new to RestAssured api testing,i'm getting exception while running my basic code.i have added all the required jars and tried all the suggestions available in the online but still not able to find solution for this. please somebody help me in this
. Thanks in advance.

code

import java.net.MalformedURLException;
import java.net.URL;

import io.restassured.RestAssured;
import io.restassured.response.Response;

public class Test1 {

    public static void main(String[] args) throws MalformedURLException {
        // TODO Auto-generated method stub
        URL url=new URL("http://dummy.restapiexample.com/");
        Response resp=RestAssured.get(url);
        int status=resp.getStatusCode();
        String respText=resp.getBody().toString();
        System.out.println(respText+"      "+status);
    }

}

Exception log

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: static io.restassured.internal.http.URIBuilder.convertToURI() is applicable for argument types: (String) values: [http://dummy.restapiexample.com/]
    at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1568)
    at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1554)
    at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:50)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:139)
    at io.restassured.internal.RequestSpecificationImpl.generateRequestUriForLogging(RequestSpecificationImpl.groovy:1103)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:107)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1262)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1029)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:816)
    at io.restassured.internal.RequestSpecificationImpl.invokeMethod(RequestSpecificationImpl.groovy)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.call(PogoInterceptableSite.java:45)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.callCurrent(PogoInterceptableSite.java:55)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:171)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:194)
    at io.restassured.internal.RequestSpecificationImpl.newFilterContext(RequestSpecificationImpl.groovy:1064)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:107)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1262)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1029)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:816)
    at io.restassured.internal.RequestSpecificationImpl.invokeMethod(RequestSpecificationImpl.groovy)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.call(PogoInterceptableSite.java:45)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.callCurrent(PogoInterceptableSite.java:55)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:171)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:203)
    at io.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:1653)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:107)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1262)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1029)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:816)
    at io.restassured.internal.RequestSpecificationImpl.invokeMethod(RequestSpecificationImpl.groovy)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.call(PogoInterceptableSite.java:45)
    at org.codehaus.groovy.runtime.callsite.PogoInterceptableSite.callCurrent(PogoInterceptableSite.java:55)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:171)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:203)
    at restAssure.Test1.main(Test1.java:14)

Jars Added

Body: Mavenise the project worked for me


问:
Java library class to handle scheduled execution of "callbacks"?
My program has a component - dubbed the Scheduler - that lets other components register points in time at which they want to be called back. This should work much like the Unix cron service, i. e. you tell the Scheduler "notify me at ten minutes past every full hour".

I realize there are no real callbacks in Java.

Here's my approach, is there a library which already does this stuff? Feel free to suggest improvements, too.

Register call to Scheduler passes:

a time specification containing hour, minute, second, year month, dom, dow, where each item may be unspecified, meaning "execute it every hour / minute etc." (just like crontabs)

an object containing data that will tell the calling object what to do when it is notified by the Scheduler. The Scheduler does not process this data, just stores it and passes it back upon notification.

a reference to the calling object

Upon startup, or after a new registration request, the Scheduler starts with a Calendar object of the current system time and checks if there are any entries in the database that match this point in time. If there are, they are executed and the process starts over. If there aren't, the time in the Calendar object is incremented by one second and the entreis are rechecked. This repeats until there is one entry or more that match(es). (Discrete Event Simulation)

The Scheduler will then remember that timestamp, sleep and wake every second to check if it is already there. If it happens to wake up and the time has already passed, it starts over, likewise if the time has come and the jobs have been executed.

Edit: Thanks for pointing me to Quartz. I'm looking for something much smaller, however.

答:
Can't believe java.util.Timer was voted as the answer. Quartz is really a much better choice.

A big advantage of quartz over java.util.Timer is that with quartz the jobs can be stored in the db. As a result one jvm can schedule and another can execute. Also (obviously) the request survives across jvm restarts.

OwnerDisplayName: Hanno Fietz

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Pat


问:
Presto - get sum of array elements
I'm using Athena and trying to get a sum of array elements which are double but the reduce function seems to only work on integers:

SELECT reduce(ARRAY [5.0, 20.0, 50.4], 0, (s, x) -> s + x, s -> s);

Will throw an error:

Unexpected parameters (array(double), integer, com.facebook.presto.sql.analyzer.TypeSignatureProvider@762f0fa7, com.facebook.presto.sql.analyzer.TypeSignatureProvider@29dfe267) for function reduce. Expected: reduce(array(T), S, function(S,T,S), function(S,R)) T, S, R

Is there a way to do it?

答:
This is a know bug in Presto. You can track https://github.com/prestosql/presto/issues/2760.

As a workaround, you can cast your array(decimal(..)) to either array(decimal(38,..)) or array(double):

```<code>presto> SELECT reduce(cast(ARRAY[5.0, 20.0, 50.4] as array(decimal(38,5))), 0, (s, x) -> s + x, s -> s);
  _col0
----------
 75.40000

presto> SELECT reduce(cast(ARRAY[5.0, 20.0, 50.4] as array(double)), 0, (s, x) -> s + x, s -> s);
 _col0
-------
  75.4
</code>```

Athena is based on an older Presto version (currently .172, 3 years old), and apparently none of the above works in Athena (based on the fact your array is already array(double)).

Title: Presto - get sum of array elements

Body:
This is a know bug in Presto. You can track https://github.com/prestosql/presto/issues/2760.

As a workaround, you can cast your array(decimal(..)) to either array(decimal(38,..)) or array(double):

presto> SELECT reduce(cast(ARRAY[5.0, 20.0, 50.4] as array(decimal(38,5))), 0, (s, x) -> s + x, s -> s);
  _col0
----------
 75.40000

presto> SELECT reduce(cast(ARRAY[5.0, 20.0, 50.4] as array(double)), 0, (s, x) -> s + x, s -> s);
 _col0
-------
  75.4

Athena is based on an older Presto version (currently .172, 3 years old), and apparently none of the above works in Athena (based on the fact your array is already array(double)).


问:
Navigation component - handle back behaviour with multiple stacks
My main problem is that the back button(device button) is not working properly as findNavController().navigateUp() does.

I have the following structure.

Main nav graph:

```<code>Login -> Home, here FlowA and FlowB are loaded in DrawerLayout
</code>```

HomeFragment code:

```<code>class HomeFragment : Fragment() {
    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private val viewModel: HomeViewModel by activityViewModels()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val flow1Nav = NavHostFragment.create(R.navigation.flow_a)
        val flow2Nav = NavHostFragment.create(R.navigation.flow_b)
        childFragmentManager.beginTransaction()
            .add(R.id.flContent, flow1Nav, flow1Nav.javaClass.name)
            .add(R.id.flContent, flow2Nav, flow2Nav.javaClass.name)
            .show(flow1Nav)
            .hide(flow2Nav)
            .commitNow()
        binding.navView.findViewById<LinearLayout>(R.id.ll_flow1).setOnClickListener {
            binding.drawerLayout.closeDrawers()
            childFragmentManager.beginTransaction()
                .show(flow1Nav)
                .hide(flow2Nav)
                .commit()
        }
        binding.navView.findViewById<LinearLayout>(R.id.ll_flow2).setOnClickListener {
            binding.drawerLayout.closeDrawers()
            childFragmentManager.beginTransaction()
                .show(flow2Nav)
                .hide(flow1Nav)
                .commit()
        }
    }
}
</code>```

fragment_home.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Use DrawerLayout as root container for activity -->
<androidx.drawerlayout.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <FrameLayout
            android:id="@+id/flContent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
    <!-- Container for contents of drawer - use NavigationView to make configuration easier -->
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="false">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <include layout="@layout/drawer_header" />
            <include layout="@layout/drawer_menu" />
        </LinearLayout>
    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

Flow A nav graph

Flow B nav graph

Questions

Why findNavController().navigateUp() works as expected and the device back button doesn't?

Multiple stacks (navigations graphs) breaks the navigation system?

All the source code can be found here.

答:
I've found a workarround</p>

```<code>requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
   findNavController().navigateUp()
}
</code>```

Body:
My main problem is that the back button(device button) is not working properly as findNavController().navigateUp() does.

I have the following structure.

Main nav graph:

Login -> Home, here FlowA and FlowB are loaded in DrawerLayout

HomeFragment code:

class HomeFragment : Fragment() {
    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private val viewModel: HomeViewModel by activityViewModels()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val flow1Nav = NavHostFragment.create(R.navigation.flow_a)
        val flow2Nav = NavHostFragment.create(R.navigation.flow_b)
        childFragmentManager.beginTransaction()
            .add(R.id.flContent, flow1Nav, flow1Nav.javaClass.name)
            .add(R.id.flContent, flow2Nav, flow2Nav.javaClass.name)
            .show(flow1Nav)
            .hide(flow2Nav)
            .commitNow()
        binding.navView.findViewById<LinearLayout>(R.id.ll_flow1).setOnClickListener {
            binding.drawerLayout.closeDrawers()
            childFragmentManager.beginTransaction()
                .show(flow1Nav)
                .hide(flow2Nav)
                .commit()
        }
        binding.navView.findViewById<LinearLayout>(R.id.ll_flow2).setOnClickListener {
            binding.drawerLayout.closeDrawers()
            childFragmentManager.beginTransaction()
                .show(flow2Nav)
                .hide(flow1Nav)
                .commit()
        }
    }
}

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <FrameLayout
            android:id="@+id/flContent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="false">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <include layout="@layout/drawer_header" />
            <include layout="@layout/drawer_menu" />
        </LinearLayout>
    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

Flow A nav graph

Flow B nav graph

Questions

Why findNavController().navigateUp() works as expected and the device back button doesn't?

Multiple stacks (navigations graphs) breaks the navigation system?

All the source code can be found here.

Body:
I've found a workarround

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
   findNavController().navigateUp()
}


问:
Repeated records when doing a JOIN in Postgres
I have the questions table:

```<code>id, title, quiz_id
</code>```

and the quiz_answers table:

```<code>id, question_id, user_id, answer
</code>```

With the following query I get the answers for a certain quiz for two users:

```<code>SELECT qa.id, qa.question_id as "questionId", qa.user_id as "userId",
            qa.answer, qa.created_at as "createdAt"
      FROM quiz_answers AS qa
      JOIN questions AS qst ON qst.quiz_id = 3
      WHERE qa.user_id IN ('foo', 'bar')
      GROUP BY "questionId", qa.id;
</code>```

I also want to add the question title to each returned row. The problem is that when I add it to the SELECT'ed columns, I also need to either aggregate it or add it to the GROUP BY clause. And both of these actions result in having the wrong result: duplicate records.

I tried to think of how to do this with a nested SELECT query on the questions table, instead of using a JOIN, but to no avail.

答:
Your join clause is not correct.
You should

JOIN on qa.question_id=qst.id

add the qst.quiz_id = 3 in the WHERE clause

Body:
I have the questions table:

id, title, quiz_id

and the quiz_answers table:

id, question_id, user_id, answer

With the following query I get the answers for a certain quiz for two users:

SELECT qa.id, qa.question_id as "questionId", qa.user_id as "userId",
            qa.answer, qa.created_at as "createdAt"
      FROM quiz_answers AS qa
      JOIN questions AS qst ON qst.quiz_id = 3
      WHERE qa.user_id IN ('foo', 'bar')
      GROUP BY "questionId", qa.id;

I also want to add the question title to each returned row. The problem is that when I add it to the SELECT'ed columns, I also need to either aggregate it or add it to the GROUP BY clause. And both of these actions result in having the wrong result: duplicate records.

I tried to think of how to do this with a nested SELECT query on the questions table, instead of using a JOIN, but to no avail.


问:
QML Remove Animation of ListView Item with a QSqlTableModel
I'm using a list view with a QSqlTableModel in the background. I use also a SwipeDelegate for the list view elements to provide a "delete button", as shown here:

When the button is now pressed, the the item is deleted from the database using this code in the QSqlTableModel subclass:

void qsoModel::deleteQSO(int id) {
    removeRow(id);
    submitAll();
}
```

<p>Side question: When I understood it correctly, removeRow is implicitly calling beginRemoveRows(...) and endRemoveRows()? </p>

<p>For the ListView I used a remove Transition:</p>

```    ListView {
        id: listView
        anchors.fill: parent
        model: qsoModel

        //...

        delegate: QSOItem {}

        remove: Transition {
               NumberAnimation { property: "opacity"; from: 1.0; to: 0; duration: 400 }
               NumberAnimation { property: "scale"; from: 1.0; to: 0.0; duration: 400 }
        }
```

However, If I press the delete button, the animation is not shown. the list element just disappears fastly. Any ideas why this is happening?

The complete source code can be found in this commit: https://github.com/myzinsky/cloudLogOffline/tree/b501d41a0f23d40139cfca9a6d4f724f4ab251b2

答:
From looking at the code on github it looks like the model is executing the beginRemoveRows() and endRemoveRows() methods so I think this won't be the issue. And you say the records are removed from the database so I think the problem is more related to qml.

So regarding the qml animations there are few things:

First thing, if you want the opacity and scale animation parallel you will need to wrap them in a ParallelAnimation. Second thing is you will need to specify a transition for removeDisplaced otherwise the items that would be moved up in the list when you delete an item from the list are just being pushed to the new position covering the record that is executing the animation for removal.
You should be able to see this if you assigned a transition to the removeDisplaced looking like this.

```<code>removeDisplaced:Transition{
    NumberAnimation{
        property:"y" // Specifying "y" so the displaced records slowly proceed upwards
        duration:5000 // 5s should be enough to see what's actually happening
        easing.type: Easing.InOutQuad
    }
}
</code>```

EDIT:

The problem I mentioned in the original post wasn't the only problem. The problem is that the removeRow() function doesn't call beginRemoveRows() and endRemoveRows()! If you wrap those calls around the removeRow() call you will see animations happening. But you will still need to assign a transition to removeDisplaced to see everything happening.

EDIT by Question Author

The idea is to update the model after the animation from QML side:

```<code>remove: Transition {
    SequentialAnimation {
        NumberAnimation {
            property: "opacity"
            from: 1.0
            to: 0
            duration: 400
        }
        ScriptAction {
            script: {
                qsoModel.select()
            }
        }
    }
}
</code>```

I just call select when the animation is done from the QML side

Body:
I'm using a list view with a QSqlTableModel in the background. I use also a SwipeDelegate for the list view elements to provide a "delete button", as shown here:

When the button is now pressed, the the item is deleted from the database using this code in the QSqlTableModel subclass:

void qsoModel::deleteQSO(int id) {
    removeRow(id);
    submitAll();
}

Side question: When I understood it correctly, removeRow is implicitly calling beginRemoveRows(...) and endRemoveRows()?

For the ListView I used a remove Transition:

    ListView {
        id: listView
        anchors.fill: parent
        model: qsoModel

        //...

        delegate: QSOItem {}

        remove: Transition {
               NumberAnimation { property: "opacity"; from: 1.0; to: 0; duration: 400 }
               NumberAnimation { property: "scale"; from: 1.0; to: 0.0; duration: 400 }
        }

However, If I press the delete button, the animation is not shown. the list element just disappears fastly. Any ideas why this is happening?

The complete source code can be found in this commit: https://github.com/myzinsky/cloudLogOffline/tree/b501d41a0f23d40139cfca9a6d4f724f4ab251b2

Body:
From looking at the code on github it looks like the model is executing the beginRemoveRows() and endRemoveRows() methods so I think this won't be the issue. And you say the records are removed from the database so I think the problem is more related to qml.

So regarding the qml animations there are few things:

First thing, if you want the opacity and scale animation parallel you will need to wrap them in a ParallelAnimation. Second thing is you will need to specify a transition for removeDisplaced otherwise the items that would be moved up in the list when you delete an item from the list are just being pushed to the new position covering the record that is executing the animation for removal.
You should be able to see this if you assigned a transition to the removeDisplaced looking like this.

removeDisplaced:Transition{
    NumberAnimation{
        property:"y" // Specifying "y" so the displaced records slowly proceed upwards
        duration:5000 // 5s should be enough to see what's actually happening
        easing.type: Easing.InOutQuad
    }
}

EDIT:

The problem I mentioned in the original post wasn't the only problem. The problem is that the removeRow() function doesn't call beginRemoveRows() and endRemoveRows()! If you wrap those calls around the removeRow() call you will see animations happening. But you will still need to assign a transition to removeDisplaced to see everything happening.

EDIT by Question Author

The idea is to update the model after the animation from QML side:

remove: Transition {
    SequentialAnimation {
        NumberAnimation {
            property: "opacity"
            from: 1.0
            to: 0
            duration: 400
        }
        ScriptAction {
            script: {
                qsoModel.select()
            }
        }
    }
}

I just call select when the animation is done from the QML side


问:
Android Studio Firebase Database DataSnapshot returning null
TLDR: I have been trying to retrieve user information from the Firebase Realtime Database, but the dataSnapshot within the addChildEventListener or addValueEventListener seems to always return null. I followed the API exactly to no avail. Please send help!!

My Profile Activity:

```<code>import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;

import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

public class ProfileActivity extends AppCompatActivity {
    private static final String tag = "ProfileActivity";
    private static final int PROFILE_ACTIVITY = 1;

    //firebase elements
    private FirebaseAuth mAuth;
    private FirebaseDatabase mDatabase;
    private DatabaseReference mReference;
    private FirebaseUser currentUser;

    //view elements
    private Button logoutBtn;
    private TextView walletBalance, tasksTaken, tasksPosted, userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        mAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance();
        currentUser = mAuth.getCurrentUser();
        mReference = mDatabase.getReference(mAuth.getUid());
        Query query = mReference;

        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Log.d(tag, dataSnapshot.getValue().toString());
                if(dataSnapshot.getValue() != null)
                {
                    Log.d(tag, "not null");
                    User newUser = dataSnapshot.getValue(User.class);
                    Log.d(tag, newUser.getName());
                    Log.d(tag, Integer.toString(newUser.getWalletBalance()));
                    Log.d(tag, Integer.toString(newUser.getTasksTaken()));
                    Log.d(tag, Integer.toString(newUser.getTasksPosted()));

                    userName.setText(newUser.getName());
                    walletBalance.setText(newUser.getWalletBalance());
                    tasksTaken.setText(newUser.getTasksTaken());
                    tasksPosted.setText(newUser.getTasksPosted());
                }
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    private void setViewElements() {
        logoutBtn = findViewById(R.id.btn_logout);
        walletBalance = findViewById(R.id.tv_walletBalance);
        tasksTaken = findViewById(R.id.tv_taskSAmount);
        tasksPosted = findViewById(R.id.tv_taskPAmount);
        userName = findViewById(R.id.tv_userName);
    }

    private void goToLoginActivity() {
        startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        finish();
    }

</code>```

My User Object:

```<code>public class User {
    //user information
    String name, email, password;
    int walletBalance, tasksTaken, tasksPosted;

    //constructor
    public User(String name, String email, String password, int walletBalance, int tasksTaken, int tasksPosted) {
        this.name = name;
        this.email = email;
        this.password = password;
        this.walletBalance = walletBalance;
        this.tasksTaken = tasksTaken;
        this.tasksPosted = tasksPosted;
    }

    //empty constructor
    public User() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getWalletBalance() {
        return walletBalance;
    }

    public void setWalletBalance(int walletBalance) {
        this.walletBalance = walletBalance;
    }

    public int getTasksTaken() {
        return tasksTaken;
    }

    public void setTasksTaken(int tasksTaken) {
        this.tasksTaken = tasksTaken;
    }

    public int getTasksPosted() {
        return tasksPosted;
    }

    public void setTasksPosted(int tasksPosted) {
        this.tasksPosted = tasksPosted;
    }
}

</code>```

My Firebase Database:

Any help is very very appreciated!!

答:
Your reference is wrong.
You should write "users" node first in your reference.
Also you shouldn't use query without filtering or sorting.</p>

```<code>mReference = mDatabase.getReference("users").child(mAuth.getUid());
</code>```

Body:
TLDR: I have been trying to retrieve user information from the Firebase Realtime Database, but the dataSnapshot within the addChildEventListener or addValueEventListener seems to always return null. I followed the API exactly to no avail. Please send help!!

My Profile Activity:

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;

import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

public class ProfileActivity extends AppCompatActivity {
    private static final String tag = "ProfileActivity";
    private static final int PROFILE_ACTIVITY = 1;

    //firebase elements
    private FirebaseAuth mAuth;
    private FirebaseDatabase mDatabase;
    private DatabaseReference mReference;
    private FirebaseUser currentUser;

    //view elements
    private Button logoutBtn;
    private TextView walletBalance, tasksTaken, tasksPosted, userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        mAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance();
        currentUser = mAuth.getCurrentUser();
        mReference = mDatabase.getReference(mAuth.getUid());
        Query query = mReference;

        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Log.d(tag, dataSnapshot.getValue().toString());
                if(dataSnapshot.getValue() != null)
                {
                    Log.d(tag, "not null");
                    User newUser = dataSnapshot.getValue(User.class);
                    Log.d(tag, newUser.getName());
                    Log.d(tag, Integer.toString(newUser.getWalletBalance()));
                    Log.d(tag, Integer.toString(newUser.getTasksTaken()));
                    Log.d(tag, Integer.toString(newUser.getTasksPosted()));

                    userName.setText(newUser.getName());
                    walletBalance.setText(newUser.getWalletBalance());
                    tasksTaken.setText(newUser.getTasksTaken());
                    tasksPosted.setText(newUser.getTasksPosted());
                }
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    private void setViewElements() {
        logoutBtn = findViewById(R.id.btn_logout);
        walletBalance = findViewById(R.id.tv_walletBalance);
        tasksTaken = findViewById(R.id.tv_taskSAmount);
        tasksPosted = findViewById(R.id.tv_taskPAmount);
        userName = findViewById(R.id.tv_userName);
    }

    private void goToLoginActivity() {
        startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        finish();
    }

My User Object:

public class User {
    //user information
    String name, email, password;
    int walletBalance, tasksTaken, tasksPosted;

    //constructor
    public User(String name, String email, String password, int walletBalance, int tasksTaken, int tasksPosted) {
        this.name = name;
        this.email = email;
        this.password = password;
        this.walletBalance = walletBalance;
        this.tasksTaken = tasksTaken;
        this.tasksPosted = tasksPosted;
    }

    //empty constructor
    public User() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getWalletBalance() {
        return walletBalance;
    }

    public void setWalletBalance(int walletBalance) {
        this.walletBalance = walletBalance;
    }

    public int getTasksTaken() {
        return tasksTaken;
    }

    public void setTasksTaken(int tasksTaken) {
        this.tasksTaken = tasksTaken;
    }

    public int getTasksPosted() {
        return tasksPosted;
    }

    public void setTasksPosted(int tasksPosted) {
        this.tasksPosted = tasksPosted;
    }
}

My Firebase Database:

Any help is very very appreciated!!

Body:
Your reference is wrong.
You should write "users" node first in your reference.
Also you shouldn't use query without filtering or sorting.

mReference = mDatabase.getReference("users").child(mAuth.getUid());


问:
Flutter pop to new route
I have a ModalRoute that once I close, I'd like to replace the entire Navigation stack below it before calling .pop

The reason I want to pop rather than push is because I want to scale the modal down to reveal the new route underneath.

This is my ScaledRoute:

import 'package:flutter/material.dart';

class ScaleRoute extends PageRouteBuilder {
  final Widget page;

  ScaleRoute({this.page}) : super(
    pageBuilder: (
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
    ) => page,
    transitionsBuilder: (
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child,
    ) => ScaleTransition(
      scale: Tween<double>(
        begin: 0.0,
        end: 1.0,
      ).animate(
        CurvedAnimation(
          parent: animation,
          curve: Curves.fastOutSlowIn,
        ),
      ),
      child: child,
    ),
  );
}
```

<p>This is how I'm opening the Modal that extends ModalRoute:</p>

<pre class="lang-dart prettyprint-override"><code>final confettiModal = ConfettiModal(
  onComplete: () {
    // Callback to close the modal to remove itself from the stack
    Navigator.pop(context);
  }
);

// New page is also a named route '/newPage'
final PageRouteBuilder route = ScaleRoute(page: NewPage());

// I can't seem to get this to work
Navigator.replaceRouteBelow(context, anchorRoute: null, newRoute: route);
</code>```

Update

Here's my code that works. I needed to return the Modal's BuildContext to get the anchorRoute to replace up until.

final confettiModal = ConfettiModal(
  onComplete: (BuildContext modalContext) {
    final anchor = ModalRoute.of(modalContext);
    final page = MaterialPageRoute(builder: (context) => NewPage());
    Navigator.replaceRouteBelow(context, anchorRoute: anchor, newRoute: page);
    Navigator.pop(context);
  }
);

Navigator.push(context, confettiModal);
```

答:
anchorRoute in Navigator.replaceRouteBelow is required so it cannot be set to null.
Documentation </p>

Title: Flutter pop to new route

Body:
I have a ModalRoute that once I close, I'd like to replace the entire Navigation stack below it before calling .pop

The reason I want to pop rather than push is because I want to scale the modal down to reveal the new route underneath.

This is my ScaledRoute:

import 'package:flutter/material.dart';

class ScaleRoute extends PageRouteBuilder {
  final Widget page;

  ScaleRoute({this.page}) : super(
    pageBuilder: (
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
    ) => page,
    transitionsBuilder: (
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child,
    ) => ScaleTransition(
      scale: Tween<double>(
        begin: 0.0,
        end: 1.0,
      ).animate(
        CurvedAnimation(
          parent: animation,
          curve: Curves.fastOutSlowIn,
        ),
      ),
      child: child,
    ),
  );
}

This is how I'm opening the Modal that extends ModalRoute:

final confettiModal = ConfettiModal(
  onComplete: () {
    // Callback to close the modal to remove itself from the stack
    Navigator.pop(context);
  }
);

// New page is also a named route '/newPage'
final PageRouteBuilder route = ScaleRoute(page: NewPage());

// I can't seem to get this to work
Navigator.replaceRouteBelow(context, anchorRoute: null, newRoute: route);

Update

Here's my code that works. I needed to return the Modal's BuildContext to get the anchorRoute to replace up until.

final confettiModal = ConfettiModal(
  onComplete: (BuildContext modalContext) {
    final anchor = ModalRoute.of(modalContext);
    final page = MaterialPageRoute(builder: (context) => NewPage());
    Navigator.replaceRouteBelow(context, anchorRoute: anchor, newRoute: page);
    Navigator.pop(context);
  }
);

Navigator.push(context, confettiModal);


问:
Cannot send email from SendGrid Account api key
i have created secret key from azure and use in code it's working perfectly fine but when i use secret key create from my gmail account i do not receive any email.

I am using the same code for both send grid api keys one from azure sendgrid account another from my direct sendgrid account but from azure sendgrid account emails are delivering without any error and in sendgrid activities tab also there is recent record but form my direct sendgrid account emails are not delivering and there is not recent record in activity tab.

```<code>static async Task Execute()
        {
            dynamic client = new SendGridClient("SG.Ge6udT3CQtKCuGIxhGwqkg.***************-B--zeJXJKnlomAzB2XzQ");
            var msg = new SendGridMessage();
            //noreply@teamx.ae
            msg.SetFrom(new EmailAddress("360loyalofficial@gmail.com", "Teamx | Services"));

            var recipients = new List<EmailAddress>
                {
                    new EmailAddress("nauman.nasir138@gmail.com")
                };
            msg.AddTos(recipients);

            msg.SetSubject("Test");

            msg.AddContent(MimeType.Text, "test");
            msg.AddContent(MimeType.Html, "test");

            var response = await client.SendEmailAsync(msg);
        }
</code>```

答:
Your messages won't be delivered because you don't own or control the gmail.com domain.
 More details can be found here:

https://sendgrid.com/blog/dont-send-email-from-domains-you-dont-control/

but essentially it's a security feature to stop scammers and your message won't be delivered.

Body:
i have created secret key from azure and use in code it's working perfectly fine but when i use secret key create from my gmail account i do not receive any email.

I am using the same code for both send grid api keys one from azure sendgrid account another from my direct sendgrid account but from azure sendgrid account emails are delivering without any error and in sendgrid activities tab also there is recent record but form my direct sendgrid account emails are not delivering and there is not recent record in activity tab.

static async Task Execute()
        {
            dynamic client = new SendGridClient("SG.Ge6udT3CQtKCuGIxhGwqkg.***************-B--zeJXJKnlomAzB2XzQ");
            var msg = new SendGridMessage();
            //noreply@teamx.ae
            msg.SetFrom(new EmailAddress("360loyalofficial@gmail.com", "Teamx | Services"));

            var recipients = new List<EmailAddress>
                {
                    new EmailAddress("nauman.nasir138@gmail.com")
                };
            msg.AddTos(recipients);

            msg.SetSubject("Test");

            msg.AddContent(MimeType.Text, "test");
            msg.AddContent(MimeType.Html, "test");

            var response = await client.SendEmailAsync(msg);
        }


问:
WPF XAML Bindings and CurrentCulture Display
I'm seeing some invalid behavior from XAML documents when the CurrentCulture is changed. When I have some elements like this in a Window:

```<code><Window x:Class="WpfLocalizationLocBaml.Test"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:glob="clr-namespace:System.Globalization;assembly=mscorlib"
        x:Name="wndTest"
    Title="Test" Height="300" Width="300">
    <StackPanel>

        <TextBlock x:Name="lblCultureName"
                   Text="{Binding Source={x:Static glob:CultureInfo.CurrentCulture},
                                  Path=DisplayName}" />

        <TextBlock x:Name="lblLocaleDateValue"
                   Text="{Binding ElementName=wndTest, Path=TestDate}"/>

        <TextBlock x:Name="lblLocaleNumberValue"
                   Text="{Binding ElementName=wndTest,Path=NumberValue,StringFormat=c}" />

    </StackPanel>
</Window>
</code>```

as well as a MessageBox.Show( NumberValue.ToString("c") ); when the form starts I'm seeing different results.

If I run the form with the default language all is well obviously. However, if I change the culture in code or at startup the bindings to the date and number values still show en-US formatting. The MessageBox.Show() value displayed appropriately reflects the current culture.

Question: Does WPF not respect CurrentCulture in bindings? And if so what exactly determines the culture that is used for the bindings. It's clearly en-US in my case, but regardless what I set in my project as the default language it always binds in en-US.

Any ideas appreciated...

答: It's also worth pointing out that the same thing happens in Silverlight, with the same solution except for swapping IetfLanguageTag for Name.</p>

Body:
I'm seeing some invalid behavior from XAML documents when the CurrentCulture is changed. When I have some elements like this in a Window:

<Window x:Class="WpfLocalizationLocBaml.Test"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:glob="clr-namespace:System.Globalization;assembly=mscorlib"
        x:Name="wndTest"
    Title="Test" Height="300" Width="300">
    <StackPanel>

        <TextBlock x:Name="lblCultureName"
                   Text="{Binding Source={x:Static glob:CultureInfo.CurrentCulture},
                                  Path=DisplayName}" />

        <TextBlock x:Name="lblLocaleDateValue"
                   Text="{Binding ElementName=wndTest, Path=TestDate}"/>

        <TextBlock x:Name="lblLocaleNumberValue"
                   Text="{Binding ElementName=wndTest,Path=NumberValue,StringFormat=c}" />

    </StackPanel>
</Window>

as well as a MessageBox.Show( NumberValue.ToString("c") ); when the form starts I'm seeing different results.

If I run the form with the default language all is well obviously. However, if I change the culture in code or at startup the bindings to the date and number values still show en-US formatting. The MessageBox.Show() value displayed appropriately reflects the current culture.

Question: Does WPF not respect CurrentCulture in bindings? And if so what exactly determines the culture that is used for the bindings. It's clearly en-US in my case, but regardless what I set in my project as the default language it always binds in en-US.

Any ideas appreciated...


问:
How to make an element's content editable with JavaScript (or jQuery)
How would I make it so the content of an element could be made editable through native JavaScript (DOM) and/or jQuery?</p>

答:
All we have to do is set the contenteditable attribute on nearly any HTML element to make it editable.

Here's a simple example which creates a  element whose contents the user can edit.

```<code><div contenteditable="true">
  This text can be edited by the user.
</div>
</code>```

Body:
All we have to do is set the contenteditable attribute on nearly any HTML element to make it editable.

Here's a simple example which creates a  element whose contents the user can edit.

<div contenteditable="true">
  This text can be edited by the user.
</div>


问:
Proplem in my OpenCart 3.0.3.3. Directory not empty in developer.php on line 69
The error :

rmdir(/home/amazonnc/ocartdata/storage/cache/so): Directory not empty
  in /home/amazonnc/public_html/admin/controller/common/developer.php on
  line 69

in the Error Log thans

2020-06-02 0:47:27 - PHP Warning:
  unlink(/home/amazonnc/ocartdata/storage/cache/cache.catalog.language.1591061429):
  No such file or directory in
  /home/amazonnc/public_html/system/library/cache/file.php on line 68

答:
Check if this file exists system/library/cache/file.php.

Check if all directories have permissions 644 and all files are 755.

Clean everything inside system/storage/cache/.

Clean the .twig. cache. https://stackoverflow.com/a/61524855/3187127


问:
Specifying different lists
I'm recently trying to compare and specify the different lists in C#.
for instance,

```<code>List <int> list1 = new List<int>{3,1,2,0};
List <int> list2 = new List<int>{2,3,5,1};
List <int> list3 = new List<int>{0,1,3,2};
List <int> list4 = new List<int>{0,1,3,2};

//I want to get  {3,1,2,0} , {2,3,5,1} , {0,1,3,2} those three types.
</code>```

I got 4 lists, list3 equals to list4, list1 and list2 are different.
Although the content in list1, list3, and list4 are the same, the orders are different so it doesn't count. Eventually, it should return only three distinct lists. ({3,1,2,0} , {2,3,5,1} , {0,1,3,2})

Thank you so much!

答:
The results that you are seeing are correct, you have 4 different lists, 2 of which happen to have the same content.

Technically you have 4 references 2 lists, and list3 and list4 are references to 2 different lists that happent to have the same content.

If you need to check that the content of the lists is the same then I would suggest the linq SequenceEqual function.

To generate the output you're looking for I would suggest, that you combine Distinct() with SequenceEqual(). However, there are a number of pitfalls here:

SequenceEqual() and Distinct() are both optimised, but I would be wary of this for long lists.

The current implementation of Distinct() has a dependency on GetHashCode() so you need to be careful here too.

I've added a simple example below, but it comes with a massive warning label.

If you're planning to use this with a decent size list, the implementation of ListValueComparer.GetHashCode() becomes critical. Like all GetHashCode() implemenations, it needs to:

be fast,

return the same result for the same input

return reasonably diffrent results for different inputs.

If it doesn't meet all 3 criteria you will be in a world of hurt!

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace list_compare
{
    class ListValueComparer : IEqualityComparer<List<int>>
    {
        public bool Equals([AllowNull] List<int> x, [AllowNull] List<int> y)
        {
            if (x == null || y == null)
                return false;

            return x.SequenceEqual(y);
        }

        public int GetHashCode([DisallowNull] List<int> obj)
        {
            return obj.Aggregate((a, b) => a ^ b);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var lists = new List<List<int>>{
                new List<int>{3,1,2,0},
                new List<int>{2,3,5,1},
                new List<int>{0,1,3,2},
                new List<int>{0,1,3,2}
            };

            var distinct = lists
                .Distinct(new ListValueComparer())
                .ToList();

            foreach (var list in distinct)
            {
                foreach (var item in list)
                {
                    Console.Write(item.ToString());
                    Console.Write(" ");
                }
                Console.WriteLine();
            }
        }
    }
}
```

<p>Which gives the output </p>

```
3 1 2 0
2 3 5 1
0 1 3 2
```

Title: Specifying different lists

Body:
I'm recently trying to compare and specify the different lists in C#.
for instance,

List <int> list1 = new List<int>{3,1,2,0};
List <int> list2 = new List<int>{2,3,5,1};
List <int> list3 = new List<int>{0,1,3,2};
List <int> list4 = new List<int>{0,1,3,2};

//I want to get  {3,1,2,0} , {2,3,5,1} , {0,1,3,2} those three types.

I got 4 lists, list3 equals to list4, list1 and list2 are different.
Although the content in list1, list3, and list4 are the same, the orders are different so it doesn't count. Eventually, it should return only three distinct lists. ({3,1,2,0} , {2,3,5,1} , {0,1,3,2})

Thank you so much!

Body:
The results that you are seeing are correct, you have 4 different lists, 2 of which happen to have the same content.

Technically you have 4 references 2 lists, and list3 and list4 are references to 2 different lists that happent to have the same content.

If you need to check that the content of the lists is the same then I would suggest the linq SequenceEqual function.

To generate the output you're looking for I would suggest, that you combine Distinct() with SequenceEqual(). However, there are a number of pitfalls here:

SequenceEqual() and Distinct() are both optimised, but I would be wary of this for long lists.

The current implementation of Distinct() has a dependency on GetHashCode() so you need to be careful here too.

I've added a simple example below, but it comes with a massive warning label.

If you're planning to use this with a decent size list, the implementation of ListValueComparer.GetHashCode() becomes critical. Like all GetHashCode() implemenations, it needs to:

be fast,

return the same result for the same input

return reasonably diffrent results for different inputs.

If it doesn't meet all 3 criteria you will be in a world of hurt!

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace list_compare
{
    class ListValueComparer : IEqualityComparer<List<int>>
    {
        public bool Equals([AllowNull] List<int> x, [AllowNull] List<int> y)
        {
            if (x == null || y == null)
                return false;

            return x.SequenceEqual(y);
        }

        public int GetHashCode([DisallowNull] List<int> obj)
        {
            return obj.Aggregate((a, b) => a ^ b);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var lists = new List<List<int>>{
                new List<int>{3,1,2,0},
                new List<int>{2,3,5,1},
                new List<int>{0,1,3,2},
                new List<int>{0,1,3,2}
            };

            var distinct = lists
                .Distinct(new ListValueComparer())
                .ToList();

            foreach (var list in distinct)
            {
                foreach (var item in list)
                {
                    Console.Write(item.ToString());
                    Console.Write(" ");
                }
                Console.WriteLine();
            }
        }
    }
}

Which gives the output

3 1 2 0
2 3 5 1
0 1 3 2


问:
Enabling XSLl in PHP
I have a server with php5 installed on it. I need to enable XSL on it. when I try phpinfo(); I don't see anything related to XSL. I already have "libxslt" installed.

Is there a way through which I can upgrade my php installation to have xsl support?
I don't want to reinstall php.

I thought of adding extension=xsl.so to php.ini but I don't know if I have xsl.so there and where it is! but does that work?? if yes I have to figure out where xsl.so is or download it if that's possible.

Please help me because this is my first experience in a real working environment.

BTW: The server OS is Linux (a property distribution base on RPM).

UPDATE:

I tried the following method but still can't enable xsl or see any difference in phpinfo():

1- decompress the php source code and cd to the directory of the extenstion i.e. cd /path/to/php/ext/xsl

2- phpize

3- ./configure

4- make

5- then move the xsl.so to the extension_dir

6- restart apache

I found this on many forums and blogs online but I don't know why it didn't work with me.

答:
I finally could enable XSL without recompiling the whole PHP, using phpize command:

How to enable php extension using `phpize`?

the most important thing is enabling DOM extension before compiling the XSL extension and enabling it..

Thanks

Title: Enabling XSLl in PHP


问:
How to create a "waiting" queue when there are more than 2 visitors on the website
Hello,
I use a form on my website. This form contains content that can only be selected once.

I would like to create some sort of "queue" when there is more than one visitor on the page.

So for example 2 visitors:
visitor 1 -> fill in the form.
visitor 2 -> gets popup with "please wait"
visitor 1 -> sends the form.
system processes data from form.
visitor 2 -> make popup invisible and show form.

Or another option would be to check if someone else has checked the checkbox yet and give a message if someone has checked this yet.

答:
Well, as you didn't provide any code I will just give you my humble thoughts on this.

First of all: May I ask why? This sounds like a horrible user experience...

If you really want to do it anyways, here's what you need: AJAX or jQuery to provide the live feedback popup you mentioned. For the visitor count caching part there are obviously many ways to do it like using scripts of any kind or even some file or database based solution. From that point on you just go with your favorite web language and code the main queue logic, I would recommend PHP with a breeze of JavaScript.

I hope this was at least a little bit helpful.

Kind regards