问:
Debug Nuget Library
I have a set of Nuget Libraries that I compile and modify myself.

I build them without publishing on any Nuget server. (It is not my library)

On the other side, I have a project that use such Nugets, but I wish to debug them...

In the best situation I wish to:

use my local .dll and .pdb

debug by using local .pdb and (updated) source code

I'm looking for the best possible solution, if possible by loading all local symbols,
but I'm not sure it is possible.

Maybe I have to build on my own local Nuget server and use a local Symbol server too, but it looks overkill?

答:
Maybe I have to build on my own local Nuget server and use a local
  Symbol server too, but it looks overkill?

As far as l know, when you want to debug a nuget library in a new project, you must add the required nuget.pdb and related xxx.cs source files in the new project.

According to your description, the nuget package is created by yourself which is more easiler to realize it:

1) If you have the nuget.pdb file  and the corresponding cs file on the local, you just need to put the PDB file in the output file of the project which references the nuget, and then right-click on the Solution-->Properties-->Common Properties-->Debug Source Files-->to add the folder path which the cs files exist into it.

2) If you do not have the current nuget.pdb file  and related cs source files for debugging on the local, you need to include these files in nuget.nupkg when creating the nuget package by using nuget.exe cli with xxx.nuspec, so that these files can be added to the current agent when you install the nuget package.

**Note:**This is the special steps for creating your nuget package:

A) please make sure that you have downloaded the nuget.exe and then set its path to environment variables so that it can be called in CMD. You can refer to this.

B) Open CMD, type cd xxxxxx(the path of the project which contains xxxx.csproj)

C) type nuget spec to generate the xxx.spec file

Then open it and add like these:

```<code><?xml version="1.0" encoding="utf-8"?>
<package >
  <metadata>
   ........
  </metadata>
<files>
<file src="bin\Debug\ClassLibrary11.pdb" target="lib\target framework version (like net472 or netstandard2.0)" />------ClassLibrary11.pdb is the nuget.pdb
 <file src="Class1.cs" target="src" />------Class1.cs is the source file
</files>
</package>
</code>```

D) then type nuget pack to generate the nuget package which contains these debug files.

E) when you install this nuget package in a new project, please do not forget to clean the nuget cache first. After that, you should add the path of the resource files into Debug Source Files.(the resource files exists in the C:\Users\xxx\.nuget\packages\package name\src or C:\xxxxx\ConsoleApp(project folder)\packages\package name\src)

Edit

F) When you start debugging it, please do not forget to disable Just My Code In Tools-->Options-->Debugging-->General-->uncheck Enable Just My Code.

Also, you can consider source links as source control so that you won't configure the source path by Solution=>properties.

In addition, you can refer to this similar issue.

Title: Debug Nuget Library

Body:
Maybe I have to build on my own local Nuget server and use a local
  Symbol server too, but it looks overkill?

As far as l know, when you want to debug a nuget library in a new project, you must add the required nuget.pdb and related xxx.cs source files in the new project.

According to your description, the nuget package is created by yourself which is more easiler to realize it:

1) If you have the nuget.pdb file  and the corresponding cs file on the local, you just need to put the PDB file in the output file of the project which references the nuget, and then right-click on the Solution-->Properties-->Common Properties-->Debug Source Files-->to add the folder path which the cs files exist into it.

2) If you do not have the current nuget.pdb file  and related cs source files for debugging on the local, you need to include these files in nuget.nupkg when creating the nuget package by using nuget.exe cli with xxx.nuspec, so that these files can be added to the current agent when you install the nuget package.

**Note:**This is the special steps for creating your nuget package:

A) please make sure that you have downloaded the nuget.exe and then set its path to environment variables so that it can be called in CMD. You can refer to this.

B) Open CMD, type cd xxxxxx(the path of the project which contains xxxx.csproj)

C) type nuget spec to generate the xxx.spec file

Then open it and add like these:

<?xml version="1.0" encoding="utf-8"?>
<package >
  <metadata>
   ........
  </metadata>
<files>
<file src="bin\Debug\ClassLibrary11.pdb" target="lib\target framework version (like net472 or netstandard2.0)" />------ClassLibrary11.pdb is the nuget.pdb
 <file src="Class1.cs" target="src" />------Class1.cs is the source file
</files>
</package>

D) then type nuget pack to generate the nuget package which contains these debug files.

E) when you install this nuget package in a new project, please do not forget to clean the nuget cache first. After that, you should add the path of the resource files into Debug Source Files.(the resource files exists in the C:\Users\xxx\.nuget\packages\package name\src or C:\xxxxx\ConsoleApp(project folder)\packages\package name\src)

Edit

F) When you start debugging it, please do not forget to disable Just My Code In Tools-->Options-->Debugging-->General-->uncheck Enable Just My Code.

Also, you can consider source links as source control so that you won't configure the source path by Solution=>properties.

In addition, you can refer to this similar issue.


来源: stackexchange

问:
Correct way to use php openssl_encrypt
I'm working with cryptography on a project and I need a little help on how to work with openssl_encrypt and openssl_decrypt, I just want to know the most basic and correct way to do it. Here is what I got so far:

```<code>// To encrypt a string

$dataToEncrypt = 'Hello World';

$cypherMethod = 'AES-256-CBC';
$key = random_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cypherMethod));

$encryptedData = openssl_encrypt($dataToEncrypt, $cypherMethod, $key, $options=0, $iv);
</code>```

I then store $cypherMethod, $key, and $iv for use when decrypting the $encryptedData. (Let's not elaborate how I store the values, thanks!)

```<code>// To decrypt an encrypted string

$decryptedData = openssl_decrypt($encryptedData, $cypherMethod, $key, $options=0, $iv);
</code>```

First off, is the above example code a correct example of how to use php openssl_encrypt?

Second, is my method to generate the $key and $iv correct and secure? Because I keep on reading, keys should be cryptographically secure.

Lastly, isn't a 32-byte value required for AES-256-CBC? If yes, then why is it that openssl_cipher_iv_length() returns only int(16) as the length? Shouldn't it be int(32)?

答:
Here is the most basic way to use openssl_encrypt and openssl_decrypt. Make sure to create 32 byte secret_key and 16 byte secret_iv </p>

```<code>function encrypt_decrypt($action, $string)
    {
        $output = false;
        $encrypt_method = "AES-256-CBC";
        $secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxx';
        $secret_iv = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
        // hash
        $key = hash('sha256', $secret_key);
        // iv - encrypt method AES-256-CBC expects 16 bytes
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
        if ( $action == 'encrypt' ) {
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
        } else if( $action == 'decrypt' ) {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }
        return $output;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Correct way to use php openssl_encrypt

Body:
I'm working with cryptography on a project and I need a little help on how to work with openssl_encrypt and openssl_decrypt, I just want to know the most basic and correct way to do it. Here is what I got so far:

// To encrypt a string

$dataToEncrypt = 'Hello World';

$cypherMethod = 'AES-256-CBC';
$key = random_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cypherMethod));

$encryptedData = openssl_encrypt($dataToEncrypt, $cypherMethod, $key, $options=0, $iv);

I then store $cypherMethod, $key, and $iv for use when decrypting the $encryptedData. (Let's not elaborate how I store the values, thanks!)

// To decrypt an encrypted string

$decryptedData = openssl_decrypt($encryptedData, $cypherMethod, $key, $options=0, $iv);

First off, is the above example code a correct example of how to use php openssl_encrypt?

Second, is my method to generate the $key and $iv correct and secure? Because I keep on reading, keys should be cryptographically secure.

Lastly, isn't a 32-byte value required for AES-256-CBC? If yes, then why is it that openssl_cipher_iv_length() returns only int(16) as the length? Shouldn't it be int(32)?

Body:
Here is the most basic way to use openssl_encrypt and openssl_decrypt. Make sure to create 32 byte secret_key and 16 byte secret_iv

function encrypt_decrypt($action, $string)
    {
        $output = false;
        $encrypt_method = "AES-256-CBC";
        $secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxx';
        $secret_iv = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
        // hash
        $key = hash('sha256', $secret_key);
        // iv - encrypt method AES-256-CBC expects 16 bytes
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
        if ( $action == 'encrypt' ) {
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
        } else if( $action == 'decrypt' ) {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }
        return $output;
    }

ContentLicense: CC BY-SA 4.0


问:
JFrame: How to add a button that adds a new text field to the frame?
I'm pretty new to Java and I thought I'd try to get my hands dirty and make a GUI but I can't seem to get it to work the way I want it to.

I wrote some code thinking that if I press the "Add" button on the GUI then a new JTextField will appear underneath where all the other textfields are but that doesn't happen.  Only one new JTextField does appear but it appears next to my Add button instead of underneath all the other textfields I have and if I press it again, nothing happens.  I tried playing around with other variables but it just doesn't seem to be working properly. I feel like something is wrong with my ActionListener but I don't know what.

```<code>public class TheGUI extends JFrame{
    List<JTextField> listOfTextFields = new ArrayList<JTextField>();

    private JTextField desc1;
    private JTextField instruct;
    private JTextField desc2;
    private JButton submit;
    private JButton addNew;

    public TheGUI() { //My GUI with the default fields & buttons that should be on there.
        super("Chili");
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        instruct = new JTextField("Choose your words");
        instruct.setEditable(false);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridx = 0;
        c.gridy = 0;
        add(instruct, c);

        addNew = new JButton("Add");
        c.weightx = 0.0;
        c.gridx = 1;
        c.gridy = 0;
        add(addNew, c);

        submit = new JButton("Submit!");
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = GridBagConstraints.PAGE_END;
        add(submit, c);

        desc1 = new JTextField(10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 1;
        add(desc1, c);

        desc2 = new JTextField(10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 2;
        add(desc2, c);

        addNew.addActionListener(new Adder());

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,300);
        setVisible(true);

    }

    private class Adder implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent event) {

            int i = 0;
            listOfTextFields.add(new JTextField());
            GridBagConstraints textFieldConstraints = new GridBagConstraints();

             //Give it a max of 9 text fields that can be created.
            while(i < 10) {
                textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
                textFieldConstraints.weightx = 0.5;
                textFieldConstraints.gridx = 0;
                textFieldConstraints.gridwidth = 2;
                textFieldConstraints.gridy = 3 + i;
                i++;

            }

            add(listOfTextFields.get(i), textFieldConstraints);
            revalidate();
            repaint();

        }

    }

}

</code>```

答:
Your while loop is really strange.

Your ActionListener should look like:

```<code> private class Adder implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            if (listOfTextFields.size() == 9) {
                // Give it a max of 9 text fields that can be created.
                return;
            }

            JTextField textfield = new JTextField();

            listOfTextFields.add(textfield);
            GridBagConstraints textFieldConstraints = new GridBagConstraints();
            textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
            textFieldConstraints.weightx = 0.5;
            textFieldConstraints.gridx = 0;
            textFieldConstraints.gridwidth = 2;
            textFieldConstraints.gridy = 3 + listOfTextFields.size();

            add(textfield, textFieldConstraints);

            revalidate();
            repaint();

        }

    }
</code>```

Body:
I'm pretty new to Java and I thought I'd try to get my hands dirty and make a GUI but I can't seem to get it to work the way I want it to.

I wrote some code thinking that if I press the "Add" button on the GUI then a new JTextField will appear underneath where all the other textfields are but that doesn't happen.  Only one new JTextField does appear but it appears next to my Add button instead of underneath all the other textfields I have and if I press it again, nothing happens.  I tried playing around with other variables but it just doesn't seem to be working properly. I feel like something is wrong with my ActionListener but I don't know what.

public class TheGUI extends JFrame{
    List<JTextField> listOfTextFields = new ArrayList<JTextField>();

    private JTextField desc1;
    private JTextField instruct;
    private JTextField desc2;
    private JButton submit;
    private JButton addNew;

    public TheGUI() { //My GUI with the default fields & buttons that should be on there.
        super("Chili");
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        instruct = new JTextField("Choose your words");
        instruct.setEditable(false);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridx = 0;
        c.gridy = 0;
        add(instruct, c);

        addNew = new JButton("Add");
        c.weightx = 0.0;
        c.gridx = 1;
        c.gridy = 0;
        add(addNew, c);

        submit = new JButton("Submit!");
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = GridBagConstraints.PAGE_END;
        add(submit, c);

        desc1 = new JTextField(10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 1;
        add(desc1, c);

        desc2 = new JTextField(10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.5;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 2;
        add(desc2, c);

        addNew.addActionListener(new Adder());

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,300);
        setVisible(true);

    }

    private class Adder implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent event) {

            int i = 0;
            listOfTextFields.add(new JTextField());
            GridBagConstraints textFieldConstraints = new GridBagConstraints();

             //Give it a max of 9 text fields that can be created.
            while(i < 10) {
                textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
                textFieldConstraints.weightx = 0.5;
                textFieldConstraints.gridx = 0;
                textFieldConstraints.gridwidth = 2;
                textFieldConstraints.gridy = 3 + i;
                i++;

            }

            add(listOfTextFields.get(i), textFieldConstraints);
            revalidate();
            repaint();

        }

    }

}

Body:
Your while loop is really strange.

Your ActionListener should look like:

 private class Adder implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            if (listOfTextFields.size() == 9) {
                // Give it a max of 9 text fields that can be created.
                return;
            }

            JTextField textfield = new JTextField();

            listOfTextFields.add(textfield);
            GridBagConstraints textFieldConstraints = new GridBagConstraints();
            textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
            textFieldConstraints.weightx = 0.5;
            textFieldConstraints.gridx = 0;
            textFieldConstraints.gridwidth = 2;
            textFieldConstraints.gridy = 3 + listOfTextFields.size();

            add(textfield, textFieldConstraints);

            revalidate();
            repaint();

        }

    }


问:
Comparing doubles to double literals?

Possible Duplicate:

  How should I do floating point comparison?

Is it not recommended to compare for equality a double and a double literal in C++, because I guess it is compiler dependent?

To be more precise it is not OK to compare a double which is hard-coded (a literal in the source code) and a double which should be computed, as the last number of the resultant of the calculation can vary from one compiler to another. Is this not standardized?

I heard this is mentioned in Knuth's TeXbook, is that right?

If this is all true, what is the solution?

答:
The problem you are talking about is due to rounding errors and will happen for every floating point number. What you can do is define an epsilon and see if the difference between the two floating point numbers is smaller than this. E.g.:

```<code>double A = somethingA();
double B = somethingB();

double epsilon = 0.00001;

if (abs(A - B) < epsilon)
  doublesAreEqual();
</code>```

[Edit] Also see this question: What is the most effective way for float and double comparison?.

Title: Comparing doubles to double literals?

Body:
The problem you are talking about is due to rounding errors and will happen for every floating point number. What you can do is define an epsilon and see if the difference between the two floating point numbers is smaller than this. E.g.:

double A = somethingA();
double B = somethingB();

double epsilon = 0.00001;

if (abs(A - B) < epsilon)
  doublesAreEqual();

[Edit] Also see this question: What is the most effective way for float and double comparison?.


问:
What is difference between router.Static() and router.Use(static.Serve()) on the gin?
I was just reading the documentation of gin and found there are 2 different way to set assets folder to the server, one is using Static() method of the router as follow:

package main

import "github.com/gin-gonic/gin"

func main() {
        r := gin.Default()
        r.Static("/assets", "./assets")
```
<p>Then the other is using static middleware as follows:</p>
<pre class="lang-golang prettyprint-override"><code>package main

import (
       "github.com/gin-gonic/gin"
       "github.com/gin-contrib/static"
)

func main() {
        r := gin.Default()
        r.Use(static.Serve("/", static.LocalFile("./assets", false)))
</code>```

Is there any difference between these 2 ways about speed, side-effect, and so on?

答:
First option from:

Static serves files from the given file system root.
  Internally a http.FileServer is used, therefore http.NotFound is used instead
  of the Router's NotFound handler.

Second option link:

Static returns a middleware handler that serves static files in the given directory.

both uses http.FileServer under the hood.

Body:
I was just reading the documentation of gin and found there are 2 different way to set assets folder to the server, one is using Static() method of the router as follow:

package main

import "github.com/gin-gonic/gin"

func main() {
        r := gin.Default()
        r.Static("/assets", "./assets")

Then the other is using static middleware as follows:

package main

import (
       "github.com/gin-gonic/gin"
       "github.com/gin-contrib/static"
)

func main() {
        r := gin.Default()
        r.Use(static.Serve("/", static.LocalFile("./assets", false)))

Is there any difference between these 2 ways about speed, side-effect, and so on?


问:
Got 'Cannot find module' error when I tried to import certain JS file
I am currently learning JS and this is codes from practice.
(which is from YDKJSY)

This is a publication.js

```<code>function printDetails(title,author,pubDate) {
    console.log(`
    Title: ${ title }
    By: ${ author }
    ${ pubDate } `
    );
}
export function create(title,author,pubDate) {
    var publicAPI = {
        print() {
            printDetails(title,author,pubDate);
        }
     };
return publicAPI;
}
</code>```

And this blogpost.js import publication.js

```<code>import { create as createPub } from "publication.js";
function printDetails(pub,URL) {
    pub.print(); console.log(URL);
}
export function create(title,author,pubDate,URL) {
    var pub = createPub(title,author,pubDate);
var publicAPI = { print() { printDetails(pub,URL);
        }
    };
return publicAPI;
}
</code>```

And finally main.js import blogpost.js

```<code>import { create as newBlogPost } from "blogpost.js";
var forAgainstLet = newBlogPost(
    "For and against let",
    "Kyle Simpson",
    "October 27, 2014",
    "https://davidwalsh.name/for-and-against-let"
);
</code>```

I converted these code by babel and got converted codes.

PS C:\users\leepc\babel> npm run build

```<code>> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js
</code>```

but when I do npm run build and tried to run main.js I got this,

PS C:\users\leepc\babel\public\lib> node main.js

```<code>internal/modules/cjs/loader.js:984
  throw err;
  ^

Error: Cannot find module 'blogpost.js'
Require stack:
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)    3:17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:117
7:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)

    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run
_main.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]

}
</code>```

I checked whether I forgot any installment.

PS C:\users\leepc\babel> npm ls --depth=0

```<code>babel@1.0.0 C:\users\leepc\babel
+-- @babel/core@7.8.4
+-- babel-cli@6.26.0
+-- babel-preset-env@1.7.0
`-- babel-preset-es2015@6.24.1
</code>```

Lastley, about .babelrc

```<code>{
  "presets": ["env"]
}
</code>```

and package.json build,

```<code>{
    ...
    "build": "babel ./public/src -d ./public/lib -w"
  }
</code>```

I used node.js preset, but it got weird errors so I just left if with "env".

Sorry for a messy and long code, but I have been trouble for this problem these days and can't get to further studying.
Please let me know is there any other information I have to post and edit in this question.

edit:
is this maybe becasue I put all of this files in a same folder?
should I have to put these in a certain different folder?
This is a picture of my practice project folder

答:
please try to have your modules relative to your file for importing. Usually, the imports with no paths are for node_modules.

```<code>import { create as newBlogPost } from "./blogpost.js";
// or wherever your blogpost.js is relative to your main.js
...
</code>```

Body:
I am currently learning JS and this is codes from practice.
(which is from YDKJSY)

This is a publication.js

function printDetails(title,author,pubDate) {
    console.log(`
    Title: ${ title }
    By: ${ author }
    ${ pubDate } `
    );
}
export function create(title,author,pubDate) {
    var publicAPI = {
        print() {
            printDetails(title,author,pubDate);
        }
     };
return publicAPI;
}

And this blogpost.js import publication.js

import { create as createPub } from "publication.js";
function printDetails(pub,URL) {
    pub.print(); console.log(URL);
}
export function create(title,author,pubDate,URL) {
    var pub = createPub(title,author,pubDate);
var publicAPI = { print() { printDetails(pub,URL);
        }
    };
return publicAPI;
}

And finally main.js import blogpost.js

import { create as newBlogPost } from "blogpost.js";
var forAgainstLet = newBlogPost(
    "For and against let",
    "Kyle Simpson",
    "October 27, 2014",
    "https://davidwalsh.name/for-and-against-let"
);

I converted these code by babel and got converted codes.

PS C:\users\leepc\babel> npm run build

> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js

but when I do npm run build and tried to run main.js I got this,

PS C:\users\leepc\babel\public\lib> node main.js

internal/modules/cjs/loader.js:984
  throw err;
  ^

Error: Cannot find module 'blogpost.js'
Require stack:
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)    3:17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:117
7:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)

    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run
_main.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]

}

I checked whether I forgot any installment.

PS C:\users\leepc\babel> npm ls --depth=0

babel@1.0.0 C:\users\leepc\babel
+-- @babel/core@7.8.4
+-- babel-cli@6.26.0
+-- babel-preset-env@1.7.0
`-- babel-preset-es2015@6.24.1

Lastley, about .babelrc

{
  "presets": ["env"]
}

and package.json build,

{
    ...
    "build": "babel ./public/src -d ./public/lib -w"
  }

I used node.js preset, but it got weird errors so I just left if with "env".

Sorry for a messy and long code, but I have been trouble for this problem these days and can't get to further studying.
Please let me know is there any other information I have to post and edit in this question.

edit:
is this maybe becasue I put all of this files in a same folder?
should I have to put these in a certain different folder?
This is a picture of my practice project folder

Body:
please try to have your modules relative to your file for importing. Usually, the imports with no paths are for node_modules.

import { create as newBlogPost } from "./blogpost.js";
// or wherever your blogpost.js is relative to your main.js
...


问:
Get Grafana alerts history for a panel by using API
I am use Grafana with a lot of Dashboards and Panels.
Many panels have alerts.
Accordingly, these alerts often change their state, for example, from OK to Altering or no_data.

I also have my application (ASP.NET Core) where I want to get the current state of alert for some panel, as well as alert history, using the Grafana HTTP API.

Using a request like:

```<code>GET api/alerts?PanelId=36
</code>```

I only get the latest notification state.
How do I get notification history for this panel? Such that I can see in the Grafana interface using Panel-> Edit-> Alert-> State History.
Maybe i need to do something with the query or dashboardQuery parameters of the API GET request?

Thanks!

答:
https://grafana.com/docs/grafana/latest/http_api/alerting/

Add state=ALL to the query string

Body:
I am use Grafana with a lot of Dashboards and Panels.
Many panels have alerts.
Accordingly, these alerts often change their state, for example, from OK to Altering or no_data.

I also have my application (ASP.NET Core) where I want to get the current state of alert for some panel, as well as alert history, using the Grafana HTTP API.

Using a request like:

GET api/alerts?PanelId=36

I only get the latest notification state.
How do I get notification history for this panel? Such that I can see in the Grafana interface using Panel-> Edit-> Alert-> State History.
Maybe i need to do something with the query or dashboardQuery parameters of the API GET request?

Thanks!


问:
How to auto login in Odoo's Web-module for res.user, not for res.partner?
I am trying to login using token-based Auth, because we are using Odoo-web module in mobile-app.

currently using GET-method url-passing approach which is "UNSECURE" on websites without SSL certificates and localhost-websites, as

myurl.com?username=foo&password=bar

How can I do that using Token based approach or passing credentials in POST-method, in Odoo-12?

Edit 1:

I found this authenticate() method in core-modules of odoo in http-controllers file and I am calling that only now, as:

request.session(db, username, password)

but I wanted it to be token based without hardcoding password as different passwords for different partners, which I can't hardcode and it's bad approach.

how can I do it by passing token and validating it?

答:
You can use the authenticate endpoint provided by odoo to create a session for your api user.
In the following requests you then use the session id to process operations.

Example call to /web/session/authenticate with body:

```<code>{
  "jsonrpc": "2.0",
  "method": "call",
  "id": 1,
  "params": {
    "db": "<YOUR-DB>",
    "login": "<YOUR@LOGIN.COM>",
    "password": "<YOUR-PASSWORD>"
  }
}
</code>```

You can find a description of the endpoints in https://github.com/odoo/odoo/blob/12.0/odoo/http.py

Body:
You can use the authenticate endpoint provided by odoo to create a session for your api user.
In the following requests you then use the session id to process operations.

Example call to /web/session/authenticate with body:

{
  "jsonrpc": "2.0",
  "method": "call",
  "id": 1,
  "params": {
    "db": "<YOUR-DB>",
    "login": "<YOUR@LOGIN.COM>",
    "password": "<YOUR-PASSWORD>"
  }
}

You can find a description of the endpoints in https://github.com/odoo/odoo/blob/12.0/odoo/http.py


问:
org.omg.CORBA.TRANSIENT: initial and forwarded IOR inaccessible vmcid: IBM minor code: E07 from IIB application
I am working on IIB 10.There is a soap application in which an iiop URL is called using java compute node.I am getting the following error"org.omg.CORBA.TRANSIENT: initial and forwarded IOR inaccessible  vmcid: IBM  minor code: E07  completed: No"</p>

答: It means the IIOP url cannot be reached, or is refusing to communicate for some other reason. </p>


问:
There are possible way of dividing two float numbers which was casted from unsigned int make negative float result?
```<code>unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);

ASSERT(0.0f <= timeOfGap, "WHAT?");
</code>```

I got a really weired result from my program. I didn't catch a scene which is happened. But I have a log which said that really raised at least multiple times.

There are possible way of dividing between two float numbers which was casted from unsigned int make negative float result?

OK, thank you guys. I'm glad to see your attentions.
Let me try to add some descriptions about it. It'll be helpful for you.

I'm working for an online game, and this situation was raised rarely but frequently while hundreds of million times game was serving. I can't debug or catch the exact shot, but it is logged on the db error messages.

The timeOfGap should be NaN as you noticed, but the log didn't alert the value exactly. The timeOfGap is accumulated like below;

```<code>mTotalFrameRateTimeAsASecond += timeOfGap;
</code>```

And this program logs mTotalFrameRateTimeAsASecond, that was a negative value. But except this sign of value was a negative, it is correct value. Meaning, it point time as look as good if I divide the final value with a framerate. A hypothetical play time was 500 sec, it is -30000(with 60 framerate per sec).

答:
This should find the problem:</p>

```<code>unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);
char s[50] ;
sprintf (s, "WHAT? %u/%u < 0!", deltaTime, freq);

ASSERT(0.0f <= timeOfGap, s);
</code>```

Body:
unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);

ASSERT(0.0f <= timeOfGap, "WHAT?");

I got a really weired result from my program. I didn't catch a scene which is happened. But I have a log which said that really raised at least multiple times.

There are possible way of dividing between two float numbers which was casted from unsigned int make negative float result?

OK, thank you guys. I'm glad to see your attentions.
Let me try to add some descriptions about it. It'll be helpful for you.

I'm working for an online game, and this situation was raised rarely but frequently while hundreds of million times game was serving. I can't debug or catch the exact shot, but it is logged on the db error messages.

The timeOfGap should be NaN as you noticed, but the log didn't alert the value exactly. The timeOfGap is accumulated like below;

mTotalFrameRateTimeAsASecond += timeOfGap;

And this program logs mTotalFrameRateTimeAsASecond, that was a negative value. But except this sign of value was a negative, it is correct value. Meaning, it point time as look as good if I divide the final value with a framerate. A hypothetical play time was 500 sec, it is -30000(with 60 framerate per sec).

Body:
This should find the problem:

unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);
char s[50] ;
sprintf (s, "WHAT? %u/%u < 0!", deltaTime, freq);

ASSERT(0.0f <= timeOfGap, s);


问:
How to trigger an AJAX call after setState() is effective?
I'm creating a search page component, that contains a number of inputs to filter the search results.

Each input changes the state of the component, and should trigger an AJAX call to refresh the search results:

handleSearchStringChange(event) {
    this.setState({
        filterSearchString: event.target.value
    });

    loadSearchResults(event.target.value);
}

render() {
    return (
        // ...

        <input type="text" value={this.state.filterSearchString} onChange={this.handleSearchStringChange} />

        // ...
    );
}
```

This is all good, however, as soon as you add more filters, it becomes cumbersome to pass all the filter values to loadSearchResults().

What I'd like to do, is update the state of the component using setState() as I do above, and then have loadSearchResults() build the AJAX request from the state alone.

I can't do this right now, because setState() is asynchronous, and doing so would make loadSearchResults() use potentially outdated data.

Is there any way to trigger the AJAX call after setState() has completed?

答:
Yes, with the callback from setState e.g.

I would also not use event.target in the setState call since it can be nullified. Instead store it in a local variable

```<code>let filterSearchString = event.target.value;

this.setState({ filterSearchString },
() => loadSearchResults(this.state.filterSearchString) );
</code>```

Body:
I'm creating a search page component, that contains a number of inputs to filter the search results.

Each input changes the state of the component, and should trigger an AJAX call to refresh the search results:

handleSearchStringChange(event) {
    this.setState({
        filterSearchString: event.target.value
    });

    loadSearchResults(event.target.value);
}

render() {
    return (
        // ...

        <input type="text" value={this.state.filterSearchString} onChange={this.handleSearchStringChange} />

        // ...
    );
}

This is all good, however, as soon as you add more filters, it becomes cumbersome to pass all the filter values to loadSearchResults().

What I'd like to do, is update the state of the component using setState() as I do above, and then have loadSearchResults() build the AJAX request from the state alone.

I can't do this right now, because setState() is asynchronous, and doing so would make loadSearchResults() use potentially outdated data.

Is there any way to trigger the AJAX call after setState() has completed?

Body:
Yes, with the callback from setState e.g.

I would also not use event.target in the setState call since it can be nullified. Instead store it in a local variable

let filterSearchString = event.target.value;

this.setState({ filterSearchString },
() => loadSearchResults(this.state.filterSearchString) );


问:
How to use withLatestFrom with a selector in ngrx?
I have ngrx application, and I can't get the value from a selector in the effect, by the payload I sent in the component.

I write an example code of what I deal with:

This is my state, a simple docs array in it.

```<code>export const initialState = {
  docs: [{ id: 1, name: "doc1" }, { id: 2, name: "doc2" }]
};

export const reducer = createReducer(
  initialState,
);
</code>```

I dont handle any action for this questions, this is not the issue.

In my component I get the array using a selector:

```<code>docs$ = this.store.pipe(select(fromStore.getAllDocs));

{{docs$ | async | json}}
</code>```

the reducer:

```<code>export const selectDocsState = createFeatureSelector("docs");

export const selectDocsStatusState = createSelector(
  selectDocsState,
  state => state["docs"]
);

export const getAllDocs = createSelector(
  selectDocsStatusState,
  getDocs
)
</code>```

I also have a selector to get by id:

```<code>{{docsById$ | async | json }}

docsById$ = this.store.pipe(select(fromStore.getById, { id: 1 }));
</code>```

in the reducer:

```<code>export const getById = createSelector(
  selectDocsStatusState,
  getDocs,
  (state, docs, props) => {
    console.log({ props });
    return docs.docs.docs.filter(d => d.id === props.id);
  }
)
</code>```

So far everything good. I get the docs array and display it.

Now, in my component I dispatch some action and catch by effect:

```<code>this.store.dispatch({ type: 'GET_DOC', payload: { id: 2 } });
</code>```

And in the effect I want to know if this id is in the store or not.

So I use withLatestFrom from rxjs with the getById selector.

```<code>withLatestFrom((a: any) =>
  this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
),
</code>```

The problem is i'm not getting the value from the selector instend I get the store instance.

```<code>tap(v => {
  console.log({ v });
}),
</code>```

The full effect:

```<code>getDoc$ = createEffect(() =>
    this.actions$.pipe(
      ofType("GET_DOC"),
      map(a => a),
      tap(a => {
        console.log({ a });
      }),
      withLatestFrom((a: any) =>
        this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
      ),
      tap(v => {
        console.log({ v }); // <--------------- HERE SHOULD BE THE DOC AND THE ACTION.PAYLOAD, v[0].a.payload, v[1].id
      }),
      exhaustMap(payload => {
        return of({ type: "SOME_ACTION", payload: null });
      })
    )
  );
</code>```

Here is my full example in stackbliz.

What do I missing here?

答:
withLatestFrom doesn't take a composite function, it takes a secondary observable source.

What you can do is use switchMap to switch to the new stream and see its value.

Try:

```<code>getDoc$ = createEffect(() =>
    this.actions$.pipe(
      ofType("GET_DOC"),
      map(a => a), // does nothing
      tap(a => {
        console.log({ a });
      }),
      switchMap((a: any) => this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))),
      tap(doc => {
        // can switch this tap to a map and see if there is a value then return this, if not then make an API call
        console.log(doc);
      }),
      exhaustMap(payload => {
        return of({ type: "SOME_ACTION", payload: null });
      })
    )
</code>```

Body:
I have ngrx application, and I can't get the value from a selector in the effect, by the payload I sent in the component.

I write an example code of what I deal with:

This is my state, a simple docs array in it.

export const initialState = {
  docs: [{ id: 1, name: "doc1" }, { id: 2, name: "doc2" }]
};

export const reducer = createReducer(
  initialState,
);

I dont handle any action for this questions, this is not the issue.

In my component I get the array using a selector:

docs$ = this.store.pipe(select(fromStore.getAllDocs));

{{docs$ | async | json}}

the reducer:

export const selectDocsState = createFeatureSelector("docs");

export const selectDocsStatusState = createSelector(
  selectDocsState,
  state => state["docs"]
);

export const getAllDocs = createSelector(
  selectDocsStatusState,
  getDocs
)

I also have a selector to get by id:

{{docsById$ | async | json }}

docsById$ = this.store.pipe(select(fromStore.getById, { id: 1 }));

in the reducer:

export const getById = createSelector(
  selectDocsStatusState,
  getDocs,
  (state, docs, props) => {
    console.log({ props });
    return docs.docs.docs.filter(d => d.id === props.id);
  }
)

So far everything good. I get the docs array and display it.

Now, in my component I dispatch some action and catch by effect:

this.store.dispatch({ type: 'GET_DOC', payload: { id: 2 } });

And in the effect I want to know if this id is in the store or not.

So I use withLatestFrom from rxjs with the getById selector.

withLatestFrom((a: any) =>
  this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
),

The problem is i'm not getting the value from the selector instend I get the store instance.

tap(v => {
  console.log({ v });
}),

The full effect:

getDoc$ = createEffect(() =>
    this.actions$.pipe(
      ofType("GET_DOC"),
      map(a => a),
      tap(a => {
        console.log({ a });
      }),
      withLatestFrom((a: any) =>
        this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))
      ),
      tap(v => {
        console.log({ v }); // <--------------- HERE SHOULD BE THE DOC AND THE ACTION.PAYLOAD, v[0].a.payload, v[1].id
      }),
      exhaustMap(payload => {
        return of({ type: "SOME_ACTION", payload: null });
      })
    )
  );

Here is my full example in stackbliz.

What do I missing here?

Body:
withLatestFrom doesn't take a composite function, it takes a secondary observable source.

What you can do is use switchMap to switch to the new stream and see its value.

Try:

getDoc$ = createEffect(() =>
    this.actions$.pipe(
      ofType("GET_DOC"),
      map(a => a), // does nothing
      tap(a => {
        console.log({ a });
      }),
      switchMap((a: any) => this.store.pipe(select(fromDocs.getById, { id: a.payload.id }))),
      tap(doc => {
        // can switch this tap to a map and see if there is a value then return this, if not then make an API call
        console.log(doc);
      }),
      exhaustMap(payload => {
        return of({ type: "SOME_ACTION", payload: null });
      })
    )


答:
You can do like that. You can read this article who will help you with this case https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296</p>

```<code>handleSearchStringChange(event) {
    this.setState({
        filterSearchString: event.target.value
    }, () => {
       loadSearchResults(event.target.value);
    });
}
</code>```

Title: How to trigger an AJAX call after setState() is effective?

Body:
You can do like that. You can read this article who will help you with this case https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296

handleSearchStringChange(event) {
    this.setState({
        filterSearchString: event.target.value
    }, () => {
       loadSearchResults(event.target.value);
    });
}


问:
Delete a value from array if exist or if no exist push it to array
I have a array define like :

```<code>selectedDocumentID = [];
</code>```

Next i have function when i get the ID, and other function where i give the id as parameter. When i click in element with id this id is going to this modifyArray.
Next i check the id using console.log (its working and i get id).
After that i create a new array list that include a selectedDocument array. (it work).
And i want to push to list a id if it not exist or if exist just slice it from list...

```<code>modifyArray(id) {
  let selectedDocumentID = [];

  let id = 10;

  console.log('this is: ' + id);
  console.log(this.selectedDocumentID);
  let list = this.selectedDocumentID;

  let index = list.findIndex( x => x === id);
  console.log(index);
  if (index !== id) {
    list.push(id);
    console.log(list);
    this.selectedDocumentID = list;
  }
  else {
    list = list.slice(list.indexOf(id));
    console.log(list);
    this.selectedDocumentID = list;
  }
}
</code>```

So for exmaple. I click for document with id 2,4,5,6.

My selectedDocumentID = [2,4,5,6] and list also have [2,4,5,6].

Next i click to document with id 8 and my arrays = [2,4,5,6,8],
after that i click to document with id 5 and my arrays you look like [2,4,6,8].
What i am doing wrong?

Code sample:

答:
You can use xor lodash function to make your code simpler. For example:</p>

```<code>modifyArray(id) {
  this.selectedDocumentID = _.xor(this.selectedDocumentID, [id]);
}
</code>```

Body:
I have a array define like :

selectedDocumentID = [];

Next i have function when i get the ID, and other function where i give the id as parameter. When i click in element with id this id is going to this modifyArray.
Next i check the id using console.log (its working and i get id).
After that i create a new array list that include a selectedDocument array. (it work).
And i want to push to list a id if it not exist or if exist just slice it from list...

modifyArray(id) {
  let selectedDocumentID = [];

  let id = 10;

  console.log('this is: ' + id);
  console.log(this.selectedDocumentID);
  let list = this.selectedDocumentID;

  let index = list.findIndex( x => x === id);
  console.log(index);
  if (index !== id) {
    list.push(id);
    console.log(list);
    this.selectedDocumentID = list;
  }
  else {
    list = list.slice(list.indexOf(id));
    console.log(list);
    this.selectedDocumentID = list;
  }
}

So for exmaple. I click for document with id 2,4,5,6.

My selectedDocumentID = [2,4,5,6] and list also have [2,4,5,6].

Next i click to document with id 8 and my arrays = [2,4,5,6,8],
after that i click to document with id 5 and my arrays you look like [2,4,6,8].
What i am doing wrong?

Code sample:

Body:
You can use xor lodash function to make your code simpler. For example:

modifyArray(id) {
  this.selectedDocumentID = _.xor(this.selectedDocumentID, [id]);
}


问:
Can I cause a floating point precision error?
I have a simple (perhaps naive) question - I'm trying to test a scenario, and was wondering if it's possible to cause a floating point precision error when parsing a string to number (is there a magic number that will cause a FPPE?).

e.g.

```<code>parseFloat("4.015") // = 4.0149999999999994
const foo = 4.015 // = 4.0149999999999994
</code>```

Or, is it only possible to produce a floating point precision error as a result of an operation?

console.log(4.015)
console.log(parseFloat("4.015"))
console.log(4.015 * 100)```

答:
Converting a number from a decimal in a string to binary floating-point is an operation, and it does produce “precision errors.” If the source number is not representable in the destination format, it is rounded.

In the examples you show, every operation has a rounding error, except for converting the source text 100 to the number 100.

In console.log(4.015), the decimal numeral “4.015” represents the number 4.015. When this is converted to the IEEE-754 64-bit binary floating-point that JavaScript uses, the result is 4.01499999999999968025576890795491635799407958984375. (That has lots of digits, but it is actually represented internally in a form equivalent to 4520488125973135 times 2−50.) Then, to print this to the console, it is converted from binary floating-point to decimal. When doing the conversion, JavaScript uses just enough decimal digits to uniquely distinguish the value from neighboring values that are representable in binary floating-point. The result is the string “4.015”. So the binary floating-point value has been rounded to a different decimal value—producing the same string as the original. So, in console.log(4.015), there are actually two conversion operations, there is rounding error in both of them, and the behavior of the software acts to conceal the rounding errors.

In console.log(parseFloat("4.015")), the same thing happens, except the first conversion is done when parseFloat is called instead of when 4.015 is interpreted in the source code.

In console.log(4.015 * 100), there are four operations and three rounding errors:

4.015 is converted to binary floating-point, which has the rounding error described above.

100 is converted to binary floating-point, and there is no rounding error because 100 is representable in binary floating-point.

The two binary floating-point numbers are multiplied, and there is a rounding error, producing 401.49999999999994315658113919198513031005859375.

That result is converted to a decimal string. The result is “401.49999999999994” because we need that many digits to distinguish it from the two neighboring representable values, 401.4999999999998863131622783839702606201171875 and 401.5.

In summary:

Every operation, including conversions between binary and decimal, may be subject to rounding error.

The default JavaScript formatting acts to conceal some rounding errors; round trips from decimal numerals shorter than 16 digits will always produce the original number (within the finite range of the format).

Body:
I have a simple (perhaps naive) question - I'm trying to test a scenario, and was wondering if it's possible to cause a floating point precision error when parsing a string to number (is there a magic number that will cause a FPPE?).

e.g.

parseFloat("4.015") // = 4.0149999999999994
const foo = 4.015 // = 4.0149999999999994

Or, is it only possible to produce a floating point precision error as a result of an operation?

console.log(4.015)
console.log(parseFloat("4.015"))
console.log(4.015 * 100)


问:
JavaScript : How to set the path to an image from a setAttribute?
I'm trying to set a path to an image in my local storage from a setAttribute, but despite of having set clearly its path keeps giving me this error of not found image, here part of my code:

```<code>if (shipLocation[0][0] == shipLocation[1][0] && i == 0) {
    var x = document.createElement("IMG");
    x.setAttribute("src", "../assets/patrolBoatHorizontalView.png"); // THIS IS THE PATH

}
</code>```

Error

GET http://localhost:8081/assets/patrolBoatHorizontalView.png 404 (Not
  Found)

I'm not clear if this is the way i should put it......i'm using VisualStudio Editor and all my images are stored in assets, and the request is done from one of my components in this VueJS App

Any advice?

答:
You could use require method to load the image during the build process. Webpack will load the image during the build process.

Example:

```<code>if (shipLocation[0][0] == shipLocation[1][0] && i == 0) {
  var x = document.createElement("img");
  let image = require("../assets/patrolBoatHorizontalView.png");
  x.setAttribute("src", image);
}

</code>```

Body:
I'm trying to set a path to an image in my local storage from a setAttribute, but despite of having set clearly its path keeps giving me this error of not found image, here part of my code:

if (shipLocation[0][0] == shipLocation[1][0] && i == 0) {
    var x = document.createElement("IMG");
    x.setAttribute("src", "../assets/patrolBoatHorizontalView.png"); // THIS IS THE PATH

}

Error

GET http://localhost:8081/assets/patrolBoatHorizontalView.png 404 (Not
  Found)

I'm not clear if this is the way i should put it......i'm using VisualStudio Editor and all my images are stored in assets, and the request is done from one of my components in this VueJS App

Any advice?

Body:
You could use require method to load the image during the build process. Webpack will load the image during the build process.

Example:

if (shipLocation[0][0] == shipLocation[1][0] && i == 0) {
  var x = document.createElement("img");
  let image = require("../assets/patrolBoatHorizontalView.png");
  x.setAttribute("src", image);
}


问:
Skipping NA rows in index column
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3
</code>```

At the moment I'm doing it as:

```<code>i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)
</code>```

but that gives me

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5
</code>```

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

答:
A base R solution using which

```<code>df$ID[which(df$VarA)]<-seq(which(df$VarA))
</code>```

Title: Skipping NA rows in index column

Body:
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3

At the moment I'm doing it as:

i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)

but that gives me

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

Body:
A base R solution using which

df$ID[which(df$VarA)]<-seq(which(df$VarA))


问:
Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvException: 'Error -4092 EACCES permission denied'
I am using TFS source control. Today, after I updated code and ran the project, I encountered this error:

I am using Visual Studio 2017. My project is Web API .NET Core 2.0.
And this is the error detail:

答:
We had this issue recently, turned out that the port the Kestrel server was trying to use had somehow now fallen within an excluded port range.

You can view what port ranges have been excluded by running the following in command prompt

```<code>netsh interface ipv4 show excludedportrange protocol=tcp
</code>```

Once we realised the cause we did try to delete the range we wanted to use using the following (in elevated Administator command prompt)

```<code>netsh int ip delete excludedportrange protocol=tcp numberofports=100 startport=49909
</code>```

This however resulted in an Access Denied.

There doesn't seem to be a way to find out the owner of the excluded port range, however in my instance it was Hyper-V. Once I turned Hyper-V off the ports were released and I could then debug in Visual Studio.

When I re-enabled Hyper-V (because I need it), it registered a different set of port ranges that do not effect the Kestrel server.

Body:
We had this issue recently, turned out that the port the Kestrel server was trying to use had somehow now fallen within an excluded port range.

You can view what port ranges have been excluded by running the following in command prompt

netsh interface ipv4 show excludedportrange protocol=tcp

Once we realised the cause we did try to delete the range we wanted to use using the following (in elevated Administator command prompt)

netsh int ip delete excludedportrange protocol=tcp numberofports=100 startport=49909

This however resulted in an Access Denied.

There doesn't seem to be a way to find out the owner of the excluded port range, however in my instance it was Hyper-V. Once I turned Hyper-V off the ports were released and I could then debug in Visual Studio.

When I re-enabled Hyper-V (because I need it), it registered a different set of port ranges that do not effect the Kestrel server.


问:
SwifUI using UIKit components by implementing UIViewRepresentable
Ok I know how to wrap UIKit components like TextField to use with SwiftUI using UIViewRepresentable and Coordinator. And it all works well. But how can I customise this components from SwiftUI perspective in way that is native to SwiftUI i.e. using modifiers?

I have example wrapper for UITextField to enable some additional delegate methods handling. And this works similar to native approach with closures passed to constructor. But how I can then apply some styling to this UITextField using SwiftUI modifiers?

```<code>struct PasswordField: UIViewRepresentable {

    @Binding var text: String
    @Binding var isSecured: Bool

    let onBeginEditing: () -> Void
    let onEndEditing: () -> Void
    let onEditingChanged: (Bool) -> Void
    let onCommit: () -> Void

    init(text: Binding<String>, isSecured : Binding<Bool> = .constant(true),
         onBeginEditing: @escaping () -> Void = { },
         onEndEditing: @escaping () -> Void = { },
         onEditingChanged: @escaping (Bool) -> Void = { _ in },
         onCommit: @escaping () -> Void = { }) {

        self._text = text
        self._isSecured = isSecured
        self.onBeginEditing = onBeginEditing
        self.onEndEditing = onEndEditing
        self.onEditingChanged = onEditingChanged
        self.onCommit = onCommit
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(onBeginEditing: onBeginEditing, onEndEditing: onEndEditing, onEditingChanged: onEditingChanged, onCommit: onCommit)
    }

    func makeUIView(context: UIViewRepresentableContext<PasswordField>) -> UITextField {

        let textField = UITextField()
        textField.delegate = context.coordinator
        textField.addTarget(context, action: #selector(Coordinator.valueChanged(sender:)), for: .valueChanged)
        return textField
    }

    func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<PasswordField>) {

        uiView.text = text
        uiView.isSecureTextEntry = isSecured
    }
}

// MARK: - Coordinator
extension PasswordField {

    class Coordinator: NSObject, UITextFieldDelegate {

        let onBeginEditing: () -> Void
        let onEndEditing: () -> Void
        let onEditingChanged: (Bool) -> Void
        let onCommit: () -> Void

        init(onBeginEditing: @escaping () -> Void,
             onEndEditing: @escaping () -> Void,
             onEditingChanged: @escaping (Bool) -> Void,
             onCommit: @escaping () -> Void) {
            self.onBeginEditing = onBeginEditing
            self.onEndEditing = onEndEditing
            self.onEditingChanged = onEditingChanged
            self.onCommit = onCommit
        }

        @objc func valueChanged(sender: UITextField) {
            onEditingChanged(true)
        }

        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            onCommit()
            return true
        }

        func textFieldDidBeginEditing(_ textField: UITextField) {
            onBeginEditing()
            onEditingChanged(true)
        }

        func textFieldDidEndEditing(_ textField: UITextField) {
            onEditingChanged(false)
            onEndEditing()
        }
    }
}

struct PasswordField_Previews: PreviewProvider {
    static var previews: some View {
        PasswordField(text: .constant("PaSSword"), isSecured: .constant(true))
    }
}
</code>```

Now I would like to use it like this:

```<code>PasswordField(text: self.$validator.value, onEditingChanged: { editing in
                            self.onEditingChanged?(editing)
                            self.isEdited = true
                        }, onCommit: {
                            self.validator.validateField()
                            self.validator.validateFieldAsync()
                        })
                        .font(.custom("AvenirNext-Light", size: 13)) // THIS IS IMPORTANT
                        .foregroundColor(Color("BodyText")) // THIS IS IMPORTANT
                        .frame(maxHeight: geometry.size.height)
                        .offset(x: 0, y: 16)
                        .padding(10)
</code>```

Ok I know I can hardcode this style in my wrapper, or pass this via constructor. yeah but this is not how SwiftUI do this natively.

答:
You need to implement your own custom modifiers. See the documentation for ViewModifier protocol, although the SwiftUI docs are still very thin.

However, you don't have to implement your own TextField for handling password input, because SwiftUI now supports natively what you want: SecureField.

Body:
Ok I know how to wrap UIKit components like TextField to use with SwiftUI using UIViewRepresentable and Coordinator. And it all works well. But how can I customise this components from SwiftUI perspective in way that is native to SwiftUI i.e. using modifiers?

I have example wrapper for UITextField to enable some additional delegate methods handling. And this works similar to native approach with closures passed to constructor. But how I can then apply some styling to this UITextField using SwiftUI modifiers?

struct PasswordField: UIViewRepresentable {

    @Binding var text: String
    @Binding var isSecured: Bool

    let onBeginEditing: () -> Void
    let onEndEditing: () -> Void
    let onEditingChanged: (Bool) -> Void
    let onCommit: () -> Void

    init(text: Binding<String>, isSecured : Binding<Bool> = .constant(true),
         onBeginEditing: @escaping () -> Void = { },
         onEndEditing: @escaping () -> Void = { },
         onEditingChanged: @escaping (Bool) -> Void = { _ in },
         onCommit: @escaping () -> Void = { }) {

        self._text = text
        self._isSecured = isSecured
        self.onBeginEditing = onBeginEditing
        self.onEndEditing = onEndEditing
        self.onEditingChanged = onEditingChanged
        self.onCommit = onCommit
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(onBeginEditing: onBeginEditing, onEndEditing: onEndEditing, onEditingChanged: onEditingChanged, onCommit: onCommit)
    }

    func makeUIView(context: UIViewRepresentableContext<PasswordField>) -> UITextField {

        let textField = UITextField()
        textField.delegate = context.coordinator
        textField.addTarget(context, action: #selector(Coordinator.valueChanged(sender:)), for: .valueChanged)
        return textField
    }

    func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<PasswordField>) {

        uiView.text = text
        uiView.isSecureTextEntry = isSecured
    }
}

// MARK: - Coordinator
extension PasswordField {

    class Coordinator: NSObject, UITextFieldDelegate {

        let onBeginEditing: () -> Void
        let onEndEditing: () -> Void
        let onEditingChanged: (Bool) -> Void
        let onCommit: () -> Void

        init(onBeginEditing: @escaping () -> Void,
             onEndEditing: @escaping () -> Void,
             onEditingChanged: @escaping (Bool) -> Void,
             onCommit: @escaping () -> Void) {
            self.onBeginEditing = onBeginEditing
            self.onEndEditing = onEndEditing
            self.onEditingChanged = onEditingChanged
            self.onCommit = onCommit
        }

        @objc func valueChanged(sender: UITextField) {
            onEditingChanged(true)
        }

        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            onCommit()
            return true
        }

        func textFieldDidBeginEditing(_ textField: UITextField) {
            onBeginEditing()
            onEditingChanged(true)
        }

        func textFieldDidEndEditing(_ textField: UITextField) {
            onEditingChanged(false)
            onEndEditing()
        }
    }
}

struct PasswordField_Previews: PreviewProvider {
    static var previews: some View {
        PasswordField(text: .constant("PaSSword"), isSecured: .constant(true))
    }
}

Now I would like to use it like this:

PasswordField(text: self.$validator.value, onEditingChanged: { editing in
                            self.onEditingChanged?(editing)
                            self.isEdited = true
                        }, onCommit: {
                            self.validator.validateField()
                            self.validator.validateFieldAsync()
                        })
                        .font(.custom("AvenirNext-Light", size: 13)) // THIS IS IMPORTANT
                        .foregroundColor(Color("BodyText")) // THIS IS IMPORTANT
                        .frame(maxHeight: geometry.size.height)
                        .offset(x: 0, y: 16)
                        .padding(10)

Ok I know I can hardcode this style in my wrapper, or pass this via constructor. yeah but this is not how SwiftUI do this natively.


问:
Replace pictures via WP CLI
I have a multisite in which more than 100 sites. I want to raise the site for development. Pictures decided not to download because they take up too much space. I want to replace pictures with a placeholder using the console:

```<code>wp search-replace "prod-image.jpg" "placeholder.jpg" wp_312_post* --network
</code>```

After this I delete all image sizes frow DB

```<code>$images = $wpdb->get_results(
    'SELECT pm.post_id, pm.meta_value FROM ' . $wpdb->posts . ' as p
         LEFT JOIN ' . $wpdb->postmeta . ' as pm ON p.ID = pm.post_id
         WHERE p.post_type = "attachment"
         AND pm.meta_key = "_wp_attachment_metadata"'
);
foreach ( $images as $key => $image ) {
    $image_meta          = unserialize( $image->meta_value );
    $image_meta['sizes'] = [];
    update_post_meta( $image->post_id, '_wp_attachment_metadata', $image_meta );
}
</code>```

This works, but for this I need to know all the image names. This process takes too much time. Anyone have an idea how to speed up migration?

P.S. Replace through WordPress hook not to offer, because the templates use a lot of different functions for displaying images and most of them are custom.

答: Can't you just have an empty uploads directory? The site will still work, but you'll see a generic icon for the missing pics when the page comes up.</p>

Title: Replace pictures via WP CLI

Body:
I have a multisite in which more than 100 sites. I want to raise the site for development. Pictures decided not to download because they take up too much space. I want to replace pictures with a placeholder using the console:

wp search-replace "prod-image.jpg" "placeholder.jpg" wp_312_post* --network

After this I delete all image sizes frow DB

$images = $wpdb->get_results(
    'SELECT pm.post_id, pm.meta_value FROM ' . $wpdb->posts . ' as p
         LEFT JOIN ' . $wpdb->postmeta . ' as pm ON p.ID = pm.post_id
         WHERE p.post_type = "attachment"
         AND pm.meta_key = "_wp_attachment_metadata"'
);
foreach ( $images as $key => $image ) {
    $image_meta          = unserialize( $image->meta_value );
    $image_meta['sizes'] = [];
    update_post_meta( $image->post_id, '_wp_attachment_metadata', $image_meta );
}

This works, but for this I need to know all the image names. This process takes too much time. Anyone have an idea how to speed up migration?

P.S. Replace through WordPress hook not to offer, because the templates use a lot of different functions for displaying images and most of them are custom.


问:
Splitting an array of points into multiple arrays that have a specific distance from each other
I have an array of points that look like this (x,y):

```<code>6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25
18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25
</code>```

This array represents a two, separate, series of points that are on a 1.25" offset from each other.  There is two series, but there can be [n] series, and I need to split them up into the appropriate number of arrays based on the specific offset like this:

```<code>6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25

18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25
</code>```

The offset can be in the X or the Y, but not both.  I have been working on it for a little while now and am kind of stuck.

Edit

What I have tried so far, is to get a point in the array, and search for all points that are on the interval specified (getDist calculates the distance from one point to another):

```<code>foreach(Point firstPoint in points){
    foreach(Point nextPoint in points){
        if(isSame(firstPoint, nextPoint)
            continue;

        if(getDist(firstPoint, nextPoint) % 1.25 == 0){
            // add to new array
        }
    }
}

double getDist(Point p1, Point p2) => Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

bool isSame(Point p1, Point p2) => p1.X == p2.X && p1.Y == p2.Y;
</code>```

The problem I run into is that this looks at all the points, then looks at them each one again creating a huge set of arrays.

答:
I tried to do it, but instead of storing the results in arrays, I used lists (the code might need improvements though):

```<code>List<List<PointF>> splitted_list = new List<List<PointF>>();

float x = 0;
float y = 0;

float offsetX = 0;
float offsetY = 0;

foreach(PointF p in points)
{
    if (splitted_list.Count() > 0)
    {
        if (splitted_list.Last().Count() >= 2 && (p.X - x != offsetX || p.Y - y != offsetY))
        {
            List<PointF> list_points = new List<PointF>();
            list_points.Add(p);
            splitted_list.Add(list_points);
        }
        else
        {
            splitted_list.Last().Add(p);
            offsetX = p.X - x;
            offsetY = p.Y - y;
        }
    }
    else
    {
        List<PointF> list_points = new List<PointF>();
        list_points.Add(p);
        splitted_list.Add(list_points);
    }

    x = p.X;
    y = p.Y;
}
</code>```

Everytime one of the offsets changes, I create a new list and I add it to my "list of lists" (it works regardless of the offset's value).

So the result is a list of series of points. If you HAVE to use those series as arrays of points, you can simply convert the lists to arrays by using the method ToArray().

Body:
I have an array of points that look like this (x,y):

6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25
18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25

This array represents a two, separate, series of points that are on a 1.25" offset from each other.  There is two series, but there can be [n] series, and I need to split them up into the appropriate number of arrays based on the specific offset like this:

6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25

18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25

The offset can be in the X or the Y, but not both.  I have been working on it for a little while now and am kind of stuck.

Edit

What I have tried so far, is to get a point in the array, and search for all points that are on the interval specified (getDist calculates the distance from one point to another):

foreach(Point firstPoint in points){
    foreach(Point nextPoint in points){
        if(isSame(firstPoint, nextPoint)
            continue;

        if(getDist(firstPoint, nextPoint) % 1.25 == 0){
            // add to new array
        }
    }
}

double getDist(Point p1, Point p2) => Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

bool isSame(Point p1, Point p2) => p1.X == p2.X && p1.Y == p2.Y;

The problem I run into is that this looks at all the points, then looks at them each one again creating a huge set of arrays.

Body:
I tried to do it, but instead of storing the results in arrays, I used lists (the code might need improvements though):

List<List<PointF>> splitted_list = new List<List<PointF>>();

float x = 0;
float y = 0;

float offsetX = 0;
float offsetY = 0;

foreach(PointF p in points)
{
    if (splitted_list.Count() > 0)
    {
        if (splitted_list.Last().Count() >= 2 && (p.X - x != offsetX || p.Y - y != offsetY))
        {
            List<PointF> list_points = new List<PointF>();
            list_points.Add(p);
            splitted_list.Add(list_points);
        }
        else
        {
            splitted_list.Last().Add(p);
            offsetX = p.X - x;
            offsetY = p.Y - y;
        }
    }
    else
    {
        List<PointF> list_points = new List<PointF>();
        list_points.Add(p);
        splitted_list.Add(list_points);
    }

    x = p.X;
    y = p.Y;
}

Everytime one of the offsets changes, I create a new list and I add it to my "list of lists" (it works regardless of the offset's value).

So the result is a list of series of points. If you HAVE to use those series as arrays of points, you can simply convert the lists to arrays by using the method ToArray().


问:
How to detect if the requested image doesn't have errros (403 Forbidden)
I have a script that loads an image from a source every 300 ms but sometimes I get back a 403 Forbidden response. In that case, the image source becomes blank, so I would like to somehow check if the image has a response of 200 and only then update my image element. How could I achive that?

Here is my code

```<code><body>
    <!-- Live view -->
    <img class="screenshot" src="screenshot.jpg">

    <script>
        setInterval(() => {
            // Sometimes I get back a 403 forbidden
            document.querySelector('.screenshot').src = 'http://192.168.1.150:80/screen/screenshot.jpg?id=' + Math.random(0, 10000)
        }, 300)
    </script>
</body>
</code>```

I would like to be able to do something like this

```<code>    if (status == 200) {
        document.querySelector('.screenshot').src = 'http://192.168.1.150:80/screen/screenshot.jpg?id=' + Math.random(0, 10000)
    } else {
        // Do nothing, keep the old image
    }
</code>```

答:
Try this

const imgTag = document.querySelector('.screenshot');
const img = new Image()
img.addEventListener("load", function() {
  imgTag.src = this.src;
  setTimeout(reload, 1000)
})
img.addEventListener("error", function() {
  setTimeout(reload, 1000)
})

const reload = () => {
  img.src = 'https://picsum.photos/seed/picsum/200/' +Math.floor(Math.random() * (300 - 100 + 1) + 100)
};
reload()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="screenshot" src="" /></code>```

Body:
I have a script that loads an image from a source every 300 ms but sometimes I get back a 403 Forbidden response. In that case, the image source becomes blank, so I would like to somehow check if the image has a response of 200 and only then update my image element. How could I achive that?

Here is my code

I would like to be able to do something like this

    if (status == 200) {
        document.querySelector('.screenshot').src = 'http://192.168.1.150:80/screen/screenshot.jpg?id=' + Math.random(0, 10000)
    } else {
        // Do nothing, keep the old image
    }

Body:
Try this

const imgTag = document.querySelector('.screenshot');
const img = new Image()
img.addEventListener("load", function() {
  imgTag.src = this.src;
  setTimeout(reload, 1000)
})
img.addEventListener("error", function() {
  setTimeout(reload, 1000)
})

const reload = () => {
  img.src = 'https://picsum.photos/seed/picsum/200/' +Math.floor(Math.random() * (300 - 100 + 1) + 100)
};
reload()

<img class="screenshot" src="" />


问:
Looking for a more pythonic way of converting list of lists to string
I have python (3.7) code that works, but it's ugly, and I'm sure there's a more elegant way of doing what I want to do.  I have 9 3x3 grids that I want to print out (plus some line separators) for a tic-tac-toe game.

I basically want the output to look like this (sample of the first row)

```<code>█ █│   │███
 █ │ 2 │█ █
█ █│   │███
</code>```

The code below does this, but it seems like there's a better way, and I'm not sure how to do this in an elegant for loop.

Thanks in advance!

```<code>choice_x = [
    ['█', ' ', '█'],
    [' ', '█', ' '],
    ['█', ' ', '█']
]

choice_o = [
    ['█', '█', '█'],
    ['█', ' ', '█'],
    ['█', '█', '█']
]

v_grid = [
    ['│'],
    ['│'],
    ['│']
]

empty_grid = [
    [' ',' ',' '],
    [' ','2',' '],
    [' ',' ',' ']
]

row1 = [
    choice_x, v_grid, empty_grid, v_grid, choice_o
]

#for n in range(0,4):
slice1 = [sublist[0][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice1])
print(result)

slice2 = [sublist[1][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice2])
print(result)

slice3 = [sublist[2][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice3])
print(result)
#end for loop
</code>```

答:
Without using list of lists, but knowing the size of the board:</p>

```<code>GRID_SIZE = 3
SEP = '|'
choice_x = ['█', ' ', '█',
            ' ', '█', ' ',
            '█', ' ', '█']
empty_grid = [' ', ' ', ' ',
              ' ', '2', ' ',
              ' ', ' ', ' ']
choice_o = ['█', '█', '█',
            '█', ' ', '█',
            '█', '█', '█']

for i in range(0, GRID_SIZE**2, GRID_SIZE):
    s1 = ''.join(choice_x[i:i+GRID_SIZE])
    s2 = ''.join(empty_grid[i:i+GRID_SIZE])
    s3 = ''.join(choice_o[i:i+GRID_SIZE])
    print(SEP.join([s1, s2, s3])
</code>```

Body:
I have python (3.7) code that works, but it's ugly, and I'm sure there's a more elegant way of doing what I want to do.  I have 9 3x3 grids that I want to print out (plus some line separators) for a tic-tac-toe game.

I basically want the output to look like this (sample of the first row)

█ █│   │███
 █ │ 2 │█ █
█ █│   │███

The code below does this, but it seems like there's a better way, and I'm not sure how to do this in an elegant for loop.

Thanks in advance!

choice_x = [
    ['█', ' ', '█'],
    [' ', '█', ' '],
    ['█', ' ', '█']
]

choice_o = [
    ['█', '█', '█'],
    ['█', ' ', '█'],
    ['█', '█', '█']
]

v_grid = [
    ['│'],
    ['│'],
    ['│']
]

empty_grid = [
    [' ',' ',' '],
    [' ','2',' '],
    [' ',' ',' ']
]

row1 = [
    choice_x, v_grid, empty_grid, v_grid, choice_o
]

#for n in range(0,4):
slice1 = [sublist[0][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice1])
print(result)

slice2 = [sublist[1][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice2])
print(result)

slice3 = [sublist[2][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice3])
print(result)
#end for loop

Body:
Without using list of lists, but knowing the size of the board:

GRID_SIZE = 3
SEP = '|'
choice_x = ['█', ' ', '█',
            ' ', '█', ' ',
            '█', ' ', '█']
empty_grid = [' ', ' ', ' ',
              ' ', '2', ' ',
              ' ', ' ', ' ']
choice_o = ['█', '█', '█',
            '█', ' ', '█',
            '█', '█', '█']

for i in range(0, GRID_SIZE**2, GRID_SIZE):
    s1 = ''.join(choice_x[i:i+GRID_SIZE])
    s2 = ''.join(empty_grid[i:i+GRID_SIZE])
    s3 = ''.join(choice_o[i:i+GRID_SIZE])
    print(SEP.join([s1, s2, s3])


问:
Coverage of powershell script using Pester
I am trying to unit test my Powershell script file with below code snippet using Pester

```<code>#code to create a 7z file
$7zipPath = "C:\Program Files\7-Zip\7z.exe"
Set-Alias 7zip $7zipPath
if (!(Test-Path -Path $7zipPath -PathType Leaf)) {
    throw "7 zip file '$7zipPath' not found"
}
7zip a -mx=9 $jenkinsWorkspacepath\IntegrationZip.7z $jenkinsWorkspacepath\IntegratedScripts
</code>```

And mocking the Test-Path command as below

```<code>    Mock -CommandName Test-Path –MockWith {
        Return $false
    }
</code>```

But the coverage report shows the below line as uncovered.. What am i doing wrong here(in the mocking part)?

```<code>**throw "7 zip file '$7zipPath' not found"**
</code>```

答:
What does your test look like?  I tried the following and it worked fine for your code:

```<code>Mock -CommandName Test-Path -MockWith { return $false }

It "fails to find executable" {
    { Invoke-SevenZip } | Should -Throw "not found"
}
</code>```

Note: I wrapped your code in a function called Invoke-SevenZip

Body:
I am trying to unit test my Powershell script file with below code snippet using Pester

#code to create a 7z file
$7zipPath = "C:\Program Files\7-Zip\7z.exe"
Set-Alias 7zip $7zipPath
if (!(Test-Path -Path $7zipPath -PathType Leaf)) {
    throw "7 zip file '$7zipPath' not found"
}
7zip a -mx=9 $jenkinsWorkspacepath\IntegrationZip.7z $jenkinsWorkspacepath\IntegratedScripts

And mocking the Test-Path command as below

    Mock -CommandName Test-Path –MockWith {
        Return $false
    }

But the coverage report shows the below line as uncovered.. What am i doing wrong here(in the mocking part)?

**throw "7 zip file '$7zipPath' not found"**

Body:
What does your test look like?  I tried the following and it worked fine for your code:

Mock -CommandName Test-Path -MockWith { return $false }

It "fails to find executable" {
    { Invoke-SevenZip } | Should -Throw "not found"
}

Note: I wrapped your code in a function called Invoke-SevenZip


答:
setState accepts a callback, when it finished with state update:</p>

```<code>handleSearchStringChange(event) {
    this.setState({
        filterSearchString: event.target.value
    }, () => {
       loadSearchResults(this.state.filterSearchString);
    });
}

render() {
    return (
        // ...

        <input type="text" value={this.props.searchString} onChange={this.handleSearchStringChange} />

        // ...
    );
}
</code>```

Body:
I'm creating a search page component, that contains a number of inputs to filter the search results.

Each input changes the state of the component, and should trigger an AJAX call to refresh the search results:

handleSearchStringChange(event) {
    this.setState({
        filterSearchString: event.target.value
    });

    loadSearchResults(event.target.value);
}

render() {
    return (
        // ...

        <input type="text" value={this.state.filterSearchString} onChange={this.handleSearchStringChange} />

        // ...
    );
}

This is all good, however, as soon as you add more filters, it becomes cumbersome to pass all the filter values to loadSearchResults().

What I'd like to do, is update the state of the component using setState() as I do above, and then have loadSearchResults() build the AJAX request from the state alone.

I can't do this right now, because setState() is asynchronous, and doing so would make loadSearchResults() use potentially outdated data.

Is there any way to trigger the AJAX call after setState() has completed?

Body:
setState accepts a callback, when it finished with state update:

handleSearchStringChange(event) {
    this.setState({
        filterSearchString: event.target.value
    }, () => {
       loadSearchResults(this.state.filterSearchString);
    });
}

render() {
    return (
        // ...

        <input type="text" value={this.props.searchString} onChange={this.handleSearchStringChange} />

        // ...
    );
}


问:
JavaFX WebView :sending a String from javafx to js webview
I currently render a web page using WebEngine. I'd like to send a String from the Java method to WebView to show it in the maps popup (Leaflet) .

Does anyone know what I'm doing wrong?

```<code> webEngine.executeScript("addpopup(" + new_val.getDescription() + "," + new_val.getLatitude() + "," + new_val.getLongitude() + ")");
</code>```

Related JavaScript code:

```<code>function addpopup(desc,lan,lat){
    var popup = L.popup().setLatLng([lan, lat]).setContent(desc).openOn(map);
}
</code>```

It works without the description parameter.

答:
I think you're missing quotes around new_val.getDescription():

```<code>webEngine.executeScript("addpopup('" + new_val.getDescription() + "',"
     + new_val.getLatitude() + "," + new_val.getLongitude() + ")");
</code>```

Body:
I currently render a web page using WebEngine. I'd like to send a String from the Java method to WebView to show it in the maps popup (Leaflet) .

Does anyone know what I'm doing wrong?

 webEngine.executeScript("addpopup(" + new_val.getDescription() + "," + new_val.getLatitude() + "," + new_val.getLongitude() + ")");

Related JavaScript code:

function addpopup(desc,lan,lat){
    var popup = L.popup().setLatLng([lan, lat]).setContent(desc).openOn(map);
}

It works without the description parameter.

Body:
I think you're missing quotes around new_val.getDescription():

webEngine.executeScript("addpopup('" + new_val.getDescription() + "',"
     + new_val.getLatitude() + "," + new_val.getLongitude() + ")");


问:
Removing spacing between Xamarin.Forms Grid Cells
I am struggling with removing spacing between grid cells. I have tried using ColumnSpacing="0" and RowSpacing = "0",however it does not make grid spaceless.

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                     x:Class="XamarinPradmenys.CalculatorPage">
    <AbsoluteLayout>
        <StackLayout AbsoluteLayout.LayoutBounds="0,0,1,0.25" AbsoluteLayout.LayoutFlags="All" >
            <Label x:Name="live" FontSize="20"/>
            <Label x:Name="rez" FontSize="15"/>
        </StackLayout>

        <Grid RowSpacing="0" ColumnSpacing="0"  AbsoluteLayout.LayoutBounds="0,1,1,0.75" AbsoluteLayout.LayoutFlags="All">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Button Grid.Column="0" Grid.Row="0" Text="mc" />
            <Button Grid.Column="1" Grid.Row="0" Text="m+"/>
            <Button Grid.Column="2" Grid.Row="0" Text="m-"/>
            <Button Grid.Column="3" Grid.Row="0" Text="mr"/>
            <Button Grid.Column="0" Grid.Row="1" Text="C"/>
            <Button Grid.Column="1" Grid.Row="1" Text="/"/>
            <Button Grid.Column="2" Grid.Row="1" Text="X"/>
            <Button Grid.Column="3" Grid.Row="1" Text="Del"/>
            <Button Grid.Column="0" Grid.Row="2" Text="7"/>
            <Button Grid.Column="1" Grid.Row="2" Text="8"/>
            <Button Grid.Column="2" Grid.Row="2" Text="9"/>
            <Button Grid.Column="3" Grid.Row="2" Text="-"/>
            <Button Grid.Column="0" Grid.Row="3" Text="4"/>
            <Button Grid.Column="1" Grid.Row="3" Text="5"/>
            <Button Grid.Column="2" Grid.Row="3" Text="6"/>
            <Button Grid.Column="3" Grid.Row="3" Text="+"/>
            <Button Grid.Column="0" Grid.Row="4" Text="1"/>
            <Button Grid.Column="1" Grid.Row="4" Text="2"/>
            <Button Grid.Column="2" Grid.Row="4" Text="3"/>
            <Button Grid.Column="3" Grid.Row="4" Grid.RowSpan="2" Text="="/>
            <Button Grid.Column="0" Grid.Row="5" Text="%" />
            <Button Grid.Column="1" Grid.Row="5" Text="0"/>
            <Button Grid.Column="2" Grid.Row="5" Text=","/>
        </Grid>

    </AbsoluteLayout>
</ContentPage>
</code>```

That I get is:

As you can see there are spaces between every row and column. Do you have any suggestions?

Do you have anything what could help me?

答:
Because material design, each button has shadows but if you add a background colour, you'll see its true size :

Code

```<code><Page.Resources>
    <Style TargetType="Button">
        <Setter Property="BackgroundColor" Value="#d6d7d7" />
    </Style>
</Page.Resources>

<AbsoluteLayout>
    <StackLayout AbsoluteLayout.LayoutBounds="0,0,1,0.25" AbsoluteLayout.LayoutFlags="All">
        <Label x:Name="live" FontSize="20" />
        <Label x:Name="rez" FontSize="15" />
    </StackLayout>

    <Grid
        AbsoluteLayout.LayoutBounds="0,1,1,0.75"
        AbsoluteLayout.LayoutFlags="All"
        ColumnSpacing="0"
        RowSpacing="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Button
            Grid.Row="0"
            Grid.Column="0"
            Text="mc" />
        <Button
            Grid.Row="0"
            Grid.Column="1"
            Text="m+" />
        <Button
            Grid.Row="0"
            Grid.Column="2"
            Text="m-" />
        <Button
            Grid.Row="0"
            Grid.Column="3"
            Text="mr" />
        <Button
            Grid.Row="1"
            Grid.Column="0"
            Text="C" />
        <Button
            Grid.Row="1"
            Grid.Column="1"
            Text="/" />
        <Button
            Grid.Row="1"
            Grid.Column="2"
            Text="X" />
        <Button
            Grid.Row="1"
            Grid.Column="3"
            Text="Del" />
        <Button
            Grid.Row="2"
            Grid.Column="0"
            Text="7" />
        <Button
            Grid.Row="2"
            Grid.Column="1"
            Text="8" />
        <Button
            Grid.Row="2"
            Grid.Column="2"
            Text="9" />
        <Button
            Grid.Row="2"
            Grid.Column="3"
            Text="-" />
        <Button
            Grid.Row="3"
            Grid.Column="0"
            Text="4" />
        <Button
            Grid.Row="3"
            Grid.Column="1"
            Text="5" />
        <Button
            Grid.Row="3"
            Grid.Column="2"
            Text="6" />
        <Button
            Grid.Row="3"
            Grid.Column="3"
            Text="+" />
        <Button
            Grid.Row="4"
            Grid.Column="0"
            Text="1" />
        <Button
            Grid.Row="4"
            Grid.Column="1"
            Text="2" />
        <Button
            Grid.Row="4"
            Grid.Column="2"
            Text="3" />
        <Button
            Grid.Row="4"
            Grid.RowSpan="2"
            Grid.Column="3"
            Text="=" />
        <Button
            Grid.Row="5"
            Grid.Column="0"
            Text="%" />
        <Button
            Grid.Row="5"
            Grid.Column="1"
            Text="0" />
        <Button
            Grid.Row="5"
            Grid.Column="2"
            Text="," />
    </Grid>

</AbsoluteLayout>
</code>```

Body:
I am struggling with removing spacing between grid cells. I have tried using ColumnSpacing="0" and RowSpacing = "0",however it does not make grid spaceless.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                     x:Class="XamarinPradmenys.CalculatorPage">
    <AbsoluteLayout>
        <StackLayout AbsoluteLayout.LayoutBounds="0,0,1,0.25" AbsoluteLayout.LayoutFlags="All" >

        </StackLayout>

        <Grid RowSpacing="0" ColumnSpacing="0"  AbsoluteLayout.LayoutBounds="0,1,1,0.75" AbsoluteLayout.LayoutFlags="All">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Button Grid.Column="0" Grid.Row="0" Text="mc" />
            <Button Grid.Column="1" Grid.Row="0" Text="m+"/>
            <Button Grid.Column="2" Grid.Row="0" Text="m-"/>
            <Button Grid.Column="3" Grid.Row="0" Text="mr"/>
            <Button Grid.Column="0" Grid.Row="1" Text="C"/>
            <Button Grid.Column="1" Grid.Row="1" Text="/"/>
            <Button Grid.Column="2" Grid.Row="1" Text="X"/>
            <Button Grid.Column="3" Grid.Row="1" Text="Del"/>
            <Button Grid.Column="0" Grid.Row="2" Text="7"/>
            <Button Grid.Column="1" Grid.Row="2" Text="8"/>
            <Button Grid.Column="2" Grid.Row="2" Text="9"/>
            <Button Grid.Column="3" Grid.Row="2" Text="-"/>
            <Button Grid.Column="0" Grid.Row="3" Text="4"/>
            <Button Grid.Column="1" Grid.Row="3" Text="5"/>
            <Button Grid.Column="2" Grid.Row="3" Text="6"/>
            <Button Grid.Column="3" Grid.Row="3" Text="+"/>
            <Button Grid.Column="0" Grid.Row="4" Text="1"/>
            <Button Grid.Column="1" Grid.Row="4" Text="2"/>
            <Button Grid.Column="2" Grid.Row="4" Text="3"/>
            <Button Grid.Column="3" Grid.Row="4" Grid.RowSpan="2" Text="="/>
            <Button Grid.Column="0" Grid.Row="5" Text="%" />
            <Button Grid.Column="1" Grid.Row="5" Text="0"/>
            <Button Grid.Column="2" Grid.Row="5" Text=","/>
        </Grid>

    </AbsoluteLayout>
</ContentPage>

That I get is:

As you can see there are spaces between every row and column. Do you have any suggestions?

Do you have anything what could help me?

Body:
Because material design, each button has shadows but if you add a background colour, you'll see its true size :

Code

<Page.Resources>
    <Style TargetType="Button">
        <Setter Property="BackgroundColor" Value="#d6d7d7" />
    </Style>
</Page.Resources>

<AbsoluteLayout>
    <StackLayout AbsoluteLayout.LayoutBounds="0,0,1,0.25" AbsoluteLayout.LayoutFlags="All">
        <Label x:Name="live" FontSize="20" />
        <Label x:Name="rez" FontSize="15" />
    </StackLayout>

    <Grid
        AbsoluteLayout.LayoutBounds="0,1,1,0.75"
        AbsoluteLayout.LayoutFlags="All"
        ColumnSpacing="0"
        RowSpacing="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Button
            Grid.Row="0"
            Grid.Column="0"
            Text="mc" />
        <Button
            Grid.Row="0"
            Grid.Column="1"
            Text="m+" />
        <Button
            Grid.Row="0"
            Grid.Column="2"
            Text="m-" />
        <Button
            Grid.Row="0"
            Grid.Column="3"
            Text="mr" />
        <Button
            Grid.Row="1"
            Grid.Column="0"
            Text="C" />
        <Button
            Grid.Row="1"
            Grid.Column="1"
            Text="/" />
        <Button
            Grid.Row="1"
            Grid.Column="2"
            Text="X" />
        <Button
            Grid.Row="1"
            Grid.Column="3"
            Text="Del" />
        <Button
            Grid.Row="2"
            Grid.Column="0"
            Text="7" />
        <Button
            Grid.Row="2"
            Grid.Column="1"
            Text="8" />
        <Button
            Grid.Row="2"
            Grid.Column="2"
            Text="9" />
        <Button
            Grid.Row="2"
            Grid.Column="3"
            Text="-" />
        <Button
            Grid.Row="3"
            Grid.Column="0"
            Text="4" />
        <Button
            Grid.Row="3"
            Grid.Column="1"
            Text="5" />
        <Button
            Grid.Row="3"
            Grid.Column="2"
            Text="6" />
        <Button
            Grid.Row="3"
            Grid.Column="3"
            Text="+" />
        <Button
            Grid.Row="4"
            Grid.Column="0"
            Text="1" />
        <Button
            Grid.Row="4"
            Grid.Column="1"
            Text="2" />
        <Button
            Grid.Row="4"
            Grid.Column="2"
            Text="3" />
        <Button
            Grid.Row="4"
            Grid.RowSpan="2"
            Grid.Column="3"
            Text="=" />
        <Button
            Grid.Row="5"
            Grid.Column="0"
            Text="%" />
        <Button
            Grid.Row="5"
            Grid.Column="1"
            Text="0" />
        <Button
            Grid.Row="5"
            Grid.Column="2"
            Text="," />
    </Grid>

</AbsoluteLayout>