问:
Android: "INSTALL_FAILED_CONFLICTING_PROVIDER" error when adding Facebook SDK
I am creating multiple white-label apps on Android.

Each of these apps use the same Facebook login.

According to the docs: https://developers.facebook.com/docs/sharing/android

I need to add:

```<code><provider android:authorities="com.facebook.app.FacebookContentProvider{APP_ID}"
          android:name="com.facebook.FacebookContentProvider"
          android:exported="true"/>
</code>```

The issue is that we get a conflict error when attempting to use the same app multiple times: INSTALL_FAILED_CONFLICTING_PROVIDER as described here: Android Facebook content provider authority

How can I solve this issue?
Note that I tried to set android:exported to false but it did not seem to work.

答:
Try to use ${APP_ID} instead of {APP_ID}. It works fine for us:

```<code><application>
    <provider
        android:name="company.name.utils.SDKInitProvider"
        android:authorities="${APP_ID}.sdk.SDKInitProvider"
        android:exported="false" />
</application>
</code>```

$applicationId is defined differently on every product flavour:

```<code>defaultConfig {
    APP_ID "some.namespace.of"
    minSdkVersion 18
    targetSdkVersion 29
    ...
}
</code>```

Body:
I am creating multiple white-label apps on Android.

Each of these apps use the same Facebook login.

According to the docs: https://developers.facebook.com/docs/sharing/android

I need to add:

<provider android:authorities="com.facebook.app.FacebookContentProvider{APP_ID}"
          android:name="com.facebook.FacebookContentProvider"
          android:exported="true"/>

The issue is that we get a conflict error when attempting to use the same app multiple times: INSTALL_FAILED_CONFLICTING_PROVIDER as described here: Android Facebook content provider authority

How can I solve this issue?
Note that I tried to set android:exported to false but it did not seem to work.

Body:
Try to use ${APP_ID} instead of {APP_ID}. It works fine for us:

<application>
    <provider
        android:name="company.name.utils.SDKInitProvider"
        android:authorities="${APP_ID}.sdk.SDKInitProvider"
        android:exported="false" />
</application>

$applicationId is defined differently on every product flavour:

defaultConfig {
    APP_ID "some.namespace.of"
    minSdkVersion 18
    targetSdkVersion 29
    ...
}


来源: stackexchange

问:
stop character been inserted into input react
I want to detect which character base on user keyboard hence I use onKeyDown, but how do I stop ',' been inserted into the input element?</p>

```<code>const [inputValue, setInputValue] = useState("");

  const handleKeyDown = (e: any) => {
    if (['188'].includes(e.keyCode)) {
      console.log("do something");
    }
  };

  const handleChange = (e: any) => {
    setInputValue(e.target.value)
  }

  return (
      <input
        type="text"
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
  );
</code>```

答:
Your includes doesn't work since '188' (string) isn't equal to 188 (number)

You can check the last inputed char in your handleChange function like so:

const handleChange = (e: any) => {
  const value = e.target.value
  if (![','].includes(value[value.length-1])) {
      setInputValue(e.target.value)
  }
}```

ContentLicense: CC BY-SA 4.0

Body:
I want to detect which character base on user keyboard hence I use onKeyDown, but how do I stop ',' been inserted into the input element?

const [inputValue, setInputValue] = useState("");

  const handleKeyDown = (e: any) => {
    if (['188'].includes(e.keyCode)) {
      console.log("do something");
    }
  };

  const handleChange = (e: any) => {
    setInputValue(e.target.value)
  }

  return (
      <input
        type="text"
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
  );


问:
making a list into dictionary
suppose you have a list

```<code>A = ["A: 1", "B: 2", "C: 3"]
</code>```

can you make this into a dictionary of

```<code>dict_A = {"A" : 1, "B": 2, "C": 3}
</code>```

I got stuck at making the list into a dictionary

答:
```<code>In [1]: A = ["A: 1", "B: 2", "C: 3"]

In [2]: {k:int(v.strip()) for k,v in (i.split(":") for i in A)}
Out[2]: {'A': 1, 'B': 2, 'C': 3}
</code>```

This can effectively be unpacked as follows:

```<code>d = {}
for item in A:  # the first time around, item = "A: 1"
    key, value = item.split(":")  # key = "A", value = " 1"
    value = value.strip()  # value = "1"
    value = int(value)  # value = 1
    d[key] = value
</code>```

Title: making a list into dictionary

Body:
suppose you have a list

A = ["A: 1", "B: 2", "C: 3"]

can you make this into a dictionary of

dict_A = {"A" : 1, "B": 2, "C": 3}

I got stuck at making the list into a dictionary

Body:
In [1]: A = ["A: 1", "B: 2", "C: 3"]

In [2]: {k:int(v.strip()) for k,v in (i.split(":") for i in A)}
Out[2]: {'A': 1, 'B': 2, 'C': 3}

This can effectively be unpacked as follows:

d = {}
for item in A:  # the first time around, item = "A: 1"
    key, value = item.split(":")  # key = "A", value = " 1"
    value = value.strip()  # value = "1"
    value = int(value)  # value = 1
    d[key] = value


问:
converting error with using Convert.ToDateTime in asp.net C#
Before that, the code was working fine, while the program didn't recognize the date format may be because of different cultureInfo.
I am using the Convert.ToDateTime method to convert the DateTime format.

```<code>Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value).ToString("yyyy-MM-dd HH:mm:ss");
</code>```

As a result, it converted but with incorrect MM and dd.

From "1/6/2020" To "2020-01-06 00:00:00"

```<code>string test1 = gvwTest.Rows[i].Cells["TxnDate"].Value.ToString();
string test2 = gvwTest.Rows[i].Cells["TxnDate"].Value.GetType().ToString();

test1 = "1/6/2020";
test2 = "System.String";
</code>```

答:
While DateTime.TryParseExact is definitely better way to go as others pointed out already, still Convert.ToDateTime also provides an overload that can accept culture information, in case you want to give it a shot.

Something like this...

```<code>Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value, CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss");
</code>```

Or...

```<code>Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value, CultureInfo.CurrentCulture).ToString("yyyy-MM-dd HH:mm:ss");
</code>```

Body:
Before that, the code was working fine, while the program didn't recognize the date format may be because of different cultureInfo.
I am using the Convert.ToDateTime method to convert the DateTime format.

Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value).ToString("yyyy-MM-dd HH:mm:ss");

As a result, it converted but with incorrect MM and dd.

From "1/6/2020" To "2020-01-06 00:00:00"

string test1 = gvwTest.Rows[i].Cells["TxnDate"].Value.ToString();
string test2 = gvwTest.Rows[i].Cells["TxnDate"].Value.GetType().ToString();

test1 = "1/6/2020";
test2 = "System.String";

Body:
While DateTime.TryParseExact is definitely better way to go as others pointed out already, still Convert.ToDateTime also provides an overload that can accept culture information, in case you want to give it a shot.

Something like this...

Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value, CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss");

Or...

Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value, CultureInfo.CurrentCulture).ToString("yyyy-MM-dd HH:mm:ss");


问:
How to call function from other file
structure

```<code>.
├── deck.go
└── main.go
</code>```

Here is the code in each .go file

main.go

```<code>package main

func main() {
    cards := newDeck()
    cards.print()
}
</code>```

deck.go

```<code>package main

import "fmt"

type card struct {
    value string
    suit  string
}

type deck []card

func newDeck() deck {
    cards := deck{}

    cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
    cardValues := []string{"Ace", "Two", "Three"}

    for _, suit := range cardSuits {
        for _, value := range cardValues {
            cards = append(cards, card{
                suit:  suit,
                value: value,
            })
        }
    }
    return cards
}

func (d deck) print() {
    for i, card := range d {
        fmt.Printf("%d) %s of %s\n", i, card.value, card.suit)
    }
}
</code>```

Why I can't run main.go file? please help TT

```<code>❯ go version
go version go1.14.3 darwin/amd64

❯ go run main.go
# command-line-arguments
./main.go:4:11: undefined: newDeck
</code>```

答: go run main.go runs only that file. You need to do go build . and run the executable.

Title: How to call function from other file

Body:
structure

.
├── deck.go
└── main.go

Here is the code in each .go file

main.go

package main

func main() {
    cards := newDeck()
    cards.print()
}

deck.go

package main

import "fmt"

type card struct {
    value string
    suit  string
}

type deck []card

func newDeck() deck {
    cards := deck{}

    cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
    cardValues := []string{"Ace", "Two", "Three"}

    for _, suit := range cardSuits {
        for _, value := range cardValues {
            cards = append(cards, card{
                suit:  suit,
                value: value,
            })
        }
    }
    return cards
}

func (d deck) print() {
    for i, card := range d {
        fmt.Printf("%d) %s of %s\n", i, card.value, card.suit)
    }
}

Why I can't run main.go file? please help TT

❯ go version
go version go1.14.3 darwin/amd64

❯ go run main.go
# command-line-arguments
./main.go:4:11: undefined: newDeck


问:
I am not able to set interval in my react app
this is my showdate.js  - >

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

class Showdate extends Component {
    componentWillMount() {
        setInterval(1000);
    }

    render() {
        return (
            <div>
                <h1>Welcome to GeeksforGeeks!</h1>
                <h2>{new Date().toLocaleTimeString()}</h2>
            </div>
        );
    }
}

export default Showdate;
</code>```

and rendering through index.js as ->

```<code>import React from "react";
import ReactDOM from "react-dom";
import Showdate from "./showDate";
const rootElement4 = document.getElementById("root4");
console.log(<Showdate />);
ReactDOM.render(<Showdate />, rootElement4);
</code>```

time is getting displayed but it is not refresshing by one sec as it should acc to setinterval(1000)

答:
The function setInterval is taking a callback function and the timeout. So, you have to implement it as follows. Plus, you should clear the interval before your component is unmounted.

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

    class Showdate extends Component {
        constructor(props) {
          super(props);
          this.state = { date: new Date() }
        }

        componentDidMount() {
          this.timer = setInterval(() => this.tick(), 1000)
        }

        componentWillUnmount() {
          clearInterval(this.timer)
        }

        tick() {
          this.setState({ date: new Date() })
        }

        render() {
            return (
                <div>
                    <h1>Welcome to GeeksforGeeks!</h1>
                    <h2>{this.state.date.toLocaleTimeString()}</h2>
                </div>
            );
        }
    }

    export default Showdate;
</code>```

Body:
this is my showdate.js  - >

import React, { Component } from "react";

class Showdate extends Component {
    componentWillMount() {
        setInterval(1000);
    }

    render() {
        return (

Welcome to GeeksforGeeks!

{new Date().toLocaleTimeString()}

        );
    }
}

export default Showdate;

and rendering through index.js as ->

import React from "react";
import ReactDOM from "react-dom";
import Showdate from "./showDate";
const rootElement4 = document.getElementById("root4");
console.log(<Showdate />);
ReactDOM.render(<Showdate />, rootElement4);

time is getting displayed but it is not refresshing by one sec as it should acc to setinterval(1000)

Body:
The function setInterval is taking a callback function and the timeout. So, you have to implement it as follows. Plus, you should clear the interval before your component is unmounted.

    import React, { Component } from "react";

    class Showdate extends Component {
        constructor(props) {
          super(props);
          this.state = { date: new Date() }
        }

        componentDidMount() {
          this.timer = setInterval(() => this.tick(), 1000)
        }

        componentWillUnmount() {
          clearInterval(this.timer)
        }

        tick() {
          this.setState({ date: new Date() })
        }

        render() {
            return (
                <div>
                    <h1>Welcome to GeeksforGeeks!</h1>
                    <h2>{this.state.date.toLocaleTimeString()}</h2>
                </div>
            );
        }
    }

    export default Showdate;


问:
Which node version will be use as default?
In my Linux mint, previous version of nodejs was v8.10.0 so I decided to upgrade it and after upgrade, I run nodejs -v but it is sill reporting v8.10.0 (after restarting pc too). If I run node -v it is reporting v12.17.0 (which is currently the latest version). I don't know what is the difference between node and nodejs.

I run a xyz.js file from both node and nodejs it runs successfuly.

You can see some terminal output for your help -

$ which -a node

/usr/local/bin/node

/usr/bin/node

$ node -v

v12.17.0

$ which -a nodejs

/usr/bin/nodejs

$ nodejs -v

v8.10.0

Is my system using node/nodejs latest version, If not what should I do ?

答: What's happening here is simply the new version of node installs as 'node' while the older version installed as 'nodejs'. Given that your older version of 'nodejs' was working fine and the new version, 'node', never overwrote it you're left with two different versions of node. As a test, I change the name of the node file and or remove it from the folder altogether and see what happens. I'm sure you will be left with only on the version of node being recognized on your system. </p>


问:
"type": "module" in package.json throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath)
I want to use import in my nodejs project instead of using require.
So, I added,

```<code>"type": "module"
</code>```

in my package.json.

```<code>import index from './index.js';
</code>```

in server.js

when I run

node server.js

Error says,

```<code>internal/modules/cjs/loader.js:1174
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ....
</code>```

server.conf.js is pasted below.

```<code>import express from 'express';

import http from 'http';
let app = express();
let server = http.createServer(app);

import morgan from 'morgan';
import methodOverride from 'method-override';;
import path from 'path';

let port = process.env.PORT || 4000;
app.use(morgan('dev'));
app.use(methodOverride('X-HTTP-Method-Override'));
let router = express.Router();
import routes from '../app/routes';
routes(app, router, client);
server.listen(port);
console.log(`Wizardry is afoot on port ${port}`);
export {
    app,
    client
};
</code>```

答:
According to stack-trace before you edit (https://stackoverflow.com/revisions/61558835/1):

internal/modules/cjs/loader.js:1174
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: H:\WORKSPACE\CMDs\node-basic\server.conf.js
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1174:13)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47 {
  code: 'ERR_REQUIRE_ESM'
}
```

<p>I tried to locate the Node src who throws this error: </p>

<p>https://github.com/nodejs/node/blob/c24b74a7abec0848484671771d250cfd961f128e/lib/internal/modules/cjs/loader.js#L1234</p>

<pre class="lang-js prettyprint-override"><code>// Native extension for .js
Module._extensions['.js'] = function(module, filename) {
  if (filename.endsWith('.js')) {
    const pkg = readPackageScope(filename);
    // Function require shouldn't be used in ES modules.
    if (pkg && pkg.data && pkg.data.type === 'module') {
      // ...
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
    }
  }
  // ...
};
</code>```

The comment Function require shouldn't be used in ES modules tells the js file to be loaded is an ES module, but the caller is trying to use require() function to load it.

Moreover, a double-check into Node src https://github.com/nodejs/node/blob/6cc94b2d7f69f1f541f7c5de3cb86e569fbd4aa3/lib/internal/errors.js#L1319 proves that H:\WORKSPACE\CMDs\node-basic\server.conf.js is the ES module to be loaded.

So I'm trying to guess who is trying to load server.conf.js in your app but no luck. Most likely there is a require('./server.conf.js') in your index.js or somewhere else. If you find it just change it into import to fix.

Body:
I want to use import in my nodejs project instead of using require.
So, I added,

"type": "module"

in my package.json.

import index from './index.js';

in server.js

when I run

node server.js

Error says,

internal/modules/cjs/loader.js:1174
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ....

server.conf.js is pasted below.

import express from 'express';

import http from 'http';
let app = express();
let server = http.createServer(app);

import morgan from 'morgan';
import methodOverride from 'method-override';;
import path from 'path';

let port = process.env.PORT || 4000;
app.use(morgan('dev'));
app.use(methodOverride('X-HTTP-Method-Override'));
let router = express.Router();
import routes from '../app/routes';
routes(app, router, client);
server.listen(port);
console.log(`Wizardry is afoot on port ${port}`);
export {
    app,
    client
};

Body:
According to stack-trace before you edit (https://stackoverflow.com/revisions/61558835/1):

internal/modules/cjs/loader.js:1174
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: H:\WORKSPACE\CMDs\node-basic\server.conf.js
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1174:13)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47 {
  code: 'ERR_REQUIRE_ESM'
}

I tried to locate the Node src who throws this error:

https://github.com/nodejs/node/blob/c24b74a7abec0848484671771d250cfd961f128e/lib/internal/modules/cjs/loader.js#L1234

// Native extension for .js
Module._extensions['.js'] = function(module, filename) {
  if (filename.endsWith('.js')) {
    const pkg = readPackageScope(filename);
    // Function require shouldn't be used in ES modules.
    if (pkg && pkg.data && pkg.data.type === 'module') {
      // ...
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
    }
  }
  // ...
};

The comment Function require shouldn't be used in ES modules tells the js file to be loaded is an ES module, but the caller is trying to use require() function to load it.

Moreover, a double-check into Node src https://github.com/nodejs/node/blob/6cc94b2d7f69f1f541f7c5de3cb86e569fbd4aa3/lib/internal/errors.js#L1319 proves that H:\WORKSPACE\CMDs\node-basic\server.conf.js is the ES module to be loaded.

So I'm trying to guess who is trying to load server.conf.js in your app but no luck. Most likely there is a require('./server.conf.js') in your index.js or somewhere else. If you find it just change it into import to fix.


问:
Aliased command in bashrc does not correctly use $OLDPWD
I have an alias in bashrc that I use to generate a particular LaTeX document (the main command used is pdflatex) but I want to be able to execute it regardless of where I am. Unfortunately, it seems like you can't use use this command with an absolute path unless the path is 'under' your current directory, so I cd into the directory my .tex file is, run pdflatex, then try to cd back to my previous directory. In bashrc, I have my command as

```<code>alias nbr="cd ~/path/to/dir && pdflatex file.tex && cd $OLDPWD"
</code>```

The command works fine outside of putting me back in my previous directory. For some reason, this command works perfectly fine in a regular bash shell, so I'm guessing there's some issue with what $OLDPWD is considered in the context of bashrc but I'm not sure. Any ideas?

答: @Cyrus's answer fixed it...should've used single quotes. </p>

Body:
I have an alias in bashrc that I use to generate a particular LaTeX document (the main command used is pdflatex) but I want to be able to execute it regardless of where I am. Unfortunately, it seems like you can't use use this command with an absolute path unless the path is 'under' your current directory, so I cd into the directory my .tex file is, run pdflatex, then try to cd back to my previous directory. In bashrc, I have my command as

alias nbr="cd ~/path/to/dir && pdflatex file.tex && cd $OLDPWD"

The command works fine outside of putting me back in my previous directory. For some reason, this command works perfectly fine in a regular bash shell, so I'm guessing there's some issue with what $OLDPWD is considered in the context of bashrc but I'm not sure. Any ideas?


问:
Array Holding an another Object
```<code>options: ['Unknown', 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE']
</code>```

<p>This is my Options Array and there are 47 states in all. i don't want to add it like this. Instead can i add something like this </p>

```<code>options: [StateValue] Which would read all the values from the Object.

var StateValue = {
    Unknown: 0,
    AL: 1,
    AK: 2,
    AZ: 3,
    AR: 4,
    CA: 5,
    CO: 6,
    CT: 7,
    DE: 8,
    FL: 9
};
</code>```

答:
You can loop through an object like so

```<code>var StateValue = {
    Unknown: 0,
    AL: 1,
    AK: 2,
    AZ: 3,
    AR: 4,
    CA: 5,
    CO: 6,
    CT: 7,
    DE: 8,
    FL: 9
};

for(var i in StateValue)
    console.log(i + " :: " + StateValue[i]);
</code>```

so you could populate your UI in that way

ContentLicense: CC BY-SA 3.0

Title: Array Holding an another Object

Body:
options: ['Unknown', 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE']

This is my Options Array and there are 47 states in all. i don't want to add it like this. Instead can i add something like this

options: [StateValue] Which would read all the values from the Object.

var StateValue = {
    Unknown: 0,
    AL: 1,
    AK: 2,
    AZ: 3,
    AR: 4,
    CA: 5,
    CO: 6,
    CT: 7,
    DE: 8,
    FL: 9
};

Body:
You can loop through an object like so

var StateValue = {
    Unknown: 0,
    AL: 1,
    AK: 2,
    AZ: 3,
    AR: 4,
    CA: 5,
    CO: 6,
    CT: 7,
    DE: 8,
    FL: 9
};

for(var i in StateValue)
    console.log(i + " :: " + StateValue[i]);

so you could populate your UI in that way


问:
Grepping a single regular expression for a very large file
file.xml is a large 74G file, I have to grep a single regular expression against it as fast as possible. I'm trying to do this by using GNU parallel:

```<code>parallel --pipe --block 10M --ungroup LC_ALL=C grep -iF "test.*pattern" < file.xml
</code>```

How can I implement this by using --pipepart since it's faster than --pipe?

Does it get faster by increasing or decreasing size of blocks (example 20M instead of 10M, or 10M instead of 20M)?

答:
1.) The largest xml file I have is 11G so YMMV but using parallel --pipepart LC_ALL=C grep -H -n 'searchterm' {} :::: file.xml was faster than parallel --pipe --block 10M --ungroup LC_ALL=C grep -iF "test.*pattern" < file.xml and significantly faster than grep "searchterm" file.xml.

2.) I didn't specify a block size for the parallel --pipepart command above, but you can with the --block option; you'll need to try different block sizes yourself to see whether they speed up / slow down the search. Using --block -1 provided the fastest speed on my system for this approach.

As @tshiono mentioned in the comments, try ripgrep - this was fastest on my test xml file (quicker than grep/parallel grep/anything else) and may prove to be a better solution for you overall.

EDIT
I tested @Ole Tange's suggested 'parallel + ripgrep' approach (parallel --pipepart --block -1 LC_ALL=C rg 'Glu299SerfsTer21' {} :::: ClinVarFullRelease_00-latest.xml) and it was ~the same as rg 'Glu299SerfsTer21' ClinVarFullRelease_00-latest.xml on my system. The difference was negligible, so the 'parallel + rg' approach may be best for a very large XML file. There are a number of potential reasons I didn't see the expected speedup, eg @Gordon Davisson suggestions in his comment above, but you would need to conduct comprehensive benchmarking with your own system to figure out the best approach.

(Thanks Ole Tange for the suggestion and for creating such kick ass software)

Body:
file.xml is a large 74G file, I have to grep a single regular expression against it as fast as possible. I'm trying to do this by using GNU parallel:

parallel --pipe --block 10M --ungroup LC_ALL=C grep -iF "test.*pattern" < file.xml

How can I implement this by using --pipepart since it's faster than --pipe?

Does it get faster by increasing or decreasing size of blocks (example 20M instead of 10M, or 10M instead of 20M)?


问:
ReactiveUI WhenAnyValue
i have this code, but when i run, i throw an exception. I try to read document but i'm not Know, where am i Wrong?

public bool IsCanvasMouseOn
{
    get => this._isCanvasMouseOn;
    set => this.RaiseAndSetIfChanged(ref _isCanvasMouseOn, value);
}

public Visibility DynamicInputVisibility => this._dynamicInputVisibility.Value;

this.WhenAnyValue(x => x.IsCanvasMouseOn)
                .Select(visibility => visibility ? Visibility.Visible : Visibility.Collapsed)
                .StartWith(Visibility.Collapsed)
                .DistinctUntilChanged()
                .ToProperty(this, x=>DynamicInputVisibility,out _dynamicInputVisibility);

```

System.ArgumentException: 'Property expression must be of the form 'x => x.SomeProperty''

答:
It's your last line

ToProperty(this, x=>DynamicInputVisibility,out _dynamicInputVisibility);
```

<p>It should be </p>

<pre class="lang-cs prettyprint-override"><code>ToProperty(this, x=> x.DynamicInputVisibility,out _dynamicInputVisibility);
</code>```

Title: ReactiveUI WhenAnyValue

Body:
i have this code, but when i run, i throw an exception. I try to read document but i'm not Know, where am i Wrong?

public bool IsCanvasMouseOn
{
    get => this._isCanvasMouseOn;
    set => this.RaiseAndSetIfChanged(ref _isCanvasMouseOn, value);
}

public Visibility DynamicInputVisibility => this._dynamicInputVisibility.Value;

this.WhenAnyValue(x => x.IsCanvasMouseOn)
                .Select(visibility => visibility ? Visibility.Visible : Visibility.Collapsed)
                .StartWith(Visibility.Collapsed)
                .DistinctUntilChanged()
                .ToProperty(this, x=>DynamicInputVisibility,out _dynamicInputVisibility);

System.ArgumentException: 'Property expression must be of the form 'x => x.SomeProperty''

Body:
It's your last line

ToProperty(this, x=>DynamicInputVisibility,out _dynamicInputVisibility);

It should be

ToProperty(this, x=> x.DynamicInputVisibility,out _dynamicInputVisibility);


问:
Looping through API response Node JS
I'm trying to pull data from an API and insert it into a MySQL Database. The API has over 100 objects but I can't find any information on how to do this? </p>

<p>I'm using node-fetch to output the Json Data but can't loop through each object? I've added a snippet of the API. </p>

```<code>[
  {
    "id": 1,
    "name": "Device_1"
  },
  {
    "id": 2,
    "name": "Device_2"
  }
]
</code>```

答:
let responseFromApi = [
  {
    "id": 1,
    "name": "Device_1"
  },
  {
    "id": 2,
    "name": "Device_2"
  }
];

let insertMany = db.query(
    'INSERT INTO your_table (id, name) VALUES ?',
    [responseFromApi.map(res => [res.id, res.name])],
);

for refrence go through the documentation -->
https://www.mysqltutorial.org/mysql-nodejs/insert/

You can also use query builders such as KnexJs and others

Title: Looping through API response Node JS

Body:
I'm trying to pull data from an API and insert it into a MySQL Database. The API has over 100 objects but I can't find any information on how to do this?

I'm using node-fetch to output the Json Data but can't loop through each object? I've added a snippet of the API.

[
  {
    "id": 1,
    "name": "Device_1"
  },
  {
    "id": 2,
    "name": "Device_2"
  }
]


问:
l want to add function in python turtle graphics
My code lets the user input the turtle count. Then, it will show the amount of input with random turtle shapes and colors. I want to add 3 functions to my turtle graphics code.

"Please enter the number of turtles: "

Function to initialize the turtle array by receiving the number of turtles as a parameter

Finally, the function draws the turtle

Please help me,
here is my code:

```<code>import turtle
import random

myturtle,tx,ty,tcolor,tsize,tshape=[None]*6
shapelist=[]
playerturtles=[]
swidth,sheight=500,500

if __name__=='__main__':
    turtle.title('Turtle list utilization')
    turtle.setup(width=swidth+50,height=sheight+50)
    turtle.screensize(swidth,sheight)
    shapelist=turtle.getshapes()
    a=int(input('Turtle Count:'))

    for i in range(0,a):
        random.shuffle(shapelist)
        myturtle=turtle.Turtle(shapelist[0])
        tx=random.randrange(-swidth/2,swidth/2)
        ty=random.randrange(-sheight/2,sheight/2)
        r=random.random();g=random.random();b=random.random()
        tsize=random.randrange(1,3)
        playerturtles.append([myturtle,tx,ty,tsize,r,g,b])

    for i in range(0,a):
        myturtle=playerturtles[i][0]
        myturtle.color((playerturtles[i][4],playerturtles[i][5],playerturtles[i][6]))
        myturtle.pencolor((playerturtles[i][4],playerturtles[i][5],playerturtles[i][6]))
        myturtle.turtlesize(playerturtles[i][3])
        myturtle.goto(playerturtles[i][1],playerturtles[i][2])
    turtle.done()
</code>```

答:
Here is the code using global variables. You should consider switching from global variables in this function and it would be interesting and important to read about global variables.

```<code>import turtle
import random

myturtle, tx, ty, tcolor, tsize, tshape = [None] * 6
shapelist = []
playerturtles = []
swidth, sheight = 500, 500

def start_turtles():
    global shapelist
    turtle.title('Turtle list utilization')
    turtle.setup(width=swidth + 50, height=sheight + 50)
    turtle.screensize(swidth, sheight)
    shapelist = turtle.getshapes()
    a = int(input('Turtle Count:'))
    return a

def turtle_start(a):
    global myturtle
    global tsize
    global tx
    global ty

    for i in range(0, a):
        random.shuffle(shapelist)
        myturtle = turtle.Turtle(shapelist[0])
        tx = random.randrange(-swidth / 2, swidth / 2)
        ty = random.randrange(-sheight / 2, sheight / 2)
        r = random.random()
        g = random.random()
        b = random.random()
        tsize = random.randrange(1, 3)
        playerturtles.append([myturtle, tx, ty, tsize, r, g, b])

def turtle_draw(a):
    global myturtle
    for i in range(0, a):
        myturtle = playerturtles[i][0]
        myturtle.color((playerturtles[i][4], playerturtles[i][5], playerturtles[i][6]))
        myturtle.pencolor((playerturtles[i][4], playerturtles[i][5], playerturtles[i][6]))
        myturtle.turtlesize(playerturtles[i][3])
        myturtle.goto(playerturtles[i][1], playerturtles[i][2])
    turtle.done()

if __name__ == '__main__':
    a = start_turtles()
    turtle_start(a)
    turtle_draw(a)
</code>```

Body:
My code lets the user input the turtle count. Then, it will show the amount of input with random turtle shapes and colors. I want to add 3 functions to my turtle graphics code.

"Please enter the number of turtles: "

Function to initialize the turtle array by receiving the number of turtles as a parameter

Finally, the function draws the turtle

Please help me,
here is my code:

import turtle
import random

myturtle,tx,ty,tcolor,tsize,tshape=[None]*6
shapelist=[]
playerturtles=[]
swidth,sheight=500,500

if __name__=='__main__':
    turtle.title('Turtle list utilization')
    turtle.setup(width=swidth+50,height=sheight+50)
    turtle.screensize(swidth,sheight)
    shapelist=turtle.getshapes()
    a=int(input('Turtle Count:'))

    for i in range(0,a):
        random.shuffle(shapelist)
        myturtle=turtle.Turtle(shapelist[0])
        tx=random.randrange(-swidth/2,swidth/2)
        ty=random.randrange(-sheight/2,sheight/2)
        r=random.random();g=random.random();b=random.random()
        tsize=random.randrange(1,3)
        playerturtles.append([myturtle,tx,ty,tsize,r,g,b])

    for i in range(0,a):
        myturtle=playerturtles[i][0]
        myturtle.color((playerturtles[i][4],playerturtles[i][5],playerturtles[i][6]))
        myturtle.pencolor((playerturtles[i][4],playerturtles[i][5],playerturtles[i][6]))
        myturtle.turtlesize(playerturtles[i][3])
        myturtle.goto(playerturtles[i][1],playerturtles[i][2])
    turtle.done()

Body:
Here is the code using global variables. You should consider switching from global variables in this function and it would be interesting and important to read about global variables.

import turtle
import random

myturtle, tx, ty, tcolor, tsize, tshape = [None] * 6
shapelist = []
playerturtles = []
swidth, sheight = 500, 500

def start_turtles():
    global shapelist
    turtle.title('Turtle list utilization')
    turtle.setup(width=swidth + 50, height=sheight + 50)
    turtle.screensize(swidth, sheight)
    shapelist = turtle.getshapes()
    a = int(input('Turtle Count:'))
    return a

def turtle_start(a):
    global myturtle
    global tsize
    global tx
    global ty

    for i in range(0, a):
        random.shuffle(shapelist)
        myturtle = turtle.Turtle(shapelist[0])
        tx = random.randrange(-swidth / 2, swidth / 2)
        ty = random.randrange(-sheight / 2, sheight / 2)
        r = random.random()
        g = random.random()
        b = random.random()
        tsize = random.randrange(1, 3)
        playerturtles.append([myturtle, tx, ty, tsize, r, g, b])

def turtle_draw(a):
    global myturtle
    for i in range(0, a):
        myturtle = playerturtles[i][0]
        myturtle.color((playerturtles[i][4], playerturtles[i][5], playerturtles[i][6]))
        myturtle.pencolor((playerturtles[i][4], playerturtles[i][5], playerturtles[i][6]))
        myturtle.turtlesize(playerturtles[i][3])
        myturtle.goto(playerturtles[i][1], playerturtles[i][2])
    turtle.done()

if __name__ == '__main__':
    a = start_turtles()
    turtle_start(a)
    turtle_draw(a)


问:
why am i getting list is not defined error in python IDLE?

I created an object of tictactoe class and then called display method on it :I'm getting error message saying List_1 is not defined
  Blockquote

```<code>Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    a.display()
  File "C:/Users/Kunall/Documents/#1 Code/#Projects/tic_tac_toe_0.2.py", line 6, in display
for l in list_1:
NameError: name 'list_1' is not defined
</code>```

Blockquote

答: instead of list_1 you should use self.list_1 and similarly self.uc_list

Body:
I created an object of tictactoe class and then called display method on it :I'm getting error message saying List_1 is not defined
  Blockquote

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    a.display()
  File "C:/Users/Kunall/Documents/#1 Code/#Projects/tic_tac_toe_0.2.py", line 6, in display
for l in list_1:
NameError: name 'list_1' is not defined

Blockquote


问:
How to use lottie animation in flutter app?
I want to animate the Lottie file in the flutter app.
I tried searching every corner of the internet and failed to find any info on it.

I found out that there is a flutter package "flutter_lottie.dart" and has a function to animate.

There is also an example provided by the author about the usage of the flutter_lottie.dart

but this I tried running the exact example : flutter Lottie example

and it gave the same error:

```<code>Creating Method Channel convictiontech/flutter_lottie_0
E/flutter (11371): [ERROR:flutter/shell/common/shell.cc(199)] Dart Error: Unhandled exception:
E/flutter (11371): PlatformException(error, java.lang.IllegalStateException: Unable to parse
composition
E/flutter (11371):  at com.airbnb.lottie.LottieAnimationView$2.onResult(LottieAnimationView.java:68)
</code>```

How to use animate using Lottie in flutter?

答:
you can animation download in gif format from lottiefiles website and open with Image.assets or
in json format

```<code>class MyApp extends StatelessWidget {
   @override
 Widget build(BuildContext context) {
  return MaterialApp(
    home: Scaffold(
      body: ListView(
      children: [
        // Load a Lottie file from your assets
        Lottie.asset('assets/LottieLogo1.json'),

        // Load a Lottie file from a remote url
        Lottie.network(
            'https://raw.githubusercontent.com/xvrh/lottie-
       flutter/master/example/assets/Mobilo/A.json'),

        // Load an animation and its images from a zip file
        Lottie.asset('assets/lottiefiles/angel.zip'),
      ],
    ),
  ),
);
}
}
</code>```

Body:
I want to animate the Lottie file in the flutter app.
I tried searching every corner of the internet and failed to find any info on it.

I found out that there is a flutter package "flutter_lottie.dart" and has a function to animate.

There is also an example provided by the author about the usage of the flutter_lottie.dart

but this I tried running the exact example : flutter Lottie example

and it gave the same error:

Creating Method Channel convictiontech/flutter_lottie_0
E/flutter (11371): [ERROR:flutter/shell/common/shell.cc(199)] Dart Error: Unhandled exception:
E/flutter (11371): PlatformException(error, java.lang.IllegalStateException: Unable to parse
composition
E/flutter (11371):  at com.airbnb.lottie.LottieAnimationView$2.onResult(LottieAnimationView.java:68)

How to use animate using Lottie in flutter?

Body:
you can animation download in gif format from lottiefiles website and open with Image.assets or
in json format

class MyApp extends StatelessWidget {
   @override
 Widget build(BuildContext context) {
  return MaterialApp(
    home: Scaffold(
      body: ListView(
      children: [
        // Load a Lottie file from your assets
        Lottie.asset('assets/LottieLogo1.json'),

        // Load a Lottie file from a remote url
        Lottie.network(
            'https://raw.githubusercontent.com/xvrh/lottie-
       flutter/master/example/assets/Mobilo/A.json'),

        // Load an animation and its images from a zip file
        Lottie.asset('assets/lottiefiles/angel.zip'),
      ],
    ),
  ),
);
}
}


问:
where are C# setting file values are saved? it's not in the appName.config
I'm using the settings files in C#. and cannot find where are the values saved.
the app works perfect but when I want to change manually the values in the appName.cpnfig it doesn't load/save the values there but in some other place.
does anyone know where?</p>

答:
Default settings' values are placed in the auto-generated, strongly-typed version of them (for example, if your settings file is "Some.settings", strongly-typed version would be "SomeSettings.Designer.cs").

You can override them by adding a configuration section in the app.config like this:

```<code><configuration>
  <configSections>
      <section
        name="SomeNamespace.SomeSettings"
        type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        requirePermission="false"
      />
    </sectionGroup>
  </configSections>

  <applicationSettings>
    <SomeNamespace.SomeSettings>
       <setting name="SomeExistingSetting" serializeAs="String">
        <value>Some new value</value>
      </setting>
  </applicationSettings>
<configuration>
</code>```

Body:
Default settings' values are placed in the auto-generated, strongly-typed version of them (for example, if your settings file is "Some.settings", strongly-typed version would be "SomeSettings.Designer.cs").

You can override them by adding a configuration section in the app.config like this:

<configuration>
  <configSections>
      <section
        name="SomeNamespace.SomeSettings"
        type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        requirePermission="false"
      />
    </sectionGroup>
  </configSections>

  <applicationSettings>
    <SomeNamespace.SomeSettings>
       <setting name="SomeExistingSetting" serializeAs="String">
        <value>Some new value</value>
      </setting>
  </applicationSettings>
<configuration>


问:
How do I display the return statement with this occurring error?
Just learned what a return statement is and trying to practice with it, but for some reasons it is saying my innerHTML is null?

var x = my_Function(20, 3);

function my_Function(a, b) {
    return a * b;
}
document.getElementById("return").innerHTML = x;
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="return" onload="my_Function()"></p></code>```

答:
Made changes in my answer, now you check-in live demo

function my_Function(a, b) {
    return a * b;
}
document.getElementById("return").innerHTML = my_Function(20, 3);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="return"></p>

</body>
</html></code>```

Body:
Made changes in my answer, now you check-in live demo

function my_Function(a, b) {
    return a * b;
}
document.getElementById("return").innerHTML = my_Function(20, 3);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="return"></p>

</body>
</html>


问:
How to merge vectors returned from function?
I have a function that returns a vector of strings and inside my main function I would like to combine all the vectors returned from the function. However I keep hitting an error vector iterators incompatible, but I make sure I return a ptr from the function so the vector is not deleted when the function ends.

```<code>const unique_ptr<vector<string>> loadTransactions(string filename){
    unique_ptr<vector<string>> transactions = make_unique<vector<T>>();
    //some processing
    return transactions;
}
int main(){
    vector<string> allTransactions;
    for(int i =0; i< 10; ++i){
        unique_ptr<vector<string>> transactions = loadTransactions("filename");
        allTransactions.insert(allTransactions.end(), transactions->begin(), transactions->end());
}
</code>```

答:
Your function can return std::vector without using pointer.

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

using namespace std;

vector<string> loadTransactions(string filename) {
    vector<string> transaction {};
    //some processing
    return transaction;
}
int main() {
    vector<string> allTransactions;
    for(int i = 0; i < 10; ++i) {
        vector<string> transactions = loadTransactions("filename");
        allTransactions.insert(allTransactions.end(), transactions.begin(), transactions.end());
    }

}
```

Body:
I have a function that returns a vector of strings and inside my main function I would like to combine all the vectors returned from the function. However I keep hitting an error vector iterators incompatible, but I make sure I return a ptr from the function so the vector is not deleted when the function ends.

const unique_ptr<vector<string>> loadTransactions(string filename){
    unique_ptr<vector<string>> transactions = make_unique<vector<T>>();
    //some processing
    return transactions;
}
int main(){
    vector<string> allTransactions;
    for(int i =0; i< 10; ++i){
        unique_ptr<vector<string>> transactions = loadTransactions("filename");
        allTransactions.insert(allTransactions.end(), transactions->begin(), transactions->end());
}


问:
Generate different object with same attributes
I am building a project. One of the requirements is to generate the object with the same attributes but randomly different values. I tried to use deep-copy, but not sure if it is conceptually correct.

So, for example, I have a Person class, inherited from the abstract class Character.

And there is a ScenarioGenerator, which I'll put the getRandomPerson method to create the instances of the Person class.

Any help of advice is highly appreciated.

Here is part of my Person class:

```<code>public class Person extends Character {
private Random random;

private boolean pregnant;
private boolean isYou;

Person(int age, Profession profession ,Gender gender, BodyType bodyType, boolean isPregnant) {
    super(age, gender, bodyType);//pass the attributes to the super class called Character
}

Person (Person otherPerson) { //copy constructor

    this.age = otherPerson.getAge();
    this.gender = otherPerson.getGender();
    this.bodyType = otherPerson.getBodyType();
}
public Profession getProfession () { // One of the getters which generate random enum value
    //only adults have profession
    if (getAge()<=16 || getAge()>68) {
        return Profession.NONE;
    } else {
        return Profession.values()[new Random().nextInt(Profession.values().length)];
    }
}
// setters and getters
}
</code>```

And the method of my ScernarioGenerator class:

```<code>public class ScenarioGenerator {
    public Person getRandomPerson() {
    //need age, gender, bodyType, profession, pregnancy
    Person people = new Person(person.getAge(), person.getProfession(), person.getGender(), person.getBodyType(), person.isPregnant());
    Person clone = new Person(people);
    return clone;
}
</code>```

答:
If you want a deeply cloned object then you can get it by implementing the clone class and overriding the clone function like

```<code>public class Person extends Character implements Cloneable {......}
</code>```

Then you may simply get the new deep copied object by

```<code>Person clone=(Person) people.clone();
</code>```

Body:
I am building a project. One of the requirements is to generate the object with the same attributes but randomly different values. I tried to use deep-copy, but not sure if it is conceptually correct.

So, for example, I have a Person class, inherited from the abstract class Character.

And there is a ScenarioGenerator, which I'll put the getRandomPerson method to create the instances of the Person class.

Any help of advice is highly appreciated.

Here is part of my Person class:

public class Person extends Character {
private Random random;

private boolean pregnant;
private boolean isYou;

Person(int age, Profession profession ,Gender gender, BodyType bodyType, boolean isPregnant) {
    super(age, gender, bodyType);//pass the attributes to the super class called Character
}

Person (Person otherPerson) { //copy constructor

    this.age = otherPerson.getAge();
    this.gender = otherPerson.getGender();
    this.bodyType = otherPerson.getBodyType();
}
public Profession getProfession () { // One of the getters which generate random enum value
    //only adults have profession
    if (getAge()<=16 || getAge()>68) {
        return Profession.NONE;
    } else {
        return Profession.values()[new Random().nextInt(Profession.values().length)];
    }
}
// setters and getters
}

And the method of my ScernarioGenerator class:

public class ScenarioGenerator {
    public Person getRandomPerson() {
    //need age, gender, bodyType, profession, pregnancy
    Person people = new Person(person.getAge(), person.getProfession(), person.getGender(), person.getBodyType(), person.isPregnant());
    Person clone = new Person(people);
    return clone;
}

Body:
If you want a deeply cloned object then you can get it by implementing the clone class and overriding the clone function like

public class Person extends Character implements Cloneable {......}

Then you may simply get the new deep copied object by

Person clone=(Person) people.clone();


问:
How to label values beyond threshold in plot type 'h'
Using the mtcars dataset and plot function with argument  type= 'h', I would like to label observations with  mtcars$wt >4 only, but did not manage. I tried:

```<code> plot(mtcars$wt,type = 'h',ylim = c(0,6))
    abline(h=4)
    text(mtcars$wt,row.names(mtcars[mtcars$wt >4,]),pos =3,col='blue',cex=0.6))
</code>```

But all bars get labelled:

I also tried the solution provided at Add labels to plot for specific values in R , but did not manage to make it work.

It would be great if the labels could also be on top of the bar with a 45 degree angle to avoid overlapping

答:
The text function arguments have a specific order (type ?text into the console), and when you don't use argument names the function fills the arguments in the order you've given. It seems you forgot to define y= or so.

Try this:

```<code>plot(mtcars$wt, type='h', ylim=c(0,6))
abline(h=4)
## here your old call with argument names
# text(x=mtcars$wt, y=row.names(mtcars[mtcars$wt >4,]), pos =3, col='blue', cex=0.6)
text(x=which(mtcars$wt > 4), y=mtcars$wt[mtcars$wt > 4],
     labels=row.names(mtcars[mtcars$wt > 4,]), pos=3, col='blue', cex=0.6)
</code>```

However, the labels are a bit lumped together. Here we could use Map that applies each argument one by one to the text function, and where we are able to add an adjustment vector to x and y arguments.

```<code>plot(mtcars$wt,type='h',ylim=c(0,6))
abline(h=4)
Map(function(x, y, labels) text(x, y, labels, pos=3, col="blue", cex=.6),
    x=which(mtcars$wt > 4) + c(0, -2.8, 0, 2.2),
    y=mtcars$wt[mtcars$wt > 4] + c(0, -.1, .1, -.1),
    labels=row.names(mtcars[mtcars$wt > 4,])
)
</code>```

When we have more labels this might still look confusing to readers. Then we could use arrows which positions are defined in startpoints x0, y0 and endpoints x1, y1 and where we use the values we already have.

```<code>plot(mtcars$wt,type='h',ylim=c(0,8))
abline(h=4)
xpos. <- which(mtcars$wt > 4)
ypos. <- mtcars$wt[mtcars$wt > 4]
Map(function(x, y, labels) text(x, y, labels, pos=3, col="blue", cex=.6),
    x=xpos. + c(0, -6, 0, 6), y=ypos. + c(0, 1, 2, 1),
    labels=row.names(mtcars[mtcars$wt > 4,])
)
arrows(x0=xpos. + c(0, -6, 0, 6), y0=ypos.+ c(0, 1, 2, 1), x1=xpos., y1=ypos.+.2,
       code=0, col="blue")
</code>```

To rotate the labels, we can use srt= option, e.g. srt=45 for 45°.

```<code>plot(mtcars$wt,type='h',ylim=c(0,8))
abline(h=4)
text(x=which(mtcars$wt > 4), y=mtcars$wt[mtcars$wt > 4],
     labels=row.names(mtcars[mtcars$wt > 4,]), pos=3, col='blue', cex=0.6, srt=45)
</code>```

Note: Better use another device than the preview window, such as png() or pdf(), because otherwise everything shifts annoyingly all the time. See answers to this question on how to do this:

How to save a plot as image on the disk?

Now, have fun with tinkering! :)

Body:
Using the mtcars dataset and plot function with argument  type= 'h', I would like to label observations with  mtcars$wt >4 only, but did not manage. I tried:

 plot(mtcars$wt,type = 'h',ylim = c(0,6))
    abline(h=4)
    text(mtcars$wt,row.names(mtcars[mtcars$wt >4,]),pos =3,col='blue',cex=0.6))

But all bars get labelled:

I also tried the solution provided at Add labels to plot for specific values in R , but did not manage to make it work.

It would be great if the labels could also be on top of the bar with a 45 degree angle to avoid overlapping

Body:
The text function arguments have a specific order (type ?text into the console), and when you don't use argument names the function fills the arguments in the order you've given. It seems you forgot to define y= or so.

Try this:

plot(mtcars$wt, type='h', ylim=c(0,6))
abline(h=4)
## here your old call with argument names
# text(x=mtcars$wt, y=row.names(mtcars[mtcars$wt >4,]), pos =3, col='blue', cex=0.6)
text(x=which(mtcars$wt > 4), y=mtcars$wt[mtcars$wt > 4],
     labels=row.names(mtcars[mtcars$wt > 4,]), pos=3, col='blue', cex=0.6)

However, the labels are a bit lumped together. Here we could use Map that applies each argument one by one to the text function, and where we are able to add an adjustment vector to x and y arguments.

plot(mtcars$wt,type='h',ylim=c(0,6))
abline(h=4)
Map(function(x, y, labels) text(x, y, labels, pos=3, col="blue", cex=.6),
    x=which(mtcars$wt > 4) + c(0, -2.8, 0, 2.2),
    y=mtcars$wt[mtcars$wt > 4] + c(0, -.1, .1, -.1),
    labels=row.names(mtcars[mtcars$wt > 4,])
)

When we have more labels this might still look confusing to readers. Then we could use arrows which positions are defined in startpoints x0, y0 and endpoints x1, y1 and where we use the values we already have.

plot(mtcars$wt,type='h',ylim=c(0,8))
abline(h=4)
xpos. <- which(mtcars$wt > 4)
ypos. <- mtcars$wt[mtcars$wt > 4]
Map(function(x, y, labels) text(x, y, labels, pos=3, col="blue", cex=.6),
    x=xpos. + c(0, -6, 0, 6), y=ypos. + c(0, 1, 2, 1),
    labels=row.names(mtcars[mtcars$wt > 4,])
)
arrows(x0=xpos. + c(0, -6, 0, 6), y0=ypos.+ c(0, 1, 2, 1), x1=xpos., y1=ypos.+.2,
       code=0, col="blue")

To rotate the labels, we can use srt= option, e.g. srt=45 for 45°.

plot(mtcars$wt,type='h',ylim=c(0,8))
abline(h=4)
text(x=which(mtcars$wt > 4), y=mtcars$wt[mtcars$wt > 4],
     labels=row.names(mtcars[mtcars$wt > 4,]), pos=3, col='blue', cex=0.6, srt=45)

Note: Better use another device than the preview window, such as png() or pdf(), because otherwise everything shifts annoyingly all the time. See answers to this question on how to do this:

How to save a plot as image on the disk?

Now, have fun with tinkering! :)


问:
How to use import () to dynamically load components in React?
I tried to use import() instead of React.lazy to dynamically load components, but it didn't work.

App.js

```<code>import React, { useState } from 'react';
function App() {
  const [Com, setCom] = useState(null);

  const handleClick = () => {
      import("./A.js").then(c => {
        //console.log(c.default)
        setCom(c.default)
      })
  }

  return (
      <div>
        <button onClick={handleClick}>Load</button>
        { Com ? <Com /> : null }
      </div>
   );
}

export default App;
</code>```

A.js

```<code>import React from "react";

export default function A () {
    return (<div>A</div>)
}
</code>```

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

In fact, I printed out c.default. It's really a function.

c.default

```<code>ƒ A() {
  return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
    __source: {
      fileName: _jsxFileName,
      lineNumber: 4
    },
    __self: this
  }, "A");
}
</code>```

答:
If setState is called with a function, it will be executed with the previous value as the argument.

```<code>const [count,setCount] = useState(0)
setCount(prevCount => prevCount + 1)
</code>```

In your case, rather than updating the state with the imported function, React will execute it and the result will be set as the state.

Solution:

setCom(() => c.default)
```

Body:
I tried to use import() instead of React.lazy to dynamically load components, but it didn't work.

App.js

import React, { useState } from 'react';
function App() {
  const [Com, setCom] = useState(null);

  const handleClick = () => {
      import("./A.js").then(c => {
        //console.log(c.default)
        setCom(c.default)
      })
  }

  return (

        <button onClick={handleClick}>Load</button>
        { Com ? <Com /> : null }

   );
}

export default App;

A.js

import React from "react";

export default function A () {
    return (
A
)
}

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

In fact, I printed out c.default. It's really a function.

c.default

ƒ A() {
  return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
    __source: {
      fileName: _jsxFileName,
      lineNumber: 4
    },
    __self: this
  }, "A");
}

Body:
If setState is called with a function, it will be executed with the previous value as the argument.

const [count,setCount] = useState(0)
setCount(prevCount => prevCount + 1)

In your case, rather than updating the state with the imported function, React will execute it and the result will be set as the state.

Solution:

setCom(() => c.default)


问:
Why is there a curled bracket on the List?
Recently stumped upon this line in a program, and I have no idea what the bracket for (List<Level>) is for . Anybody got any idea ?

List<Level> levelList = (List<Level>)dao.getAllLevels();

答: It's depend on what getAllLevels method is returning.


问:
asp.net Core 3.1 Filter Form trigger refresh of page
I am struggling to figure out the proper way of achieving this objective.

I have a view that contains a bunch of data. At the top of the view, I have added a form with some options to filter on. Once they click submit, I want to trigger a call to the C# controller to filter out the data and trigger the page to refresh. I was able to do this without passing any parameters by calling on the window to refresh via javascript. But as soon as I tried to get the user entered data, I keep hitting a wall. When trying to pass to javascript, it always loaded the initial state of the model. So I tried changing it to use a form that calls the action, which worked on the backend but now it just errors out 500 when it returns the view and I have no idea why.

What is the proper way of doing something like this?

Summary.cshtml

```<code>@model SummaryModel

<!-- ... excluding content -->
<form id="form" asp-area="" asp-controller="Home" asp-action="refreshSummary">
    <div class="col-md-6">
        <div class="form-group">
            <label asp-for="EpicType" class="label-control"></label>
            <select asp-for="EpicType" class="form-control" asp-items="@QueryModel.EpicTypes"></select>
            <span asp-validation-for="EpicType" class="text-danger"></span>
        </div>
    </div>

    <p></p>
    <div class="form-group" style="align-content: center; text-align: center; padding-bottom: 5px;" ;>
        <button type="submit" id="submitbtn" class="btn btn-sm btn-primary rounded-0">Apply</button>
    </div>
</form>

<!-- ... excluding content -->
</code>```

Rest of the page is just displaying data, not sure its relevant to question. On apply, I want to update the page with the newly filtered results.

HomeController.cs

```<code>/// <summary>
    /// Refreshes the list of epics based on filters
    /// </summary>
    /// <param name="FilterModel">filterData</param>
    /// <returns>result</returns>
    public IActionResult refreshSummary(SummaryModel filterData)
    {
        .. do filtering here ..

        filteredPorts.Sort();
        return View("Summary");
    }
</code>```

I hit this call fine. But the return is when a 500 error hits and I get no insight in visual studio as to why.
In startup I have:

```<code>endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Summary}");
</code>```

答:
Your code is not provided completely. We cannot know exactly what you
  did in refreshSummary action.

But the 500 error here is that you did not re-bind the corresponding data source to the select (@QueryModel.EpicTypes) when you returned to the Summary view.

When returning to the Summary view, you need to return the value of @QueryModel.EpicTypes as a parameter and rebind the selected data source.

```<code>    public IActionResult refreshSummary(SummaryModel filterData)
    {
        //  .. do filtering here ..
        filteredPorts.Sort();
        return View("Index", summary);//here summary contains @QueryModel.EpicTypes data
    }
</code>```

Body:
I am struggling to figure out the proper way of achieving this objective.

I have a view that contains a bunch of data. At the top of the view, I have added a form with some options to filter on. Once they click submit, I want to trigger a call to the C# controller to filter out the data and trigger the page to refresh. I was able to do this without passing any parameters by calling on the window to refresh via javascript. But as soon as I tried to get the user entered data, I keep hitting a wall. When trying to pass to javascript, it always loaded the initial state of the model. So I tried changing it to use a form that calls the action, which worked on the backend but now it just errors out 500 when it returns the view and I have no idea why.

What is the proper way of doing something like this?

Summary.cshtml

@model SummaryModel

<form id="form" asp-area="" asp-controller="Home" asp-action="refreshSummary">

            <select asp-for="EpicType" class="form-control" asp-items="@QueryModel.EpicTypes"></select>

        <button type="submit" id="submitbtn" class="btn btn-sm btn-primary rounded-0">Apply</button>

</form>

Rest of the page is just displaying data, not sure its relevant to question. On apply, I want to update the page with the newly filtered results.

HomeController.cs

///
    /// Refreshes the list of epics based on filters
    ///
    /// <param name="FilterModel">filterData</param>
    /// <returns>result</returns>
    public IActionResult refreshSummary(SummaryModel filterData)
    {
        .. do filtering here ..

        filteredPorts.Sort();
        return View("Summary");
    }

I hit this call fine. But the return is when a 500 error hits and I get no insight in visual studio as to why.
In startup I have:

endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Summary}");

Body:
Your code is not provided completely. We cannot know exactly what you
  did in refreshSummary action.

But the 500 error here is that you did not re-bind the corresponding data source to the select (@QueryModel.EpicTypes) when you returned to the Summary view.

When returning to the Summary view, you need to return the value of @QueryModel.EpicTypes as a parameter and rebind the selected data source.

    public IActionResult refreshSummary(SummaryModel filterData)
    {
        //  .. do filtering here ..
        filteredPorts.Sort();
        return View("Index", summary);//here summary contains @QueryModel.EpicTypes data
    }


问:
Why is the output of `typeid(T&).name()` given as `T` instead of `T&`?
As the subject, you could check the related code on https://godbolt.org/z/qtjVP6.

For your convience, the code is posted below:

```<code>#include<typeinfo>
#include<iostream>

class Widget{};

Widget someWidget;

int main()
{
    Widget&& var1 = Widget{};      // here, “&&” means rvalue reference
    auto&& var2 = var1;              // here, “&&” does not mean rvalue reference

    std::cout << typeid(var2).name() << std::endl;
}
</code>```

Output:6Widget

echo 6Widget | c++filt -t says Widget.

I would be grateful to have some help on this question.

答:
Per C++ Reference (emphasis mine):

1) Refers to a std::type_info object representing the type type. If type is a reference type, the result refers to a std::type_info object representing the referenced type.

So for type = T&, typeid(type) will give results about T (reference removed).

It's easy to understand IMO, as for all purposes, a variable of type T& is functionally equivalent to one of type T.

Body:
As the subject, you could check the related code on https://godbolt.org/z/qtjVP6.

For your convience, the code is posted below:

#include<typeinfo>
#include<iostream>

class Widget{};

Widget someWidget;

int main()
{
    Widget&& var1 = Widget{};      // here, “&&” means rvalue reference
    auto&& var2 = var1;              // here, “&&” does not mean rvalue reference

    std::cout << typeid(var2).name() << std::endl;
}

Output:6Widget

echo 6Widget | c++filt -t says Widget.

I would be grateful to have some help on this question.


问:
How to wait for React useEffect hook finish before moving to next screen
I'm having issue where hook is being used in multiple files and it is being called twice for useEffect before the 1st one's async method finish (which should block the 2nd hook call, but it's not). See below 2 scenarios:

Stack Navigator

```<code>const { context, state } = useLobby(); // Hook is called here 1st, which will do the initial render and checks

return (
  <LobbyContext.Provider value={context}>
    <LobbyStack.Navigator>
      {state.roomId
        ? <LobbyStack.Screen name="Lobby" component={LobbyScreen} />
        : <LobbyStack.Screen name="Queue" component={QueueScreen} />
      }
    </LobbyStack.Navigator>
  </LobbyContext.Provider>
)
</code>```

Lobby Hooks

```<code>export const useLobby = () => {
  const [state, dispatch] = React.useReducer(...)

  //
  // Scenario 1
  // This get called twice (adds user to room twice)
  //
  React.useEffect(() => {
    if (!state.isActive) assignRoom();
  }, [state.isActive])

  const assignRoom = async () => {
    // dispatch room id
  }

  const context = React.useMemo(() => ({
    join: () => { assignRoom(); }
  })
}
</code>```

Queue Screen

```<code>const { context, state } = useLobby(); // Hook is called here 2nd right after checking state from stack navigator

//
// Scenario 2
// Only does it once, however after state is changed to active
// the stack navigator didn't get re-render like it did in Scenario 1
//
React.useEffect(() => {
  roomLobby.join();
}, []);

return (
...
  {state.isActive
    ? "Show the room Id"
    : "Check again"
...
)
</code>```

In scenario 1, I guess while 1st hook is called and useEffect is doing async to add user to the room and set active to true. Meanwhile the conditional render part is moving straight to Queue screen which calls the hook again and doing the useEffect (since 1st haven't finished and isActive is still false).

How can I properly setup useReducer and useMemo so that it renders the screen base on the state.

Edited codes based on the answer

```<code>/* LobbyProvider */

const LobbyContext = React.createContext();

const lobbyReducer = (state, action) => {
  switch (action.type) {
    case 'SET_LOBBY':
      return {
        ...state,
        isActive: action.active,
        lobby: action.lobby
      };
    case 'SET_ROOM':
      return {
        ...state,
        isQueued: action.queue,
        roomId: action.roomId,
      };
    default:
      return state;
  }
}

const LobbyProvider = ({ children }) => {
  const [state, dispatch] = React.useReducer(lobbyReducer, initialState);

  React.useEffect(() => {
    console.log("Provider:", state)
    if (!state.isActive) joinRoom();
  }, [])

  // Using Firebase functions
  const joinRoom = async () => {
    try {
      const response = await functions().httpsCallable('getActiveLobby')();
      if (response) {
        dispatch({ type: 'SET_LOBBY', active: true, lobby: response.data })
        const room = await functions().httpsCallable('assignRoom')({ id: response.data.id });
        dispatch({ type: 'SET_ROOM', queue: false, roomId: room.data.id })
      }
    } catch (e) {
      console.error(e);
    }
  }

  return (
    <LobbyContext.Provider value={{state, dispatch}}>
      { children }
    </LobbyContext.Provider>
  )
}

/* StackNavigator */

const {state} = React.useContext(LobbyContext);

return (
  <LobbyProvider>
    // same as above <LobbyStack.Navigator>
    // state doesn't seem to be updated here or to re-render
  </LobbyProvider>
);

/* Queue Screen */

const {state} = React.useContext(LobbyContext);

// accessing state.isActive to do some conditional rendering
// which roomId does get rendered after dispatch
</code>```

答:
You must note that a custom hook will create a new instance of state everytime its called.

For example, you call the hook in StackNavigator component and then again in QueueScreen, so 2 different useReducers will be invoked instead of them sharing the states.

You should instead use useReducer in StackNavigator's parent and then utilize that as context within useLobby hook

```<code>const LobbyStateContext = React.createContext();

const Component =  ({children}) => {
   const [state, dispatch] = React.useReducer(...)
   return (
      <LobbyStateContext.Provider value={[state, dispatch]]>
         {children}
     </LobbyStateContext>
   )
}
</code>```

and use it like

```<code><Component>
  <StackNavigator />
</Component>
</code>```

useLobby will then look like

```<code>export const useLobby = () => {
  const [state, dispatch] = React.useContext(LobbyStateContext)

  const assignRoom = async () => {
    // dispatch room id
  }

  const context = React.useMemo(() => ({
    join: () => { assignRoom(); }
  })

  return { context, assignRoom, state};
}
</code>```

StackNavigator will utilize useLobby and have the useEFfect logic

```<code>const { context, state, assignRoom } = useLobby();

React.useEffect(() => {
    if (!state.isActive) assignRoom();
}, [state.isActive])

return (
  <LobbyContext.Provider value={context}>
    <LobbyStack.Navigator>
      {state.roomId
        ? <LobbyStack.Screen name="Lobby" component={LobbyScreen} />
        : <LobbyStack.Screen name="Queue" component={QueueScreen} />
      }
    </LobbyStack.Navigator>
  </LobbyContext.Provider>
)
</code>```

Body:
I'm having issue where hook is being used in multiple files and it is being called twice for useEffect before the 1st one's async method finish (which should block the 2nd hook call, but it's not). See below 2 scenarios:

Stack Navigator

const { context, state } = useLobby(); // Hook is called here 1st, which will do the initial render and checks

return (
  <LobbyContext.Provider value={context}>
    <LobbyStack.Navigator>
      {state.roomId
        ? <LobbyStack.Screen name="Lobby" component={LobbyScreen} />
        : <LobbyStack.Screen name="Queue" component={QueueScreen} />
      }
    </LobbyStack.Navigator>
  </LobbyContext.Provider>
)

Lobby Hooks

export const useLobby = () => {
  const [state, dispatch] = React.useReducer(...)

  //
  // Scenario 1
  // This get called twice (adds user to room twice)
  //
  React.useEffect(() => {
    if (!state.isActive) assignRoom();
  }, [state.isActive])

  const assignRoom = async () => {
    // dispatch room id
  }

  const context = React.useMemo(() => ({
    join: () => { assignRoom(); }
  })
}

Queue Screen

const { context, state } = useLobby(); // Hook is called here 2nd right after checking state from stack navigator

//
// Scenario 2
// Only does it once, however after state is changed to active
// the stack navigator didn't get re-render like it did in Scenario 1
//
React.useEffect(() => {
  roomLobby.join();
}, []);

return (
...
  {state.isActive
    ? "Show the room Id"
    : "Check again"
...
)

In scenario 1, I guess while 1st hook is called and useEffect is doing async to add user to the room and set active to true. Meanwhile the conditional render part is moving straight to Queue screen which calls the hook again and doing the useEffect (since 1st haven't finished and isActive is still false).

How can I properly setup useReducer and useMemo so that it renders the screen base on the state.

Edited codes based on the answer

/* LobbyProvider */

const LobbyContext = React.createContext();

const lobbyReducer = (state, action) => {
  switch (action.type) {
    case 'SET_LOBBY':
      return {
        ...state,
        isActive: action.active,
        lobby: action.lobby
      };
    case 'SET_ROOM':
      return {
        ...state,
        isQueued: action.queue,
        roomId: action.roomId,
      };
    default:
      return state;
  }
}

const LobbyProvider = ({ children }) => {
  const [state, dispatch] = React.useReducer(lobbyReducer, initialState);

  React.useEffect(() => {
    console.log("Provider:", state)
    if (!state.isActive) joinRoom();
  }, [])

  // Using Firebase functions
  const joinRoom = async () => {
    try {
      const response = await functions().httpsCallable('getActiveLobby')();
      if (response) {
        dispatch({ type: 'SET_LOBBY', active: true, lobby: response.data })
        const room = await functions().httpsCallable('assignRoom')({ id: response.data.id });
        dispatch({ type: 'SET_ROOM', queue: false, roomId: room.data.id })
      }
    } catch (e) {
      console.error(e);
    }
  }

  return (
    <LobbyContext.Provider value={{state, dispatch}}>
      { children }
    </LobbyContext.Provider>
  )
}

/* StackNavigator */

const {state} = React.useContext(LobbyContext);

return (
  <LobbyProvider>
    // same as above <LobbyStack.Navigator>
    // state doesn't seem to be updated here or to re-render
  </LobbyProvider>
);

/* Queue Screen */

const {state} = React.useContext(LobbyContext);

// accessing state.isActive to do some conditional rendering
// which roomId does get rendered after dispatch

Body:
You must note that a custom hook will create a new instance of state everytime its called.

For example, you call the hook in StackNavigator component and then again in QueueScreen, so 2 different useReducers will be invoked instead of them sharing the states.

You should instead use useReducer in StackNavigator's parent and then utilize that as context within useLobby hook

const LobbyStateContext = React.createContext();

const Component =  ({children}) => {
   const [state, dispatch] = React.useReducer(...)
   return (
      <LobbyStateContext.Provider value={[state, dispatch]]>
         {children}
     </LobbyStateContext>
   )
}

and use it like

<Component>
  <StackNavigator />
</Component>

useLobby will then look like

export const useLobby = () => {
  const [state, dispatch] = React.useContext(LobbyStateContext)

  const assignRoom = async () => {
    // dispatch room id
  }

  const context = React.useMemo(() => ({
    join: () => { assignRoom(); }
  })

  return { context, assignRoom, state};
}

StackNavigator will utilize useLobby and have the useEFfect logic

const { context, state, assignRoom } = useLobby();

React.useEffect(() => {
    if (!state.isActive) assignRoom();
}, [state.isActive])

return (
  <LobbyContext.Provider value={context}>
    <LobbyStack.Navigator>
      {state.roomId
        ? <LobbyStack.Screen name="Lobby" component={LobbyScreen} />
        : <LobbyStack.Screen name="Queue" component={QueueScreen} />
      }
    </LobbyStack.Navigator>
  </LobbyContext.Provider>
)


问:
Binding Docker container created through api
I have a command that creates a docker container, from a docker container and I want to bind a port to the host

```<code>exec(`curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{ "Image": "strategy_baseline", "ExposedPorts": { "${PORT}/tcp": {} }, "HostConfig": { "Binds": ["strategies:/usr/src/app/strategies"], "NetworkMode": "titan_backend" }, "PortBindings": { "${PORT}/tcp": [{ "HostPort": "${PORT}" }]}, "Env": ["BOTNAME=${BOT_ID}", "PORT=${PORT}", "ASSETS=${ASSETS}"]}' -X POST http:/v1.4/containers/create?name=${BOT_ID}`,
</code>```

All variables are properly defined within the file so the error is not there.

As it stands I call this command through an API endpoint, and the container gets created correctly at the correct port running docker ps outputs:

```<code>CONTAINER ID        IMAGE                       COMMAND                  CREATED             STATUS                          PORTS                                                 NAMES
ab8e28ccd50f        strategy_baseline           "docker-entrypoint.s…"   2 hours ago         Up 2 hours                      3009/tcp                                              defaultKeys
</code>```

Id expect something that specifies the container port to be 0.0.0.0:3009->3009/tcp. but alas that doesn't work.

I know I can call the container by specifying its name, so from within any other container in the network I can just do  http://container_name:3009/endpoint

but ideally I should be able to do: hhtp://vps_ip:3009/endpoint which as of now I cant do.

Any pointer or help is greately appreciated, thanks in advance!!

答:
This modification did the trick   </p>

```<code>exec(`curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{ "Image": "strategy_baseline", "ExposedPorts": { "${PORT}/tcp": {} }, "HostConfig": { "Binds": ["strategies:/usr/src/app/strategies"], "NetworkMode": "titan_backend", "PortBindings": { "${PORT}/tcp": [{ "HostPort": "${PORT}" }]}}, "Env": ["BOTNAME=${BOT_ID}", "PORT=${PORT}", "ASSETS=${ASSETS}"]}' -X POST http:/v1.4/containers/create?name=${BOT_ID}`,
</code>```

Body:
I have a command that creates a docker container, from a docker container and I want to bind a port to the host

exec(`curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{ "Image": "strategy_baseline", "ExposedPorts": { "${PORT}/tcp": {} }, "HostConfig": { "Binds": ["strategies:/usr/src/app/strategies"], "NetworkMode": "titan_backend" }, "PortBindings": { "${PORT}/tcp": [{ "HostPort": "${PORT}" }]}, "Env": ["BOTNAME=${BOT_ID}", "PORT=${PORT}", "ASSETS=${ASSETS}"]}' -X POST http:/v1.4/containers/create?name=${BOT_ID}`,

All variables are properly defined within the file so the error is not there.

As it stands I call this command through an API endpoint, and the container gets created correctly at the correct port running docker ps outputs:

CONTAINER ID        IMAGE                       COMMAND                  CREATED             STATUS                          PORTS                                                 NAMES
ab8e28ccd50f        strategy_baseline           "docker-entrypoint.s…"   2 hours ago         Up 2 hours                      3009/tcp                                              defaultKeys

Id expect something that specifies the container port to be 0.0.0.0:3009->3009/tcp. but alas that doesn't work.

I know I can call the container by specifying its name, so from within any other container in the network I can just do  http://container_name:3009/endpoint

but ideally I should be able to do: hhtp://vps_ip:3009/endpoint which as of now I cant do.

Any pointer or help is greately appreciated, thanks in advance!!

Body:
This modification did the trick

exec(`curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{ "Image": "strategy_baseline", "ExposedPorts": { "${PORT}/tcp": {} }, "HostConfig": { "Binds": ["strategies:/usr/src/app/strategies"], "NetworkMode": "titan_backend", "PortBindings": { "${PORT}/tcp": [{ "HostPort": "${PORT}" }]}}, "Env": ["BOTNAME=${BOT_ID}", "PORT=${PORT}", "ASSETS=${ASSETS}"]}' -X POST http:/v1.4/containers/create?name=${BOT_ID}`,


问:
How to install Python package installer PIP on Ubuntu 20.04 Linux
Trying to install pip with Ubuntu version 20.04, Python version 3.8 on my Oracle virtual box.
Tried everything to install pip but failed

Steps tried

```<code>$ sudo apt update
$ sudo apt install python3-pip
</code>```

Also tried

```<code>$ sudo apt-get install python3-pip
</code>```

Error both times

python3-pip is not available but is being used by another candidate. This may mean that the package has been obsolete, has been missing or is only available from another source.

E: Package 'python3-pip' has no installation candidate

答:
Option 1

1.vim /etc/apt/sources.list

2.add these lines in the above file.

```<code>   deb http://http.kali.org/kali kali-rolling main non-free contribs
   deb http://kali.cs.nctu.edu.tw/kali kali-rolling main contrib non-free
   deb-src http://http.kali.org/kali kali-rolling main non-free contrib
</code>```

sudo apt update

sudo apt install python3-pip

Option 2

```<code>sudo apt-get update
sudo apt-get upgrade
sudo apt install python3-pip
</code>```

Option 3
https://stackoverflow.com/a/59922280/11741464

Source:
facing problem in kali linuix python3-pip

Body:
Trying to install pip with Ubuntu version 20.04, Python version 3.8 on my Oracle virtual box.
Tried everything to install pip but failed

Steps tried

$ sudo apt update
$ sudo apt install python3-pip

Also tried

$ sudo apt-get install python3-pip

Error both times

python3-pip is not available but is being used by another candidate. This may mean that the package has been obsolete, has been missing or is only available from another source.

E: Package 'python3-pip' has no installation candidate

Body:
Option 1

1.vim /etc/apt/sources.list

2.add these lines in the above file.

   deb http://http.kali.org/kali kali-rolling main non-free contribs
   deb http://kali.cs.nctu.edu.tw/kali kali-rolling main contrib non-free
   deb-src http://http.kali.org/kali kali-rolling main non-free contrib

sudo apt update

sudo apt install python3-pip

Option 2

sudo apt-get update
sudo apt-get upgrade
sudo apt install python3-pip

Option 3
https://stackoverflow.com/a/59922280/11741464

Source:
facing problem in kali linuix python3-pip


问:
How to find out which Visual Studio extensions are installed on user's machines?
How to find out which Visual Studio extensions are installed on user's machines?

I want to track which VS extensions are installed on users' computers in AD environment. I think that's easy when an extension installs via Windows Installer (*.msi). But what about VSIX extensions (vsixinstaller.exe)?

答:
There is no direct way that I am aware of to list all installed VSIX extensions, but vsixInstaller has an option to generate a logfile which identifies the extension.vsixmanifest files it locates, and each such file is an XML that contains the relevant details about the extension (name, version etc).

To have vsixInstaller generate the logfile, pretend to uninstall an extension that does not exist. This may take a while, especially if multiple versions of VS are installed (the following must go all on one line).

```<code>C:\Program Files (x86)\Microsoft Visual Studio\Installer\resources\
   app\ServiceHub\Services\Microsoft.VisualStudio.Setup.Service>
   vsixInstaller /logFile:vsix.log /appIdName:VS /uninstall:nosuchxt
</code>```

The generated logfile will then be %TEMP%\vsix.log and the Found lines point to the extensions that vsixInstaller located, for example (with root paths replaced by %VS20xx%):

```<code>vsixinstaller.exe version:
16.5.2047
...
BEGIN: Processing extension pack
...
Found '%ProgramFiles(x86)%\COMMON FILES\MICROSOFT\EXTENSIONMANAGER\EXTENSIONS\Microsoft\Windows Kits\10\Desktop SDK\extension.vsixmanifest'
...
Found '%VS2015%\COMMON7\IDE\EXTENSIONS\VSSDK\extension.vsixmanifest'
...
Found '%VS2019%\COMMON7\IDE\EXTENSIONS\VSSDK\extension.vsixmanifest'
...
END: Processing extension pack

</code>```

Each extension.vsixmanifest file referenced in the list begins with a metadata node that identifies the name and version of the respective extension, for example:

```<code><Metadata>
  <Identity Id="Microsoft.VisualStudio.SDK"
            Version="16.0"
            Language="en-US"
            Publisher="Microsoft Corporation" />
  <DisplayName>Microsoft Visual Studio SDK</DisplayName>
  <Description>Tools for building Visual Studio extensions</Description>
</Metadata>
</code>```

With some (not entirely trivial) plumbing work, this could all be automated in a script/batch job.

Body:
There is no direct way that I am aware of to list all installed VSIX extensions, but vsixInstaller has an option to generate a logfile which identifies the extension.vsixmanifest files it locates, and each such file is an XML that contains the relevant details about the extension (name, version etc).

To have vsixInstaller generate the logfile, pretend to uninstall an extension that does not exist. This may take a while, especially if multiple versions of VS are installed (the following must go all on one line).

C:\Program Files (x86)\Microsoft Visual Studio\Installer\resources\
   app\ServiceHub\Services\Microsoft.VisualStudio.Setup.Service>
   vsixInstaller /logFile:vsix.log /appIdName:VS /uninstall:nosuchxt

The generated logfile will then be %TEMP%\vsix.log and the Found lines point to the extensions that vsixInstaller located, for example (with root paths replaced by %VS20xx%):

vsixinstaller.exe version:
16.5.2047
...
BEGIN: Processing extension pack
...
Found '%ProgramFiles(x86)%\COMMON FILES\MICROSOFT\EXTENSIONMANAGER\EXTENSIONS\Microsoft\Windows Kits\10\Desktop SDK\extension.vsixmanifest'
...
Found '%VS2015%\COMMON7\IDE\EXTENSIONS\VSSDK\extension.vsixmanifest'
...
Found '%VS2019%\COMMON7\IDE\EXTENSIONS\VSSDK\extension.vsixmanifest'
...
END: Processing extension pack

Each extension.vsixmanifest file referenced in the list begins with a metadata node that identifies the name and version of the respective extension, for example:

<Metadata>
  <Identity Id="Microsoft.VisualStudio.SDK"
            Version="16.0"
            Language="en-US"
            Publisher="Microsoft Corporation" />
  <DisplayName>Microsoft Visual Studio SDK</DisplayName>
  <Description>Tools for building Visual Studio extensions</Description>
</Metadata>

With some (not entirely trivial) plumbing work, this could all be automated in a script/batch job.


问:
How to test values which depends on localization jest, enzyme?
How to test values that can depend on current localization?

```<code>function DateNavigation({ locale, date }) {
  return (locale === 'en')
    ? <span>{moment(date).format('DD.MM.YYYY')}</span>
    : <span>{moment(date).format('YYYY.MM.DD')}</span>
}
</code>```

This test doesn't work sometimes because of locations

```<code>it('display date correctly', () => {
    const component = mount(<DateNavigation date={'2022-01-31'} />);

    expect(component.html()).toEqual("<span>31.01.2022</span>");
});
</code>```

答:
You can use jest.mock(moduleName, factory, options) to mock moment(), moment().format() functions and its returned value. Test results must be predictable. For the test about date, we need to make the test case return a certain value in different systems, time zones and localization.

E.g.

DateNavigation.jsx:

import React from 'react';
import moment from 'moment';

function DateNavigation({ locale, date }) {
  return locale === 'en' ? (
    {moment(date).format('DD.MM.YYYY')}
  ) : (
    {moment(date).format('YYYY.MM.DD')}
  );
}

export default DateNavigation;
```

<p><code>DateNavigation.test.jsx</code>:</p>

<pre class="lang-js prettyprint-override"><code>import DateNavigation from './DateNavigation';
import moment from 'moment';

jest.mock('moment', () => {
  const mMoment = { format: jest.fn() };
  return jest.fn(() => mMoment);
});

describe('62042433', () => {
  it('display date correctly', () => {
    const date = '31.01.2022';
    moment().format.mockReturnValueOnce(date);
    const component = mount(<DateNavigation date={'2022-01-31'} locale={'en'} />);
    expect(component.html()).toEqual('<span>31.01.2022</span>');
    expect(moment).toBeCalledWith('2022-01-31');
    expect(moment().format).toBeCalledWith('DD.MM.YYYY');
  });
});
</code>```

unit test results:

 PASS  stackoverflow/62042433/DateNavigation.test.jsx (13.544s)
  62042433
    ✓ display date correctly (54ms)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files           |     100 |       50 |     100 |     100 |
 DateNavigation.jsx |     100 |       50 |     100 |     100 | 6
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.23s
```

Body:
How to test values that can depend on current localization?

function DateNavigation({ locale, date }) {
  return (locale === 'en')
    ? {moment(date).format('DD.MM.YYYY')}
    : {moment(date).format('YYYY.MM.DD')}
}

This test doesn't work sometimes because of locations

it('display date correctly', () => {
    const component = mount(<DateNavigation date={'2022-01-31'} />);

    expect(component.html()).toEqual("31.01.2022");
});

Body:
You can use jest.mock(moduleName, factory, options) to mock moment(), moment().format() functions and its returned value. Test results must be predictable. For the test about date, we need to make the test case return a certain value in different systems, time zones and localization.

E.g.

DateNavigation.jsx:

import React from 'react';
import moment from 'moment';

function DateNavigation({ locale, date }) {
  return locale === 'en' ? (
    <span>{moment(date).format('DD.MM.YYYY')}</span>
  ) : (
    <span>{moment(date).format('YYYY.MM.DD')}</span>
  );
}

export default DateNavigation;

DateNavigation.test.jsx:

import DateNavigation from './DateNavigation';
import moment from 'moment';

jest.mock('moment', () => {
  const mMoment = { format: jest.fn() };
  return jest.fn(() => mMoment);
});

describe('62042433', () => {
  it('display date correctly', () => {
    const date = '31.01.2022';
    moment().format.mockReturnValueOnce(date);
    const component = mount(<DateNavigation date={'2022-01-31'} locale={'en'} />);
    expect(component.html()).toEqual('<span>31.01.2022</span>');
    expect(moment).toBeCalledWith('2022-01-31');
    expect(moment().format).toBeCalledWith('DD.MM.YYYY');
  });
});

unit test results:

 PASS  stackoverflow/62042433/DateNavigation.test.jsx (13.544s)
  62042433
    ✓ display date correctly (54ms)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files           |     100 |       50 |     100 |     100 |
 DateNavigation.jsx |     100 |       50 |     100 |     100 | 6
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.23s


问:
Can I use a collection initializer with LINQ to return a fully populated collection?
I would like to rewrite the following code in one line, using LINQ. Is it possible?

```<code>var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}
</code>```

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

```<code>var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});
</code>```

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

答:
You could write an extension method on IEnumerable<MailAddress> which returns a MailAddressCollection:

```<code>public static MailAddressCollection ToAddressCollection(this IEnumerable<MailAddress> source)
{
  var to = new MailAddressCollection();
  foreach(string r in source)
  {
    to.Add(new MailAddress(r));
  }
  return to;
}
</code>```

Then use it like this:

```<code>var to = recipients.Select(r => new MailAddress(r)).ToAddressCollection();
</code>```

Body:
I would like to rewrite the following code in one line, using LINQ. Is it possible?

var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

Body:
You could write an extension method on IEnumerable<MailAddress> which returns a MailAddressCollection:

public static MailAddressCollection ToAddressCollection(this IEnumerable<MailAddress> source)
{
  var to = new MailAddressCollection();
  foreach(string r in source)
  {
    to.Add(new MailAddress(r));
  }
  return to;
}

Then use it like this:

var to = recipients.Select(r => new MailAddress(r)).ToAddressCollection();