问:
How do I refresh the information from text fields in this loop?
I am trying to make a login GUI, which closes when a correct combination of username and password are entered. When I enter them correctly, it works fine, but if an incorrect combination is entered, the loop just keeps repeating with the same values of "u" and "pw", stopping me from typing anything else.

I tried adding a logB.setSelected(false); at the end of the while loop, but it still doesn't let me enter new values.

(BTW I know that the incorrect password label shows up from the beginning, but I'm just trying to solve this problem right now. Also the Login class started off as CLI, so there are some remnants of that left in the code, but I just want to get it working before I clean it up.)

GUI class:

```<code>import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Login_GUI implements ActionListener {

private static JLabel userL;
private static JTextField userT;
private static JLabel pwL;
private static JPasswordField pwT;
private static JLabel respL;
private static JFrame f;
public static boolean authorized;
public static void GUIfunc(){
    JPanel p = new JPanel();
    f = new JFrame("RMT 1.0");
    f.setSize(250, 225);
    f.setLocation(1080,530);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    f.add(p);

    userL = new JLabel("Username:");
    userL.setBounds(10,20,80,25);
    p.add(userL);
    userT = new JTextField(20);
    userT.setBounds(100,20,165,25);
    p.add(userT);

    pwL = new JLabel("Password:");
    pwL.setBounds(10,50,80,25);
    p.add(pwL);
    pwT = new JPasswordField(20);
    pwT.setBounds(100,50,165,25);
    p.add(pwT);

    JButton logB = new JButton("Login");
    logB.setBounds(10,80,80,25);
    logB.addActionListener(new Login_GUI());
    p.add(logB);

    respL = new JLabel("Incorrect username or password.");
    respL.setBounds(10,100,80,25);
    respL.setEnabled(false);
    p.add(respL);

}
@Override
    public void actionPerformed(ActionEvent e){
    while (authorized != true){
        String u = userT.getText();
        String pw = pwT.getText();
        try {
            authorized = Login2.loginfunc(u,pw);
        }
        catch(IOException exc){
            exc.printStackTrace();
        }
        logB.setSelected(false);

    }
    f.dispatchEvent(new WindowEvent(f, WindowEvent.WINDOW_CLOSING));

}
}
</code>```

Login class:

```<code>import java.util.*;
import java.io.*;
import java.nio.*;

class Login2{
public static boolean loginfunc(String u, String pw)throws IOException{
    File users = new File("C:\\Users\\Marcell\\OneDrive\\Computer Science\\IA\\users.txt");
    Scanner kb = new Scanner (System.in);
    Scanner sc = new Scanner (users);

    String token1 = "";
    int numOfEmp = 3;
    boolean authorized = false;
    boolean repeat = true;
    String temp[] = new String[numOfEmp];

    for(int x=0;x<numOfEmp;x++){
       token1 = sc.nextLine();
       temp[x] = token1;
    }

    String full = u + "," + pw;
    for (int x=0;x<numOfEmp;x++ ){
        String pass = temp[x];
        if (pass.equals(full)){
             System.out.println("Login successful.");
             authorized = true;
             repeat = false;
            }
    }
    if (repeat = false){
        return(false);
    }

    return(authorized);
}
}
</code>```

Thanks for the help in advance!

答:
Replace actionPerformed as follows:

```<code>public void actionPerformed(ActionEvent e){
    if (!authorized){
        String u = userT.getText();
        String pw = pwT.getText();
        try {
            authorized = Login2.loginfunc(u,pw);
            if(authorized) {
                f.dispatchEvent(new WindowEvent(f, WindowEvent.WINDOW_CLOSING));
            }
        }
        catch(IOException exc){
            exc.printStackTrace();
        }
        logB.setSelected(false);
    }
}
</code>```

Body:
I am trying to make a login GUI, which closes when a correct combination of username and password are entered. When I enter them correctly, it works fine, but if an incorrect combination is entered, the loop just keeps repeating with the same values of "u" and "pw", stopping me from typing anything else.

I tried adding a logB.setSelected(false); at the end of the while loop, but it still doesn't let me enter new values.

(BTW I know that the incorrect password label shows up from the beginning, but I'm just trying to solve this problem right now. Also the Login class started off as CLI, so there are some remnants of that left in the code, but I just want to get it working before I clean it up.)

GUI class:

import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Login_GUI implements ActionListener {

private static JLabel userL;
private static JTextField userT;
private static JLabel pwL;
private static JPasswordField pwT;
private static JLabel respL;
private static JFrame f;
public static boolean authorized;
public static void GUIfunc(){
    JPanel p = new JPanel();
    f = new JFrame("RMT 1.0");
    f.setSize(250, 225);
    f.setLocation(1080,530);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    f.add(p);

    userL = new JLabel("Username:");
    userL.setBounds(10,20,80,25);
    p.add(userL);
    userT = new JTextField(20);
    userT.setBounds(100,20,165,25);
    p.add(userT);

    pwL = new JLabel("Password:");
    pwL.setBounds(10,50,80,25);
    p.add(pwL);
    pwT = new JPasswordField(20);
    pwT.setBounds(100,50,165,25);
    p.add(pwT);

    JButton logB = new JButton("Login");
    logB.setBounds(10,80,80,25);
    logB.addActionListener(new Login_GUI());
    p.add(logB);

    respL = new JLabel("Incorrect username or password.");
    respL.setBounds(10,100,80,25);
    respL.setEnabled(false);
    p.add(respL);

}
@Override
    public void actionPerformed(ActionEvent e){
    while (authorized != true){
        String u = userT.getText();
        String pw = pwT.getText();
        try {
            authorized = Login2.loginfunc(u,pw);
        }
        catch(IOException exc){
            exc.printStackTrace();
        }
        logB.setSelected(false);

    }
    f.dispatchEvent(new WindowEvent(f, WindowEvent.WINDOW_CLOSING));

}
}

Login class:

import java.util.*;
import java.io.*;
import java.nio.*;

class Login2{
public static boolean loginfunc(String u, String pw)throws IOException{
    File users = new File("C:\\Users\\Marcell\\OneDrive\\Computer Science\\IA\\users.txt");
    Scanner kb = new Scanner (System.in);
    Scanner sc = new Scanner (users);

    String token1 = "";
    int numOfEmp = 3;
    boolean authorized = false;
    boolean repeat = true;
    String temp[] = new String[numOfEmp];

    for(int x=0;x<numOfEmp;x++){
       token1 = sc.nextLine();
       temp[x] = token1;
    }

    String full = u + "," + pw;
    for (int x=0;x<numOfEmp;x++ ){
        String pass = temp[x];
        if (pass.equals(full)){
             System.out.println("Login successful.");
             authorized = true;
             repeat = false;
            }
    }
    if (repeat = false){
        return(false);
    }

    return(authorized);
}
}

Thanks for the help in advance!

Body:
Replace actionPerformed as follows:

public void actionPerformed(ActionEvent e){
    if (!authorized){
        String u = userT.getText();
        String pw = pwT.getText();
        try {
            authorized = Login2.loginfunc(u,pw);
            if(authorized) {
                f.dispatchEvent(new WindowEvent(f, WindowEvent.WINDOW_CLOSING));
            }
        }
        catch(IOException exc){
            exc.printStackTrace();
        }
        logB.setSelected(false);
    }
}


来源: stackexchange

问:
Listings days and hours in a 2D list using python
I want to list all dates and hours between 2 given inout datetimes using dateutil library.

Example:
input: date_from= 02/16/2020:00:00:00, date_to = 02/17/2020:00:00:00

I want to have a list with the below structure

```<code>02/16/2020, 02/16/2020:00:00:00

02/16/2020, 02/16/2020:01:00:00

02/16/2020, 02/16/2020:02:00:00

... till hour 23

02/17/2020, 02/17/2020:00:00:00

02/17/2020, 02/17/2020:01:00:00

02/17/2020, 02/17/2020:02:00:00

.... till hour 23
</code>```

I tried the below code and it seems the logic need to be changed.

```<code>days = [[], []]
for day in rrule.rrule(rrule.DAILY, dtstart=date_from, until=date_to):
    for hour in rrule.rrule(rrule.HOURLY, dtstart=date_from, until=date_to):
        days.append(str(day))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to list all dates and hours between 2 given inout datetimes using dateutil library.

Example:
input: date_from= 02/16/2020:00:00:00, date_to = 02/17/2020:00:00:00

I want to have a list with the below structure

02/16/2020, 02/16/2020:00:00:00

02/16/2020, 02/16/2020:01:00:00

02/16/2020, 02/16/2020:02:00:00

... till hour 23

02/17/2020, 02/17/2020:00:00:00

02/17/2020, 02/17/2020:01:00:00

02/17/2020, 02/17/2020:02:00:00

.... till hour 23

I tried the below code and it seems the logic need to be changed.

days = [[], []]
for day in rrule.rrule(rrule.DAILY, dtstart=date_from, until=date_to):
    for hour in rrule.rrule(rrule.HOURLY, dtstart=date_from, until=date_to):
        days.append(str(day))

Body:
As a 2D array of date and datetime:

from datetime import datetime as dt
from datetime import timedelta

date_from= '02/16/2020 00:00:00'
date_to = '02/17/2020 00:00:00'

date_from = dt.strptime(date_from, '%m/%d/%Y %H:%M:%S')
date_to = dt.strptime(date_to, '%m/%d/%Y %H:%M:%S')
new_date = date_from
all_dates = []
while new_date < date_to:
    date_only = dt.strftime(new_date,'%m/%d/%Y')
    date_and_time = dt.strftime(new_date,'%m/%d/%Y %H:%M:%S')
    all_dates.append([date_only,date_and_time])
    new_date = new_date + timedelta(minutes=60)

print(all_dates)

output:

[['02/16/2020', '02/16/2020 00:00:00'], ['02/16/2020', '02/16/2020 01:00:00'], ['02/16/2020', '02/16/2020 02:00:00'], ['02/16/2020', '02/16/2020 03:00:00'], ['02/16/2020', '02/16/2020 04:00:00'], ['02/16/2020', '02/16/2020 05:00:00'], ['02/16/2020', '02/16/2020 06:00:00'], ['02/16/2020', '02/16/2020 07:00:00'], ['02/16/2020', '02/16/2020 08:00:00'], ['02/16/2020', '02/16/2020 09:00:00'], ['02/16/2020', '02/16/2020 10:00:00'], ['02/16/2020', '02/16/2020 11:00:00'], ['02/16/2020', '02/16/2020 12:00:00'], ['02/16/2020', '02/16/2020 13:00:00'], ['02/16/2020', '02/16/2020 14:00:00'], ['02/16/2020', '02/16/2020 15:00:00'], ['02/16/2020', '02/16/2020 16:00:00'], ['02/16/2020', '02/16/2020 17:00:00'], ['02/16/2020', '02/16/2020 18:00:00'], ['02/16/2020', '02/16/2020 19:00:00'], ['02/16/2020', '02/16/2020 20:00:00'], ['02/16/2020', '02/16/2020 21:00:00'], ['02/16/2020', '02/16/2020 22:00:00'], ['02/16/2020', '02/16/2020 23:00:00']]

Is this what you want?


问:
Using the Symfony Router with vue.js
I'm quite new to symfony and a litte bit experienced in vue.js. After a bit of research I wasn't able to find a solution to my problem.

I have the following problem:

I'm building a multi-page-application with Symfony and vue.js for the frontend. I use a search-form in my template index.html.twig to get information about the given search query from an API.

Therefore I use routing with Symfony. When hitting the search button the URL xxx/search?query=test is called. This URL is handled by my symfony controller which gets data from the API and renders the page search-result.html.twig. I use Vue.js in index.html.twig and I want to use Vue in search-result.html.twig (and other routes and pages) as well, but I'm not quite sure how to use different vue instances on different pages.

I hope I was able to describe the problem properly! Looking forward to your suggestions.

UPDATE:

This is my current infrastructure:

base.html.twig (all other pages inherit from this template):

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}
            {{ encore_entry_link_tags('app') }}
        {% endblock %}
    </head>
    <body>
        <div id="app">
            {% block body %}{% endblock %}
        </div>
   </body>
   {% block javascripts %}
     {{ encore_entry_script_tags('app') }}
   {% endblock %}
</html>
</code>```

This is how I initialize my vue instance:

```<code>import Vue from 'vue';
import App from './App.vue';

new Vue({
  render: h => h(App)
}).$mount('#app');
</code>```

From App.vue I then dispatch my different components.

Problem is: When I now open a different twig-file I cannot use a different page layout.

答:
You probably want to have multiple Vue-Apps with different entrypoints that can be used in your Symfony application. From what it looks like you have 3 places where you have to make changes. Depending on details you might have to make additional changes as well.

Webpack configuration

This requires that you add these entrypoints to your webpack.config.js e.g. by adding an entrypoint for searchApp.

Your vue "bootstrap" file

Then you have to copy the app.js (or wherever the Vue-snippet from your question is stored) for the new app and make the adjustments, e.g. instead of import App from './App.vue' you could have import SearchApp from './SearchApp.vue' (and then update the App call further down).

Your templates

Now you should have 2 vue apps in your project with 2 webpack entrypoints to load their data (CSS/JS). Your base.html.twig will load the javascript for the original app with entrypoint app. You now have to tell search-result.html.twig to overwrite these files with the ones for the new entrypoint (assuming: searchApp):

```<code>{% extends "base.html.twig" %}

{% block stylesheets %}{{ encore_entry_link_tags('searchApp') }}{% endblock %}
{% block javascripts %}{{ encore_entry_script_tags('searchApp') }}{% endblock %}
</code>```

In case one of these blocks contains some shared resources you can also add a {{ parent() }} call to load them from the base.html.twig, but be careful to not get conflicts in your JS calls. Now the search-result.html.twig should load the new Vue-app. You can now change the layout for that app as you see fit and it should not bother your other app.

Title: Using the Symfony Router with vue.js

Body:
I'm quite new to symfony and a litte bit experienced in vue.js. After a bit of research I wasn't able to find a solution to my problem.

I have the following problem:

I'm building a multi-page-application with Symfony and vue.js for the frontend. I use a search-form in my template index.html.twig to get information about the given search query from an API.

Therefore I use routing with Symfony. When hitting the search button the URL xxx/search?query=test is called. This URL is handled by my symfony controller which gets data from the API and renders the page search-result.html.twig. I use Vue.js in index.html.twig and I want to use Vue in search-result.html.twig (and other routes and pages) as well, but I'm not quite sure how to use different vue instances on different pages.

I hope I was able to describe the problem properly! Looking forward to your suggestions.

UPDATE:

This is my current infrastructure:

base.html.twig (all other pages inherit from this template):

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}
            {{ encore_entry_link_tags('app') }}
        {% endblock %}

            {% block body %}{% endblock %}

   {% block javascripts %}
     {{ encore_entry_script_tags('app') }}
   {% endblock %}

This is how I initialize my vue instance:

import Vue from 'vue';
import App from './App.vue';

new Vue({
  render: h => h(App)
}).$mount('#app');

From App.vue I then dispatch my different components.

Problem is: When I now open a different twig-file I cannot use a different page layout.

Body:
You probably want to have multiple Vue-Apps with different entrypoints that can be used in your Symfony application. From what it looks like you have 3 places where you have to make changes. Depending on details you might have to make additional changes as well.

Webpack configuration

This requires that you add these entrypoints to your webpack.config.js e.g. by adding an entrypoint for searchApp.

Your vue "bootstrap" file

Then you have to copy the app.js (or wherever the Vue-snippet from your question is stored) for the new app and make the adjustments, e.g. instead of import App from './App.vue' you could have import SearchApp from './SearchApp.vue' (and then update the App call further down).

Your templates

Now you should have 2 vue apps in your project with 2 webpack entrypoints to load their data (CSS/JS). Your base.html.twig will load the javascript for the original app with entrypoint app. You now have to tell search-result.html.twig to overwrite these files with the ones for the new entrypoint (assuming: searchApp):

{% extends "base.html.twig" %}

{% block stylesheets %}{{ encore_entry_link_tags('searchApp') }}{% endblock %}
{% block javascripts %}{{ encore_entry_script_tags('searchApp') }}{% endblock %}

In case one of these blocks contains some shared resources you can also add a {{ parent() }} call to load them from the base.html.twig, but be careful to not get conflicts in your JS calls. Now the search-result.html.twig should load the new Vue-app. You can now change the layout for that app as you see fit and it should not bother your other app.


问:
How to open pdf file stored in firebase storage in next tab

In the above image, on clicking ViewFile, i can see file URL in console (bottom right), on clicking that link, file is opening in next tab. I want file to directly open in next tab when I click on 'View File'.
Below im dropping my code, can anyone help me doing it.

```<code>DownloadEvidence(){
    const files = firebase.storage().ref('pdf/498df57c-c470-40e4-8077-0fa3ae4863a4.pdf/');
    files.getDownloadURL().then((url) => {
      console.log(url);
    })
  }
</code>```

答:
```<code>DownloadEvidence(){
    const files = firebase.storage().ref('pdf/498df57c-c470-40e4-8077-0fa3ae4863a4.pdf/');
    files.getDownloadURL().then((url) => {
      window.open(url, "_blank")
    })
  }
</code>```

Body:
In the above image, on clicking ViewFile, i can see file URL in console (bottom right), on clicking that link, file is opening in next tab. I want file to directly open in next tab when I click on 'View File'.
Below im dropping my code, can anyone help me doing it.

DownloadEvidence(){
    const files = firebase.storage().ref('pdf/498df57c-c470-40e4-8077-0fa3ae4863a4.pdf/');
    files.getDownloadURL().then((url) => {
      console.log(url);
    })
  }


问:
Type Any don't have member count, two dimensional array
hi I want to make a view like this picture below, so what I try to do is to make a two dimensional array with UITableViewCell and a string. Since it types Any the compiler complain "Type Any don't have a member of count and subscript". is it my approach right? to make this view like the picture below, or should I create one by one?

This is my code

```<code>var tableItems = [
        [ProgressCell.self],
        ["Information", "Address", "Password"],
        ["Help", "Term and Condition", "Privacy"],
        [SignOutCell]
    ] as Any

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return tableItems[section].count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)

    let name                = tableItems[indexPath.section][indexPath.row] as! Int

    cell.textLabel?.text    = name
    cell.textLabel?.font    = UIFont(name: "NunitoSans-Regular", size: 16)
    cell.accessoryType      = .disclosureIndicator

    return cell
}
</code>```

答:
I believe you want to define an array that contains Any item, which would look like this [[Any]]

Update your code to the following:

```<code>var tableItems = [
    [ProgressCell.self],
    ["Information", "Address", "Password"],
    ["Help", "Term and Condition", "Privacy"],
    [SignOutCell]
] as [[Any]]
</code>```

As suggested by @fogmeister in the comment below you shouldn't be really be using Any and that further work needs to be done to define the types correctly.

Body:
hi I want to make a view like this picture below, so what I try to do is to make a two dimensional array with UITableViewCell and a string. Since it types Any the compiler complain "Type Any don't have a member of count and subscript". is it my approach right? to make this view like the picture below, or should I create one by one?

This is my code

var tableItems = [
        [ProgressCell.self],
        ["Information", "Address", "Password"],
        ["Help", "Term and Condition", "Privacy"],
        [SignOutCell]
    ] as Any

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return tableItems[section].count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)

    let name                = tableItems[indexPath.section][indexPath.row] as! Int

    cell.textLabel?.text    = name
    cell.textLabel?.font    = UIFont(name: "NunitoSans-Regular", size: 16)
    cell.accessoryType      = .disclosureIndicator

    return cell
}

Body:
I believe you want to define an array that contains Any item, which would look like this [[Any]]

Update your code to the following:

var tableItems = [
    [ProgressCell.self],
    ["Information", "Address", "Password"],
    ["Help", "Term and Condition", "Privacy"],
    [SignOutCell]
] as [[Any]]

As suggested by @fogmeister in the comment below you shouldn't be really be using Any and that further work needs to be done to define the types correctly.


答: Try window.open(url, '_blank');

Title: How to open pdf file stored in firebase storage in next tab

Body: Try window.open(url, '_blank');


问:
Why doesn't my delete button work in PHP?
I'm just starting out with PHP and am a bit lost. I feel like it's probably something small I'm missing but when I click the delete button it does not work. It doesn't give me any errors, the button just clicks and does nothing. Any ideas why? I've spent hours trying to figure it out but I have come up with nothing. I've done add user and show users in much the same way and it works but this has me stumped. Thanks in advance :)

users.controller.php

```<code>static public function DeleteUserController(){

        if(isset($_GET["userId"])){

            $table ="users";
            $data = $_GET["userId"];
            var_dump($data);
            $answer = UserModel::DeleteUserModel($table, $data);

            if($answer == "ok"){

                echo'<script>

                swal({
                      type: "success",
                      title: "User has been Deleted",
                      showConfirmButton: true,
                      confirmButtonText: "Close"

                      }).then(function(result){

                        if (result.value) {

                        window.location = "users";

                        }
                    })

                </script>';

            }

        }

    }
</code>```

users.model.php

```<code>static public function DeleteUserModel($table, $data){

        $stmt = Connection::connect()->prepare("DELETE FROM $table WHERE id = :id");

        $stmt -> bindParam(":id", $data, PDO::PARAM_STR);

        if ($stmt->execute()) {

            return 'ok';

        } else {

            return 'error';

        }

        $stmt -> close();

        $stmt = null;
    }
</code>```

users.js

```<code>$(".btnDeleteUser").click(function(){
    var userId = $(this).attr("userId");
    var username = $(this).attr("username");

    swal({
        title: 'Are you sure you want to delete user?',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          cancelButtonText: 'Cancel',
          confirmButtonText: 'Confirm'
        }).then((result)=>{

        if(result.value){

          window.location = "index.php?route=users&userId="+userId+"&username="+username;

        }

    })

})

</code>```

users.php

```<code><button class="btn btn-danger btnDeleteUser" userId="'.$value["id"].'" username="'.$value["user"].'"><i class="fa fa-times"></i></button>
</code>```

users.php

```<code><?php

  $deleteUser = new ControllerUsers();
  $deleteUser -> DeleteUserController();

?>
</code>```

index.php

```<code><?php

require_once "controllers/template.controller.php";
require_once "controllers/products.controller.php";
require_once "controllers/sales.controller.php";
require_once "controllers/users.controller.php";

require_once "models/products.model.php";
require_once "models/sales.model.php";
require_once "models/users.model.php";

$template = new TemplateController();
$template -> tempController();
</code>```

答:
Thanks for all your help. It was, as I said, a simple error. I didn't link the Javascript file in my template.php file:</p>

```<code><script src="views/javascript/template.js"></script>
<script src="views/javascript/users.js"></script>
<script src="views/javascript/categories.js"></script>
</code>```

Body:
I'm just starting out with PHP and am a bit lost. I feel like it's probably something small I'm missing but when I click the delete button it does not work. It doesn't give me any errors, the button just clicks and does nothing. Any ideas why? I've spent hours trying to figure it out but I have come up with nothing. I've done add user and show users in much the same way and it works but this has me stumped. Thanks in advance :)

users.controller.php

static public function DeleteUserController(){

        if(isset($_GET["userId"])){

            $table ="users";
            $data = $_GET["userId"];
            var_dump($data);
            $answer = UserModel::DeleteUserModel($table, $data);

            if($answer == "ok"){

                echo'';

            }

        }

    }

users.model.php

static public function DeleteUserModel($table, $data){

        $stmt = Connection::connect()->prepare("DELETE FROM $table WHERE id = :id");

        $stmt -> bindParam(":id", $data, PDO::PARAM_STR);

        if ($stmt->execute()) {

            return 'ok';

        } else {

            return 'error';

        }

        $stmt -> close();

        $stmt = null;
    }

users.js

$(".btnDeleteUser").click(function(){
    var userId = $(this).attr("userId");
    var username = $(this).attr("username");

    swal({
        title: 'Are you sure you want to delete user?',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          cancelButtonText: 'Cancel',
          confirmButtonText: 'Confirm'
        }).then((result)=>{

        if(result.value){

          window.location = "index.php?route=users&userId="+userId+"&username="+username;

        }

    })

})

users.php

<button class="btn btn-danger btnDeleteUser" userId="'.$value["id"].'" username="'.$value["user"].'"></button>

users.php

<?php

  $deleteUser = new ControllerUsers();
  $deleteUser -> DeleteUserController();

?>

index.php

<?php

require_once "controllers/template.controller.php";
require_once "controllers/products.controller.php";
require_once "controllers/sales.controller.php";
require_once "controllers/users.controller.php";

require_once "models/products.model.php";
require_once "models/sales.model.php";
require_once "models/users.model.php";

$template = new TemplateController();
$template -> tempController();

Body:
Thanks for all your help. It was, as I said, a simple error. I didn't link the Javascript file in my template.php file:

<script src="views/javascript/template.js"></script>
<script src="views/javascript/users.js"></script>
<script src="views/javascript/categories.js"></script>


问:
Storetext from a table choice correct lines to store for Selenium Ide Ui Vision Kantu
I need to storetext all lines from a table where CODICE CATASTALE have a value

I add an image to show, I need to save all line in variable with storetext with this characteristic CODICE CATASTALE have a value, in the image I add 1 - 2 - 3 - 4 to explain line to store.

This is a relative storetext when CODICE CATASTALE have a value stored the line.

Here the page

nonsolocap.it/cap?k=56040

Image

答:
After the execution such script in Selenium IDE table variable will contain data from the table. xpath_to_all_rows_with_CODICE_CATASTALE should be replaced with corresponding xpath.

```<code>store xpath count | xpath = xpath_to_all_rows_with_CODICE_CATASTALE | n
store | 0 | j
while | ${j} < ${n} |
store | | rowElement
store | 0 | i
while | ${i} < 7 |
store text | xpath = xpath_to_all_rows_with_CODICE_CATASTALE[${j}]/td[${i}] | element
execute script | if (${i} != 0) var arr = ${rowElement}; else var arr = []; var element = ${element}; arr.push(element); return arr; | rowElement
execute script | return Number(${i}) + 1; | i
end| |
execute script | if (${j} != 0) var arr = ${table}; else var arr = []; var rowElement = ${rowElement}; arr.push(rowElement); return arr; | table
execute script | return Number(${j}) + 1; | j
end| |
</code>```

Body:
After the execution such script in Selenium IDE table variable will contain data from the table. xpath_to_all_rows_with_CODICE_CATASTALE should be replaced with corresponding xpath.

store xpath count | xpath = xpath_to_all_rows_with_CODICE_CATASTALE | n
store | 0 | j
while | ${j} < ${n} |
store | | rowElement
store | 0 | i
while | ${i} < 7 |
store text | xpath = xpath_to_all_rows_with_CODICE_CATASTALE[${j}]/td[${i}] | element
execute script | if (${i} != 0) var arr = ${rowElement}; else var arr = []; var element = ${element}; arr.push(element); return arr; | rowElement
execute script | return Number(${i}) + 1; | i
end| |
execute script | if (${j} != 0) var arr = ${table}; else var arr = []; var rowElement = ${rowElement}; arr.push(rowElement); return arr; | table
execute script | return Number(${j}) + 1; | j
end| |


问:
How to make drupal see client IP behind nginx Reverse Proxy->Varnish->Apache stack?
I'm using nginx as a reverse proxy that handles port 80 -> 443 redirect and then onto a varnish cache (port 8181) that talks to an Apache2.4 backend (port 8182) serving a drupal (7.69) site.

I've configured nginx to forward the client IP as:

```<code>proxy_pass            http://127.0.0.1:8181;
proxy_read_timeout    90;
proxy_connect_timeout 90;
proxy_redirect        off;
proxy_set_header      X-Real-IP $remote_addr;
proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header      X-Forwarded-Proto https;
proxy_set_header      X-Forwarded-Port 443;
proxy_set_header      X-Forwarded-Host $remote_addr;
proxy_set_header      Host $host;
</code>```

In varnish vcl_recv I'm adding:

```<code>if (req.restarts == 0) {
  if (req.http.X-Forwarded-For) {
    set req.http.X-Forwarded-For =
    req.http.X-Forwarded-For + ", " + client.ip;
  } else {
    set req.http.X-Forwarded-For = client.ip;
  }
}
</code>```

In apache I have installed remoteip module and set the following config:

```<code>RemoteIPHeader X-Forwarded-For
RemoteIPTrustedProxy 127.0.0.1
</code>```

In drupal's settings.php I have

```<code>$conf['reverse_proxy'] = True;
$conf['reverse_proxy_header'] = 'X-Forwarded-For';
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
</code>```

...But drupal seems to be nonetheless seeing and loggin only the localhost (127.0.0.1) ip rather than the genuine client IP. So forms are being logged as submitted not from the genuine user but the server itself.

I'm wondering if my varnish config is off, because I'm also proxying from nginx and bypassing varnish to go directly to a forum which bypasses drupal (it's SMF) but runs on the same apache config; the forum is logging the client IPs sent from nginx (using the same header changes and apache remoteip config) just fine.

I'd be grateful for guidance / suggestions.

答:
Varnish

Your Varnish configuration for X-Forwarded-For is correct, in theory.

In practice you don't even need to set X-Forwarded-For in Varnish, because Varnish will do this automatically.

Drupal configuration

As far as Drupal configuration goes, it may have something to do with the reverse_proxy_header. I stumbled upon this piece of Drupal 7 documentation: https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/ip_address/7.x.

The crucial part of the code on that page is the following:

$reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');

Apparently this ip_address() function can be made aware of the X-Forwarded-For header through a configuration parameter.

However, the header format is not the official HTTP format, but rather the way that the PHP $_SERVER superglobal stores it. In this case the format would be HTTP_X_FORWARDED_FOR.

So please try replacing $conf['reverse_proxy_header'] = 'X-Forwarded-For'; with $conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';.

Body:
I'm using nginx as a reverse proxy that handles port 80 -> 443 redirect and then onto a varnish cache (port 8181) that talks to an Apache2.4 backend (port 8182) serving a drupal (7.69) site.

I've configured nginx to forward the client IP as:

proxy_pass            http://127.0.0.1:8181;
proxy_read_timeout    90;
proxy_connect_timeout 90;
proxy_redirect        off;
proxy_set_header      X-Real-IP $remote_addr;
proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header      X-Forwarded-Proto https;
proxy_set_header      X-Forwarded-Port 443;
proxy_set_header      X-Forwarded-Host $remote_addr;
proxy_set_header      Host $host;

In varnish vcl_recv I'm adding:

if (req.restarts == 0) {
  if (req.http.X-Forwarded-For) {
    set req.http.X-Forwarded-For =
    req.http.X-Forwarded-For + ", " + client.ip;
  } else {
    set req.http.X-Forwarded-For = client.ip;
  }
}

In apache I have installed remoteip module and set the following config:

RemoteIPHeader X-Forwarded-For
RemoteIPTrustedProxy 127.0.0.1

In drupal's settings.php I have

$conf['reverse_proxy'] = True;
$conf['reverse_proxy_header'] = 'X-Forwarded-For';
$conf['reverse_proxy_addresses'] = array('127.0.0.1');

...But drupal seems to be nonetheless seeing and loggin only the localhost (127.0.0.1) ip rather than the genuine client IP. So forms are being logged as submitted not from the genuine user but the server itself.

I'm wondering if my varnish config is off, because I'm also proxying from nginx and bypassing varnish to go directly to a forum which bypasses drupal (it's SMF) but runs on the same apache config; the forum is logging the client IPs sent from nginx (using the same header changes and apache remoteip config) just fine.

I'd be grateful for guidance / suggestions.


问:
Making Comments on pull request for jupyter notebook
Jupyter notebook's now render as html files in github, which is fantastic; however, if you want to leave a comment on a pull request I only see an option to do so on the raw notebook.  Does anyone know how you can leave comments on the html file?

If not, are people aware of other services that allow for commenting on jupyter notebooks?

答:
Does anyone know how you can leave comments on the html file?

You can use ReviewNB to look at visual diff for notebooks & write comments on notebook cells in a pull request.

Disclaimer: I built ReviewNB.

ContentLicense: CC BY-SA 3.0


问:
Spring Data Elastic - Java.Time.Instant class Jackson deserliization not working
Following is my WorkroomDTO:

```<code>  @NotNull
  private Instant createdOn;

  @JsonInclude(JsonInclude.Include.NON_NULL)
  private Instant changedOn;
</code>```

As you can see i am using Java 8 Instant class.
In the elasticsearch Index server i store the following as JSON:

```<code>  "createdOn": {
    "nano": 877000000,
    "epochSecond": 1579861613
  },
  "changedOn": {
    "nano": 920000000,
    "epochSecond": 1579861613
  },
</code>```

The problem is when i query the elasticsearch server to get me the workroom

```<code>    return elasticsearchOperations.queryForPage(new NativeSearchQueryBuilder().withQuery(mainQuery)
                                                                          .withPageable(elasticUtils.interceptPageable(searchDto.getPageable(), "name"))
                                                                          .build(),
                                            WorkroomDTO.class);
</code>```

, i make a mapping of these fields to my WorkroomDTO i get the following exception:

```<code>    com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.Instant` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"createdOn":{"nano":68000000,"epochSecond":1580127683}
</code>```

FYI:

I have created a configuration file where is register explicitly the JavaTimeModule to the Object Mapper

```<code> @Configuration
public class JacksonConfiguration {

  @Value("${application.serialization.include-type-key:true}")
  private boolean includeTypeKey = true;

  @Bean
  public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.addHandler(new MissingTypeIdHandler());
    if (includeTypeKey) {
      mapper.setMixInResolver(new TypeKeyMixInResolver());
    }
    return mapper;
  }

}
</code>```

Need help!

答:
Where does this data come from? Is it written by your application?

It seems that the used Jackson mapper does not have the jackson-datatype-jsr310 module registered.

On reading the data tries to find a constructor of Instant that can be used to create an Instant object. But Instant does not have a default constructor and the Mapper should use the Instant.ofEpochSecond(long, long) method. This page pretty declares the problem and shows how the Jackson Mapper is configured.

Storing an instant in this way, as an object with two properties, is not the right way for storing dates in Elasticsearch. You should read the Elasticsearch documentation about how Elastcisearch handles date/time fields. When storing the instant as an object like this, you loose the ability to use Elasticsearch queries with criteria based on a date/time.

Which version of Spring Data Elasticsearch do you use? Because of problems like this, from the upcoming version 4.0 on, Spring Data Elasticsearch will not use the Jackson mapper anymore for entity mapping. The MappingElasticsearchConverter supports the use of the Elasticsearch date format and the java.time classes.

Body:
Following is my WorkroomDTO:

  @NotNull
  private Instant createdOn;

  @JsonInclude(JsonInclude.Include.NON_NULL)
  private Instant changedOn;

As you can see i am using Java 8 Instant class.
In the elasticsearch Index server i store the following as JSON:

  "createdOn": {
    "nano": 877000000,
    "epochSecond": 1579861613
  },
  "changedOn": {
    "nano": 920000000,
    "epochSecond": 1579861613
  },

The problem is when i query the elasticsearch server to get me the workroom

    return elasticsearchOperations.queryForPage(new NativeSearchQueryBuilder().withQuery(mainQuery)
                                                                          .withPageable(elasticUtils.interceptPageable(searchDto.getPageable(), "name"))
                                                                          .build(),
                                            WorkroomDTO.class);

, i make a mapping of these fields to my WorkroomDTO i get the following exception:

    com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.Instant` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"createdOn":{"nano":68000000,"epochSecond":1580127683}

FYI:

I have created a configuration file where is register explicitly the JavaTimeModule to the Object Mapper

 @Configuration
public class JacksonConfiguration {

  @Value("${application.serialization.include-type-key:true}")
  private boolean includeTypeKey = true;

  @Bean
  public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.addHandler(new MissingTypeIdHandler());
    if (includeTypeKey) {
      mapper.setMixInResolver(new TypeKeyMixInResolver());
    }
    return mapper;
  }

}

Need help!


问:
$(...).cells is undefined in jQuery
i have two forms, form1 contains the date and the display button, the show button allows you to hide the form1 and display the form2, the form2 contains the chosen date and a datatable with checkboxes and button valider, i want when i click the show button console show matricules of salaries.

$(document).ready(function() {
  $('#check_all').on('click', function(e) {
    if ($(this).is(':checked', true)) {
      $(".checkbox").prop('checked', true);
    } else {
      $(".checkbox").prop('checked', false);
    }
  });

  $('.checkbox').on('click', function() {
    if ($('.checkbox:checked').length == $('.checkbox').length) {
      $('#check_all').prop('checked', true);
    } else {
      $('#check_all').prop('checked', false);
    }
  });

  $("#form2").hide();

  $("#hide").click(function() {
    $("#form1").hide();
    $("#form2").show();
    let dat = $("#dateS").val();
    $("#da").text(dat);

    $("tr").each(function(i, r) {
      let mat = $(r).cells[2].innerText;
      console.log(mat);
    });
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- form 1 -->
<div id="form1">
  <div class=" col-md-10 col-md-offset-1">
    <div class="form-group col-md-3">
      <label for="titre">date</label>
    </div>
    <div class="form-group col-md-5">
      <input type="date" name="dateS" id="dateS" class="form-control">
    </div>
  </div>
  <div class="col-md-6 col-md-offset-3">
    <div class="form-group col-md-2">
      <button class="btn btn-primary" id="hide" data-url="">show</button>
    </div>
  </div>
</div>

<!-- form 2 -->
<div id="form2">
  <div class="col-md-10 col-md-offset-1">
    <h4>dateS : <span id="da"></span></h4>
  </div>
  <table class="table table-bordered" id="mytable">
    <tr>
      <th><input type="checkbox" id="check_all"></th>
      <th>nom</th>
      <th>matricule</th>
      <th>adresse</th>
      <th>prime</th>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox"></td>
      <td>najib</td>
      <td>52</td>
      <td>tihit</td>
      <td><input type="text" name="prime" class="form-control prime" value="0"></td>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox"></td>
      <td>adil</td>
      <td>62</td>
      <td>tagmast</td>
      <td><input type="text" name="prime" class="form-control prime" value="0"></td>
    </tr>
  </table>
  <div class="form-group col-md-offset-5 ">
    <button class="btn btn-success add-all" type="submit" id="hide">valider</button>
  </div>
</div></code>```

答:
Instead of $(r).cells[2].innerText use jQuery

```<code>$(r).find('td').eq(2).text()
</code>```

or:

```<code>$(this).find('td:eq(2)').text();
</code>```

cells is used in vanilla JavaScript to get the cells from TableRowElement, while your $(r) is a reference to a collection of elements wrapped into a jQuery object

therefore if you want to use JavaScript you still can, but like:

```<code>r.cells[2].textContent
</code>```

also, notice the use of the preferred textContent vs innerText

Title: $(...).cells is undefined in jQuery

Body:
i have two forms, form1 contains the date and the display button, the show button allows you to hide the form1 and display the form2, the form2 contains the chosen date and a datatable with checkboxes and button valider, i want when i click the show button console show matricules of salaries.

$(document).ready(function() {
  $('#check_all').on('click', function(e) {
    if ($(this).is(':checked', true)) {
      $(".checkbox").prop('checked', true);
    } else {
      $(".checkbox").prop('checked', false);
    }
  });

  $('.checkbox').on('click', function() {
    if ($('.checkbox:checked').length == $('.checkbox').length) {
      $('#check_all').prop('checked', true);
    } else {
      $('#check_all').prop('checked', false);
    }
  });

  $("#form2").hide();

  $("#hide").click(function() {
    $("#form1").hide();
    $("#form2").show();
    let dat = $("#dateS").val();
    $("#da").text(dat);

    $("tr").each(function(i, r) {
      let mat = $(r).cells[2].innerText;
      console.log(mat);
    });
  });
})

      date

      <input type="date" name="dateS" id="dateS" class="form-control">

      <button class="btn btn-primary" id="hide" data-url="">show</button>

dateS :

      <input type="checkbox" id="check_all">
      nom
      matricule
      adresse
      prime

      <input type="checkbox" class="checkbox">
      najib
      52
      tihit
      <input type="text" name="prime" class="form-control prime" value="0">

      <input type="checkbox" class="checkbox">
      adil
      62
      tagmast
      <input type="text" name="prime" class="form-control prime" value="0">

    <button class="btn btn-success add-all" type="submit" id="hide">valider</button>

Body:
Instead of $(r).cells[2].innerText use jQuery

$(r).find('td').eq(2).text()

or:

$(this).find('td:eq(2)').text();

cells is used in vanilla JavaScript to get the cells from TableRowElement, while your $(r) is a reference to a collection of elements wrapped into a jQuery object

therefore if you want to use JavaScript you still can, but like:

r.cells[2].textContent

also, notice the use of the preferred textContent vs innerText


问:
Django Postman error this field is required
I'm getting

{"franchise":["This field is required."]}

when I send POST request to localhost Django via

http://localhost:8000/api/franchise/charge/

I'm sending the following 2 fields as Postman's body

```<code>key: price       value: 1000
key: franchise   value: 1
</code>```

URL

```<code>router.register(r'franchise/charge', views.FranchiseChargeViewSet)
</code>```

View

```<code>class FranchiseChargeViewSet(viewsets.ModelViewSet):
    queryset = FranchiseCharge.objects.all()
    serializer_class = FranchiseChargeSerializer

    def get_permissions(self):
        permission_classes = []
        if self.action == 'create':
            permission_classes = [IsFranchise]
        elif self.action == 'retrieve':
            permission_classes = [IsFranchise]
        elif self.action == 'list':
            permission_classes = [IsFranchise]
        elif self.action == 'update' or self.action == 'partial_update':
            permission_classes = [IsFranchise]
        elif self.action == 'destroy':
            permission_classes = [IsFranchise]
        return [permission() for permission in permission_classes]
</code>```

Model

```<code>class FranchiseCharge(models.Model):
    franchise = models.ForeignKey(Franchise,null=True,on_delete=models.SET_NULL, default=1)
    time = models.DateTimeField(default=timezone.now)
    price = models.PositiveIntegerField(default=0)
</code>```

Serializer

```<code>class FranchiseChargeSerializer(RelationModelSerializer):
    franchise = FranchiseSerializer(is_relation=True)
    class Meta:
        model = FranchiseCharge
        fields = ('id','franchise','time','price')

    @transaction.atomic
    def create(self, validated_data):
        instance = FranchiseCharge.objects.create(**validated_data)
        return instance
</code>```

What do I need to do to fix this?

答:
You are using nested serializer, so the data for it should be nested json object in data.

As I see, you are using RelationModelSerializer - if it corresponds to the one described in linked article - it also suggests putting related model pk field name in nested json:

```<code>{
  "price": 1000,
  "franchise": {
    "id": 1
  }
}
</code>```

For regular DRF nested serilizers - one option is to use different serializers for read and write. That way serializer for write can be configured without nested serializer, just accept franchise_id directly in franchise field.

Check this SO answer on nested serializers.

Body:
I'm getting

{"franchise":["This field is required."]}

when I send POST request to localhost Django via

http://localhost:8000/api/franchise/charge/

I'm sending the following 2 fields as Postman's body

key: price       value: 1000
key: franchise   value: 1

URL

router.register(r'franchise/charge', views.FranchiseChargeViewSet)

View

class FranchiseChargeViewSet(viewsets.ModelViewSet):
    queryset = FranchiseCharge.objects.all()
    serializer_class = FranchiseChargeSerializer

    def get_permissions(self):
        permission_classes = []
        if self.action == 'create':
            permission_classes = [IsFranchise]
        elif self.action == 'retrieve':
            permission_classes = [IsFranchise]
        elif self.action == 'list':
            permission_classes = [IsFranchise]
        elif self.action == 'update' or self.action == 'partial_update':
            permission_classes = [IsFranchise]
        elif self.action == 'destroy':
            permission_classes = [IsFranchise]
        return [permission() for permission in permission_classes]

Model

class FranchiseCharge(models.Model):
    franchise = models.ForeignKey(Franchise,null=True,on_delete=models.SET_NULL, default=1)
    time = models.DateTimeField(default=timezone.now)
    price = models.PositiveIntegerField(default=0)

Serializer

class FranchiseChargeSerializer(RelationModelSerializer):
    franchise = FranchiseSerializer(is_relation=True)
    class Meta:
        model = FranchiseCharge
        fields = ('id','franchise','time','price')

    @transaction.atomic
    def create(self, validated_data):
        instance = FranchiseCharge.objects.create(**validated_data)
        return instance

What do I need to do to fix this?

Body:
You are using nested serializer, so the data for it should be nested json object in data.

As I see, you are using RelationModelSerializer - if it corresponds to the one described in linked article - it also suggests putting related model pk field name in nested json:

{
  "price": 1000,
  "franchise": {
    "id": 1
  }
}

For regular DRF nested serilizers - one option is to use different serializers for read and write. That way serializer for write can be configured without nested serializer, just accept franchise_id directly in franchise field.

Check this SO answer on nested serializers.


问:
Pass a param to my AppComponent at Bootstrap time
I'm working on a angular v7 app that is hosted on a asp.net application.
Basically I will have a dropdown on my .net app and I want to call the angular one with the selected value.
I did several attempts to pass a param at the bootstrap (app.module.ts) but am getting an error.

```<code>@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  entryComponents: [AppComponent]
})
export class AppModule {

  ngDoBootstrap(app: ApplicationRef) {
    document.addEventListener('myAppA', function(e : CustomEvent) {
        app.bootstrap(AppComponent, [{provide:'MESSAGE', useValue: 'Hello Angular'}]);
    });
  }
}
</code>```

I believe there is a simple way to achieve it. Any ideas?

答:
I found the solution.

```<code>@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    ConfigService
  ],
  entryComponents: [AppComponent]
})
export class AppModule implements DoBootstrap {
  constructor(private config: ConfigService) { }

  ngDoBootstrap(app: ApplicationRef) {
    const self = this;
    document.addEventListener('myAppA', function(e : CustomEvent) {
      self.config.setScheme("BBB");
      app.bootstrap(AppComponent);
    });
  }
}
</code>```

Basically I create a service and inject it into the AppModule constructor. Then, before calling the bootstrap I set the values I want using the service. Could't find anything else.

Body:
I'm working on a angular v7 app that is hosted on a asp.net application.
Basically I will have a dropdown on my .net app and I want to call the angular one with the selected value.
I did several attempts to pass a param at the bootstrap (app.module.ts) but am getting an error.

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  entryComponents: [AppComponent]
})
export class AppModule {

  ngDoBootstrap(app: ApplicationRef) {
    document.addEventListener('myAppA', function(e : CustomEvent) {
        app.bootstrap(AppComponent, [{provide:'MESSAGE', useValue: 'Hello Angular'}]);
    });
  }
}

I believe there is a simple way to achieve it. Any ideas?

Body:
I found the solution.

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    ConfigService
  ],
  entryComponents: [AppComponent]
})
export class AppModule implements DoBootstrap {
  constructor(private config: ConfigService) { }

  ngDoBootstrap(app: ApplicationRef) {
    const self = this;
    document.addEventListener('myAppA', function(e : CustomEvent) {
      self.config.setScheme("BBB");
      app.bootstrap(AppComponent);
    });
  }
}

Basically I create a service and inject it into the AppModule constructor. Then, before calling the bootstrap I set the values I want using the service. Could't find anything else.


问:
Cookie not setting in Scala Play
I am trying to set a cookie from a response when using the scala play framework. I am creating a cookie called session with its value being a UUID (I do know play comes with its own session management).
I can see the response headers contain the set cookie instruction, but the cookie ins't being set.

Below is the scala code in the action in the controller where the cookie is set

```<code>val cookie= Cookie("session",
    sessionToken,
    httpOnly=true,
    sameSite=Some(Cookie.SameSite.Lax))

Ok(Json.toJson(res))
  .withCookies(cookie)
// Also tried with .bakeCookies() after the withCookies() call
</code>```

I can see the cookie header in the response in both FireFox and Chrome. They both show what appears to be a correctly formed cookie in their respective response cookie viewer in their developer tools.

```<code>Set-Cookie: session=c0174ed1-ebd3-4a8d-a5b2-5b09a3fe616b; SameSite=Lax; Path=/; HTTPOnly
</code>```

However, in both browsers the cookie does not get set. I have tried true and false httpOnly, and messing with the maxAge value. I have tried setting the domain to a url and then setting the url in the hosts file as suggested here.

The URL on the react frontend is

```<code>http://localhost:49161/login/hydrate
</code>```

and the endpoint in play is

```<code>http://localhost:49162/user/login/rehydrate
</code>```

I did also try setting the path to /login/hydrate/ on the cookie

The react code on the front end

```<code>     // Inside async function
     // methodStrings[method] = "post" in this request
     axios[methodStrings[method]](url, params)
        .then(result => {
          resolve(result);
        })
        .catch(err => {
          console.error(`Error with request to ${url} - ${err}`);
          reject(err.response.status);
        });
</code>```

And then I console.log the result from awaiting the request

答:
Problem is in axios (and/or browser).

Based on this issue Cookies headers are present but Cookies are not stored in browser #1553 you need to set withCredentials Axios config to store cookies in browser after request:

  axios.post('domain.com', {
    name: 'name',
    password: 'password'
  }, {
    //AxiosRequestConfig parameter
    withCredentials: true //correct
  })
```

Title: Cookie not setting in Scala Play

Body:
I am trying to set a cookie from a response when using the scala play framework. I am creating a cookie called session with its value being a UUID (I do know play comes with its own session management).
I can see the response headers contain the set cookie instruction, but the cookie ins't being set.

Below is the scala code in the action in the controller where the cookie is set

val cookie= Cookie("session",
    sessionToken,
    httpOnly=true,
    sameSite=Some(Cookie.SameSite.Lax))

Ok(Json.toJson(res))
  .withCookies(cookie)
// Also tried with .bakeCookies() after the withCookies() call

I can see the cookie header in the response in both FireFox and Chrome. They both show what appears to be a correctly formed cookie in their respective response cookie viewer in their developer tools.

Set-Cookie: session=c0174ed1-ebd3-4a8d-a5b2-5b09a3fe616b; SameSite=Lax; Path=/; HTTPOnly

However, in both browsers the cookie does not get set. I have tried true and false httpOnly, and messing with the maxAge value. I have tried setting the domain to a url and then setting the url in the hosts file as suggested here.

The URL on the react frontend is

http://localhost:49161/login/hydrate

and the endpoint in play is

http://localhost:49162/user/login/rehydrate

I did also try setting the path to /login/hydrate/ on the cookie

The react code on the front end

     // Inside async function
     // methodStrings[method] = "post" in this request
     axios[methodStrings[method]](url, params)
        .then(result => {
          resolve(result);
        })
        .catch(err => {
          console.error(`Error with request to ${url} - ${err}`);
          reject(err.response.status);
        });

And then I console.log the result from awaiting the request


问:
Trouble With CPAN Module
I've tried to install the WWW::Mechanize module with

```<code>'cpan WWW::Mechanize'
</code>```

I get no errors on the 'use WWW::Mechanize' line which means its finding the files, but upon trying to instantiate it with:

```<code>$m = WWW::Mechanize->new();
</code>```

I get the following problem:

Can't locate HTTP/Config.pm in @INC (@INC contains: /Library/Perl/Updates/5.10.0/darwin-    thread-multi-2level /Library/Perl/Updates/5.10.0 /System/Library/Perl/5.10.0/darwin-thread-multi-2level /System/Library/Perl/5.10.0 /Library/Perl/5.10.0/darwin-thread-multi-2level /Library/Perl/5.10.0 /Network/Library/Perl/5.10.0/darwin-thread-multi-2level /Network/Library/Perl/5.10.0 /Network/Library/Perl /System/Library/Perl/Extras/5.10.0/darwin-thread-multi-2level /System/Library/Perl/Extras/5.10.0 .) at      /Library/Perl/5.10.0/LWP/UserAgent.pm line 746.

I'm not exactly sure what is going on.  I feel like I have all the neccessary dependencies, but I can't seem to find what this particular error means.

My script is empty besides the previously mentioned lines and

```<code>use strict;
use warnings;
</code>```

Has anyone run into this?

答:
try installing it with the following command (from the shell):

```<code>perl -MCPAN -e 'install WWW::Mechanize'
</code>```

follow the installation process, and answer 'Y' where needed.

Title: Trouble With CPAN Module

Body:
I've tried to install the WWW::Mechanize module with

'cpan WWW::Mechanize'

I get no errors on the 'use WWW::Mechanize' line which means its finding the files, but upon trying to instantiate it with:

$m = WWW::Mechanize->new();

I get the following problem:

Can't locate HTTP/Config.pm in @INC (@INC contains: /Library/Perl/Updates/5.10.0/darwin-    thread-multi-2level /Library/Perl/Updates/5.10.0 /System/Library/Perl/5.10.0/darwin-thread-multi-2level /System/Library/Perl/5.10.0 /Library/Perl/5.10.0/darwin-thread-multi-2level /Library/Perl/5.10.0 /Network/Library/Perl/5.10.0/darwin-thread-multi-2level /Network/Library/Perl/5.10.0 /Network/Library/Perl /System/Library/Perl/Extras/5.10.0/darwin-thread-multi-2level /System/Library/Perl/Extras/5.10.0 .) at      /Library/Perl/5.10.0/LWP/UserAgent.pm line 746.

I'm not exactly sure what is going on.  I feel like I have all the neccessary dependencies, but I can't seem to find what this particular error means.

My script is empty besides the previously mentioned lines and

use strict;
use warnings;

Has anyone run into this?

Body:
try installing it with the following command (from the shell):

perl -MCPAN -e 'install WWW::Mechanize'

follow the installation process, and answer 'Y' where needed.


问:
Best way to implement dynamic array of inputs in React
Currently I have implemented it using plain javascript array. But there seems to be few problems.

onChange, onDelete has to iterate all over the array which could be better like O(1)

When some item gets deleted key property of other items get changed. I'm not sure if it's bad or not.

Using immutable.js can get rid of problem 1. Is number 2 really a problem? Is there a better alternative than immutable.js?
Maybe I'm not asking the right questions, what's the best way?

import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState([""]);

    const onChange = (e, i) => {
        setRows(rows.map((row, index) => (index !== i ? row : e.target.value)));
    };

    const onDelete = i => {
        setRows(rows.filter((_, index) => i !== index));
    };

    return (
        <>
            {rows.map((row, index) => {
                return (

                        <input value={row} onChange={e => onChange(e, index)} />
                        {index !== 0 && (
                            <button onClick={() => onDelete(index)}>
                                - delete row
                            </button>
                        )}

                );
            })}

            <button onClick={() => setRows(rows.concat([""]))}>
                + add row
            </button>
        </>
    );
}
```

<p><strong>UPDATE</strong></p>

<p>I tried using <code>immutable-js</code> <code>OrderedMap</code>. Now <code>key</code> property of elements won't change and <code>onChange</code> and <code>onDelete</code> won't iterate over everything. Is this better than before?</p>

```import React, { useState } from "react";
import { OrderedMap } from "immutable";

export default function() {
    const [inputState, setInputState] = useState({
        rows: OrderedMap(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        setInputState({
            ...inputState,
            rows: inputState.rows.update(k, () => v),
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        setInputState({
            rows: rows.set(nextKey, ""),
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        setInputState({
            ...inputState,
            rows: inputState.rows.delete(k),
        });
    }

    return (
        <>
            {inputState.rows.entrySeq().map(([k, v]) => {
                return (

                        <input
                            value={v}
                            onChange={({ target: { value } }) => {
                                onChange(k, value);
                            }}
                        />
                        <button onClick={() => deleteItem(k)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
```

<p><strong>UPDATE: 2</strong>
Also tried using plain javascript <code>Map</code>.</p>

<pre class="lang-js prettyprint-override"><code>import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: new Map(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        const { rows, nextKey } = inputState;
        rows.set(k, v);
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.set(nextKey, "");
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        const { rows, nextKey } = inputState;
        rows.delete(k);
        setInputState({
            nextKey,
            rows,
        });
    }

    const uiList = [];

    for (const [k, v] of inputState.rows.entries()) {
        uiList.push(
            <div key={k}>
                <input
                    value={v}
                    onChange={({ target: { value } }) => {
                        onChange(k, value);
                    }}
                />
                <button onClick={() => deleteItem(k)}>-</button>
            </div>
        );
    }

    return (
        <>
            {uiList}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
</code>```

UPDATE 3
Using plain array but with key property.

```<code>import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: [],
        nextKey: Number.MIN_VALUE,
    });

    function onChange(i, v) {
        const { rows, nextKey } = inputState;
        rows[i].value = v;
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.push({ key: nextKey, value: "" });
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(i) {
        const { rows, nextKey } = inputState;
        rows.splice(i, 1);
        setInputState({
            nextKey,
            rows,
        });
    }

    return (
        <>
            {inputState.rows.map(({ key, value }, index) => {
                return (
                    <div key={key}>
                        <input
                            value={value}
                            onChange={({ target: { value } }) => {
                                onChange(index, value);
                            }}
                        />
                        <button onClick={() => deleteItem(index)}>-</button>
                    </div>
                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
</code>```

答:
So far, best choices are

Generate key to use as key.

Use map to have efficient update and delete.

Don't mutate the state.

The immutable library fits the point 2 and 3 perfectly. Since it can update and delete without mutation efficiently it seems like a good choice.

```<code>import React, { useState, useEffect } from "react";
import { OrderedMap } from "immutable";

function UsingImmutableJS({ onChange }) {
    const [inputState, setInputState] = useState({
        rows: OrderedMap(),
        nextKey: 0,
    });

    useEffect(() => {
        if (onChange) onChange([...inputState.rows.values()]);
    }, [inputState, onChange]);

    function onInputChange(k, v) {
        setInputState(prev => ({
            ...prev,
            rows: prev.rows.update(k, () => v),
        }));
    }

    function addRow() {
        setInputState(prev => ({
            nextKey: prev.nextKey + 1,
            rows: prev.rows.set(prev.nextKey, ""),
        }));
    }

    function deleteItem(k) {
        setInputState(prev => ({
            ...prev,
            rows: prev.rows.delete(k),
        }));
    }

    return (
        <>
            {inputState.rows.entrySeq().map(([k, v]) => {
                return (
                    <div key={k}>
                        <input
                            value={v}
                            onChange={({ target: { value } }) => {
                                onInputChange(k, value);
                            }}
                        />
                        <button onClick={() => deleteItem(k)}>-</button>
                    </div>
                );
            })}
            <button onClick={addRow}>+ add row</button>
            <button onClick={() => console.log([...inputState.rows.values()])}>
                print
            </button>
        </>
    );
}
</code>```

Body:
Currently I have implemented it using plain javascript array. But there seems to be few problems.

onChange, onDelete has to iterate all over the array which could be better like O(1)

When some item gets deleted key property of other items get changed. I'm not sure if it's bad or not.

Using immutable.js can get rid of problem 1. Is number 2 really a problem? Is there a better alternative than immutable.js?
Maybe I'm not asking the right questions, what's the best way?

import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState([""]);

    const onChange = (e, i) => {
        setRows(rows.map((row, index) => (index !== i ? row : e.target.value)));
    };

    const onDelete = i => {
        setRows(rows.filter((_, index) => i !== index));
    };

    return (
        <>
            {rows.map((row, index) => {
                return (

                        <input value={row} onChange={e => onChange(e, index)} />
                        {index !== 0 && (
                            <button onClick={() => onDelete(index)}>
                                - delete row
                            </button>
                        )}

                );
            })}

            <button onClick={() => setRows(rows.concat([""]))}>
                + add row
            </button>
        </>
    );
}

UPDATE

I tried using immutable-js OrderedMap. Now key property of elements won't change and onChange and onDelete won't iterate over everything. Is this better than before?

import React, { useState } from "react";
import { OrderedMap } from "immutable";

export default function() {
    const [inputState, setInputState] = useState({
        rows: OrderedMap(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        setInputState({
            ...inputState,
            rows: inputState.rows.update(k, () => v),
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        setInputState({
            rows: rows.set(nextKey, ""),
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        setInputState({
            ...inputState,
            rows: inputState.rows.delete(k),
        });
    }

    return (
        <>
            {inputState.rows.entrySeq().map(([k, v]) => {
                return (

                        <input
                            value={v}
                            onChange={({ target: { value } }) => {
                                onChange(k, value);
                            }}
                        />
                        <button onClick={() => deleteItem(k)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

UPDATE: 2
Also tried using plain javascript Map.

import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: new Map(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        const { rows, nextKey } = inputState;
        rows.set(k, v);
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.set(nextKey, "");
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        const { rows, nextKey } = inputState;
        rows.delete(k);
        setInputState({
            nextKey,
            rows,
        });
    }

    const uiList = [];

    for (const [k, v] of inputState.rows.entries()) {
        uiList.push(

                <input
                    value={v}
                    onChange={({ target: { value } }) => {
                        onChange(k, value);
                    }}
                />
                <button onClick={() => deleteItem(k)}>-</button>

        );
    }

    return (
        <>
            {uiList}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

UPDATE 3
Using plain array but with key property.

import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: [],
        nextKey: Number.MIN_VALUE,
    });

    function onChange(i, v) {
        const { rows, nextKey } = inputState;
        rows[i].value = v;
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.push({ key: nextKey, value: "" });
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(i) {
        const { rows, nextKey } = inputState;
        rows.splice(i, 1);
        setInputState({
            nextKey,
            rows,
        });
    }

    return (
        <>
            {inputState.rows.map(({ key, value }, index) => {
                return (

                        <input
                            value={value}
                            onChange={({ target: { value } }) => {
                                onChange(index, value);
                            }}
                        />
                        <button onClick={() => deleteItem(index)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

Body:
So far, best choices are

Generate key to use as key.

Use map to have efficient update and delete.

Don't mutate the state.

The immutable library fits the point 2 and 3 perfectly. Since it can update and delete without mutation efficiently it seems like a good choice.

import React, { useState, useEffect } from "react";
import { OrderedMap } from "immutable";

function UsingImmutableJS({ onChange }) {
    const [inputState, setInputState] = useState({
        rows: OrderedMap(),
        nextKey: 0,
    });

    useEffect(() => {
        if (onChange) onChange([...inputState.rows.values()]);
    }, [inputState, onChange]);

    function onInputChange(k, v) {
        setInputState(prev => ({
            ...prev,
            rows: prev.rows.update(k, () => v),
        }));
    }

    function addRow() {
        setInputState(prev => ({
            nextKey: prev.nextKey + 1,
            rows: prev.rows.set(prev.nextKey, ""),
        }));
    }

    function deleteItem(k) {
        setInputState(prev => ({
            ...prev,
            rows: prev.rows.delete(k),
        }));
    }

    return (
        <>
            {inputState.rows.entrySeq().map(([k, v]) => {
                return (
                    <div key={k}>
                        <input
                            value={v}
                            onChange={({ target: { value } }) => {
                                onInputChange(k, value);
                            }}
                        />
                        <button onClick={() => deleteItem(k)}>-</button>
                    </div>
                );
            })}
            <button onClick={addRow}>+ add row</button>
            <button onClick={() => console.log([...inputState.rows.values()])}>
                print
            </button>
        </>
    );
}


问:
Mapbox Terrain RGB image '
I am new to mapbox and am trying to get the Terrain rgb data. I have followed the example from the documentation here :
https://www.mapbox.com/help/access-elevation-data/

and used the following query:

api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token={my_access_token}

which works find for zoom levels from 0 to 5 and returns RGB tiles of elevation data from a high level.

api.mapbox.com/v4/mapbox.terrain-rgb/5/0/0.pngraw?access_token={my_access_token}

I need to get the data at a much higher zoom level than 5, but once I use a zoom level above 5 it returns 'Tile Does Not Exist'.

The documentation says that there is data up to zoom of 15. My access token works and I have tried x,y tiles of 0, 0 (which should exist at all levels). Has anyone any help or suggestions ?

答:
Had a similar issue and in my case the mistake was assuming that given an {x}/{y} tuple the zoom {z} was free to change, but it isn't, if zoom changes xy changes too.

To get the correct tiles I used mercantile (pip install mercantile)

```<code>import mercantile

print(mercantile.tile(-71.0638031, 42.3578952, 15))
>>> Tile(x=9915, y=12120, z=15)
</code>```

Title: Mapbox Terrain RGB image '

Body:
Had a similar issue and in my case the mistake was assuming that given an {x}/{y} tuple the zoom {z} was free to change, but it isn't, if zoom changes xy changes too.

To get the correct tiles I used mercantile (pip install mercantile)

import mercantile

print(mercantile.tile(-71.0638031, 42.3578952, 15))
>>> Tile(x=9915, y=12120, z=15)


问:
Add a query result (on any computed value) to a new WIT
I am creating new WorkItemType and would like to populate parts of the WIT card in the board with computed values, examples include:

Given a start date calculate the duration in weeks since then

Count the number of fields that contain a valid value

I am interested in either a way to include query results in the WIT card, or how to fill a defined field with computed values.

EDIT: Running an on-prem installation of azure-dev ops and using the new process template with an inherited process

答:
You may check Query based boards extension which allows you to visualize the result of work item queries on a board:

https://marketplace.visualstudio.com/items?itemName=realdolmen.querybasedboards


问:
Error converting data type nvarchar to real
I need to subtract two nvarchar values and store the result in another column. I understand that first I need to convert nvarchar to numeric values, but I always get this error

Error converting data type nvarchar to real

Just to mention in varchar values are stored only numeric values but I can't seem to get this conversion right.

答:
This looks like a SQL Server error.  If so, use try_convert():

```<code>select try_convert(real, string_col)
</code>```

This returns NULL instead of an error if there are conversion issues.

You can find the offending values using:

```<code>select string_col
from t
where try_convert(real, string_col) is null and
      string_col is not null;
</code>```

Body:
This looks like a SQL Server error.  If so, use try_convert():

select try_convert(real, string_col)

This returns NULL instead of an error if there are conversion issues.

You can find the offending values using:

select string_col
from t
where try_convert(real, string_col) is null and
      string_col is not null;


问:
MongoDB Custom Serializer not setting properties
Whenever using a custom serializer it sets the property value correctly in the database but the property on the object remains the default value.

Custom Serializer:

```<code>public class RngSerializer : SerializerBase<int>
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, int value)
    {
        var rng = new Random().Next(0, 100);
        Console.WriteLine($"Generated rng {rng}");
        context.Writer.WriteInt32(rng);
    }
}
</code>```

The object:

```<code>public class Entity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonSerializer(typeof(RngSerializer))]
    public int RngProp { get; set; }
}
</code>```

The code that does the inserting:

```<code>var entity = new Entity();
collection.InsertOne(entity);
Console.WriteLine($"Inserted Id {entity.Id}, Rng {entity.RngProp}");
</code>```

You can see that the serializer is called corrected, the value is also set when I check the object in the database. However, the driver doesn't seem to correctly set the property.

Generated rng 32

Inserted Id 5e4ade582c509931f4467e38, Rng 0

答:
UPDATE: pass down the value to the serializer encapsulated in a reference type.

public class MyInt
{
    public int RngProp { get; set; }
}

public class Entity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonSerializer(typeof(RngSerializer))]
    public MyInt MyProp { get; set; } = new MyInt();
}

public class RngSerializer : SerializerBase<MyInt>
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, MyInt value)
    {
        var rnd = new Random().Next(0, 100);
        value.RngProp = rnd;
        Console.WriteLine($"written rng {rnd}");
        context.Writer.WriteInt32(rnd);
    }

    public override MyInt Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return new MyInt
        {
            RngProp = context.Reader.ReadInt32()
        };
    }
}

var entity = new Entity();
collection.InsertOne(entity);
Console.WriteLine($"Inserted Id {entity.Id}, Rng {entity.MyProp.RngProp}");

var result = collection.FindSync(e => e.Id == entity.Id).Single();
Console.WriteLine($"Retrieved Id {entity.Id}, Rng {result.MyProp.RngProp}");

Console.ReadLine();
```

Body:
Whenever using a custom serializer it sets the property value correctly in the database but the property on the object remains the default value.

Custom Serializer:

public class RngSerializer : SerializerBase<int>
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, int value)
    {
        var rng = new Random().Next(0, 100);
        Console.WriteLine($"Generated rng {rng}");
        context.Writer.WriteInt32(rng);
    }
}

The object:

public class Entity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonSerializer(typeof(RngSerializer))]
    public int RngProp { get; set; }
}

The code that does the inserting:

var entity = new Entity();
collection.InsertOne(entity);
Console.WriteLine($"Inserted Id {entity.Id}, Rng {entity.RngProp}");

You can see that the serializer is called corrected, the value is also set when I check the object in the database. However, the driver doesn't seem to correctly set the property.

Generated rng 32

Inserted Id 5e4ade582c509931f4467e38, Rng 0


问:
Connecting Flutter to the a local nodejs socket server
I am developing a chat part form my app and I coded a basic socket server with node js and socket.io.

I tested this API with this site: https://www.websocket.org/echo.html

Here is some source code :

```<code>  var server = require('http').Server(app)
  var io = require('socket.io')(server);

  app.use(bodyParser.urlencoded({
    extended: true,
    limit: '50mb',
  }));
  app.use(bodyParser.json());
  app.use("/f",express.static(__dirname+"/files"));
  app.use('/api', listenRoutes);

  io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
      console.log('user disconnected');
    });
  });

  server.listen(port);

  console.log('Bukalemun RESTful API server started on: ' + port);
</code>```

My API is served on http://localhost:3000

However I am having trouble connecting this API to my flutter app. I used various types of packages including original dart.io but I never succeeded.

This is the function to connect my API:

```<code>import 'dart:io';

  void setupSocketConnections() async {

    Socket socket = await Socket.connect('10.0.2.2', 3000);

    print('connected');

    // listen to the received data event stream
    socket.listen((List<int> event) {
      print(utf8.decode(event));
    });

    // send hello
    socket.add(utf8.encode('hello'));

    // wait 5 seconds
    await Future.delayed(Duration(seconds: 5));

    // .. and close the socket
    socket.close();

  }
</code>```

I would be grateful for any suggestions.

答:
Try using this mostly you might have used some headers with the sockets as .

```<code>'transports': ['websocket', 'polling']
</code>```

Use this dependency in your pubspec.yaml

```<code>[socket_io_client: ^0.9.7+2][1]
</code>```

Well use this code to connect in your flutter app.

```<code>connectToSocket() {
socket = IO.io("http://your url/", <String, dynamic>{
  'transports': ['websocket', 'polling'],
});
socket.connect();
</code>```

}

Hope it works for you ! It has worked for me.

Body:
I am developing a chat part form my app and I coded a basic socket server with node js and socket.io.

I tested this API with this site: https://www.websocket.org/echo.html

Here is some source code :

  var server = require('http').Server(app)
  var io = require('socket.io')(server);

  app.use(bodyParser.urlencoded({
    extended: true,
    limit: '50mb',
  }));
  app.use(bodyParser.json());
  app.use("/f",express.static(__dirname+"/files"));
  app.use('/api', listenRoutes);

  io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
      console.log('user disconnected');
    });
  });

  server.listen(port);

  console.log('Bukalemun RESTful API server started on: ' + port);

My API is served on http://localhost:3000

However I am having trouble connecting this API to my flutter app. I used various types of packages including original dart.io but I never succeeded.

This is the function to connect my API:

import 'dart:io';

  void setupSocketConnections() async {

    Socket socket = await Socket.connect('10.0.2.2', 3000);

    print('connected');

    // listen to the received data event stream
    socket.listen((List<int> event) {
      print(utf8.decode(event));
    });

    // send hello
    socket.add(utf8.encode('hello'));

    // wait 5 seconds
    await Future.delayed(Duration(seconds: 5));

    // .. and close the socket
    socket.close();

  }

I would be grateful for any suggestions.

Body:
Try using this mostly you might have used some headers with the sockets as .

'transports': ['websocket', 'polling']

Use this dependency in your pubspec.yaml

[socket_io_client: ^0.9.7+2][1]

Well use this code to connect in your flutter app.

connectToSocket() {
socket = IO.io("http://your url/", <String, dynamic>{
  'transports': ['websocket', 'polling'],
});
socket.connect();

}

Hope it works for you ! It has worked for me.


问:
Application could not be Installed on this phone
I have my own Android Application, I named it "SMS App" and I want to install it at my Android Phone, but every time I install this application in phone there is a message that pop up:

Application not Installed. SMS App could not be Installed on this
  phone.

Anyone who encountered this and solved this kind of problems?

答: Please check your phone android version and you develop "SMS App" APK version your phone version is lower than you develop "SMS App" apk so not installed.</p>


问:
Applications for bug detections - training for manual tester
Hello dear Stackoverflow community,

I want to challenge myself with testing and bug detection. I am looking for opportunities to get some practice. Tutorials and blogs are great source of knowledge but I think that practice gives far more awareness and experience than just watching other testers. I have tried multiple questions for both Google and Stackoverflow to find any applications, but with no results by now.

My question is: does any of you know any applications, both executable on local device or accessible via Web, where bugs are intentional so they to be detected for practice?
It would be great if there would be any list of bugs for reference.

答:
I worked on two websites long back for practicing my Manual Testing skills, they are still working. Hope this helps.</p>

```<code>https://asta.pgs-soft.com/
http://www.mrbuggy.pi/
</code>```

Body:
I worked on two websites long back for practicing my Manual Testing skills, they are still working. Hope this helps.

https://asta.pgs-soft.com/
http://www.mrbuggy.pi/


问:
How to keep context when creating new thread in spring?
```<code>System.out.println(LocaleContextHolder.getLocale()); // zh
new Thread(() -> {
    System.out.println(LocaleContextHolder.getLocale()); // en_US
}).start();
</code>```

From parent thread, I see that context locale is "zh" from child thread, I see "en_US". New thread is losing the context locale. Is there a way to pass context to new created thread?

答:
According to the Javadocs

The LocaleContext will be inherited by any child threads spawned by the current thread if the inheritable flag is set to true.

This means locale can be set using the method  setLocale(Locale locale, boolean inheritable) by passing inheritable as true. So before spawning a new child thread you can call setLocale with inheritable equals to true.

Body:
System.out.println(LocaleContextHolder.getLocale()); // zh
new Thread(() -> {
    System.out.println(LocaleContextHolder.getLocale()); // en_US
}).start();

From parent thread, I see that context locale is "zh" from child thread, I see "en_US". New thread is losing the context locale. Is there a way to pass context to new created thread?


问:
How Can Compare Database Table Name With Textbox?
I making create table button in visual studio with C#. But I have problem create table function. If I use same table name when I create table, I get error. How can I compare my textbox with database table names?</p>

```<code>if(txtbox_loladı.Text=)
        {
            con.Open();
            SqlCommand Cmd = new SqlCommand();
            string Sql = "CREATE TABLE " + txtbox_loladı.Text + " (No nvarchar(50), [Name Surname] nvarchar(50), PRIMARY KEY (No))";
            Cmd = new SqlCommand(Sql, con);
            SqlDataReader SQLDR = Cmd.ExecuteReader();
            MessageBox.Show("Table Has Been Created!");
        }
        else
        {
            MessageBox.Show("You Need Change Table Name");
        }
</code>```

答:
Do not do that. Use create table if not exists command instead

Edit:

this does the trick: example:

```<code>IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='tbl_name' and xtype='U')
    CREATE TABLE tbl_name (
        Name varchar(64) not null
    )
GO
</code>```

with your code:

```<code>string Sql = "IF NOT EXISTS SELECT * FROM sysobjects WHERE name='" + txtbox_loladı.Text + "' and xtype='U') "
Sql += "CREATE TABLE " + txtbox_loladı.Text + " (No nvarchar(50), [Name Surname] nvarchar(50), PRIMARY KEY (No))";
// I don't know whether you need "Go" as well
</code>```

And you should use $" {...} ... {...}" instead of "..." + .. + "..."

Body:
I making create table button in visual studio with C#. But I have problem create table function. If I use same table name when I create table, I get error. How can I compare my textbox with database table names?

if(txtbox_loladı.Text=)
        {
            con.Open();
            SqlCommand Cmd = new SqlCommand();
            string Sql = "CREATE TABLE " + txtbox_loladı.Text + " (No nvarchar(50), [Name Surname] nvarchar(50), PRIMARY KEY (No))";
            Cmd = new SqlCommand(Sql, con);
            SqlDataReader SQLDR = Cmd.ExecuteReader();
            MessageBox.Show("Table Has Been Created!");
        }
        else
        {
            MessageBox.Show("You Need Change Table Name");
        }

Body:
Do not do that. Use create table if not exists command instead

Edit:

this does the trick: example:

IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='tbl_name' and xtype='U')
    CREATE TABLE tbl_name (
        Name varchar(64) not null
    )
GO

with your code:

string Sql = "IF NOT EXISTS SELECT * FROM sysobjects WHERE name='" + txtbox_loladı.Text + "' and xtype='U') "
Sql += "CREATE TABLE " + txtbox_loladı.Text + " (No nvarchar(50), [Name Surname] nvarchar(50), PRIMARY KEY (No))";
// I don't know whether you need "Go" as well

And you should use $" {...} ... {...}" instead of "..." + .. + "..."


问:
Unable to target button to separate behaviour using :not()
I have a HTML5 application which has a table (ID is #myTable in the remainder of this question). The table is populated by an ajax request.

Following the ajax response a single row of the table looks like this:

```<code><tr>
    <td>ID 001</td>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td><a href="/fge?id=001" class="btn-fge">Find group entries</a></td>
</tr>
</code>```

The anchor in the last column isn't present on every row. It only appears for certain rows. If the anchor doesn't appear an empty row is rendered: 	.

Prior to this anchor being added I'd written a function which toggles expanding/collapsing each row. Upon expansion an additional ajax request was made to present further data. The behaviour was such that the user could click anywhere inside the row.

```<code>$('#myTable tbody').on('click', 'td', function (e) {
    var tr = $(this).closest('tr');

    // Code to expand/collapse tr
    // ...

    // Ajax request for additional row data
    // ...
}
</code>```

This all worked without any problems.

However, I want to segregate the behaviour such that the code above doesn't fire if the user has clicked the anchor. Conversely if they click anywhere inside the row other than the anchor it should fire.

I've read Check if clicked element doesn't have a specific class and attempted to target .btn-fge using a :not() condition as follows.

```<code>$('#myTable tbody').on('click', 'td:not(.btn-fge)', function (e) {

}
</code>```

This doesn't work (although I believe this might be because .btn-fge isn't a class on the  but rather an anchor inside it?). The collapsing/expanding row behaviour still fires followed by the browser redirecting to the href value. In the example given the behaviour is:

Click .btn-fge.

The row is expanded (or if it was already expanded it is collapsed).

The browser follows the href on .btn-fge so in this case redirects to /fge?id=001.

I want (1) followed by (3) to occur, but not (2) when clicking .btn-fge.

I've tried logging console.log($(this)); followed by e.preventDefault(). It doesn't matter whereabouts inside the row I click - whether it's on the button or not - it gives the same output as follows.

How can I target this such that the button behaviour is different to clicking other places inside the row?

I'm using jquery version 3.2.1 and would prefer a jquery solution but a vanilla JavaScript one would also be acceptable.

Edit - I've made a fiddle here https://jsfiddle.net/adrq0nhz/ and if you click anywhere inside the table it will console log "this is still firing" which is effectively the issue of the anchor having no separate behavior. Note: the .btn-fge class is on the anchor, not the , and this cannot be changed.

答:
Very similar to Mark's method, you can also use the .matches method and pass it the class name you want to target.

$('#myTable tbody').on('click', function(e) {
  if (e.target.matches('[class=btn-fge]')) {
    console.log('anchor clicked');
  } else {
    console.log(' clicked');
  }
  e.preventDefault();
});
```

Body:
I have a HTML5 application which has a table (ID is #myTable in the remainder of this question). The table is populated by an ajax request.

Following the ajax response a single row of the table looks like this:

    ID 001
    Foo
    Bar
    Baz
    Find group entries

The anchor in the last column isn't present on every row. It only appears for certain rows. If the anchor doesn't appear an empty row is rendered: 	.

Prior to this anchor being added I'd written a function which toggles expanding/collapsing each row. Upon expansion an additional ajax request was made to present further data. The behaviour was such that the user could click anywhere inside the row.

$('#myTable tbody').on('click', 'td', function (e) {
    var tr = $(this).closest('tr');

    // Code to expand/collapse tr
    // ...

    // Ajax request for additional row data
    // ...
}

This all worked without any problems.

However, I want to segregate the behaviour such that the code above doesn't fire if the user has clicked the anchor. Conversely if they click anywhere inside the row other than the anchor it should fire.

I've read Check if clicked element doesn't have a specific class and attempted to target .btn-fge using a :not() condition as follows.

$('#myTable tbody').on('click', 'td:not(.btn-fge)', function (e) {

}

This doesn't work (although I believe this might be because .btn-fge isn't a class on the  but rather an anchor inside it?). The collapsing/expanding row behaviour still fires followed by the browser redirecting to the href value. In the example given the behaviour is:

Click .btn-fge.

The row is expanded (or if it was already expanded it is collapsed).

The browser follows the href on .btn-fge so in this case redirects to /fge?id=001.

I want (1) followed by (3) to occur, but not (2) when clicking .btn-fge.

I've tried logging console.log($(this)); followed by e.preventDefault(). It doesn't matter whereabouts inside the row I click - whether it's on the button or not - it gives the same output as follows.

How can I target this such that the button behaviour is different to clicking other places inside the row?

I'm using jquery version 3.2.1 and would prefer a jquery solution but a vanilla JavaScript one would also be acceptable.

Edit - I've made a fiddle here https://jsfiddle.net/adrq0nhz/ and if you click anywhere inside the table it will console log "this is still firing" which is effectively the issue of the anchor having no separate behavior. Note: the .btn-fge class is on the anchor, not the , and this cannot be changed.

Body:
Very similar to Mark's method, you can also use the .matches method and pass it the class name you want to target.

$('#myTable tbody').on('click', function(e) {
  if (e.target.matches('[class=btn-fge]')) {
    console.log('anchor clicked');
  } else {
    console.log('<td> clicked');
  }
  e.preventDefault();
});