问:
How to cut a selection on Opencv images
Tell me how to cut the selected area in Opencv. At the moment, the area is highlighted and I want everything to be removed. White background.

Screenshot (https://i.stack.imgur.com/jVcUf.jpg)

```<code>import cv2
import numpy as np
img = cv2.imread("57.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

th, threshed = cv2.threshold(gray, 100, 255,
cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)
morphed = cv2.morphologyEx(threshed, cv2.MORPH_OPEN, np.ones((2,2)))

cnts = cv2.findContours(morphed, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE[-2]

nh, nw = img.shape[:2]
for cnt in cnts:
    x,y,w,h = bbox = cv2.boundingRect(cnt)
    if h < 0.4 * nh:
        continue
    cv2.rectangle(img, (x,y), (x+w, y+h), (255, 0, 255), 1, cv2.LINE_AA)

cv2.imshow("gray", img)
</code>```

All that I could do, I tried to select the outlines of all the objects and delete everything less than the main text (you need to leave only 9 digits)

答:
If you already have the rectangles detected, you can fill in the rectangle with the white background and for that you must change the rectangle parameter (-1)

```<code>cv2.rectangle(img, (x,y), (x+w, y+h), (255, 255, 255), -1, cv2.LINE_AA)
</code>```

Original image

An image detected with rectangles

An image with white background

My code:

```<code>import cv2
import numpy as np

img = cv2.imread("numeros_romanos.jpg")
img = cv2.resize(img, (1024, 800), interpolation = cv2.INTER_AREA)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

th, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)

im2, cnts, hierarchy = cv2.findContours(threshed, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)

for cnt in cnts:
    x,y,w,h = bbox = cv2.boundingRect(cnt)
    cv2.rectangle(img, (x,y), (x+w, y+h), (255, 255, 255), -1, cv2.LINE_AA)

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Title: How to cut a selection on Opencv images

Body:
Tell me how to cut the selected area in Opencv. At the moment, the area is highlighted and I want everything to be removed. White background.

Screenshot (https://i.stack.imgur.com/jVcUf.jpg)

import cv2
import numpy as np
img = cv2.imread("57.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

th, threshed = cv2.threshold(gray, 100, 255,
cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)
morphed = cv2.morphologyEx(threshed, cv2.MORPH_OPEN, np.ones((2,2)))

cnts = cv2.findContours(morphed, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE[-2]

nh, nw = img.shape[:2]
for cnt in cnts:
    x,y,w,h = bbox = cv2.boundingRect(cnt)
    if h < 0.4 * nh:
        continue
    cv2.rectangle(img, (x,y), (x+w, y+h), (255, 0, 255), 1, cv2.LINE_AA)

cv2.imshow("gray", img)

All that I could do, I tried to select the outlines of all the objects and delete everything less than the main text (you need to leave only 9 digits)

Body:
If you already have the rectangles detected, you can fill in the rectangle with the white background and for that you must change the rectangle parameter (-1)

cv2.rectangle(img, (x,y), (x+w, y+h), (255, 255, 255), -1, cv2.LINE_AA)

Original image

An image detected with rectangles

An image with white background

My code:

import cv2
import numpy as np

img = cv2.imread("numeros_romanos.jpg")
img = cv2.resize(img, (1024, 800), interpolation = cv2.INTER_AREA)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

th, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)

im2, cnts, hierarchy = cv2.findContours(threshed, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)

for cnt in cnts:
    x,y,w,h = bbox = cv2.boundingRect(cnt)
    cv2.rectangle(img, (x,y), (x+w, y+h), (255, 255, 255), -1, cv2.LINE_AA)

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: How to change the date in a datetime index

Body:
Consider a df with such an index:

index = pd.DatetimeIndex(['2018-04-26 15:55:00', '2018-04-26 16:00:00', '2018-04-26 16:05:00', '2018-04-26 16:10:00', '2018-04-26 16:15:00'], dtype='datetime64[ns]', name='date', freq=None)

df = pd.DataFrame({'x': [1,1,1,1,1]}, index = index)

In[308]: df
Out[308]:
                     x
date
2018-04-26 15:55:00  1
2018-04-26 16:00:00  1
2018-04-26 16:05:00  1
2018-04-26 16:10:00  1
2018-04-26 16:15:00  1

How can I set the date part of the index to an arbitrary date without using shift or timedelta, while keeping the time part of the index intact. For example, how do I change the date from 2018-04-26 to 2018-04-20 and have:

In[308]: df
Out[308]:
                     x
date
2018-04-20 15:55:00  1
2018-04-20 16:00:00  1
2018-04-20 16:05:00  1
2018-04-20 16:10:00  1
2018-04-20 16:15:00  1

df.index.date = datetime.date(2018, 4, 20) leads to AttributeError: can't set attribute.

Body:
Try with index replace with datetime

df.index=df.index.map(lambda x : x.replace(day=20))
df
Out[785]:
                     x
date
2018-04-20 15:55:00  1
2018-04-20 16:00:00  1
2018-04-20 16:05:00  1
2018-04-20 16:10:00  1
2018-04-20 16:15:00  1


问:
distance between two pointers in C
I have a function that it is supposed to read a string (only with numbers in it) and return the biggest sequence that doenst have repeated numbers.
for example:
12345267890

it should return: 345267890

i've experimented the code manually and I believe it should work. but when I run it, and when it reaches this line i=(strchr(v+i, *(v+j)))-v; instead of getting the distance between the pointers I get something like -1046583. can I do this?

```<code>char* bigSeq(char *v){

    int i, j;
    char *aux, *bgst;
    aux=(char*) malloc(10*sizeof(char));
    bgst=(char*) malloc(10*sizeof(char));
    for(i=0;i<strlen(v);i++){
        for(j=0;j<strlen(v+i);j++){
            if(strchr(v+i, *(v+j)) != (v+j)){
                if(strlen(strncpy(aux, (v+i),j)) > strlen(bgst))
                    strncpy(bgst, (v+i),j);
                i=(strchr(v+i, *(v+j)))-v;
                break;
            }
        }
    }
    return bgst;
}
</code>```

答:
```<code>if(strlen(strncpy(aux, (v+i),j))
</code>```

and

```<code>strncpy(bgst, (v+i),j);
</code>```

If j is > 10 you're overwriting memory you don't own - which can lead to all sorts of funny issues.

ContentLicense: CC BY-SA 3.0

Title: distance between two pointers in C

Body:
I have a function that it is supposed to read a string (only with numbers in it) and return the biggest sequence that doenst have repeated numbers.
for example:
12345267890

it should return: 345267890

i've experimented the code manually and I believe it should work. but when I run it, and when it reaches this line i=(strchr(v+i, *(v+j)))-v; instead of getting the distance between the pointers I get something like -1046583. can I do this?

char* bigSeq(char *v){

    int i, j;
    char *aux, *bgst;
    aux=(char*) malloc(10*sizeof(char));
    bgst=(char*) malloc(10*sizeof(char));
    for(i=0;i<strlen(v);i++){
        for(j=0;j<strlen(v+i);j++){
            if(strchr(v+i, *(v+j)) != (v+j)){
                if(strlen(strncpy(aux, (v+i),j)) > strlen(bgst))
                    strncpy(bgst, (v+i),j);
                i=(strchr(v+i, *(v+j)))-v;
                break;
            }
        }
    }
    return bgst;
}

Body:
if(strlen(strncpy(aux, (v+i),j))

and

strncpy(bgst, (v+i),j);

If j is > 10 you're overwriting memory you don't own - which can lead to all sorts of funny issues.


问:
I cannot understand the DP solution of javascript in leetcode 70
I am confused by the reference answer of climbing stairs in leetcode.

Here is the problem:

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

```<code>   var climbStairs = function(n) {

    if (n < 1) return 0;
    if (n == 1) return 1;
    if (n == 2) return 2;

    // a saves the second-to-last sub-state data, b saves the first sub-state data, temp saves the current state data
    let a = 1, b = 2;
    let temp = a + b;
    for (let i = 3; i <= n; i++) {
        temp = a + b;
        a = b;
        b = temp;
    }
    return temp;
   };
</code>```

The answer uses DP to solve, but I cannot understand how the for loop works，I think I missed some javascript characteristics.

答:
This is equivalent to the coin change problem:

Given a set of coins and amount, Write an algorithm to find out how
  many ways we can make the change of the amount using the coins given.

N is your amount, and the available coins are 1 and 2 cents.

Here's a comprehensive explanation of the coin change problem: https://hackernoon.com/the-coin-change-problem-explained-ddd035a8f22f

Here's a thread on Quora: https://www.quora.com/What-is-an-easy-way-to-understand-the-coin-change-problem-in-dynamic-programming

Body:
I am confused by the reference answer of climbing stairs in leetcode.

Here is the problem:

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

   var climbStairs = function(n) {

    if (n < 1) return 0;
    if (n == 1) return 1;
    if (n == 2) return 2;

    // a saves the second-to-last sub-state data, b saves the first sub-state data, temp saves the current state data
    let a = 1, b = 2;
    let temp = a + b;
    for (let i = 3; i <= n; i++) {
        temp = a + b;
        a = b;
        b = temp;
    }
    return temp;
   };

The answer uses DP to solve, but I cannot understand how the for loop works，I think I missed some javascript characteristics.


问:
Are decision trees (e.g. C4.5) considered nonparametric learning?
I am relatively new to machine learning and am trying to place decision tree induction into the grand scheme of things. Are decision trees (for example, those built with C4.5 or ID3) considered parametric or nonparametric? I would guess that they may be indeed parametric because the decision split points for real values may be determined from some distribution of features values, for example the mean. However, they do not share the nonparametric characteristic of having to keep all the original training data (like one would do with kNN).</p>

答:
The term parametric refers to the relation between the number of parameters of the model and the data.

If the number of parameters is fixed, the model is parametric.

If the number of parameters grows with the data, the model is non parametric.

A decision tree is non parametric but if you cap its size for regularization then the number of parameters is also capped and could be considered fixed. So it's not that clear cut for decision trees.

KNN is definitely non parametric because the parameter set is the data set: to predict new data points the KNN model needs to have access to the training data points and nothing else (except hyper-parameter K).


问:
How to fix 'Error: missing: 0' on d3.forceLink
I created a test case where a react component on mount creates link between two nodes. For some strange reason it throws me error Error: missing: 0

The only case when code is working and actually links the elements is when i use .force('link', d3.forceLink()) which is really strange, no clue where it looks up for the links in this case.

```<code>constructor(props) {
    super(props);
    this.graphRef = React.createRef();
    this.state = {
      nodes: [{ id: 0, title: 'Valley', type: 'ford' }, { id: 1, title: 'Valley 2', type: 'ford' }],
      links: [{ source: 0, target: 1 }],
    }; //testing data
    this.linkGroup = null;
    this.iconGroup = null;
    this.nodeGroup = null;
    this.textGroup = null;
    this.simulation = null;
  }

componentDidMount() {
    const domNode = this.graphRef.current;
    const { links } = this.state;
    const { width, height } = domNode.getBoundingClientRect();

    const svg = d3.select(domNode);
    this.linkGroup = svg.append('g').attr('class', 'links');
    this.iconGroup = svg.append('g').attr('class', 'icons');
    this.nodeGroup = svg.append('g').attr('class', 'nodes');
    this.textGroup = svg.append('g').attr('class', 'texts');

    this.simulation = d3.forceSimulation()
      .force('charge', d3.forceManyBody().strength(5))
      .force('link', d3.forceLink(links))
      .force('centerX', d3.forceX(width / 2))
      .force('centerY', d3.forceY(height / 2))
      .force('collision', d3.forceCollide().radius(25).strength(1));
    this.triggerSimulation();
  }
</code>```

EDIT:

The solution that Gerardo Furtado offers is:

```<code>.force("link", d3.forceLink(links)
     .id(function(d,i) {
         return d.id
     })
    .distance(20)
    .strength(1)
)
</code>```

However for some reason this doesn't work for me.
In order to make the code to work for me it should be like this:

```<code>.force("link", d3.forceLink()
     .id(function(d,i) {
         return d.id
     })
    .distance(20)
    .strength(1)
)
</code>```

I dont have any clue how my code find those links, but somehow it does.

答: I am still not sure why, but it worked with .force('link', d3.forceLink().id(link => link.id))

Body:
I created a test case where a react component on mount creates link between two nodes. For some strange reason it throws me error Error: missing: 0

The only case when code is working and actually links the elements is when i use .force('link', d3.forceLink()) which is really strange, no clue where it looks up for the links in this case.

constructor(props) {
    super(props);
    this.graphRef = React.createRef();
    this.state = {
      nodes: [{ id: 0, title: 'Valley', type: 'ford' }, { id: 1, title: 'Valley 2', type: 'ford' }],
      links: [{ source: 0, target: 1 }],
    }; //testing data
    this.linkGroup = null;
    this.iconGroup = null;
    this.nodeGroup = null;
    this.textGroup = null;
    this.simulation = null;
  }

componentDidMount() {
    const domNode = this.graphRef.current;
    const { links } = this.state;
    const { width, height } = domNode.getBoundingClientRect();

    const svg = d3.select(domNode);
    this.linkGroup = svg.append('g').attr('class', 'links');
    this.iconGroup = svg.append('g').attr('class', 'icons');
    this.nodeGroup = svg.append('g').attr('class', 'nodes');
    this.textGroup = svg.append('g').attr('class', 'texts');

    this.simulation = d3.forceSimulation()
      .force('charge', d3.forceManyBody().strength(5))
      .force('link', d3.forceLink(links))
      .force('centerX', d3.forceX(width / 2))
      .force('centerY', d3.forceY(height / 2))
      .force('collision', d3.forceCollide().radius(25).strength(1));
    this.triggerSimulation();
  }

EDIT:

The solution that Gerardo Furtado offers is:

.force("link", d3.forceLink(links)
     .id(function(d,i) {
         return d.id
     })
    .distance(20)
    .strength(1)
)

However for some reason this doesn't work for me.
In order to make the code to work for me it should be like this:

.force("link", d3.forceLink()
     .id(function(d,i) {
         return d.id
     })
    .distance(20)
    .strength(1)
)

I dont have any clue how my code find those links, but somehow it does.


问:
SearchView in expanded mode doesn't hide all action bar icons starting from Marshmallow
SearchView looks fine on Lollipop devices (Android 21):

But on Android 23-28 it doesn't hide all icons on the right side:

```<code><item android:id="@+id/action_search"
      android:title="@string/search"
      app:actionViewClass="androidx.appcompat.widget.SearchView"
      app:showAsAction="ifRoom"/>

<item android:id="@+id/action_sort"
      android:title="@string/sorting"
      android:icon="@drawable/sort"
      app:showAsAction="ifRoom"/>
</code>```

How can I fix it?

Update

Seems Android 23 and higher don't hide icons anymore on the right (because there is enough space)

But it only works fine if you don't have home button or hamburger menu on the left:

But I have an icon on the left and that's why my action bar looks ugly when SearchView is expanded:

Should be a bug in newest Android ActionBar design...

I add menu button like this:

```<code>supportActionBar?.let {
    it.setDisplayHomeAsUpEnabled(true)
    it.setHomeAsUpIndicator(R.drawable.ic_menu)
}
</code>```

答:
My solution is to hide the button on the left (home/menu) programmatically when SearchView is expanded:

```<code>val searchItem = menu.findItem(R.id.action_search)

val searchView = searchItem.actionView as SearchView

searchView?.setOnSearchClickListener {
    supportActionBar?.setDisplayHomeAsUpEnabled(false)
}
searchView?.setOnCloseListener {
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
    false
}
</code>```

p.s. the next method didn't work for me because it works only if your SearchView is always expanded (marked as collapseActionView) but I don't want such weird thing in my app (it's not a search app, search function is just an additional feature):

```<code>searchItem.setOnActionExpandListener(object: MenuItem.OnActionExpandListener {
    override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
        supportActionBar?.setDisplayHomeAsUpEnabled(false)
        return true
    }

    override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        return true
    }
})
</code>```

Closed:

Expanded:

Body:
SearchView looks fine on Lollipop devices (Android 21):

But on Android 23-28 it doesn't hide all icons on the right side:

<item android:id="@+id/action_search"
      android:title="@string/search"
      app:actionViewClass="androidx.appcompat.widget.SearchView"
      app:showAsAction="ifRoom"/>

<item android:id="@+id/action_sort"
      android:title="@string/sorting"
      android:icon="@drawable/sort"
      app:showAsAction="ifRoom"/>

How can I fix it?

Update

Seems Android 23 and higher don't hide icons anymore on the right (because there is enough space)

But it only works fine if you don't have home button or hamburger menu on the left:

But I have an icon on the left and that's why my action bar looks ugly when SearchView is expanded:

Should be a bug in newest Android ActionBar design...

I add menu button like this:

supportActionBar?.let {
    it.setDisplayHomeAsUpEnabled(true)
    it.setHomeAsUpIndicator(R.drawable.ic_menu)
}

Body:
My solution is to hide the button on the left (home/menu) programmatically when SearchView is expanded:

val searchItem = menu.findItem(R.id.action_search)

val searchView = searchItem.actionView as SearchView

searchView?.setOnSearchClickListener {
    supportActionBar?.setDisplayHomeAsUpEnabled(false)
}
searchView?.setOnCloseListener {
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
    false
}

p.s. the next method didn't work for me because it works only if your SearchView is always expanded (marked as collapseActionView) but I don't want such weird thing in my app (it's not a search app, search function is just an additional feature):

searchItem.setOnActionExpandListener(object: MenuItem.OnActionExpandListener {
    override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
        supportActionBar?.setDisplayHomeAsUpEnabled(false)
        return true
    }

    override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        return true
    }
})

Closed:

Expanded:


问:
Pushing a local Docker image to a private repository with a self-signed certificate
I'm trying to push an image, say foo/bar, from my local Docker registry to a registry running on OpenShift 3.11 (actually Minishift v1.33.0+ba29431).

The registry is at 192.168.64.3:2376 and it expects HTTPS connections. It uses a self-signed certificate.

First I copy the tag for the new image:

```<code>docker tag foo/bar 192.168.64.3:2376/app/foo/bar
</code>```

This succeeds. Then I try pushing:

```<code>$ docker push 192.168.64.3:2376/app/foo/bar
The push refers to repository [192.168.64.3:2376/app/foo/bar]
Get https://192.168.64.3:2376/v2/: x509: certificate signed by unknown authority
</code>```

or, when Docker is configured to allow use of unsafe registries in 192.168.64.0/24, it talks HTTP to the server instead of disabling certificate verification:

```<code>$ docker push 192.168.64.3:2376/app/foo/bar
The push refers to repository [192.168.64.3:2376/app/foo/bar]
Get http://192.168.64.3:2376/v2/: EOF
</code>```

The documentation says that for an unsafe registry, it should "First, try using HTTPS. If HTTPS is available but the certificate is invalid, ignore the error about the certificate. If HTTPS is not available, fall back to HTTP." So I would not expect to see an EOF error.

I also cannot try to tell Docker to use the Minishift certs, because it suddenly loses the ability to talk to the local Docker daemon (it should use a Unix domain socket, not tcp://localhost:2376):

```<code>$ export DOCKER_TLS_VERIFY="1"
$ export DOCKER_CERT_PATH="/Users/rzg/.minishift/certs"
$ docker push 192.168.64.3:2376/app/foo/bar
Cannot connect to the Docker daemon at tcp://localhost:2376. Is the docker daemon running?
</code>```

This is the version of Docker I'm using:

```<code>Client: Docker Engine - Community
 Version:           18.09.2
 API version:       1.39
 Go version:        go1.10.8
 Git commit:        6247962
 Built:             Sun Feb 10 04:12:39 2019
 OS/Arch:           darwin/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.2
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.6
  Git commit:       6247962
  Built:            Sun Feb 10 04:13:06 2019
  OS/Arch:          linux/amd64
  Experimental:     false
</code>```

答:
As per documentation:

 You can put your client certificates and key in

~/.docker/certs.d/<MyRegistry>:<Port>/client.cert

and

~/.docker/certs.d/<MyRegistry>:<Port>/client.key

https://docs.docker.com/docker-for-mac/faqs/#how-do-i-add-custom-ca-certificates

Alternatively you configure a credential store and load the certs there and then configure the store in ~/.docker/config json

Documentation here : https://docs.docker.com/engine/reference/commandline/login/

Body:
I'm trying to push an image, say foo/bar, from my local Docker registry to a registry running on OpenShift 3.11 (actually Minishift v1.33.0+ba29431).

The registry is at 192.168.64.3:2376 and it expects HTTPS connections. It uses a self-signed certificate.

First I copy the tag for the new image:

docker tag foo/bar 192.168.64.3:2376/app/foo/bar

This succeeds. Then I try pushing:

$ docker push 192.168.64.3:2376/app/foo/bar
The push refers to repository [192.168.64.3:2376/app/foo/bar]
Get https://192.168.64.3:2376/v2/: x509: certificate signed by unknown authority

or, when Docker is configured to allow use of unsafe registries in 192.168.64.0/24, it talks HTTP to the server instead of disabling certificate verification:

$ docker push 192.168.64.3:2376/app/foo/bar
The push refers to repository [192.168.64.3:2376/app/foo/bar]
Get http://192.168.64.3:2376/v2/: EOF

The documentation says that for an unsafe registry, it should "First, try using HTTPS. If HTTPS is available but the certificate is invalid, ignore the error about the certificate. If HTTPS is not available, fall back to HTTP." So I would not expect to see an EOF error.

I also cannot try to tell Docker to use the Minishift certs, because it suddenly loses the ability to talk to the local Docker daemon (it should use a Unix domain socket, not tcp://localhost:2376):

$ export DOCKER_TLS_VERIFY="1"
$ export DOCKER_CERT_PATH="/Users/rzg/.minishift/certs"
$ docker push 192.168.64.3:2376/app/foo/bar
Cannot connect to the Docker daemon at tcp://localhost:2376. Is the docker daemon running?

This is the version of Docker I'm using:

Client: Docker Engine - Community
 Version:           18.09.2
 API version:       1.39
 Go version:        go1.10.8
 Git commit:        6247962
 Built:             Sun Feb 10 04:12:39 2019
 OS/Arch:           darwin/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.2
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.6
  Git commit:       6247962
  Built:            Sun Feb 10 04:13:06 2019
  OS/Arch:          linux/amd64
  Experimental:     false


问:
IllegalArgumentException: navigation destination xxx is unknown to this NavController
I am having an issue with the new Android Navigation Architecture component when I try to navigate from one Fragment to another, I get this weird error:

```<code>java.lang.IllegalArgumentException: navigation destination XXX
is unknown to this NavController
</code>```

Every other navigation works fine except this particular one.

I use findNavController() function of Fragment to get access to the NavController.

Any help will be appreciated.

答:
TL;DR Navigation controller changes faster than UI and you send two identical navigate(R.id.destn_id) to the navigation controller in two different states.

To fix wrap your navigate calls with try-catch (simple way), or make sure there will be only one call of navigate in short period of time. This issue likely won't go away. Copy bigger code snippet in your app and try out.

Hello. Based on a couple of useful responses above, I would like to share my solution that can be extended.

Here is the code that caused this crash in my application:

```<code>@Override
public void onListItemClicked(ListItem item) {
    Bundle bundle = new Bundle();
    bundle.putParcelable(SomeFragment.LIST_KEY, item);
    Navigation.findNavController(recyclerView).navigate(R.id.action_listFragment_to_listItemInfoFragment, bundle);
}
</code>```

A way to easily reproduce the bug is to tap with multiple fingers on the list of items where click on each item resolves in the navigation to the new screen (basically the same as people noted - two or more clicks in a very short period of time). I noticed that:

First navigate invocation always works fine;

Second and all other invocations of the navigate method resolve in IllegalArgumentException.

From my point of view, this situation may appear very often. Since the repeating of code is a bad practice and it is always good to have one point of influence I thought of the next solution:

```<code>public class NavigationHandler {

public static void navigate(View view, @IdRes int destination) {
    navigate(view, destination, /* args */null);
}

/**
 * Performs a navigation to given destination using {@link androidx.navigation.NavController}
 * found via {@param view}. Catches {@link IllegalArgumentException} that may occur due to
 * multiple invocations of {@link androidx.navigation.NavController#navigate} in short period of time.
 * The navigation must work as intended.
 *
 * @param view        the view to search from
 * @param destination destination id
 * @param args        arguments to pass to the destination
 */
public static void navigate(View view, @IdRes int destination, @Nullable Bundle args) {
    try {
        Navigation.findNavController(view).navigate(destination, args);
    } catch (IllegalArgumentException e) {
        Log.e(NavigationHandler.class.getSimpleName(), "Multiple navigation attempts handled.");
    }
}
</code>```

}

And thus the code above changes only in one line from this:

```<code>Navigation.findNavController(recyclerView).navigate(R.id.action_listFragment_to_listItemInfoFragment, bundle);
</code>```

to this:

```<code>NavigationHandler.navigate(recyclerView, R.id.action_listFragment_to_listItemInfoFragment, bundle);
</code>```

It even became a little bit shorter. The code was tested in the exact place where the crash occurred. Did not experience it anymore, and will use the same solution for other navigations to avoid the same mistake further.

Any thoughts are welcome!

What exactly causes the crash

Remember that here we work with the same navigation graph, navigation controller and back-stack when we use method Navigation.findNavController.

We always get the same controller and graph here. When navigate(R.id.my_next_destination) is called graph and back-stack changes almost instantly while UI is not updated yet. Just not fast enough, but that is ok. After back-stack has changed the navigation system receives the second navigate(R.id.my_next_destination) call. Since back-stack has changed we now operate relative to the top fragment in the stack. The top fragment is the fragment you navigate to by using R.id.my_next_destination, but it does not contain next any further destinations with ID R.id.my_next_destination. Thus you get IllegalArgumentException because of the ID that the fragment knows nothing about.

This exact error can be found in NavController.java method findDestination.

Body:
I am having an issue with the new Android Navigation Architecture component when I try to navigate from one Fragment to another, I get this weird error:

java.lang.IllegalArgumentException: navigation destination XXX
is unknown to this NavController

Every other navigation works fine except this particular one.

I use findNavController() function of Fragment to get access to the NavController.

Any help will be appreciated.

Body:
TL;DR Navigation controller changes faster than UI and you send two identical navigate(R.id.destn_id) to the navigation controller in two different states.

To fix wrap your navigate calls with try-catch (simple way), or make sure there will be only one call of navigate in short period of time. This issue likely won't go away. Copy bigger code snippet in your app and try out.

Hello. Based on a couple of useful responses above, I would like to share my solution that can be extended.

Here is the code that caused this crash in my application:

@Override
public void onListItemClicked(ListItem item) {
    Bundle bundle = new Bundle();
    bundle.putParcelable(SomeFragment.LIST_KEY, item);
    Navigation.findNavController(recyclerView).navigate(R.id.action_listFragment_to_listItemInfoFragment, bundle);
}

A way to easily reproduce the bug is to tap with multiple fingers on the list of items where click on each item resolves in the navigation to the new screen (basically the same as people noted - two or more clicks in a very short period of time). I noticed that:

First navigate invocation always works fine;

Second and all other invocations of the navigate method resolve in IllegalArgumentException.

From my point of view, this situation may appear very often. Since the repeating of code is a bad practice and it is always good to have one point of influence I thought of the next solution:

public class NavigationHandler {

public static void navigate(View view, @IdRes int destination) {
    navigate(view, destination, /* args */null);
}

/**
 * Performs a navigation to given destination using {@link androidx.navigation.NavController}
 * found via {@param view}. Catches {@link IllegalArgumentException} that may occur due to
 * multiple invocations of {@link androidx.navigation.NavController#navigate} in short period of time.
 * The navigation must work as intended.
 *
 * @param view        the view to search from
 * @param destination destination id
 * @param args        arguments to pass to the destination
 */
public static void navigate(View view, @IdRes int destination, @Nullable Bundle args) {
    try {
        Navigation.findNavController(view).navigate(destination, args);
    } catch (IllegalArgumentException e) {
        Log.e(NavigationHandler.class.getSimpleName(), "Multiple navigation attempts handled.");
    }
}

}

And thus the code above changes only in one line from this:

Navigation.findNavController(recyclerView).navigate(R.id.action_listFragment_to_listItemInfoFragment, bundle);

to this:

NavigationHandler.navigate(recyclerView, R.id.action_listFragment_to_listItemInfoFragment, bundle);

It even became a little bit shorter. The code was tested in the exact place where the crash occurred. Did not experience it anymore, and will use the same solution for other navigations to avoid the same mistake further.

Any thoughts are welcome!

What exactly causes the crash

Remember that here we work with the same navigation graph, navigation controller and back-stack when we use method Navigation.findNavController.

We always get the same controller and graph here. When navigate(R.id.my_next_destination) is called graph and back-stack changes almost instantly while UI is not updated yet. Just not fast enough, but that is ok. After back-stack has changed the navigation system receives the second navigate(R.id.my_next_destination) call. Since back-stack has changed we now operate relative to the top fragment in the stack. The top fragment is the fragment you navigate to by using R.id.my_next_destination, but it does not contain next any further destinations with ID R.id.my_next_destination. Thus you get IllegalArgumentException because of the ID that the fragment knows nothing about.

This exact error can be found in NavController.java method findDestination.


问:
Java avoid java.lang.OutOfMemoryError while reading a file but using streams at the same time
I'm trying to read a very large file with streams so I need parallel streams and not iterations per line... I'm trying as follows:

```<code>String cont = new String(Files.readAllBytes(Paths.get(this.File_Path)),
            StandardCharsets.UTF_8);
List<String> words = Arrays.asList(cont.split("\\PL+"));

yep = words.parallelStream()
            .filter(x -> x.contains(toMatch))
            .distinct()
            .collect(Collectors.toList());
</code>```

This works for small file size, but if I try to make the same with a file that has some gbs of size java gives me this exception:

```<code>java.lang.OutOfMemoryError: Required array size too large
</code>```

There is a way to avoid this exception but using parallel stream at the same time instead of iterate with BufferReader or Scanner?

答:
The java heap memory is limited. We cannot read whole data of files at the same time. Over a certain size it is just impossible (unless you increase the heap memory, which is not ideal for few reasons). What I would recommend is, read the file in chunks like few lines, fixed size of 1000 lines maybe. Then run your operation of splitting into array and counting on that chunk.

You can parallelize chunks through multithreading.

Body:
I'm trying to read a very large file with streams so I need parallel streams and not iterations per line... I'm trying as follows:

String cont = new String(Files.readAllBytes(Paths.get(this.File_Path)),
            StandardCharsets.UTF_8);
List<String> words = Arrays.asList(cont.split("\\PL+"));

yep = words.parallelStream()
            .filter(x -> x.contains(toMatch))
            .distinct()
            .collect(Collectors.toList());

This works for small file size, but if I try to make the same with a file that has some gbs of size java gives me this exception:

java.lang.OutOfMemoryError: Required array size too large

There is a way to avoid this exception but using parallel stream at the same time instead of iterate with BufferReader or Scanner?


问:
Google sheets - conditional formatting from other sheet
I have two spreadsheets (S1 and S2). I want to apply conditional formatting to column D from S1 such that:

if text from cell D1, D2,... from S1 is present in column A from S2, a cell is colored green

if text from cell D1, D2,... from S1 is not present in column A from S2, a cell is colored red

Could not get my mind around it, could you please help? I assume I must use a formula, but not sure how...

答:
Select S1!D:D and (i) apply 'standard' red fill, (ii) Format > Conditional formatting..., Format cells if... Custom formula is and:

```<code>=match(D1,indirect("S2!A:A"),)
</code>```

with green highlighting and Done.

Body:
Select S1!D:D and (i) apply 'standard' red fill, (ii) Format > Conditional formatting..., Format cells if... Custom formula is and:

=match(D1,indirect("S2!A:A"),)

with green highlighting and Done.


问:
FilteringSelect with a QueryReadStore: selection doesn't stick
I am using a dijit.form.FilteringSelect backed by a dojox.data.QueryReadStore in order to allow the user to select a region (think "auto-complete" mechanism).  On each character entered by the user, the QueryReadStore sends a request to the server, awaiting a json list of matching regions (with associated IDs).  By the time a short enough list is shown, the user picks the desired item.  [Admittedly, querying on every keystroke is not the most efficient pattern, but it's good enough for now.]

Unexpected behaviour:  in some rare but specific occasions, the choice made by the user "doesn't stick".  For instance, if the user types "can", she is presented with the following choices in that order:

```<code>Atlantic Canada
Canada
English Canada
Lower Canada
Upper Canada
Western Canada
</code>```

If she chooses "Canada" among these, the dijit closes the drop down selection, having correctly selected her choice.  But by the time the user leaves the field, the selection switches to "Atlantic Canada"!

That bizarre phenomenon occurs systematically for a small number of specific regions.  (At first, I thought that the common factor between those badly behaved regions was that their name contained accented characters or hyphens, but clearly not so with the Canadian example.  So far, I fail to spot a regular pattern.)

I have not found any mention of a similar problem anywhere.  I am quite willing to investigate, but, as I am new to dojo, I would really appreciate pointers before I resort to delving inside dojo's code:  where should I first look?  what are some likely problems that could cause that behaviour? can i rule out certain hypotheses? how should I best use the console (or Firebug) to get to the bottom of this?  etc.

The problem occurs with both dojo 1.1.1 and dojo 1.2.3.

Here is the (programmatic) generation of the FilteringSelect:

```<code>new dijit.form.FilteringSelect({
   name = "region";
   autoComplete = false;
   hasDownArrow = false;
   labelAttr = "name";
   queryExpr = "${0}";
   store = new dojox.data.QueryReadStore({url:'/query/regions'});
}, myNode);
</code>```

EDIT (2009/02/18): Additional details

Following damelin's answer, I wanted to understand what FilteringSelect saw of this situation.  Suppose I connect logging functions to the FilteringSelect's events onChange and onBlur, I get the following play-by-play sequence:

I click in the field and type: can

drop-down list of 6 regions (listed above) appears

with the keyboard cursors, I move down the list to "Canada" (which is region with id 1)

I press Enter (thus selecting an item of the store).  The drop-down list has by now disappeared and the text "Canada" appears in the field.  At this point, the first event is fired, with the following logging:

```<code>onChange event: region 1
</code>```

I leave the field by pressing tab.  Here, two events are fired one after the other, in the following order:

```<code>onBlur event: region 1
onChange event: region 246
</code>```

(Region 246 is Atlantic Canada.) Now that's very interesting...  By the time I leave the field (onBlur), Canada still is the selected value.  The mysterious swap happens only after that...

答:
I've had the same problem today, affecting both Dojo versions 1.1.1 and 1.2.0.

As far as I can figure out, the FilteringSelect does a final query after the user leaves the field and expects the query result to contain only one result, which it then uses for the value of the field.

It looks to me like a bug (although I hope I'm proven wrong), but one you might have to with for now.

This page has some (incomplete) information on it: http://www.nabble.com/Problems-with-QueryReadStore-td19269498.html.

Later edit:

If fact you get the same problem with a FilteringSelect regardless of the data store behind it, whenever there is are duplicate labels.

For example, after the widget loses focus it resets to the first option:

```<code> <select id="coffee2" name="coffee2"
    dojotype="dijit.form.FilteringSelect"
    autoComplete="false">
    <script type="dojo/method" event="onChange"  args="newValue">
        console.log(dijit.byId('coffee2').getValue() + '/' + dijit.byId('coffee2').getDisplayedValue());
    </script>
    <option value="0">AAA</option>
    <option value="1">AAA</option>
    <option value="2">AAA</option>
    <option value="3">AAA</option>
    <option value="4">AAA</option>
  </select>
</code>```

In my opinion more of a bug than a feature.

OwnerDisplayName: pierdeux

ContentLicense: CC BY-SA 2.5

Body:
I am using a dijit.form.FilteringSelect backed by a dojox.data.QueryReadStore in order to allow the user to select a region (think "auto-complete" mechanism).  On each character entered by the user, the QueryReadStore sends a request to the server, awaiting a json list of matching regions (with associated IDs).  By the time a short enough list is shown, the user picks the desired item.  [Admittedly, querying on every keystroke is not the most efficient pattern, but it's good enough for now.]

Unexpected behaviour:  in some rare but specific occasions, the choice made by the user "doesn't stick".  For instance, if the user types "can", she is presented with the following choices in that order:

Atlantic Canada
Canada
English Canada
Lower Canada
Upper Canada
Western Canada

If she chooses "Canada" among these, the dijit closes the drop down selection, having correctly selected her choice.  But by the time the user leaves the field, the selection switches to "Atlantic Canada"!

That bizarre phenomenon occurs systematically for a small number of specific regions.  (At first, I thought that the common factor between those badly behaved regions was that their name contained accented characters or hyphens, but clearly not so with the Canadian example.  So far, I fail to spot a regular pattern.)

I have not found any mention of a similar problem anywhere.  I am quite willing to investigate, but, as I am new to dojo, I would really appreciate pointers before I resort to delving inside dojo's code:  where should I first look?  what are some likely problems that could cause that behaviour? can i rule out certain hypotheses? how should I best use the console (or Firebug) to get to the bottom of this?  etc.

The problem occurs with both dojo 1.1.1 and dojo 1.2.3.

Here is the (programmatic) generation of the FilteringSelect:

new dijit.form.FilteringSelect({
   name = "region";
   autoComplete = false;
   hasDownArrow = false;
   labelAttr = "name";
   queryExpr = "${0}";
   store = new dojox.data.QueryReadStore({url:'/query/regions'});
}, myNode);

EDIT (2009/02/18): Additional details

Following damelin's answer, I wanted to understand what FilteringSelect saw of this situation.  Suppose I connect logging functions to the FilteringSelect's events onChange and onBlur, I get the following play-by-play sequence:

I click in the field and type: can

drop-down list of 6 regions (listed above) appears

with the keyboard cursors, I move down the list to "Canada" (which is region with id 1)

I press Enter (thus selecting an item of the store).  The drop-down list has by now disappeared and the text "Canada" appears in the field.  At this point, the first event is fired, with the following logging:

onChange event: region 1

I leave the field by pressing tab.  Here, two events are fired one after the other, in the following order:

onBlur event: region 1
onChange event: region 246

(Region 246 is Atlantic Canada.) Now that's very interesting...  By the time I leave the field (onBlur), Canada still is the selected value.  The mysterious swap happens only after that...

LastEditorDisplayName: pierdeux

Body:
I've had the same problem today, affecting both Dojo versions 1.1.1 and 1.2.0.

As far as I can figure out, the FilteringSelect does a final query after the user leaves the field and expects the query result to contain only one result, which it then uses for the value of the field.

It looks to me like a bug (although I hope I'm proven wrong), but one you might have to with for now.

This page has some (incomplete) information on it: http://www.nabble.com/Problems-with-QueryReadStore-td19269498.html.

Later edit:

If fact you get the same problem with a FilteringSelect regardless of the data store behind it, whenever there is are duplicate labels.

For example, after the widget loses focus it resets to the first option:

 <select id="coffee2" name="coffee2"
    dojotype="dijit.form.FilteringSelect"
    autoComplete="false">
    <script type="dojo/method" event="onChange"  args="newValue">
        console.log(dijit.byId('coffee2').getValue() + '/' + dijit.byId('coffee2').getDisplayedValue());
    </script>
    <option value="0">AAA</option>
    <option value="1">AAA</option>
    <option value="2">AAA</option>
    <option value="3">AAA</option>
    <option value="4">AAA</option>
  </select>

In my opinion more of a bug than a feature.

OwnerDisplayName: pnt

LastEditorDisplayName: pnt


问:
Xcode 4 hangs at "Attaching to (app name)"
I just upgraded to Xcode 4 and for some reason my app won't run in the simulator or iOS device. It was working perfectly in Xcode 3, but all of a sudden now when I press run the program stops at "Attaching to...". There doesn't seem to be any other info to help with this problem either.

For summary you can try following things to tackle the issue:

Restart the simulator.

Make sure that you haven't included the Info.plist file in your Building Phases -> Copy Bundle Resources.

Resources folder added to the project as a folder reference (the blue folder icon). That caused the trouble, after adding the folder as a group the problem went away.

答:
Solution provided didn't fix the problem in my case.

In order to solve it (XCode 4 only), I had to go to Product -> Edit Scheme. Then select the "Run " scheme, and marked "Automatically" which wasn't enabled.

Hope it helps someone.


问:
How can I cache a downloaded ISO with Terraform?
Is there a way I can cache an ISO being downloaded?

Right now if I terraform destroy, and terraform apply it'll once again download the ISO.

I'm using the libvirt provider and the related resource is:

```<code>resource "libvirt_volume" "ubuntu-qcow3" {
  name   = "ubuntu-qcow3"
  pool   = "default"
  source = "https://cloud-images.ubuntu.com/releases/xenial/release/ubuntu-16.04-server-cloudimg-amd64-disk1.img"
  format = "qcow2"
}
</code>```

答:
You could download the image manually to a specific location (e.g. /opt/images)

```<code>wget https://cloud-images.ubuntu.com/releases/16.04/release/ubuntu-16.04-server-cloudimg-amd64-disk1.img -P /opt/images
</code>```

and simply refer to this path, since source accepts local paths as well as remote urls:

```<code>resource "libvirt_volume" "ubuntu-qcow3" {
  name   = "ubuntu-qcow3"
  pool   = "default"
  source = "/opt/images/ubuntu-16.04-server-cloudimg-amd64-disk1.img"
  format = "qcow2"
}
</code>```

Seems very usefull for testing purpose. I learned it from this tutorial where using local file paths was commented out. Since I don't want to mix config files with binary images, I moved them to /opt but feel free to place them where you like.

Body:
Is there a way I can cache an ISO being downloaded?

Right now if I terraform destroy, and terraform apply it'll once again download the ISO.

I'm using the libvirt provider and the related resource is:

resource "libvirt_volume" "ubuntu-qcow3" {
  name   = "ubuntu-qcow3"
  pool   = "default"
  source = "https://cloud-images.ubuntu.com/releases/xenial/release/ubuntu-16.04-server-cloudimg-amd64-disk1.img"
  format = "qcow2"
}

Body:
You could download the image manually to a specific location (e.g. /opt/images)

wget https://cloud-images.ubuntu.com/releases/16.04/release/ubuntu-16.04-server-cloudimg-amd64-disk1.img -P /opt/images

and simply refer to this path, since source accepts local paths as well as remote urls:

resource "libvirt_volume" "ubuntu-qcow3" {
  name   = "ubuntu-qcow3"
  pool   = "default"
  source = "/opt/images/ubuntu-16.04-server-cloudimg-amd64-disk1.img"
  format = "qcow2"
}

Seems very usefull for testing purpose. I learned it from this tutorial where using local file paths was commented out. Since I don't want to mix config files with binary images, I moved them to /opt but feel free to place them where you like.


问:
nestjs rendering error after connecting webpack with hotreload
I have followed the tutorial for nestJs and have a basic working app. After that, I tried the tutorial to connect my app with webpack and hotreloading and am now presented with the following error:

```<code>import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:703:23)
</code>```

I have tried looking at similar errors and cannot find anything conclusive other than hints here and there to something that is not compiling in my test files - any direction would be greatly appreciated.

Using Node 12, npm 6.9.0

Package JSON below:

```<code>"scripts": {
    "build": "tsc -p tsconfig.build.json",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "node dist/server",
    "webpack": "webpack --config webpack.config.js",
    "start:dev": "concurrently --handle-input \"wait-on dist/main.js && nodemon\" \"tsc -w -p tsconfig.build.json\" ",
    "start:debug": "nodemon --config nodemon-debug.json",
    "prestart:prod": "rimraf dist && npm run build",
    "start:prod": "node dist/main.js",
    "lint": "tslint -p tsconfig.json -c tslint.json",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@nestjs/common": "^6.0.4",
    "@nestjs/core": "^6.0.4",
    "@nestjs/microservices": "^6.0.4",
    "@nestjs/platform-express": "^6.0.4",
    "@nestjs/swagger": "^3.0.2",
    "@nestjs/typeorm": "^6.1.1",
    "@nestjs/websockets": "^6.0.4",
    "mysql": "^2.17.1",
    "reflect-metadata": "0.1.13",
    "rimraf": "2.6.3",
    "rxjs": "6.4.0",
    "swagger-ui-express": "^4.0.4",
    "typeorm": "^0.2.17"
  },
  "devDependencies": {
    "@nestjs/testing": "6.1.1",
    "@types/express": "^4.16.1",
    "@types/jest": "24.0.11",
    "@types/node": "11.13.4",
    "@types/supertest": "2.0.7",
    "concurrently": "^4.1.0",
    "jest": "24.7.1",
    "nodemon": "1.18.11",
    "prettier": "1.17.0",
    "supertest": "4.0.2",
    "ts-jest": "24.0.2",
    "ts-loader": "^6.0.1",
    "ts-node": "8.1.0",
    "tsconfig-paths": "3.8.0",
    "tslint": "5.16.0",
    "typescript": "3.4.3",
    "wait-on": "^3.2.0",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2",
    "webpack-node-externals": "^1.7.2"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
</code>```

答:
this is probably the tsconfig, are you using:
"module": "commonjs" In the compilerOptions ? When you working with nodejs this is the option that you have to use

Body:
I have followed the tutorial for nestJs and have a basic working app. After that, I tried the tutorial to connect my app with webpack and hotreloading and am now presented with the following error:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:703:23)

I have tried looking at similar errors and cannot find anything conclusive other than hints here and there to something that is not compiling in my test files - any direction would be greatly appreciated.

Using Node 12, npm 6.9.0

Package JSON below:

"scripts": {
    "build": "tsc -p tsconfig.build.json",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "node dist/server",
    "webpack": "webpack --config webpack.config.js",
    "start:dev": "concurrently --handle-input \"wait-on dist/main.js && nodemon\" \"tsc -w -p tsconfig.build.json\" ",
    "start:debug": "nodemon --config nodemon-debug.json",
    "prestart:prod": "rimraf dist && npm run build",
    "start:prod": "node dist/main.js",
    "lint": "tslint -p tsconfig.json -c tslint.json",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@nestjs/common": "^6.0.4",
    "@nestjs/core": "^6.0.4",
    "@nestjs/microservices": "^6.0.4",
    "@nestjs/platform-express": "^6.0.4",
    "@nestjs/swagger": "^3.0.2",
    "@nestjs/typeorm": "^6.1.1",
    "@nestjs/websockets": "^6.0.4",
    "mysql": "^2.17.1",
    "reflect-metadata": "0.1.13",
    "rimraf": "2.6.3",
    "rxjs": "6.4.0",
    "swagger-ui-express": "^4.0.4",
    "typeorm": "^0.2.17"
  },
  "devDependencies": {
    "@nestjs/testing": "6.1.1",
    "@types/express": "^4.16.1",
    "@types/jest": "24.0.11",
    "@types/node": "11.13.4",
    "@types/supertest": "2.0.7",
    "concurrently": "^4.1.0",
    "jest": "24.7.1",
    "nodemon": "1.18.11",
    "prettier": "1.17.0",
    "supertest": "4.0.2",
    "ts-jest": "24.0.2",
    "ts-loader": "^6.0.1",
    "ts-node": "8.1.0",
    "tsconfig-paths": "3.8.0",
    "tslint": "5.16.0",
    "typescript": "3.4.3",
    "wait-on": "^3.2.0",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2",
    "webpack-node-externals": "^1.7.2"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }


问:
Starting ipcluster from code
I want to dynamically start clusters from my Jupyter notebook for specific functions. While I can start the cluster and get the engines running, I am having two issues:

(1) I am unable to run the ipcluster command in the background. When I run the command through notebook, the cell is running till the the time the clusters are running, i.e. I can't run further cells in the same notebook. I can use the engines once they are fired in a different notebook. How can I run ipcluster in the background?

(2) My code is always starting 8 engines, regardless of the setting in ipcluster_config.py.

Code:

```<code>server_num = 3
ip_new = '10.0.1.' + str(10+server_num)
cluster_profile = "ssh" + str(server_num)

import commands
import time
commands.getstatusoutput("ipython profile create --parallel --profile=" + cluster_profile)

text = """
c.SSHEngineSetLauncher.engines = {'""" +ip_new + """' : 12}
c.LocalControllerLauncher.controller_args = ["--ip=10.0.1.163"]
c.SSHEngineSetLauncher.engine_cmd = ['/home/ubuntu/anaconda2/pkgs/ipyparallel-6.0.2-py27_0/bin/ipengine']
"""

with open("/home/ubuntu/.ipython/profile_" + cluster_profile + "/ipcluster_config.py", "a") as myfile:
    myfile.write(text)

result = commands.getstatusoutput("(ipcluster start --profile='"+ cluster_profile+"' &)")
time.sleep(120)
print(result[1])
</code>```

答:
I am not familiar with the details of the commands module (it's been deprecated since 2.6, according to https://docs.python.org/2/library/commands.html) but I know that with the subprocess module capturing output will make the make the interpreter block until the system call completes.

Also, the number of engines can be set from the command line if you're using the ipcluster command, even without adjusting the configuration files.  So, something like this worked for me:

```<code>from ipyparallel import Client
import subprocess

nengines = 3 # or whatever
subprocess.Popen(["ipcluster", "start", "-n={:d}".format(nengines)])
rc = Client()
# send your jobs to the engines; when done do
subprocess.Popen(["ipcluster", "stop"])
</code>```

This doesn't, of course, address the issue of adding or removing hosts dynamically (which from your code it looks like you may be trying to do), but if you only care how many hosts are available, and not which ones, you can make a default ipcluster configuration which includes all of the possible hosts, and allocate them as needed via code similar to the above.

Note also that it can take a second or two for ipcluster to spin up, so you may want to add a time.sleep call between your first subprocess.Popen call and trying to spawn the client.

Title: Starting ipcluster from code

Body:
I want to dynamically start clusters from my Jupyter notebook for specific functions. While I can start the cluster and get the engines running, I am having two issues:

(1) I am unable to run the ipcluster command in the background. When I run the command through notebook, the cell is running till the the time the clusters are running, i.e. I can't run further cells in the same notebook. I can use the engines once they are fired in a different notebook. How can I run ipcluster in the background?

(2) My code is always starting 8 engines, regardless of the setting in ipcluster_config.py.

Code:

server_num = 3
ip_new = '10.0.1.' + str(10+server_num)
cluster_profile = "ssh" + str(server_num)

import commands
import time
commands.getstatusoutput("ipython profile create --parallel --profile=" + cluster_profile)

text = """
c.SSHEngineSetLauncher.engines = {'""" +ip_new + """' : 12}
c.LocalControllerLauncher.controller_args = ["--ip=10.0.1.163"]
c.SSHEngineSetLauncher.engine_cmd = ['/home/ubuntu/anaconda2/pkgs/ipyparallel-6.0.2-py27_0/bin/ipengine']
"""

with open("/home/ubuntu/.ipython/profile_" + cluster_profile + "/ipcluster_config.py", "a") as myfile:
    myfile.write(text)

result = commands.getstatusoutput("(ipcluster start --profile='"+ cluster_profile+"' &)")
time.sleep(120)
print(result[1])

Body:
I am not familiar with the details of the commands module (it's been deprecated since 2.6, according to https://docs.python.org/2/library/commands.html) but I know that with the subprocess module capturing output will make the make the interpreter block until the system call completes.

Also, the number of engines can be set from the command line if you're using the ipcluster command, even without adjusting the configuration files.  So, something like this worked for me:

from ipyparallel import Client
import subprocess

nengines = 3 # or whatever
subprocess.Popen(["ipcluster", "start", "-n={:d}".format(nengines)])
rc = Client()
# send your jobs to the engines; when done do
subprocess.Popen(["ipcluster", "stop"])

This doesn't, of course, address the issue of adding or removing hosts dynamically (which from your code it looks like you may be trying to do), but if you only care how many hosts are available, and not which ones, you can make a default ipcluster configuration which includes all of the possible hosts, and allocate them as needed via code similar to the above.

Note also that it can take a second or two for ipcluster to spin up, so you may want to add a time.sleep call between your first subprocess.Popen call and trying to spawn the client.


问:
Animation using Animator 0.1.2 stopped working
I'm using the Animator 0.1.2 package to make a raised button rotate on it's axis. All of a sudden it just stopped working. Has anyone else experienced this? I even tried an earlier version of my app in case I changed or deleted something and it doesn't work there anymore either. Weird (and frustrating)!</p>

答: I figured out that the logic to stop my animation didn't work anymore. I had to code this differently and I got it working again.</p>


问:
The "ResolvePackageAssets" task failed unexpectedly - System.TypeLoadException
I am trying to set up visual studio 2019 on macos (10.14.3), but when attempting to build a default web MVC project I get this dependency error:

```<code>    Target _CheckForNETCoreSdkIsPreview:
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.RuntimeIdentifierInference.targets(151,5): message NETSDK1057: You are using a preview version of .NET Core. See: https://aka.ms/dotnet-core-preview
Target ResolvePackageAssets:
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018: The "ResolvePackageAssets" task failed unexpectedly.
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018: System.TypeLoadException: Could not resolve type with token 0100003f from typeref (expected class 'NuGet.Packaging.Core.PackageDependency' in assembly 'NuGet.Packaging, Version=5.0.0.4, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets+CacheWriter.GetPlatformPackageExclusions () [0x000d7] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets+CacheWriter..ctor (Microsoft.NET.Build.Tasks.ResolvePackageAssets task, System.IO.Stream stream) [0x0009b] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets+CacheReader.CreateReaderFromDisk (Microsoft.NET.Build.Tasks.ResolvePackageAssets task, System.Byte[] settingsHash) [0x0003a] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets+CacheReader..ctor (Microsoft.NET.Build.Tasks.ResolvePackageAssets task) [0x00015] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ReadItemGroups () [0x00000] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ExecuteCore () [0x00018] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.TaskBase.Execute () [0x00000] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute () [0x00023] in /Users/builder/jenkins/workspace/build-package-osx-mono/2018-10/external/bockbuild/builds/msbuild-15/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs:573
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask (Microsoft.Build.BackEnd.ITaskExecutionHost taskExecutionHost, Microsoft.Build.BackEnd.Logging.TaskLoggingContext taskLoggingContext, Microsoft.Build.BackEnd.TaskHost taskHost, Microsoft.Build.BackEnd.ItemBucket bucket, Microsoft.Build.BackEnd.TaskExecutionMode howToExecuteTask) [0x00212] in /Users/builder/jenkins/workspace/build-package-osx-mono/2018-10/external/bockbuild/builds/msbuild-15/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs:784
Done building target "ResolvePackageAssets" in project "TestingApp.csproj" -- FAILED.

Done building project "TestingApp.csproj" -- FAILED.

Build FAILED.
</code>```

I also tried to run it from terminal with dotnet run and it works, but I cannot use Visual Studio. Thanks.

答:
Root cause :-

This error due to Nuget packages version compatibility different in projects(Shared project,iOS Project,Android Projects).

Solution:-

1.Update the each Nuget packages where shows update version in front of nuget package.

2.Clean solution.

3.Build Solution,

Body:
I am trying to set up visual studio 2019 on macos (10.14.3), but when attempting to build a default web MVC project I get this dependency error:

    Target _CheckForNETCoreSdkIsPreview:
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.RuntimeIdentifierInference.targets(151,5): message NETSDK1057: You are using a preview version of .NET Core. See: https://aka.ms/dotnet-core-preview
Target ResolvePackageAssets:
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018: The "ResolvePackageAssets" task failed unexpectedly.
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018: System.TypeLoadException: Could not resolve type with token 0100003f from typeref (expected class 'NuGet.Packaging.Core.PackageDependency' in assembly 'NuGet.Packaging, Version=5.0.0.4, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets+CacheWriter.GetPlatformPackageExclusions () [0x000d7] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets+CacheWriter..ctor (Microsoft.NET.Build.Tasks.ResolvePackageAssets task, System.IO.Stream stream) [0x0009b] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets+CacheReader.CreateReaderFromDisk (Microsoft.NET.Build.Tasks.ResolvePackageAssets task, System.Byte[] settingsHash) [0x0003a] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets+CacheReader..ctor (Microsoft.NET.Build.Tasks.ResolvePackageAssets task) [0x00015] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ReadItemGroups () [0x00000] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ExecuteCore () [0x00018] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.NET.Build.Tasks.TaskBase.Execute () [0x00000] in <9524e6fbf1724027a475d15b01fab866>:0
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute () [0x00023] in /Users/builder/jenkins/workspace/build-package-osx-mono/2018-10/external/bockbuild/builds/msbuild-15/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs:573
    /usr/local/share/dotnet/sdk/3.0.100-preview3-010431/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(228,5): error MSB4018:   at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask (Microsoft.Build.BackEnd.ITaskExecutionHost taskExecutionHost, Microsoft.Build.BackEnd.Logging.TaskLoggingContext taskLoggingContext, Microsoft.Build.BackEnd.TaskHost taskHost, Microsoft.Build.BackEnd.ItemBucket bucket, Microsoft.Build.BackEnd.TaskExecutionMode howToExecuteTask) [0x00212] in /Users/builder/jenkins/workspace/build-package-osx-mono/2018-10/external/bockbuild/builds/msbuild-15/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs:784
Done building target "ResolvePackageAssets" in project "TestingApp.csproj" -- FAILED.

Done building project "TestingApp.csproj" -- FAILED.

Build FAILED.

I also tried to run it from terminal with dotnet run and it works, but I cannot use Visual Studio. Thanks.


问:
How to find the same values next to each other in multidimensional array?
I tried to write a function that would find in a multidimensional array (with values from 3 to 7) repeating values for at least 3 times next to each other (vertical and horizontal). And if it finds that, change it for a different value. Let's say 1.

I tried to do this by loops but it doesn't seem to be a good way to solve that or I messed it up. Because for some array it works, for some it does not.

Here's my code:

function searching(array) {
  for (i = 0; i < array.length; i++) {
    let horizontal = array[i][0];
    let howMany = 1;

    for (j = 1; j < array[i].length; j++) {
      if (horizontal === array[i][j]) {
        howMany += 1;
        horizontal = array[i][j];
        if (howMany >= 3) {
          for (d = j; d > j - howMany; d--) {
            array[i][d] = 0;
          }
        }
      } else {
        horizontal = array[i][j];
        howMany = 1;
      }

    }

  }

  for (v = 0; v < array.length; v++) {
    let vertical = array[0][v];
    let howMany = 1;
    for (x = 1; x < array.length; x++) {
      if (vertical === array[x][v]) {
        howMany++;
        vertical = array[x][v];
        if (howMany >= 3) {
          for (d = x; d > x - howMany; d--) {
            array[d][v] = 0;
          }
        }
      } else {
        vertical = array[x][v];
        howMany = 1;
      }
    }
  }
}```
</div>
</div>
</p>

<p>The idea is to for example give array:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let array = [
    [3, 4, 5, 6, 7],
    [3, 4, 5, 6, 7],
    [3, 4, 5, 5, 5],
    [3, 5, 6, 7, 4]
  ]</code>```

And the result should be:

let result = [
    [1, 1, 1, 6, 7],
    [1, 1, 1, 6, 7],
    [1, 1, 1, 1, 1],
    [1, 5, 6, 7, 4]
  ]```

Thanks in advance for any ideas how to solve it :) Greetings!

答:
I didn't understand the question at first...
So this is my code:

let array = [
  [3, 4, 5, 6, 7],
  [3, 4, 5, 6, 7],
  [3, 4, 5, 5, 5],
  [3, 5, 6, 7, 4]
];

function replace(arr, target = 1) {
  let needToChange = []; // save the index to change
  const numbers = [3, 4, 5, 6, 7];
  const m = arr.length; // m rows
  const n = arr[0].length; // n columns

  let mi = 0;
  let ni = 0;

  // search in row
  for (mi = 0; mi < m; mi++) {
    for (let x = 0; x < numbers.length; x++) {
      const num = numbers[x]; // number to search
      let counter = 0; // counter for this number in row mi
      let tempArr = [];
      for (ni = 0; ni < n; ni++) {
        const currentNum = arr[mi][ni];
        if (currentNum === num) {
          counter++;
          tempArr.push([mi, ni]);
        }
      }
      if (counter >= 3) {
        needToChange = needToChange.concat(tempArr);
      }
    }
  }

  // search in column
  for (ni = 0; ni < n; ni++) {
    for (let x = 0; x < numbers.length; x++) {
      const num = numbers[x]; // number to search
      let counter = 0; // counter for this number in row mi
      let tempArr = [];
      for (mi = 0; mi < m; mi++) {
        const currentNum = arr[mi][ni];
        if (currentNum === num) {
          counter++;
          tempArr.push([mi, ni]);
        }
      }
      if (counter >= 3) {
        needToChange = needToChange.concat(tempArr);
      }
    }
  }

  // replace
  needToChange.forEach(([i, j]) => {
    array[i][j] = target;
  });
}

replace(array);
array.forEach(row => {
  console.log(row.join(', '));
})```

Body:
I tried to write a function that would find in a multidimensional array (with values from 3 to 7) repeating values for at least 3 times next to each other (vertical and horizontal). And if it finds that, change it for a different value. Let's say 1.

I tried to do this by loops but it doesn't seem to be a good way to solve that or I messed it up. Because for some array it works, for some it does not.

Here's my code:

function searching(array) {
  for (i = 0; i < array.length; i++) {
    let horizontal = array[i][0];
    let howMany = 1;

    for (j = 1; j < array[i].length; j++) {
      if (horizontal === array[i][j]) {
        howMany += 1;
        horizontal = array[i][j];
        if (howMany >= 3) {
          for (d = j; d > j - howMany; d--) {
            array[i][d] = 0;
          }
        }
      } else {
        horizontal = array[i][j];
        howMany = 1;
      }

    }

  }

  for (v = 0; v < array.length; v++) {
    let vertical = array[0][v];
    let howMany = 1;
    for (x = 1; x < array.length; x++) {
      if (vertical === array[x][v]) {
        howMany++;
        vertical = array[x][v];
        if (howMany >= 3) {
          for (d = x; d > x - howMany; d--) {
            array[d][v] = 0;
          }
        }
      } else {
        vertical = array[x][v];
        howMany = 1;
      }
    }
  }
}

The idea is to for example give array:

let array = [
    [3, 4, 5, 6, 7],
    [3, 4, 5, 6, 7],
    [3, 4, 5, 5, 5],
    [3, 5, 6, 7, 4]
  ]

And the result should be:

let result = [
    [1, 1, 1, 6, 7],
    [1, 1, 1, 6, 7],
    [1, 1, 1, 1, 1],
    [1, 5, 6, 7, 4]
  ]

Thanks in advance for any ideas how to solve it :) Greetings!


问:
Different behavior of sql server SSMS vs ODBC for BACKUP DATABASE
I use Sql server Native client 11 for database programing. I use this command to create a full backup

```<code>BACKUP DATABASE [AminDB] TO DISK = 'E:\AminExe\Hogug02\BKUP\PYBKUPyy-13970515-1211-1.BAK' WITH INIT, COMPRESSION, NOSKIP;
</code>```

When I execute this command in SSMS, I get this result:

Processed 175632 pages for database 'AminDB', file 'AminDB_dat' on file 1.
Processed 2 pages for database 'AminDB', file 'AminDB_log' on file 1.
BACKUP DATABASE successfully processed 175634 pages in 6.029 seconds (227.588 MB/sec).

When I execute this command using SqlExecDirect, I get SUCCESS_WITH_INFO and SQLGetDiagRec returns this result:

Processed 175632 pages for database 'AminDB', file 'AminDB_dat' on file 1.

and backup is not created.
for many other databases, executing backup database command always returns SQL_SUCCESS_WITH_INFO, but the backup file randomly is created or not.
What should I do for my Application create successful backup?
thanks in advance
mr.abzadeh

答: I called SQLMoreResults after BACKUP DATABASE statement repeatedly until it returned SQL_NO_DATA. This completely solved the problem.</p>

Body:
I use Sql server Native client 11 for database programing. I use this command to create a full backup

BACKUP DATABASE [AminDB] TO DISK = 'E:\AminExe\Hogug02\BKUP\PYBKUPyy-13970515-1211-1.BAK' WITH INIT, COMPRESSION, NOSKIP;

When I execute this command in SSMS, I get this result:

Processed 175632 pages for database 'AminDB', file 'AminDB_dat' on file 1.
Processed 2 pages for database 'AminDB', file 'AminDB_log' on file 1.
BACKUP DATABASE successfully processed 175634 pages in 6.029 seconds (227.588 MB/sec).

When I execute this command using SqlExecDirect, I get SUCCESS_WITH_INFO and SQLGetDiagRec returns this result:

Processed 175632 pages for database 'AminDB', file 'AminDB_dat' on file 1.

and backup is not created.
for many other databases, executing backup database command always returns SQL_SUCCESS_WITH_INFO, but the backup file randomly is created or not.
What should I do for my Application create successful backup?
thanks in advance
mr.abzadeh


问:
Cast angular http response into class
I am trying to cast a response object from an HTTP Post request in my angular project to a Person class that I have defined.  I have defined a generic post method in an HTTP Service, and am calling that in my person service with the generic replaced with Person.  So, I would think, since I have done that the HTTP response should be a Person, but it's not - it's just an Object.  I need it to be a Person because my Person class has some custom logic on it that I need to access.  I could write a helper method in my person service, but I feel like this should work - especially since VS Code intellisense says that the response in my component is a Person when I hover my mouse over it.

Here is my code:

http.service.ts

```<code>@Injectable()
export class HttpService {
    baseUrl = 'https://baseurl.com';

    constructor(private http: HttpClient) { }

    post<T>(endpointUrl: string, body: any): Observable<T> {
        const fullUrl = this.baseUrl + endpointUrl;
        return this.http
            .post<T>(fullUrl, body)
            .pipe(
                map(response => response as T)
            );
    }
}
</code>```

person.service.ts

```<code>@Injectable()
export class PersonService {

    constructor(private httpService: HttpService) { }

    newPerson(body: Person): Observable<Person> {
        return this.httpService.post<Person>('/people', JSON.stringify(body));
    }
}
</code>```

person.component.ts

```<code>@Component({
    selector: 'app-person',
    templateUrl: './person.component.html',
    styleUrls: ['./person.component.css'],
})
export class PersonComponent {
        person: Person = new Person();

        onSubmit(id: number) {
        if (id == 0) {
            console.log(this.person);                              // Person {id: 0, ...
            console.log(this.person.constructor.name);             // Person
            let body = this.person.fromFormGroup(this.formGroup);

            this.personService.newPerson(body)
                .subscribe(response => {                           // VS Code intellisense says this: (parameter) response : Person
                    this.person = response as Person;
                    console.log(this.person);                      // {id: 72, ...
                    console.log(this.person.constructor.name);     // Object

                    // Trying a different way
                    this.person = <Person>response;
                    console.log(this.person);                      // {id: 72, ...
                    console.log(this.person.constructor.name);     // Object
                })

        }
    }

}
</code>```

答:
newPerson(body: Person): Observable<Person> {
  return this.httpService.post<Person>('/people', JSON.stringify(body));
}
```

<p>The <code>HttpClient.post()</code> method can not return type <code>Person</code>, because JSON responses are just cast to types. The default type is just <code>Object</code>, but you need to create a new instance of <code>Person</code> for each response. If the type was an <em>interface</em> then there would be no problem.</p>

<p>You can create a new instance of <code>Person</code> and then assign the values to that instance.</p>

<pre class="lang-js prettyprint-override"><code>newPerson(body: Person): Observable<Person> {
  return this.httpService.post('/people', JSON.stringify(body)).pipe
    map(value => Object.assign(new Person(), value)
  );
}
</code>```

Title: Cast angular http response into class

Body:
I am trying to cast a response object from an HTTP Post request in my angular project to a Person class that I have defined.  I have defined a generic post method in an HTTP Service, and am calling that in my person service with the generic replaced with Person.  So, I would think, since I have done that the HTTP response should be a Person, but it's not - it's just an Object.  I need it to be a Person because my Person class has some custom logic on it that I need to access.  I could write a helper method in my person service, but I feel like this should work - especially since VS Code intellisense says that the response in my component is a Person when I hover my mouse over it.

Here is my code:

http.service.ts

@Injectable()
export class HttpService {
    baseUrl = 'https://baseurl.com';

    constructor(private http: HttpClient) { }

    post<T>(endpointUrl: string, body: any): Observable<T> {
        const fullUrl = this.baseUrl + endpointUrl;
        return this.http
            .post<T>(fullUrl, body)
            .pipe(
                map(response => response as T)
            );
    }
}

person.service.ts

@Injectable()
export class PersonService {

    constructor(private httpService: HttpService) { }

    newPerson(body: Person): Observable<Person> {
        return this.httpService.post<Person>('/people', JSON.stringify(body));
    }
}

person.component.ts

@Component({
    selector: 'app-person',
    templateUrl: './person.component.html',
    styleUrls: ['./person.component.css'],
})
export class PersonComponent {
        person: Person = new Person();

        onSubmit(id: number) {
        if (id == 0) {
            console.log(this.person);                              // Person {id: 0, ...
            console.log(this.person.constructor.name);             // Person
            let body = this.person.fromFormGroup(this.formGroup);

            this.personService.newPerson(body)
                .subscribe(response => {                           // VS Code intellisense says this: (parameter) response : Person
                    this.person = response as Person;
                    console.log(this.person);                      // {id: 72, ...
                    console.log(this.person.constructor.name);     // Object

                    // Trying a different way
                    this.person = <Person>response;
                    console.log(this.person);                      // {id: 72, ...
                    console.log(this.person.constructor.name);     // Object
                })

        }
    }

}

Body:
newPerson(body: Person): Observable<Person> {
  return this.httpService.post<Person>('/people', JSON.stringify(body));
}

The HttpClient.post() method can not return type Person, because JSON responses are just cast to types. The default type is just Object, but you need to create a new instance of Person for each response. If the type was an interface then there would be no problem.

You can create a new instance of Person and then assign the values to that instance.

newPerson(body: Person): Observable<Person> {
  return this.httpService.post('/people', JSON.stringify(body)).pipe
    map(value => Object.assign(new Person(), value)
  );
}


问:
Find html label associated with a given input
Let's say I have an html form.  Each input/select/textarea will have a corresponding  with the for attribute set to the id of it's companion. In this case, I know that each input will only have a single label.

Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?

答:
Use a JQuery selector:</p>

```<code>$("label[for="+inputElement.id+"]")
</code>```

OwnerDisplayName: Joel Coehoorn

Body:
Use a JQuery selector:

$("label[for="+inputElement.id+"]")


问:
How do I give my simple java program memory?
I am new to programming and I have a simple program I am working on for fun that keeps track of my money. For instance, I want it to record how much money is in my wallet. So I will give it some data, and it complies. However, when I rerun the program at a different time to add or subtract money from my wallet for example, it will revert back to 0 instead of saving the changes I made before.

I assume I have to make a txt file for this data to save to, and then have it read it every time I run the program?

```<code>//here is my wallet class
public class Wallet extends UserInterface{

    public String WalletName;
    public double WalletCash;

    public Wallet(String name) {
        this.WalletName = name;

    }

    public String addCashtoWallet(double income) {
        WalletCash += income;
        return "Added $" + income + "to " + this.WalletName;
    }

    public String removeCashfromWallet(double cost) {
        WalletCash -= cost;
        return "Removed $" + cost + "from " + this.WalletName;
    }

}
</code>```

The output when I add money to the wallet for example, will be
"Your wallet now has $64.0 would you like to do anything else"
However, when I run the program again, it will say 0, but I want it to display the 64 dollars I added before. How do I get it to save this data?

答:
It's not 'memory', it's called 'persistent storage'.

And simple TXT file is a worst solution, like for me. I suggest you to use at least structured file like JSON, but better - an embedded database like HSQLDB.

Body:
I am new to programming and I have a simple program I am working on for fun that keeps track of my money. For instance, I want it to record how much money is in my wallet. So I will give it some data, and it complies. However, when I rerun the program at a different time to add or subtract money from my wallet for example, it will revert back to 0 instead of saving the changes I made before.

I assume I have to make a txt file for this data to save to, and then have it read it every time I run the program?

//here is my wallet class
public class Wallet extends UserInterface{

    public String WalletName;
    public double WalletCash;

    public Wallet(String name) {
        this.WalletName = name;

    }

    public String addCashtoWallet(double income) {
        WalletCash += income;
        return "Added $" + income + "to " + this.WalletName;
    }

    public String removeCashfromWallet(double cost) {
        WalletCash -= cost;
        return "Removed $" + cost + "from " + this.WalletName;
    }

}

The output when I add money to the wallet for example, will be
"Your wallet now has $64.0 would you like to do anything else"
However, when I run the program again, it will say 0, but I want it to display the 64 dollars I added before. How do I get it to save this data?


问:
How to store results of a Dynamic Query in a temp table without creating a table?
We are writing a stored procedure responsible for getting a stored procedure name and returning a result containing the stored procedure columns and their data types.
However, we bumped into a problem executing a dynamic query to return the results of stored procedure, but we can't store it in a temp table!

You can see our query below:

```<code>  DECLARE @ProcName VARCHAR(100)='spGetOraganizationsList',
  @ParamName VARCHAR(100),@DataType VARCHAR(20),
  @Query NVARCHAR(MAX)='EXEC '+'spGetOraganizationsList '

  SELECT  PARAMETER_NAME,DATA_TYPE
  INTO #Tmp
  FROM  information_schema.PARAMETERS
  WHERE SPECIFIC_NAME=@ProcName

  DECLARE ParamCursor CURSOR
  FOR SELECT * FROM #Tmp
  OPEN ParamCursor
  FETCH NEXT FROM ParamCursor
  INTO @ParamName,@DataType

  WHILE @@FETCH_STATUS = 0
  BEGIN
  SET @Query=@Query+@ParamName+'=Null,'
  FETCH NEXT FROM ParamCursor INTO @ParamName,@DataType
  END
  CLOSE ParamCursor
  DEALLOCATE ParamCursor
  DROP TABLE #Tmp

  EXEC sp_executesql @Query
</code>```

The thing is I can't store the results of it in a temp table,
and OPENROWSET does not accept variables.

答:
Use global temp table and dynamic OPENROWSET

```<code>  DROP TABLE ##Tmp;
  GO

  DECLARE @ProcName VARCHAR(100)='spGetOraganizationsList',
  @ParamName VARCHAR(100), @DataType VARCHAR(20),
  -- Mind to specify database and schema of the SP
  @Query NVARCHAR(MAX)=' EXEC [mydb].[dbo].spGetOraganizationsList ';
  SELECT  PARAMETER_NAME,DATA_TYPE
  INTO #Tmp
  FROM  information_schema.PARAMETERS
  WHERE SPECIFIC_NAME=@ProcName;

  -- Build SP exec

  DECLARE ParamCursor CURSOR
  FOR SELECT * FROM #Tmp
  OPEN ParamCursor
  FETCH NEXT FROM ParamCursor
  INTO @ParamName,@DataType

  WHILE @@FETCH_STATUS = 0
  BEGIN
     SET @Query=@Query+@ParamName+'=Null,'
     FETCH NEXT FROM ParamCursor INTO @ParamName,@DataType
  END
  CLOSE ParamCursor
  DEALLOCATE ParamCursor
  SET @Query = left(@Query, len(@Query) - 1);

  -- Build ad hoc distributed query which creates ##Tmp from SP exec.

  SET @Query = 'SELECT * INTO ##Tmp FROM OPENROWSET(''SQLNCLI'', ''Server=localhost;Trusted_Connection=yes;'',''' + @Query + ''')';

  EXEC (@Query);

  -- Created by dynamic sql `##Tmp` is availabe in the current context.
  SELECT *
  FROM ##Tmp;
</code>```

Don't forget to enable ad hoc distributed queries first.

```<code>sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
</code>```

EDIT

My answer solves only one problem, storing the result of a dynamic proc call in a temp table. And there are more problems.

First, @p=null just will not compile if the type of @p is user-defined table type. You need kind of declare @t myType;
exec mySp ...  ,@p=@t ....

Next is the 'cannot retrieve matadata for sp because contain dynamic query' error you commented on. Looks like you need an application, SqlClr or standalone, which would be capable to read and parse Datasets returned by procs.

Finally, if an SP contains conditional sql which can return a result set of different schema depending on parameter values, the result of all those efforts is still questionable.

Body:
We are writing a stored procedure responsible for getting a stored procedure name and returning a result containing the stored procedure columns and their data types.
However, we bumped into a problem executing a dynamic query to return the results of stored procedure, but we can't store it in a temp table!

You can see our query below:

  DECLARE @ProcName VARCHAR(100)='spGetOraganizationsList',
  @ParamName VARCHAR(100),@DataType VARCHAR(20),
  @Query NVARCHAR(MAX)='EXEC '+'spGetOraganizationsList '

  SELECT  PARAMETER_NAME,DATA_TYPE
  INTO #Tmp
  FROM  information_schema.PARAMETERS
  WHERE SPECIFIC_NAME=@ProcName

  DECLARE ParamCursor CURSOR
  FOR SELECT * FROM #Tmp
  OPEN ParamCursor
  FETCH NEXT FROM ParamCursor
  INTO @ParamName,@DataType

  WHILE @@FETCH_STATUS = 0
  BEGIN
  SET @Query=@Query+@ParamName+'=Null,'
  FETCH NEXT FROM ParamCursor INTO @ParamName,@DataType
  END
  CLOSE ParamCursor
  DEALLOCATE ParamCursor
  DROP TABLE #Tmp

  EXEC sp_executesql @Query

The thing is I can't store the results of it in a temp table,
and OPENROWSET does not accept variables.

Body:
Use global temp table and dynamic OPENROWSET

  DROP TABLE ##Tmp;
  GO

  DECLARE @ProcName VARCHAR(100)='spGetOraganizationsList',
  @ParamName VARCHAR(100), @DataType VARCHAR(20),
  -- Mind to specify database and schema of the SP
  @Query NVARCHAR(MAX)=' EXEC [mydb].[dbo].spGetOraganizationsList ';
  SELECT  PARAMETER_NAME,DATA_TYPE
  INTO #Tmp
  FROM  information_schema.PARAMETERS
  WHERE SPECIFIC_NAME=@ProcName;

  -- Build SP exec

  DECLARE ParamCursor CURSOR
  FOR SELECT * FROM #Tmp
  OPEN ParamCursor
  FETCH NEXT FROM ParamCursor
  INTO @ParamName,@DataType

  WHILE @@FETCH_STATUS = 0
  BEGIN
     SET @Query=@Query+@ParamName+'=Null,'
     FETCH NEXT FROM ParamCursor INTO @ParamName,@DataType
  END
  CLOSE ParamCursor
  DEALLOCATE ParamCursor
  SET @Query = left(@Query, len(@Query) - 1);

  -- Build ad hoc distributed query which creates ##Tmp from SP exec.

  SET @Query = 'SELECT * INTO ##Tmp FROM OPENROWSET(''SQLNCLI'', ''Server=localhost;Trusted_Connection=yes;'',''' + @Query + ''')';

  EXEC (@Query);

  -- Created by dynamic sql `##Tmp` is availabe in the current context.
  SELECT *
  FROM ##Tmp;

Don't forget to enable ad hoc distributed queries first.

sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

EDIT

My answer solves only one problem, storing the result of a dynamic proc call in a temp table. And there are more problems.

First, @p=null just will not compile if the type of @p is user-defined table type. You need kind of declare @t myType;
exec mySp ...  ,@p=@t ....

Next is the 'cannot retrieve matadata for sp because contain dynamic query' error you commented on. Looks like you need an application, SqlClr or standalone, which would be capable to read and parse Datasets returned by procs.

Finally, if an SP contains conditional sql which can return a result set of different schema depending on parameter values, the result of all those efforts is still questionable.


问:
DBeaver does not keep primary keys on import/export
I'm using DBeaver to migrate data from Postgres to Derby.  When I use the wizard in DBeaver to go directly from one table to another, the primary key in Derby is being generated instead of inserted.  This causes issues on foreign keys for subsequent tables.

If I generate the SQL, the primary key is part of the SQL statement and is properly inserted.  However there are too many rows to handle in this way.

Is there a way to have DBeaver insert the primary key instead of letting it be generated when importing / exporting directly to database tables?

Schema of target table

CREATE TABLE APP.THREE_PHASE_MOTOR (
    ID BIGINT NOT NULL DEFAULT GENERATED_BY_DEFAULT,
    VERSION INTEGER NOT NULL,
    CONSTRAINT SQL130812103636700 PRIMARY KEY (ID)
);

CREATE INDEX SQL160416184259290 ON APP.THREE_PHASE_MOTOR (ID);
```
<p><strong>Schema of source table</strong></p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE public.three_phase_motor (
    id int8 NOT NULL DEFAULT nextval('three_phase_motor_id_seq'::regclass),
    "version" int4 NOT NULL,
    CONSTRAINT three_phase_motor_pkey PRIMARY KEY (id)
)
WITH (
    OIDS=FALSE
);
</code>```

答:
I found a trick working with version 6.0.5; do these steps:

double click a table name

then select Data tab

then click the gray table corner (the one on top of row order numbers) in order to select all rows

then right click the same gray table corner

then select Generate SQL -> INSERT menu

a window with the INSERT instructions including id (primary key) will popup.

PS: when selecting a subset of rows the same menu would work for only those too

Body:
I'm using DBeaver to migrate data from Postgres to Derby.  When I use the wizard in DBeaver to go directly from one table to another, the primary key in Derby is being generated instead of inserted.  This causes issues on foreign keys for subsequent tables.

If I generate the SQL, the primary key is part of the SQL statement and is properly inserted.  However there are too many rows to handle in this way.

Is there a way to have DBeaver insert the primary key instead of letting it be generated when importing / exporting directly to database tables?

Schema of target table

CREATE TABLE APP.THREE_PHASE_MOTOR (
    ID BIGINT NOT NULL DEFAULT GENERATED_BY_DEFAULT,
    VERSION INTEGER NOT NULL,
    CONSTRAINT SQL130812103636700 PRIMARY KEY (ID)
);

CREATE INDEX SQL160416184259290 ON APP.THREE_PHASE_MOTOR (ID);

Schema of source table

CREATE TABLE public.three_phase_motor (
    id int8 NOT NULL DEFAULT nextval('three_phase_motor_id_seq'::regclass),
    "version" int4 NOT NULL,
    CONSTRAINT three_phase_motor_pkey PRIMARY KEY (id)
)
WITH (
    OIDS=FALSE
);


问:
Removing a string that starts with a substring
I want to remove all the words that contain a specific substring.</p>

```<code>Sentence = 'walking my dog https://github.com/'
substring = 'http'

# Remove all words that start with the substring
#...

result = 'walking my dog'
</code>```

答:
There is a simple approach that we can use for this.

Split the sentence into words

Find all the works that

Check if that word contains the substring and remove it

Join back the remaining words.

```<code>>>> sentence = 'walking my dog https://github.com/'
>>> substring = 'http'
>>> f = lambda v, w: ' '.join(filter(lambda x: w not in x, v.split(' ')))
>>> f(sentence, substring)
'walking my dog'
</code>```

Explanation:

```<code>1. ' '.join(
2.   filter(
3.     lambda x: w not in x,
4.     v.split(' ')
6.  )
7. )
</code>```

1 stars with a join. 2 is for filtering all the elements from 4, which splits the string into words. The condition to filter is substring not in word. The not in does a O(len(substring) * len(word)) complexity comparison.

Note: The only step that can be sped up is line 3. The fact that you are comparing words to a constant string, you can use Rabin-Karp String Matching to find the string in O(len(word)) or Z-Function to find the string in O(len(word) + len(substring))

Body:
I want to remove all the words that contain a specific substring.

Sentence = 'walking my dog https://github.com/'
substring = 'http'

# Remove all words that start with the substring
#...

result = 'walking my dog'

Body:
There is a simple approach that we can use for this.

Split the sentence into words

Find all the works that

Check if that word contains the substring and remove it

Join back the remaining words.

>>> sentence = 'walking my dog https://github.com/'
>>> substring = 'http'
>>> f = lambda v, w: ' '.join(filter(lambda x: w not in x, v.split(' ')))
>>> f(sentence, substring)
'walking my dog'

Explanation:

1. ' '.join(
2.   filter(
3.     lambda x: w not in x,
4.     v.split(' ')
6.  )
7. )

1 stars with a join. 2 is for filtering all the elements from 4, which splits the string into words. The condition to filter is substring not in word. The not in does a O(len(substring) * len(word)) complexity comparison.

Note: The only step that can be sped up is line 3. The fact that you are comparing words to a constant string, you can use Rabin-Karp String Matching to find the string in O(len(word)) or Z-Function to find the string in O(len(word) + len(substring))