问:
updating an array in state
I am attempting to update an object of names in the state before passing it as a props to another component.

```<code>// some code above

this.state = {
    // some other states
    playerName: {
        player1Name: 'Default Player 1 Name',
        player2Name: 'Default Player 2 Name',
        player3Name: 'Default Player 3 Name'
    }
};
this.nameChange = this.nameChange.bind(this);

nameChange(e){
    this.setState( prevState => ({
        playerName: {
            ...prevState.playerName,
            [e.target.id]: e.target.value
        }
    })
}

render(){
    return(
        <div>
            <input type='name' id='player1Name' onChange={this.nameChange}/>
            <input type='name' id='player2Name' onChange={this.nameChange}/>
            <input type='name' id='player3Name' onChange={this.nameChange}/>
        </div>
    )
}

</code>```

However, it returns the error of unable to read 'id' of null and 'value' of null

答:
State updates are asynchronous, and react uses synthetic events, so by the time the queued state update is processed the event has been nullified and returned back to the pool. You can either destructure the id and value properties before enqueueing the update.

```<code>nameChange(e){
  const { id, value } = e.target;
  this.setState( prevState => ({
    playerName: { ...prevState.playerName, [id]: value }
  });
}
</code>```

Or you can flag the event to persist (event pooling)

Note:

If you want to access the event properties in an asynchronous way, you
  should call event.persist() on the event, which will remove the
  synthetic event from the pool and allow references to the event to be
  retained by user code.

```<code>nameChange(e){
  e.persist();
  this.setState( prevState => ({
    playerName: { ...prevState.playerName, [e.target.id]: e.target.value }
  })
}
</code>```

Title: updating an array in state

Body:
I am attempting to update an object of names in the state before passing it as a props to another component.

// some code above

this.state = {
    // some other states
    playerName: {
        player1Name: 'Default Player 1 Name',
        player2Name: 'Default Player 2 Name',
        player3Name: 'Default Player 3 Name'
    }
};
this.nameChange = this.nameChange.bind(this);

nameChange(e){
    this.setState( prevState => ({
        playerName: {
            ...prevState.playerName,
            [e.target.id]: e.target.value
        }
    })
}

render(){
    return(

            <input type='name' id='player1Name' onChange={this.nameChange}/>
            <input type='name' id='player2Name' onChange={this.nameChange}/>
            <input type='name' id='player3Name' onChange={this.nameChange}/>

    )
}

However, it returns the error of unable to read 'id' of null and 'value' of null

Body:
State updates are asynchronous, and react uses synthetic events, so by the time the queued state update is processed the event has been nullified and returned back to the pool. You can either destructure the id and value properties before enqueueing the update.

nameChange(e){
  const { id, value } = e.target;
  this.setState( prevState => ({
    playerName: { ...prevState.playerName, [id]: value }
  });
}

Or you can flag the event to persist (event pooling)

Note:

If you want to access the event properties in an asynchronous way, you
  should call event.persist() on the event, which will remove the
  synthetic event from the pool and allow references to the event to be
  retained by user code.

nameChange(e){
  e.persist();
  this.setState( prevState => ({
    playerName: { ...prevState.playerName, [e.target.id]: e.target.value }
  })
}


来源: stackexchange

问:
iText Font set to Phrase not being reflected
I am trying to add font to phrase, I am using iText 5. Font is not being reflected in text that is being display for which I am trying to set.

Let me know If anybody came across the same.

```<code>private static void addDataToCell(PdfPTable table, String cellData, int border, Font font) {

    final Phrase phrase = new Phrase(cellData);
    if (font != null) {
      phrase.setFont(font);
    }
    PdfPCell cell = new PdfPCell(phrase);

    cell.setBorder(border);
    cell.setUseAscender(true);
    cell.setUseDescender(true);

    cell.setPaddingLeft(3);
    cell.setPaddingBottom(3);
    cell.setPaddingTop(3);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.addCell(cell);
  }
</code>```

答:
Answer is in below link
 https://itextpdf.com/en/resources/faq/fonts/itext-5-legacy/why-cant-i-set-font-phrase

In short, we need to set font while creating Phrase, not afterwards like with .setFont

```<code>new Phrase(cellData, font);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to add font to phrase, I am using iText 5. Font is not being reflected in text that is being display for which I am trying to set.

Let me know If anybody came across the same.

private static void addDataToCell(PdfPTable table, String cellData, int border, Font font) {

    final Phrase phrase = new Phrase(cellData);
    if (font != null) {
      phrase.setFont(font);
    }
    PdfPCell cell = new PdfPCell(phrase);

    cell.setBorder(border);
    cell.setUseAscender(true);
    cell.setUseDescender(true);

    cell.setPaddingLeft(3);
    cell.setPaddingBottom(3);
    cell.setPaddingTop(3);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.addCell(cell);
  }

Body:
Answer is in below link
 https://itextpdf.com/en/resources/faq/fonts/itext-5-legacy/why-cant-i-set-font-phrase

In short, we need to set font while creating Phrase, not afterwards like with .setFont

new Phrase(cellData, font);


问:
Azure Data Factory Pricing - Activity Count
I'm thinking of using Data Factory in order to copy data from a Blob Storage container to an SQL table but I'm not quite sure I understand how the pricing works, specifically how the activities are counted.

So if I have a pipeline with 3 activities that copies the data from a CSV with 1000 lines will the total activity count be 3*1 or 3*1000? In other words, will I be charged based on the number o files it processes or the total number of lines it copies?

答:
That's 3 activity runs. Activity runs are measured by the thousand, at $1 per. Since these are Copy activities, they consume Data Integration Units (DIU) at $.25 per hour. Pipeline execution time is billed at $.005 per hour. If you add all this up for 1 pipeline with 3 Copy activities that runs for 1 hour, your total bill is like 27 cents.

We run THOUSANDS of pipelines a month, all with many activities including quite a few Copy activities. Our Data Factory billing is still so low that it looks like a rounding error in our total Azure spend.

The exception to this is Data Flow. Data Flow is a Spark wrapper, so you have to pay for Cluster time, which can get expensive quickly if you aren't careful.


问:
Selenium Webdriver click and send keys etc dont work on Google Chrome Version 78.0.3904.87
Google chrome automatically updated to Version 78.0.3904.87 yesterday and i now seem to have a problem with Selenium Webdriver.

When i run my tests in Visual Studio, the click events seem to occur but the expected result on screen does not happen e.g. clicking a link passes through the code (link.Click) successfully with no failure but the link does not get clicked on screen.

When i run the same test in Debug mode and Step Into each section of code it works fine, its as if selenium is running too fast for the browser (i have an implicit wait built in but its irrelevant, the element is there its just not clicking properly). I'm also finding things like sendKeys does not populate the field though it passes through the code successfully, again fine when stepping into it in Debug mode.

I've tried updating my Chromedriver to the version for V78 but this has made no difference

Similar problem here but my issue is not restricted to pdfs only
Chromedriver 78 cant find element in pdf

答:
I finally got to the bottom of this with our setup and it turned out to be the --enable-automation flag that seemed to be causing page flickering on page load.
After adding excludeSwitches: ['enable-automation'] to my config it has resolved the issue.</p>


问:
Git short command for checking out, pulling, prune fetching and deleting
Is there a shortcut for:

Checking out on master

Pulling from master

Prune Fetch (check which remote branches are removed)

Delete those local branches

Scenario:
Let's say I'm on master and I checkout on the branch foo, I do some commits and publish foo to remote and push to it as well. Next I merge that branch to master on GitHub and delete the online version of foo since it's complete. Now in the offline environment, I have to do the following:

$ git checkout master
$ git pull
$ git fetch -p
$ git branch -d foo
```

<p>or shorthand:</p>

```git checkout master && git pull && git fetch -p && git branch -D foo
```

<p>Is there a command I can execute to make this much shorter? Like</p>

<pre class="lang-sh prettyprint-override"><code>$ git complete foo
</code>```

or something along those lines..?

答:
aliases can be used for solving this problem.

An alias can be created by running:

```<code>$ alias cpfb="git checkout master && git pull && git fetch -p && git branch -D"
</code>```

Now, you can execute

```<code>$ cpfb foo
</code>```

which will execute those commands specified in the alias.

Setting alias through terminal lasts for only that particular terminal instance.

Hence, save them in ~/.bashrc to make the alias permanent.

Body:
Is there a shortcut for:

Checking out on master

Pulling from master

Prune Fetch (check which remote branches are removed)

Delete those local branches

Scenario:
Let's say I'm on master and I checkout on the branch foo, I do some commits and publish foo to remote and push to it as well. Next I merge that branch to master on GitHub and delete the online version of foo since it's complete. Now in the offline environment, I have to do the following:

$ git checkout master
$ git pull
$ git fetch -p
$ git branch -d foo

or shorthand:

git checkout master && git pull && git fetch -p && git branch -D foo

Is there a command I can execute to make this much shorter? Like

$ git complete foo

or something along those lines..?

Body:
aliases can be used for solving this problem.

An alias can be created by running:

$ alias cpfb="git checkout master && git pull && git fetch -p && git branch -D"

Now, you can execute

$ cpfb foo

which will execute those commands specified in the alias.

Setting alias through terminal lasts for only that particular terminal instance.

Hence, save them in ~/.bashrc to make the alias permanent.


问:
Improve HL7 FHIR ContactPoint Extension: TEL-address example
I've reviewing the FHIR Extension: TEL-address (https://www.hl7.org/fhir/extension-iso21090-tel-address.html) and at the sample section (https://www.hl7.org/fhir/datatypes-examples.html#ContactPoint) I guess there is a mistake, as valueUrl must be used instead of valueUri.

Hope useful

Martí

答: Thanks.  Please use the 'propose a change' link at the bottom of any page in the FHIR specification to submit a change request.  There's a 1-time free registration (where we verify you're a human), after which you're free to submit any issues you find.</p>


问:
Substitute bitwise operation in ESLint
I'm trying to apply this code: How to get X Y Z coordinates of tile by click on Leaflet map - which contains bitwise operator "<<". In the environment that I'm running it on (NodeJS, ExpressJS, AngularJS), codes are checked by ESLint upon compiling it but I need the solution given on the link. I get this error on compilation .

Unexpected use of '<<'  no-bitwise

According to this link: http://eslint.org/docs/rules/no-bitwise - ESLint disallows bitwise operators. Is there any way to bypass this rule or if not, provide an alternate calculation  that produces similar results to bitwise operation '<<'?

I hope my question is clear, thanks.

答:
For power of two you can use Math.pow

```<code>const scale = Math.pow( 2, zoom );
</code>```

ContentLicense: CC BY-SA 3.0

Title: Substitute bitwise operation in ESLint

Body:
For power of two you can use Math.pow

const scale = Math.pow( 2, zoom );


问:
Can you explain what this line does in Matlab
I'm new to Matlab and I'm just stuck with this line of code:

```<code>[r,c] = find(abs(fh) <= 2 );
</code>```

Beware: ironically it was easy for me understanding what the right part of the assignment is.

The left part however (which is maybe the definition of a variable)... I don't know how to search because I have too generic results by googling just square brackets with something inside.

My assumption is this line of code is creating some a matrix with r rows and c columns but r and c are nowhere to be found in the rest of the code.... or maybe it's a simple array with two elements... but it doesn't make much sense to me honestly.

Can you guys help me please?

答:
Take a look in Matlab find() docs.

If X is a vector, then find returns a vector with the same    orientation as X.

If X is a multidimensional array, then find returns a column vector of the linear indices of the result.

If X contains no nonzero elements or is empty, then find returns an empty array.

If you call

```<code>X = [18 3 1 11;
     8 10 11 3;
     9 14 6  1;
     4 3 15 21 ]

[row,col] = find(X>0 & X<10,3)
</code>```

You will get:

```<code>row = 3×1

     2
     3
     4

col = 3×1

     1
     1
     1
</code>```

Which represents the index (row number and column number) of each elements that satifies the condition you defined. Since it returns more than 1 value, you can divide the output in two different variables and that is what the left side represents.

Body:
I'm new to Matlab and I'm just stuck with this line of code:

[r,c] = find(abs(fh) <= 2 );

Beware: ironically it was easy for me understanding what the right part of the assignment is.

The left part however (which is maybe the definition of a variable)... I don't know how to search because I have too generic results by googling just square brackets with something inside.

My assumption is this line of code is creating some a matrix with r rows and c columns but r and c are nowhere to be found in the rest of the code.... or maybe it's a simple array with two elements... but it doesn't make much sense to me honestly.

Can you guys help me please?

Body:
Take a look in Matlab find() docs.

If X is a vector, then find returns a vector with the same    orientation as X.

If X is a multidimensional array, then find returns a column vector of the linear indices of the result.

If X contains no nonzero elements or is empty, then find returns an empty array.

If you call

X = [18 3 1 11;
     8 10 11 3;
     9 14 6  1;
     4 3 15 21 ]

[row,col] = find(X>0 & X<10,3)

You will get:

row = 3×1

     2
     3
     4

col = 3×1

     1
     1
     1

Which represents the index (row number and column number) of each elements that satifies the condition you defined. Since it returns more than 1 value, you can divide the output in two different variables and that is what the left side represents.


问:
Issues with labels in ggplot bar chart
I currently have a data frame that has structure as below:

```<code>  Establishment.date Species  Shade.Tol         Ele    Kipuka
1                1980  PSEMEN Intolerant Under 1050m On Kipuka
2                1981  PINCON Intolerant Above 1050m On Kipuka
3                1981  ABIPRO Intolerant Under 1050m On Kipuka
4                1981  ABIPRO Intolerant Under 1050m On Kipuka
5                1981  ABILAS   Tolerant Above 1050m On Kipuka
6                1982  ABILAS   Tolerant Above 1050m On Kipuka
7                1983  PSEMEN Intolerant Under 1050m On Kipuka
8                1984  TSUHET   Tolerant Under 1050m On Kipuka
9                1984  TSUHET   Tolerant Under 1050m On Kipuka
10               1984  PSEMEN Intolerant Under 1050m On Kipuka
11               1984  PINCON Intolerant Under 1050m On Kipuka
12               1984  ABIPRO Intolerant Above 1050m On Kipuka
13               1984  ABIPRO Intolerant Above 1050m On Kipuka
</code>```

I am trying to make a bar plot to highlight the number of establishments that occurred at both high and low elevations faceted by their shade tolerance and showing the count of each class as a label. My current approach is filtering the data frame to have a new summarized data frame as below as below:

```<code># A tibble: 9 x 4
# Groups:   Establishment.date, Shade.Tol [7]
  Establishment.date Shade.Tol  Ele         count
               <int> <fct>      <fct>       <int>
1               1980 Intolerant Under 1050m     1
2               1981 Intolerant Above 1050m     1
3               1981 Intolerant Under 1050m     2
4               1981 Tolerant   Above 1050m     1
5               1982 Tolerant   Above 1050m     1
6               1983 Intolerant Under 1050m     1
7               1984 Intolerant Above 1050m     2
8               1984 Intolerant Under 1050m     2
9               1984 Tolerant   Under 1050m     2
</code>```

and plotting that new information into ggplot as follows:

```<code>cores_clean %>%
  group_by(Establishment.date,Shade.Tol,Ele) %>%
  summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count, label=count)) +
  geom_bar(stat = "identity",position = "dodge") +
  geom_text(aes(label=count),size = 3)+
  facet_wrap(~ Shade.Tol)+
  #scale_fill_grey()+
  theme_bw() +
  labs(x = "Elevation Range",
       y = "Count",
       title = "Establishments")+
  theme(plot.title = element_text(hjust = 0.5))
</code>```

But when I run the code, the graphic output prints a stacked line of values as below,

which do not represent those found in the data frame (n=740). I tried adding geom_text(aes(label=sum(count))) but that printed the same positioning of numbers with the total number of observations repeated multiple times. Not sure if I am filtering the data wrong or not adding it to ggplot correctly.

答:
Your main issue is that you group_by(Estabilishment.date), but you don't seem to even want that in your graph. Here is one option that uses stat_summary to calculate the sums:

```<code>cores_clean %>%
  group_by(Establishment.date,Shade.Tol,Ele) %>%
  dplyr::summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count, fill = as.factor(Establishment.date))) +
  geom_bar(stat = "identity") +
  stat_summary(geom = "text", aes(label = ..y.., group = Ele),
               fun = sum, vjust = -0.1) +
  facet_wrap(~ Shade.Tol) +
  theme_bw() +
  labs(x = "Elevation Range", y = "Count",
       title = "Establishments", fill = "Year")+
  theme(plot.title = element_text(hjust = 0.5))
</code>```

Alternatively, you could remove Estabilishment.date from your group_by and do this:

```<code>cores_clean %>%
  group_by(Shade.Tol,Ele) %>%
  dplyr::summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count)) +
  geom_bar(stat = "identity") +
  stat_summary(geom = "text", aes(label = ..y.., group = Ele),
               fun = sum, vjust = -0.1) +
  facet_wrap(~ Shade.Tol) +
  theme_bw() +
  labs(x = "Elevation Range", y = "Count",
       title = "Establishments")+
  theme(plot.title = element_text(hjust = 0.5))
</code>```

Title: Issues with labels in ggplot bar chart

Body:
I currently have a data frame that has structure as below:

  Establishment.date Species  Shade.Tol         Ele    Kipuka
1                1980  PSEMEN Intolerant Under 1050m On Kipuka
2                1981  PINCON Intolerant Above 1050m On Kipuka
3                1981  ABIPRO Intolerant Under 1050m On Kipuka
4                1981  ABIPRO Intolerant Under 1050m On Kipuka
5                1981  ABILAS   Tolerant Above 1050m On Kipuka
6                1982  ABILAS   Tolerant Above 1050m On Kipuka
7                1983  PSEMEN Intolerant Under 1050m On Kipuka
8                1984  TSUHET   Tolerant Under 1050m On Kipuka
9                1984  TSUHET   Tolerant Under 1050m On Kipuka
10               1984  PSEMEN Intolerant Under 1050m On Kipuka
11               1984  PINCON Intolerant Under 1050m On Kipuka
12               1984  ABIPRO Intolerant Above 1050m On Kipuka
13               1984  ABIPRO Intolerant Above 1050m On Kipuka

I am trying to make a bar plot to highlight the number of establishments that occurred at both high and low elevations faceted by their shade tolerance and showing the count of each class as a label. My current approach is filtering the data frame to have a new summarized data frame as below as below:

# A tibble: 9 x 4
# Groups:   Establishment.date, Shade.Tol [7]
  Establishment.date Shade.Tol  Ele         count
               <int> <fct>      <fct>       <int>
1               1980 Intolerant Under 1050m     1
2               1981 Intolerant Above 1050m     1
3               1981 Intolerant Under 1050m     2
4               1981 Tolerant   Above 1050m     1
5               1982 Tolerant   Above 1050m     1
6               1983 Intolerant Under 1050m     1
7               1984 Intolerant Above 1050m     2
8               1984 Intolerant Under 1050m     2
9               1984 Tolerant   Under 1050m     2

and plotting that new information into ggplot as follows:

cores_clean %>%
  group_by(Establishment.date,Shade.Tol,Ele) %>%
  summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count, label=count)) +
  geom_bar(stat = "identity",position = "dodge") +
  geom_text(aes(label=count),size = 3)+
  facet_wrap(~ Shade.Tol)+
  #scale_fill_grey()+
  theme_bw() +
  labs(x = "Elevation Range",
       y = "Count",
       title = "Establishments")+
  theme(plot.title = element_text(hjust = 0.5))

But when I run the code, the graphic output prints a stacked line of values as below,

which do not represent those found in the data frame (n=740). I tried adding geom_text(aes(label=sum(count))) but that printed the same positioning of numbers with the total number of observations repeated multiple times. Not sure if I am filtering the data wrong or not adding it to ggplot correctly.

Body:
Your main issue is that you group_by(Estabilishment.date), but you don't seem to even want that in your graph. Here is one option that uses stat_summary to calculate the sums:

cores_clean %>%
  group_by(Establishment.date,Shade.Tol,Ele) %>%
  dplyr::summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count, fill = as.factor(Establishment.date))) +
  geom_bar(stat = "identity") +
  stat_summary(geom = "text", aes(label = ..y.., group = Ele),
               fun = sum, vjust = -0.1) +
  facet_wrap(~ Shade.Tol) +
  theme_bw() +
  labs(x = "Elevation Range", y = "Count",
       title = "Establishments", fill = "Year")+
  theme(plot.title = element_text(hjust = 0.5))

Alternatively, you could remove Estabilishment.date from your group_by and do this:

cores_clean %>%
  group_by(Shade.Tol,Ele) %>%
  dplyr::summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count)) +
  geom_bar(stat = "identity") +
  stat_summary(geom = "text", aes(label = ..y.., group = Ele),
               fun = sum, vjust = -0.1) +
  facet_wrap(~ Shade.Tol) +
  theme_bw() +
  labs(x = "Elevation Range", y = "Count",
       title = "Establishments")+
  theme(plot.title = element_text(hjust = 0.5))


问:
How to show the row or line number in powershell format-table
I'd like the data presented by format-table to include the line or row number of the items.
How can I achieve this?

some-command | ft

```<code>Line    Something       Else
----    ---------       ----
0       Item1           Property1
1       Item2           Property2
</code>```

答:
I believe you are looking something like this: </p>

```<code>[ref]$id = 0 ; @( @{ youritems='a' }, @{ youritems='b' }, @{ youritems='c' }) |ForEach-Object{ new-object PSObject -Property $_ } | Format-Table @{ n="SerialNumber"; e={ "{0}" -f ++$id.value }; a="left" },youritems
</code>```

<p>The output would be : </p>

```<code>SerialNumber youritems
------------- ---------
1             a
2             b
3             c
</code>```

Body:
I'd like the data presented by format-table to include the line or row number of the items.
How can I achieve this?

some-command | ft

Line    Something       Else
----    ---------       ----
0       Item1           Property1
1       Item2           Property2

Body:
I believe you are looking something like this:

[ref]$id = 0 ; @( @{ youritems='a' }, @{ youritems='b' }, @{ youritems='c' }) |ForEach-Object{ new-object PSObject -Property $_ } | Format-Table @{ n="SerialNumber"; e={ "{0}" -f ++$id.value }; a="left" },youritems

The output would be :

SerialNumber youritems
------------- ---------
1             a
2             b
3             c


问:
Nock reply with 302 and 404 throws an HTTPError
I am making a function that should retry on 302 err code and return data on 200, else just throw an error.

```<code>  async retry(url: string): Promise<Response<string>> {
      const response = await got.get(url)
      switch(res.statusCode){
        case 200: {
          return response
        }
        case 302: {
          -> call login
          -> call retry again with retry(url)
        }
        default: {
          throw error
        }
      }
    }
</code>```

Problem is when I setup nock like this

```<code>const scope = nock('https://airtable.com')
  .get(`/${baseID}/api/docs`)
  .reply(302)
})

</code>```

Problem is that it cannot even call retry because mock returns 302 status code which internally for him throws an HTTPError which is not wanted behavior here, so is there to add tell him not to throw errors?

答:
This is happening because of the default behavior of Got.
It throws errors for certain status codes it deems an error.

You can configure Got to not throw errors based on status codes by setting the throwHttpErrors option (docs).

Body:
I am making a function that should retry on 302 err code and return data on 200, else just throw an error.

  async retry(url: string): Promise<Response<string>> {
      const response = await got.get(url)
      switch(res.statusCode){
        case 200: {
          return response
        }
        case 302: {
          -> call login
          -> call retry again with retry(url)
        }
        default: {
          throw error
        }
      }
    }

Problem is when I setup nock like this

const scope = nock('https://airtable.com')
  .get(`/${baseID}/api/docs`)
  .reply(302)
})

Problem is that it cannot even call retry because mock returns 302 status code which internally for him throws an HTTPError which is not wanted behavior here, so is there to add tell him not to throw errors?


问:
Assigning callbacks for a $.post call in jQuery
I have this script that works pretty well, but it keeps triggering the "error" callback, even though there is no error:

```<code>$(".comment-form").submit(function(e) {
    e.preventDefault();

    var $form = $(this),
        text = $form.find('textarea').val();
        url = $form.attr('action');

    $.post(url, { comment: text,
        beforeSend: function() {
            alert("before send");
        },
        error: function() {
            alert("error");
        },
        success: function(data) {
            alert(data);
        }
    });
});
</code>```

Am I using the callbacks incorrectly here? Shouldn't the error callback fire only if there's an ajax error?

My intention is react to the request. If it has an error, I want to do something. If it's successful, I want to do something else, etc...

答:
```<code>  $.post("example.php", { comment: "my comment" }, function() {
    alert("success"); })
    .success(function() { alert("second success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete");
  });
</code>```

edit: added post data to callback

Body:
I have this script that works pretty well, but it keeps triggering the "error" callback, even though there is no error:

$(".comment-form").submit(function(e) {
    e.preventDefault();

    var $form = $(this),
        text = $form.find('textarea').val();
        url = $form.attr('action');

    $.post(url, { comment: text,
        beforeSend: function() {
            alert("before send");
        },
        error: function() {
            alert("error");
        },
        success: function(data) {
            alert(data);
        }
    });
});

Am I using the callbacks incorrectly here? Shouldn't the error callback fire only if there's an ajax error?

My intention is react to the request. If it has an error, I want to do something. If it's successful, I want to do something else, etc...

Body:
  $.post("example.php", { comment: "my comment" }, function() {
    alert("success"); })
    .success(function() { alert("second success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete");
  });

edit: added post data to callback


问:
How to iterate over a selector?
I am creating a copy of whatsappweb and I am in the component of listing all the latest messages from friends of the "user main".

I always insert all selector results from app.component, but this time I have to insert this logic into my dumb component, as it needs a user's id to be able to render the information.

And I fell into a curiosity, which is:

I have a list of users and I need to iterate under it to get the id of each user and be able to intersect the data to get the latest messages etc.

How can I do this?

HTML:

```<code><ul>
    <li *ngFor="let user of userFriends">
        <app-avatar [isBig]="true" [src]="user.avatar" [alt]="user.full_name"></app-avatar>
        <app-userfriend-last-messages-container
            [isNewLastMessage]="false"
            [username]="user.full_name"
            [lastmessage]="chatSelectorsService.getLastFriendMessage(userId).id | async"
        ></app-userfriend-last-messages-container>
        <app-userfriend-last-messages-information-container
            [isNewLastMessage]="false"
            [lastMessageTime]="chatSelectorsService.getLastFriendMessage(userId).time | async"
            [lastMessageAmount]="9"
        ></app-userfriend-last-messages-information-container>
    </li>
</ul>
</code>```

TS:

```<code>@Component({
    selector: 'app-last-messages-list',
    templateUrl: './last-messages-list.component.html',
    styleUrls: ['./last-messages-list.component.scss'],
})
export class LastMessagesListComponent implements OnInit {
    @Input() userFriends: IUser[];
    @Input() chatLastMessages: IChatMessage[];

    constructor(readonly chatSelectorsService: ChatSelectorsService) {}

    ngOnInit(): void {}
}
</code>```

答:
try to keep just 1 async pipe in the template that fetches all information it needs, your template could be

        <app-avatar [isBig]="true" [src]="user.avatar" [alt]="user.full_name"></app-avatar>
        <app-userfriend-last-messages-container
            [isNewLastMessage]="false"
            [username]="user.full_name"
            [lastmessage]="user.lastmessage"
        ></app-userfriend-last-messages-container>
        <app-userfriend-last-messages-information-container
            [isNewLastMessage]="false"
            [lastMessageTime]="user.lastMessageTime"
            [lastMessageAmount]="9"
        ></app-userfriend-last-messages-information-container>

```

<p>and in your component you should add <code>data$</code> that aggregates all data you need for the template.</p>

<pre class="lang-js prettyprint-override"><code>@Component({
    selector: 'app-last-messages-list',
    templateUrl: './last-messages-list.component.html',
    styleUrls: ['./last-messages-list.component.scss'],
})
export class LastMessagesListComponent implements OnInit, OnChanges {
    @Input() userFriends: IUser[];
    @Input() chatLastMessages: IChatMessage[];

    // internal subject to notify on changes of userFriends
    protected userFriends$ = new Subject();

    // our stream that provides data for the template asynchronously.
    public readonly data$ = this.userFriends$.pipe(
        filter(users => Array.isArray(users)),
        switchMap(users => {
            const data = [];
            for (const user of users) {
                data.push(chatSelectorsService.getLastFriendMessage(user.id).pipe(
                    map(lastMessage => ({
                        ...user,
                        lastmessage: lastMessage ? lastMessage.id : undefined,
                        lastMessageTime: lastMessage ? lastMessage.time : undefined,
                    })),
                ));
            }
            return combineLatest(data);
        }),
        map(userFriends => ({userFriends})),
    );

    constructor(readonly chatSelectorsService: ChatSelectorsService) {}

    ngOnInit(): void {
        this.userFriends$.next(this.userFriends);
    }

    // listening on changes of the input.
    public ngOnChanges(changes: SimpleChanges): void {
        if (changes.userFriends && changes.userFriends.currentValue !== changes.userFriends.previousValue) {
            this.userFriends$.next(changes.userFriends.currentValue);
        }
    }
}
</code>```

Title: How to iterate over a selector?

Body:
I am creating a copy of whatsappweb and I am in the component of listing all the latest messages from friends of the "user main".

I always insert all selector results from app.component, but this time I have to insert this logic into my dumb component, as it needs a user's id to be able to render the information.

And I fell into a curiosity, which is:

I have a list of users and I need to iterate under it to get the id of each user and be able to intersect the data to get the latest messages etc.

How can I do this?

HTML:

        <app-avatar [isBig]="true" [src]="user.avatar" [alt]="user.full_name"></app-avatar>
        <app-userfriend-last-messages-container
            [isNewLastMessage]="false"
            [username]="user.full_name"
            [lastmessage]="chatSelectorsService.getLastFriendMessage(userId).id | async"
        ></app-userfriend-last-messages-container>
        <app-userfriend-last-messages-information-container
            [isNewLastMessage]="false"
            [lastMessageTime]="chatSelectorsService.getLastFriendMessage(userId).time | async"
            [lastMessageAmount]="9"
        ></app-userfriend-last-messages-information-container>

TS:

@Component({
    selector: 'app-last-messages-list',
    templateUrl: './last-messages-list.component.html',
    styleUrls: ['./last-messages-list.component.scss'],
})
export class LastMessagesListComponent implements OnInit {
    @Input() userFriends: IUser[];
    @Input() chatLastMessages: IChatMessage[];

    constructor(readonly chatSelectorsService: ChatSelectorsService) {}

    ngOnInit(): void {}
}

Body:
try to keep just 1 async pipe in the template that fetches all information it needs, your template could be

<ul *ngIf="data$ | async as data">
    <li *ngFor="let user of data.userFriends">
        <app-avatar [isBig]="true" [src]="user.avatar" [alt]="user.full_name"></app-avatar>
        <app-userfriend-last-messages-container
            [isNewLastMessage]="false"
            [username]="user.full_name"
            [lastmessage]="user.lastmessage"
        ></app-userfriend-last-messages-container>
        <app-userfriend-last-messages-information-container
            [isNewLastMessage]="false"
            [lastMessageTime]="user.lastMessageTime"
            [lastMessageAmount]="9"
        ></app-userfriend-last-messages-information-container>
    </li>
</ul>

and in your component you should add data$ that aggregates all data you need for the template.

@Component({
    selector: 'app-last-messages-list',
    templateUrl: './last-messages-list.component.html',
    styleUrls: ['./last-messages-list.component.scss'],
})
export class LastMessagesListComponent implements OnInit, OnChanges {
    @Input() userFriends: IUser[];
    @Input() chatLastMessages: IChatMessage[];

    // internal subject to notify on changes of userFriends
    protected userFriends$ = new Subject();

    // our stream that provides data for the template asynchronously.
    public readonly data$ = this.userFriends$.pipe(
        filter(users => Array.isArray(users)),
        switchMap(users => {
            const data = [];
            for (const user of users) {
                data.push(chatSelectorsService.getLastFriendMessage(user.id).pipe(
                    map(lastMessage => ({
                        ...user,
                        lastmessage: lastMessage ? lastMessage.id : undefined,
                        lastMessageTime: lastMessage ? lastMessage.time : undefined,
                    })),
                ));
            }
            return combineLatest(data);
        }),
        map(userFriends => ({userFriends})),
    );

    constructor(readonly chatSelectorsService: ChatSelectorsService) {}

    ngOnInit(): void {
        this.userFriends$.next(this.userFriends);
    }

    // listening on changes of the input.
    public ngOnChanges(changes: SimpleChanges): void {
        if (changes.userFriends && changes.userFriends.currentValue !== changes.userFriends.previousValue) {
            this.userFriends$.next(changes.userFriends.currentValue);
        }
    }
}


问:
Angular2: how to add/change css style in svg?
I have the following code to add svg to angular2 component's template:

```<code><object type="image/svg+xml" data="kiwi.svg" class="logo">
  Kiwi Logo
</object>
</code>```

In order to add css style on the fly, I tried several ways to get  contents:

1)

```<code>public ngAfterViewInit(): void {
        this.el = this._doc.getElementsByTagName('svg');
        console.log(this.el);
    }
</code>```

result in console: [ ]

2)

```<code>public ngAfterViewInit(): void {
  this.el = this._elementRef.nativeElement.querySelector('object');
  console.log(this.el);
}
</code>```

result in console: null

Question:

Can anyone help me about how to access svg and how to change css style in typescript?

答:
There are two issues here:
First you are not using an inline svg therefore as cited here
Changing color of SVG which was embedded using <object>, so you won't be able to change the svg styles, such as the fill of the element.
This is not an angular problem.

To do this in angular in a practical way I suggest creating a component which has the full svg on its html:

svg-component.html

<svg.... [style.fill]="color"/></svg>
```

<p>svg-component.ts,</p>

<pre class="lang-js prettyprint-override"><code>// svg-component.ts, where we  map to inputs these properties for easy
import { Component, OnInit, Input } from '@angular/core';

@Component({
 ...
})
export class SvgComponent implements OnInit {
  @Input color = '#fff';
  ...
}
</code>```

Usage:

```<code><svg-component color="#000"></svg-component>
</code>```

.

Another idea would be to try copying the approach of icon libraries and create a font, but unless its a very large collection and you want to use fonts css properties and almost create a library I would vote against it.

Body:
I have the following code to add svg to angular2 component's template:

<object type="image/svg+xml" data="kiwi.svg" class="logo">
  Kiwi Logo
</object>

In order to add css style on the fly, I tried several ways to get  contents:

1)

public ngAfterViewInit(): void {
        this.el = this._doc.getElementsByTagName('svg');
        console.log(this.el);
    }

result in console: [ ]

2)

public ngAfterViewInit(): void {
  this.el = this._elementRef.nativeElement.querySelector('object');
  console.log(this.el);
}

result in console: null

Question:

Can anyone help me about how to access svg and how to change css style in typescript?

Body:
There are two issues here:
First you are not using an inline svg therefore as cited here
Changing color of SVG which was embedded using <object>, so you won't be able to change the svg styles, such as the fill of the element.
This is not an angular problem.

To do this in angular in a practical way I suggest creating a component which has the full svg on its html:

svg-component.html

<!-- svg-component.html, where we bind some properties of the svg-->
<svg.... [style.fill]="color"/></svg>

svg-component.ts,

// svg-component.ts, where we  map to inputs these properties for easy
import { Component, OnInit, Input } from '@angular/core';

@Component({
 ...
})
export class SvgComponent implements OnInit {
  @Input color = '#fff';
  ...
}

Usage:

<svg-component color="#000"></svg-component>

.

Another idea would be to try copying the approach of icon libraries and create a font, but unless its a very large collection and you want to use fonts css properties and almost create a library I would vote against it.


问:
How to access hystrix dashboard?
I added following dependency to my spring boot aplication:

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>
</code>```

And marked configuration class with :

```<code>@EnableHystrixDashboard
@EnableHystrix
</code>```

I try to access http://localhost:8080/hystrix   (I also tried http://localhost:8081/hystrix)

and I see:

Whitelabel Error Page This application has no explicit mapping for
  /error, so you are seeing this as a fallback.

Mon Nov 11 21:47:56 MSK 2019 There was an unexpected error (type=Not
  Found, status=404). No message available

During startup I see following messages:

```<code>2019-11-11 21:43:17.724  INFO 15912 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-11-11 21:43:22.581  INFO 15912 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-11-11 21:43:23.362  INFO 15912 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2019-11-11 21:43:23.507  INFO 15912 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
</code>```

How to acces hystrix dashboard?

P.S.

In debug I see that these methods are invoked but anyway I see error:

Also I see following response when I access URL: http://localhost:8080/actuator/hystrix.stream

```<code>data: {"type":"HystrixCommand","name":"executeHttpCall","group":"MyAPIConnectorImpl","currentTime":1573503001364,"isCircuitBreakerOpen":false,"errorPercentage":0,"errorCount":0,"requestCount":0,"rollingCountBadRequests":0,"rollingCountCollapsedRequests":0,"rollingCountEmit":0,"rollingCountExceptionsThrown":0,"rollingCountFailure":0,"rollingCountFallbackEmit":0,"rollingCountFallbackFailure":0,"rollingCountFallbackMissing":0,"rollingCountFallbackRejection":0,"rollingCountFallbackSuccess":0,"rollingCountResponsesFromCache":0,"rollingCountSemaphoreRejected":0,"rollingCountShortCircuited":0,"rollingCountSuccess":0,"rollingCountThreadPoolRejected":0,"rollingCountTimeout":0,"currentConcurrentExecutionCount":0,"rollingMaxConcurrentExecutionCount":0,"latencyExecute_mean":948,"latencyExecute":{"0":16,"25":18,"50":23,"75":1008,"90":3767,"95":3767,"99":3767,"99.5":3767,"100":3767},"latencyTotal_mean":950,"latencyTotal":{"0":16,"25":18,"50":24,"75":1019,"90":3767,"95":3767,"99":3767,"99.5":3767,"100":3767},"propertyValue_circuitBreakerRequestVolumeThreshold":20,"propertyValue_circuitBreakerSleepWindowInMilliseconds":5000,"propertyValue_circuitBreakerErrorThresholdPercentage":50,"propertyValue_circuitBreakerForceOpen":false,"propertyValue_circuitBreakerForceClosed":false,"propertyValue_circuitBreakerEnabled":true,"propertyValue_executionIsolationStrategy":"THREAD","propertyValue_executionIsolationThreadTimeoutInMilliseconds":1000,"propertyValue_executionTimeoutInMilliseconds":1000,"propertyValue_executionIsolationThreadInterruptOnTimeout":true,"propertyValue_executionIsolationThreadPoolKeyOverride":null,"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"propertyValue_requestCacheEnabled":true,"propertyValue_requestLogEnabled":true,"reportingHosts":1,"threadPool":"MyAPIConnectorImpl"}

data: {"type":"HystrixThreadPool","name":"MyAPIConnectorImpl","currentTime":1573503001364,"currentActiveCount":0,"currentCompletedTaskCount":18,"currentCorePoolSize":10,"currentLargestPoolSize":10,"currentMaximumPoolSize":10,"currentPoolSize":10,"currentQueueSize":0,"currentTaskCount":18,"rollingCountThreadsExecuted":0,"rollingMaxActiveThreads":0,"rollingCountCommandRejections":0,"propertyValue_queueSizeRejectionThreshold":5,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"reportingHosts":1}

ping:
</code>```

In debug log I see:

```<code>2019-11-11 23:41:28.436 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : GET "/hystrix/index", parameters={}
2019-11-11 23:41:28.447 DEBUG 6604 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.cloud.netflix.hystrix.dashboard.HystrixDashboardController#monitor(String, Model, WebRequest)
2019-11-11 23:41:28.480 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [hystrix/index_ru_RU.ftlh]
2019-11-11 23:41:28.482 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [hystrix/index_ru.ftlh]
2019-11-11 23:41:28.482 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [hystrix/index.ftlh]
2019-11-11 23:41:28.485 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, image/apng, application/signed-exchange;v=b3, application/xml;q=0.9, */*;q=0.8]
2019-11-11 23:41:28.485 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView  : View name 'hystrix/index', model {basePath=/hystrix/index, contextPath=}
2019-11-11 23:41:28.487 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView  : Forwarding to [hystrix/index]
2019-11-11 23:41:28.491 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : "FORWARD" dispatch for GET "/hystrix/hystrix/index", parameters={}
2019-11-11 23:41:28.494 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-11-11 23:41:28.497 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
2019-11-11 23:41:28.498 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Exiting from "FORWARD" dispatch, status 404
2019-11-11 23:41:28.499 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 404 NOT_FOUND
2019-11-11 23:41:28.502 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/error", parameters={}
2019-11-11 23:41:28.503 DEBUG 6604 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2019-11-11 23:41:28.513 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [error_ru_RU.ftlh]
2019-11-11 23:41:28.514 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [error_ru.ftlh]
2019-11-11 23:41:28.514 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [error.ftlh]
2019-11-11 23:41:28.515 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2019-11-11 23:41:28.519 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 404
</code>```

答:
I had the same problem which got fixed using the below steps

Add the below annotations to the SpringBootApplication -- Where main method is present

@EnableHystrixDashboard

@EnableHystrix

In pom.xml

        org.springframework.cloud
        spring-cloud-netflix-hystrix-dashboard

    org.springframework.boot
    spring-boot-starter-actuator

In application.properties

management.endpoints.web.exposure.include=hystrix.stream

Hit the URL

http://localhost:8081/hystrix

You should be able to see Hystrix Dashboard

Title: How to access hystrix dashboard?

Body:
I added following dependency to my spring boot aplication:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>

And marked configuration class with :

@EnableHystrixDashboard
@EnableHystrix

I try to access http://localhost:8080/hystrix   (I also tried http://localhost:8081/hystrix)

and I see:

Whitelabel Error Page This application has no explicit mapping for
  /error, so you are seeing this as a fallback.

Mon Nov 11 21:47:56 MSK 2019 There was an unexpected error (type=Not
  Found, status=404). No message available

During startup I see following messages:

2019-11-11 21:43:17.724  INFO 15912 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-11-11 21:43:22.581  INFO 15912 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-11-11 21:43:23.362  INFO 15912 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2019-11-11 21:43:23.507  INFO 15912 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''

How to acces hystrix dashboard?

P.S.

In debug I see that these methods are invoked but anyway I see error:

Also I see following response when I access URL: http://localhost:8080/actuator/hystrix.stream

data: {"type":"HystrixCommand","name":"executeHttpCall","group":"MyAPIConnectorImpl","currentTime":1573503001364,"isCircuitBreakerOpen":false,"errorPercentage":0,"errorCount":0,"requestCount":0,"rollingCountBadRequests":0,"rollingCountCollapsedRequests":0,"rollingCountEmit":0,"rollingCountExceptionsThrown":0,"rollingCountFailure":0,"rollingCountFallbackEmit":0,"rollingCountFallbackFailure":0,"rollingCountFallbackMissing":0,"rollingCountFallbackRejection":0,"rollingCountFallbackSuccess":0,"rollingCountResponsesFromCache":0,"rollingCountSemaphoreRejected":0,"rollingCountShortCircuited":0,"rollingCountSuccess":0,"rollingCountThreadPoolRejected":0,"rollingCountTimeout":0,"currentConcurrentExecutionCount":0,"rollingMaxConcurrentExecutionCount":0,"latencyExecute_mean":948,"latencyExecute":{"0":16,"25":18,"50":23,"75":1008,"90":3767,"95":3767,"99":3767,"99.5":3767,"100":3767},"latencyTotal_mean":950,"latencyTotal":{"0":16,"25":18,"50":24,"75":1019,"90":3767,"95":3767,"99":3767,"99.5":3767,"100":3767},"propertyValue_circuitBreakerRequestVolumeThreshold":20,"propertyValue_circuitBreakerSleepWindowInMilliseconds":5000,"propertyValue_circuitBreakerErrorThresholdPercentage":50,"propertyValue_circuitBreakerForceOpen":false,"propertyValue_circuitBreakerForceClosed":false,"propertyValue_circuitBreakerEnabled":true,"propertyValue_executionIsolationStrategy":"THREAD","propertyValue_executionIsolationThreadTimeoutInMilliseconds":1000,"propertyValue_executionTimeoutInMilliseconds":1000,"propertyValue_executionIsolationThreadInterruptOnTimeout":true,"propertyValue_executionIsolationThreadPoolKeyOverride":null,"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"propertyValue_requestCacheEnabled":true,"propertyValue_requestLogEnabled":true,"reportingHosts":1,"threadPool":"MyAPIConnectorImpl"}

data: {"type":"HystrixThreadPool","name":"MyAPIConnectorImpl","currentTime":1573503001364,"currentActiveCount":0,"currentCompletedTaskCount":18,"currentCorePoolSize":10,"currentLargestPoolSize":10,"currentMaximumPoolSize":10,"currentPoolSize":10,"currentQueueSize":0,"currentTaskCount":18,"rollingCountThreadsExecuted":0,"rollingMaxActiveThreads":0,"rollingCountCommandRejections":0,"propertyValue_queueSizeRejectionThreshold":5,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"reportingHosts":1}

ping:

In debug log I see:

2019-11-11 23:41:28.436 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : GET "/hystrix/index", parameters={}
2019-11-11 23:41:28.447 DEBUG 6604 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.cloud.netflix.hystrix.dashboard.HystrixDashboardController#monitor(String, Model, WebRequest)
2019-11-11 23:41:28.480 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [hystrix/index_ru_RU.ftlh]
2019-11-11 23:41:28.482 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [hystrix/index_ru.ftlh]
2019-11-11 23:41:28.482 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [hystrix/index.ftlh]
2019-11-11 23:41:28.485 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, image/apng, application/signed-exchange;v=b3, application/xml;q=0.9, */*;q=0.8]
2019-11-11 23:41:28.485 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView  : View name 'hystrix/index', model {basePath=/hystrix/index, contextPath=}
2019-11-11 23:41:28.487 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView  : Forwarding to [hystrix/index]
2019-11-11 23:41:28.491 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : "FORWARD" dispatch for GET "/hystrix/hystrix/index", parameters={}
2019-11-11 23:41:28.494 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-11-11 23:41:28.497 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
2019-11-11 23:41:28.498 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Exiting from "FORWARD" dispatch, status 404
2019-11-11 23:41:28.499 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 404 NOT_FOUND
2019-11-11 23:41:28.502 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/error", parameters={}
2019-11-11 23:41:28.503 DEBUG 6604 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2019-11-11 23:41:28.513 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [error_ru_RU.ftlh]
2019-11-11 23:41:28.514 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [error_ru.ftlh]
2019-11-11 23:41:28.514 DEBUG 6604 --- [nio-8080-exec-1] o.s.ui.freemarker.SpringTemplateLoader   : Looking for FreeMarker template with name [error.ftlh]
2019-11-11 23:41:28.515 DEBUG 6604 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2019-11-11 23:41:28.519 DEBUG 6604 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 404


问:
Using Multi-threading for Slow Ms Interop
I have a program that creates two pdf files when a button is clicked. It uses Microsoft office interop in WinForms and the file creation goes like this;

User works on something in the program

Clicks the button

Program creates a word file based on a template that has bookmarks in it

Writes into the bookmarks as well as its table

Saves it as pdf

Closes active documents

Closes the word app

Closes the child form and switches to another one

*the word app is not visible to the user

It works fine on its own, but then it takes up 8 seconds to complete the two files, so I tried using multi-threading so that the user won't have to wait and can work on other things or proceed to step 1 again.

However, it throws various errors; COM, RPC, etc. even in the database connection ones, and I think the reason is that since there are two separate threads that works and it uses the same resources, some point in time the other might have close the resources that the other thread is using / about to use
So I tried using join(), so that the other thread might finish its job first, close its respective resources, then proceeds to the next one.

This works fine, IF, the user does not click the button to create another file right after the other (in a scenario that the user finishes the first step faster than expected)

The join() is sufficient enough to handle the errors as well as to work on the file creations on background, however, I want to deal with the scenario when the file creation is done right after the other, because in this scenarios, it then seems like the process is linear due to the threads waiting for each other, aside from it creates bottlenecks wherein the threads are now in line and blocks the main thread, which makes the user wait for 12 seconds or more.

What I want to know / to be clarified in is that;

Can I create those two files that uses interop use different resources so that it won’t produce errors?

Can I use or is there an alternative to join() wherein it does not block the UI thread or the main thread? So that the file creating threads just line up in background (still waits for each other to finish) without making the user wait.

Did I incorrectly use join() or the threads that ends up eating more time?

Here is my code;

Procedure and public variables in a module for creating the documents:

```<code>Public tsThread As Thread
Public psThread As Thread

Sub SaveDoc(docType,someArgs)
        Dim wordApp = New Word.Application
        Dim templateBookmarks As Word.Bookmarks
        Dim templateName As String
        Dim template As New Word.Document
        wordApp = CreateObject("Word.Application")

        Select Case docType
            Case "Type1"
                templateName = "SampleType.docx"
                template = wordApp.Documents.Add(templatePath & templateName)
                templateBookmarks = template.Bookmarks

                templateBookmarks.Item("bookmarkInWord").Range.Text = "Foo"
                template.Tables(1).Cell(msWordRow, 1).Range.Text = "Value in cell 1"
            Case "Type2"
                ‘Same thing, just different values and template
            Case "Type3"
        End select
        template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)
        wordApp.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
        wordApp.Quit()
End Sub
</code>```

Procedure in the child form when the button is clicked:

```<code>        If Not IsNothing(tsThread) Then
            If tsThread.IsAlive Then
                tsThread.Join()
            End If
        End If
        If Not IsNothing(psThread) Then
            If psThread.IsAlive Then
                psThread.Join()
            End If
        End If
        tsThread = New Thread(Sub() SaveDoc(docType1,someArgs))
        tsThread.Start()

        If Not IsNothing(tsThread) Then
            If tsThread.IsAlive Then
                tsThread.Join()
            End If
        End If
        psThread = New Thread(Sub() SaveDoc(docType2,someArgs))
        psThread.Start()

        If records = maxRecords Then
            If psThread.IsAlive or tsThread.isAlive Then
                tsThread.Join()
                psThread.Join()
                Dim fooThread = New Thread(Sub() SaveDoc(docType3,someArgs))
                fooThread.Start()
            End If
        End If
   SwitchForm("Child Form for Step 1")
   End Sub
</code>```

The errors i.e. without using the join() are commonly in these parts of code:

wordApp.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

or in

wordApp.Quit()

Or in the bookmarks

templateBookmarks.Item("bookmarkInWord").Range.Text = "Foo"

Or sometimes anywhere inside one of the cases in different timings or in database connection procedures.

I am still relatively new to multi-threading as well as in Ms Interop so I seek help if I have any misconceptions. The code is in VB but I can understand C# as well. Any help / guidance is greatly appreciated. Thanks!

答: My suggestion would be to create a macro enabled template with embedded VBA procedures that do all of the bookmarking and saving to PDF.  This reduces Interop calls to just creating/disposing the word application and running the VBA procedure with passed in parameters.</p>

Body:
I have a program that creates two pdf files when a button is clicked. It uses Microsoft office interop in WinForms and the file creation goes like this;

User works on something in the program

Clicks the button

Program creates a word file based on a template that has bookmarks in it

Writes into the bookmarks as well as its table

Saves it as pdf

Closes active documents

Closes the word app

Closes the child form and switches to another one

*the word app is not visible to the user

It works fine on its own, but then it takes up 8 seconds to complete the two files, so I tried using multi-threading so that the user won't have to wait and can work on other things or proceed to step 1 again.

However, it throws various errors; COM, RPC, etc. even in the database connection ones, and I think the reason is that since there are two separate threads that works and it uses the same resources, some point in time the other might have close the resources that the other thread is using / about to use
So I tried using join(), so that the other thread might finish its job first, close its respective resources, then proceeds to the next one.

This works fine, IF, the user does not click the button to create another file right after the other (in a scenario that the user finishes the first step faster than expected)

The join() is sufficient enough to handle the errors as well as to work on the file creations on background, however, I want to deal with the scenario when the file creation is done right after the other, because in this scenarios, it then seems like the process is linear due to the threads waiting for each other, aside from it creates bottlenecks wherein the threads are now in line and blocks the main thread, which makes the user wait for 12 seconds or more.

What I want to know / to be clarified in is that;

Can I create those two files that uses interop use different resources so that it won’t produce errors?

Can I use or is there an alternative to join() wherein it does not block the UI thread or the main thread? So that the file creating threads just line up in background (still waits for each other to finish) without making the user wait.

Did I incorrectly use join() or the threads that ends up eating more time?

Here is my code;

Procedure and public variables in a module for creating the documents:

Public tsThread As Thread
Public psThread As Thread

Sub SaveDoc(docType,someArgs)
        Dim wordApp = New Word.Application
        Dim templateBookmarks As Word.Bookmarks
        Dim templateName As String
        Dim template As New Word.Document
        wordApp = CreateObject("Word.Application")

        Select Case docType
            Case "Type1"
                templateName = "SampleType.docx"
                template = wordApp.Documents.Add(templatePath & templateName)
                templateBookmarks = template.Bookmarks

                templateBookmarks.Item("bookmarkInWord").Range.Text = "Foo"
                template.Tables(1).Cell(msWordRow, 1).Range.Text = "Value in cell 1"
            Case "Type2"
                ‘Same thing, just different values and template
            Case "Type3"
        End select
        template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)
        wordApp.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
        wordApp.Quit()
End Sub

Procedure in the child form when the button is clicked:

        If Not IsNothing(tsThread) Then
            If tsThread.IsAlive Then
                tsThread.Join()
            End If
        End If
        If Not IsNothing(psThread) Then
            If psThread.IsAlive Then
                psThread.Join()
            End If
        End If
        tsThread = New Thread(Sub() SaveDoc(docType1,someArgs))
        tsThread.Start()

        If Not IsNothing(tsThread) Then
            If tsThread.IsAlive Then
                tsThread.Join()
            End If
        End If
        psThread = New Thread(Sub() SaveDoc(docType2,someArgs))
        psThread.Start()

        If records = maxRecords Then
            If psThread.IsAlive or tsThread.isAlive Then
                tsThread.Join()
                psThread.Join()
                Dim fooThread = New Thread(Sub() SaveDoc(docType3,someArgs))
                fooThread.Start()
            End If
        End If
   SwitchForm("Child Form for Step 1")
   End Sub

The errors i.e. without using the join() are commonly in these parts of code:

wordApp.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

or in

wordApp.Quit()

Or in the bookmarks

templateBookmarks.Item("bookmarkInWord").Range.Text = "Foo"

Or sometimes anywhere inside one of the cases in different timings or in database connection procedures.

I am still relatively new to multi-threading as well as in Ms Interop so I seek help if I have any misconceptions. The code is in VB but I can understand C# as well. Any help / guidance is greatly appreciated. Thanks!


问:
Out-of-memory condition error when updating agda with cabal?
I'm trying to upgrade agda, getting a memory error.  Any ways to fix this?

I tried cabal install --ghc-options="+RTS -M600M" --force-reinstalls agda but per a similair question, but this just gave a heap error.

```<code>wmacmil@w:~$ cabal install --force-reinstalls agda
Resolving dependencies...
Warning: The following packages are likely to be broken by the reinstalls:
Agda-2.6.0.1
Continuing even though the plan contains dangerous reinstalls.
Downloading base-compat-0.10.5...
</code>```

...

```<code>[325 of 369] Compiling Agda.TypeChecking.IApplyConfluence ( src/full/Agda/TypeChecking/IApplyConfluence.hs, dist/build/Agda/TypeChecking/IApplyConfluence.o )
[326 of 369] Compiling Agda.TypeChecking.Rules.LHS.Unify ( src/full/Agda/TypeChecking/Rules/LHS/Unify.hs, dist/build/Agda/TypeChecking/Rules/LHS/Unify.o )
cabal: Leaving directory '/tmp/cabal-tmp-30263/Agda-2.6.1'
cabal: Error: some packages failed to install:
Agda-2.6.1 failed during the building phase. The exception was:
ExitFailure (-9)
This may be due to an out-of-memory condition.
</code>```

答:
Ah, GHC's memory hunger is insaturable...

What I usually do for bigger installs is, hardly limit GHC's -M (or perhaps to 80% of the total memory), but ensure that it actually has all of this available per-process, by limiting compilation to a single process.

```cabal install --ghc-options="+RTS -M7G" <b>-j1</b> --force-reinstalls agda```

Obviously, this makes it all really slow, but at least it'll generally succeed.

Body:
I'm trying to upgrade agda, getting a memory error.  Any ways to fix this?

I tried cabal install --ghc-options="+RTS -M600M" --force-reinstalls agda but per a similair question, but this just gave a heap error.

wmacmil@w:~$ cabal install --force-reinstalls agda
Resolving dependencies...
Warning: The following packages are likely to be broken by the reinstalls:
Agda-2.6.0.1
Continuing even though the plan contains dangerous reinstalls.
Downloading base-compat-0.10.5...

...

[325 of 369] Compiling Agda.TypeChecking.IApplyConfluence ( src/full/Agda/TypeChecking/IApplyConfluence.hs, dist/build/Agda/TypeChecking/IApplyConfluence.o )
[326 of 369] Compiling Agda.TypeChecking.Rules.LHS.Unify ( src/full/Agda/TypeChecking/Rules/LHS/Unify.hs, dist/build/Agda/TypeChecking/Rules/LHS/Unify.o )
cabal: Leaving directory '/tmp/cabal-tmp-30263/Agda-2.6.1'
cabal: Error: some packages failed to install:
Agda-2.6.1 failed during the building phase. The exception was:
ExitFailure (-9)
This may be due to an out-of-memory condition.

Body:
Ah, GHC's memory hunger is insaturable...

What I usually do for bigger installs is, hardly limit GHC's -M (or perhaps to 80% of the total memory), but ensure that it actually has all of this available per-process, by limiting compilation to a single process.

cabal install --ghc-options="+RTS -M7G" -j1 --force-reinstalls agda

Obviously, this makes it all really slow, but at least it'll generally succeed.


问:
ASP.NET Core 3.0 not showing on Visual Studio 2019
I want to test the new Blazor server-side framework (aka Razor Components).

I installed Visual Studio 2019 RC, and then the .Net Core 3.0 preview 2, following this official tutorial.

After the install, I only see the ASP.NET Core 2.0 and the 2.1 on the "Create a new ASP.NET Core Web Application" page. The 3.0 is not showing up.

I started to mess around, trying to install other packages from this page, uninstalled and reinstalled Visual Studio 2019, updated to the .NET Core Preview 3, installed several times the x64 and x86 packages in different orders, copy/paste the .Net Core binaries to random folders and so on. Nothing works. The ASP.NET Core 3.0 does not show up.

Here is what my VS looks like when creating a project (the yellow message appeared latter after some messing around with the packages, so it is not the real problem):

Here is the output of the dotnet --list-sdks command:

EDIT

For some reason, I installed the Blazor VSIX package (the WebAssembly - not exactly what I want, but I installed it anyways) and now the ASP.NET Core 3.0 simply shows up. However, just for the blazor templates:

I don't understand. Is there anything obvious I'm missing?

答:
I noticed an interesting behavior. I had the latest version of VS with all the dependencies installed. But when I try to add a new project to the solution, the dialog does not show me the options beyond .Net Core 2.2

But When I create the new project from the startup page, the drop down does show the ASP.NET Core 3.1

So I was able to work around the issue by creating the new project from the startup page, then add the existing project to the solution.


答:
Actually, you have to pay for 2 important metrics: Orchestration and Execution. Please refer to more details from this document.

1.Orchestration, $1 per 1,000 runs. You have 3 activities, then it should be $ 3/1000.

2.Execution, it depends on the DIU you configured,which means the performance of your transmission.

Title: Azure Data Factory Pricing - Activity Count

Body:
I'm thinking of using Data Factory in order to copy data from a Blob Storage container to an SQL table but I'm not quite sure I understand how the pricing works, specifically how the activities are counted.

So if I have a pipeline with 3 activities that copies the data from a CSV with 1000 lines will the total activity count be 3*1 or 3*1000? In other words, will I be charged based on the number o files it processes or the total number of lines it copies?


问:
Disable echo and set raw terminal mode via ANSI escape sequence or X11 escape sequence
Is there possibility to disable echo (except ESC[8m which only hides text) programatically in remote terminal? Any equivalent for stty -echo?

Is there also any escape command to enable raw mode (equivalent of stty raw) in remote terminal? Without raw mode getchar works only after ENTER press.

答: Unfortunately, it seems that there is not a way to do this just using escape codes of any kind. You will have to take a look at termios.h. If you need to do this low-level and can't use C, see How do i read single character input from keyboard using nasm (assembly) under ubuntu?, other than that, try searching for "non-canonical terminal input" (Canonical vs. non-canonical terminal input)


问:
How to avoid pressing Enter with getchar() for reading a single character only?
In the next code:

```<code>#include <stdio.h>

int main(void) {
  int c;
  while ((c=getchar())!= EOF)
    putchar(c);
  return 0;
}
</code>```

I have to press Enter to print all the letters I entered with getchar, but I don't want to do this, what I want to do is to press the letter and immediately see the the letter I introduced repeated without pressing Enter. For example, if I press the letter 'a' I want to see an other 'a' next to it, and so on:

```<code>aabbccddeeff.....
</code>```

But when I press 'a' nothing happens, I can write other letters and the copy appears only when I press Enter:

```<code>abcdef
abcdef
</code>```

How can I do this?

I am using the command cc -o example example.c under Ubuntu for compiling.

答:
"How to avoid pressing Enter with getchar()?"

First of all, terminal input is commonly either line or fully buffered. This means that the operating system stores the actual input from the terminal in a buffer. Usually, this buffer is flushed to the program when e.g. \n was signalized/provided in stdin. This is f.e. made by a press to Enter.

getchar() is just at the end of the chain. It has no ability to actually influence the buffering process.

"How can I do this?"

Ditch getchar() in the first place, if you don´t want to use specific system calls to change the behavior of the terminal explicitly like well explained in the other answers.

There is unfortunately no standard library function and with that no portable way to flush the buffer at single character input. However, there are implementation-based and non-portable solutions.

In Windows/MS-DOS, there are the getch() and getche() functions in the conio.h header file, which do exactly the thing you want - read a single character without the need to wait for the newline to flush the buffer.

The main difference between getch() and getche() is that getch() does not immediately output the actual input character in the console, while getche() does. The additional "e" stands for echo.

Example:

```<code>#include <stdio.h>
#include <conio.h>

int main (void)
{
    int c;

    while ((c = getche()) != EOF)
    {
        if (c == '\n')
        {
            break;
        }

        printf("\n");
    }

    return 0;
}
</code>```

In Linux, a way to obtain direct character processing and output is to use the cbreak() and echo() options and the getch() and refresh() routines in the ncurses-library.

Note, that you need to initialize the so called standard screen with the initscr() and close the same with the endwin() routines.

Example:

```<code>#include <stdio.h>
#include <ncurses.h>

int main (void)
{
    int c;

    cbreak();
    echo();

    initscr();

    while ((c = getch()) != ERR)
    {
        if (c == '\n')
        {
            break;
        }

        printf("\n");
        refresh();
    }

    endwin();

    return 0;
}
</code>```

Note: You need to invoke the compiler with the -lncurses option, so that the linker can search and find the ncurses-library.

Body:
In the next code:

#include <stdio.h>

int main(void) {
  int c;
  while ((c=getchar())!= EOF)
    putchar(c);
  return 0;
}

I have to press Enter to print all the letters I entered with getchar, but I don't want to do this, what I want to do is to press the letter and immediately see the the letter I introduced repeated without pressing Enter. For example, if I press the letter 'a' I want to see an other 'a' next to it, and so on:

aabbccddeeff.....

But when I press 'a' nothing happens, I can write other letters and the copy appears only when I press Enter:

abcdef
abcdef

How can I do this?

I am using the command cc -o example example.c under Ubuntu for compiling.

Body:
"How to avoid pressing Enter with getchar()?"

First of all, terminal input is commonly either line or fully buffered. This means that the operating system stores the actual input from the terminal in a buffer. Usually, this buffer is flushed to the program when e.g. \n was signalized/provided in stdin. This is f.e. made by a press to Enter.

getchar() is just at the end of the chain. It has no ability to actually influence the buffering process.

"How can I do this?"

Ditch getchar() in the first place, if you don´t want to use specific system calls to change the behavior of the terminal explicitly like well explained in the other answers.

There is unfortunately no standard library function and with that no portable way to flush the buffer at single character input. However, there are implementation-based and non-portable solutions.

In Windows/MS-DOS, there are the getch() and getche() functions in the conio.h header file, which do exactly the thing you want - read a single character without the need to wait for the newline to flush the buffer.

The main difference between getch() and getche() is that getch() does not immediately output the actual input character in the console, while getche() does. The additional "e" stands for echo.

Example:

#include <stdio.h>
#include <conio.h>

int main (void)
{
    int c;

    while ((c = getche()) != EOF)
    {
        if (c == '\n')
        {
            break;
        }

        printf("\n");
    }

    return 0;
}

In Linux, a way to obtain direct character processing and output is to use the cbreak() and echo() options and the getch() and refresh() routines in the ncurses-library.

Note, that you need to initialize the so called standard screen with the initscr() and close the same with the endwin() routines.

Example:

#include <stdio.h>
#include <ncurses.h>

int main (void)
{
    int c;

    cbreak();
    echo();

    initscr();

    while ((c = getch()) != ERR)
    {
        if (c == '\n')
        {
            break;
        }

        printf("\n");
        refresh();
    }

    endwin();

    return 0;
}

Note: You need to invoke the compiler with the -lncurses option, so that the linker can search and find the ncurses-library.


问:
Python equivalent of password encryption from RSA key Java code
Below is the Java code that uses rsa private key (ex: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB)

and encrypts a plain string test123 using rsa public key (public key generated from rsa private key above)

```<code>byte[] array = javax.xml.bind.DatatypeConverter.parseBase64Binary(key); KeyFactorykf = KeyFactory.getInstance(“RSA”);
publicKey = kf.generatePublic(new X509EncodedKeySpec(array)); Cipher = Cipher.getInstance(“RSA”);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal (“test123”.getBytes(“UTF-8”));
String output = javax.xml.bind.DatatypeConverter.printBase64Binary(result);
</code>```

I tried m2crypto library to do so in python:

```<code>import base64
from M2Crypto import BIO, RSA

pubkey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB'

# encryption
text = "test123".encode('utf-8')  # Plaintext
pub_bio = BIO.MemoryBuffer(pubkey.encode('utf-8'))  # Public key string
pub_rsa = RSA.load_pub_key_bio(pub_bio)  # Load public key
secret = pub_rsa.public_encrypt(text, RSA.pkcs1_padding)  # Public key encryption
sign = base64.b64encode(secret)  # Ciphertext base64 encoding
print(sign)
</code>```

The error I am getting is:

```<code>Traceback (most recent call last):
  File "encrypt_rsa_public_key.py", line 13, in <module>
    pub_rsa = RSA.load_pub_key_bio(pub_bio)  # Load public key
  File "/Users/umeshpathak/env/py3env/lib/python3.7/site-packages/M2Crypto/RSA.py", line 444, in load_pub_key_bio
    rsa_error()
  File "/Users/umeshpathak/env/py3env/lib/python3.7/site-packages/M2Crypto/RSA.py", line 333, in rsa_error
    raise RSAError(Err.get_error_message())
M2Crypto.RSA.RSAError: no start line
</code>```

How can I solve this?

答:
The library that you are using might expect to get the public key in PEM format i.e. enclosed between -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY-----. So you would have to change your pubkey to :

```<code>pubkey = '-----BEGIN PUBLIC KEY-----\n' \
         'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB' \
         '\n-----END PUBLIC KEY-----'
</code>```

the line breaks are important.

Body:
Below is the Java code that uses rsa private key (ex: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB)

and encrypts a plain string test123 using rsa public key (public key generated from rsa private key above)

byte[] array = javax.xml.bind.DatatypeConverter.parseBase64Binary(key); KeyFactorykf = KeyFactory.getInstance(“RSA”);
publicKey = kf.generatePublic(new X509EncodedKeySpec(array)); Cipher = Cipher.getInstance(“RSA”);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal (“test123”.getBytes(“UTF-8”));
String output = javax.xml.bind.DatatypeConverter.printBase64Binary(result);

I tried m2crypto library to do so in python:

import base64
from M2Crypto import BIO, RSA

pubkey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB'

# encryption
text = "test123".encode('utf-8')  # Plaintext
pub_bio = BIO.MemoryBuffer(pubkey.encode('utf-8'))  # Public key string
pub_rsa = RSA.load_pub_key_bio(pub_bio)  # Load public key
secret = pub_rsa.public_encrypt(text, RSA.pkcs1_padding)  # Public key encryption
sign = base64.b64encode(secret)  # Ciphertext base64 encoding
print(sign)

The error I am getting is:

Traceback (most recent call last):
  File "encrypt_rsa_public_key.py", line 13, in <module>
    pub_rsa = RSA.load_pub_key_bio(pub_bio)  # Load public key
  File "/Users/umeshpathak/env/py3env/lib/python3.7/site-packages/M2Crypto/RSA.py", line 444, in load_pub_key_bio
    rsa_error()
  File "/Users/umeshpathak/env/py3env/lib/python3.7/site-packages/M2Crypto/RSA.py", line 333, in rsa_error
    raise RSAError(Err.get_error_message())
M2Crypto.RSA.RSAError: no start line

How can I solve this?

Body:
The library that you are using might expect to get the public key in PEM format i.e. enclosed between -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY-----. So you would have to change your pubkey to :

pubkey = '-----BEGIN PUBLIC KEY-----\n' \
         'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBXTe278Lwg2MoI7iGKolSYuF+sNFKrsZplxCN9x0kItU3KIf8+1q60ILLwLewCEf7foxzpWp32j9YYU9vNBghuJ7BHcDYTffTRcv+QdNno491j701Hq7DIw13AGCQQTRcnfclvblnytIEWoQsiUvPJcdiWgqJIX3IQGA47a+uwIDAQAB' \
         '\n-----END PUBLIC KEY-----'

the line breaks are important.


问:
How is memory management in PHP different from that in Python?
What is the difference in how they are handled?

Specifically, why is it common to find Python used in production-level long lived applications like web-servers while PHP isn't given their similar efficiency levels?

答:
PHP was designed as a hypertext scripting language. Every process was designed to end after a very short time. So memory management and GC basically didn't matter.

However the ease and popularity of PHP have invoked its usage in long lived programs such as daemons, extensive calculations, socket servers etc.

PHP 5.3 introduced a lot of features and fixes that made it suitable for such applications, however in my opinion memory management was of lower significance on that matter.

PHPs error management is quite good now, but as in every programming language that I know of you can produce memory leaks.

You still cannot code in the same style that you can code Java or Python applications. A lot of PHP programs will probably show severe problems where Java/Python do not.

You can characterize this as "worse", but I would not. PHP just is a different set of tools that you have to handle different.

The company I work at has a lot of system programs and daemons written in PHP that run like a charm.

I think the biggest caveat for PHP when it comes to as you describe "production-level long lived applications" is its multi-processing and threading ability (the 2nd is basically nonexistent).

Of course there is the possibility to fork processes, access shared memory, do inter process communications and have message queues and stuff. But Python is far ahead on that matter, because it was designed bottom up for jobs like that.


问:
How do I get sum of two different columns from two diffrent tables and group them
I have two tables which I wanna perform join between two tables and group them by date

Table one is fb_data

```<code>id  name created_at           revenue
1   as   2020-05-29 19:30:54  5
2   as   2020-05-28 19:30:54  10
3   ad   2020-05-29 19:31:42  6
4  ad    2020-05-28 19:31:54 65
5  as    2020-05-29 19:32:10 7
6  ad    2020-05-28 19:31:54 5
</code>```

Table two is google_data

```<code>id name   created_at           sessions
1  as     2020-05-29 19:38:32    5
2  ad     2020-05-29 19:38:41    10
3  as      2020-05-29 19:38:49   7
4  as      2020-05-28 19:39:02   6
5  ad     2020-05-28 19:39:13   8
6  ad    2020-05-28 19:41:41   13
</code>```

Now what I want is to join two columns by name then group them by created_at . Something like this

```<code>Name , date(created_at) as date , sum(fb_data.revenue) , sum(google_data.revenue)
</code>```

I have one sql query but that doesn't gives result as I expected

```<code>select gd.name,fb.total_revenue,fb.created_at,gd.total_sessions
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as total_revenue, name
      from fb_data
      group by date(fb_data.created_at), name) fb,
     (select date(google_data.created_at) as created_at, sum(google_data.session) as total_sessions, name
      from google_data
      group by name, date(google_data.created_at)) as gd
      where fb.name = gd.name
      group by  gd.name,fb.name,fb.created_at,gd.total_sessions
</code>```

The result I get is

```<code>Name total_revenue   created_at     total_sessions
as   12              2020-05-29     12
as   12              2020-05-29     6
as   10              2020-05-28     12
as   10              2020-05-28     6
ad   6               2020-05-29     10
ad   6              2020-05-29      21
ad  70             2020-05-28       10
ad  70             2020-05-28      21
</code>```

The result that I am expecting is

```<code>name  total_revenue   created_at total_sessions
as    12              2020-05-29   12
as    10              2020-05-28   6
ad    6               2020-05-29   10
ad    70              2020-05-28   21
</code>```

答:
Try the following query:</p>

```<code>SELECT t.name, t.total_revenue, t.created_at, t2.total_sessions
FROM
  (SELECT name, date(created_at) created_at, sum(revenue) total_revenue
   FROM fb_data
   GROUP BY name,
            date(created_at)) t
INNER JOIN
  (SELECT name, date(created_at) created_at, sum(sessions) total_sessions
   FROM google_data
   GROUP BY name,
            date(created_at)) t2 ON t2.created_at = t.created_at
AND t2.name = t.name;
</code>```

Body:
I have two tables which I wanna perform join between two tables and group them by date

Table one is fb_data

id  name created_at           revenue
1   as   2020-05-29 19:30:54  5
2   as   2020-05-28 19:30:54  10
3   ad   2020-05-29 19:31:42  6
4  ad    2020-05-28 19:31:54 65
5  as    2020-05-29 19:32:10 7
6  ad    2020-05-28 19:31:54 5

Table two is google_data

id name   created_at           sessions
1  as     2020-05-29 19:38:32    5
2  ad     2020-05-29 19:38:41    10
3  as      2020-05-29 19:38:49   7
4  as      2020-05-28 19:39:02   6
5  ad     2020-05-28 19:39:13   8
6  ad    2020-05-28 19:41:41   13

Now what I want is to join two columns by name then group them by created_at . Something like this

Name , date(created_at) as date , sum(fb_data.revenue) , sum(google_data.revenue)

I have one sql query but that doesn't gives result as I expected

select gd.name,fb.total_revenue,fb.created_at,gd.total_sessions
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as total_revenue, name
      from fb_data
      group by date(fb_data.created_at), name) fb,
     (select date(google_data.created_at) as created_at, sum(google_data.session) as total_sessions, name
      from google_data
      group by name, date(google_data.created_at)) as gd
      where fb.name = gd.name
      group by  gd.name,fb.name,fb.created_at,gd.total_sessions

The result I get is

Name total_revenue   created_at     total_sessions
as   12              2020-05-29     12
as   12              2020-05-29     6
as   10              2020-05-28     12
as   10              2020-05-28     6
ad   6               2020-05-29     10
ad   6              2020-05-29      21
ad  70             2020-05-28       10
ad  70             2020-05-28      21

The result that I am expecting is

name  total_revenue   created_at total_sessions
as    12              2020-05-29   12
as    10              2020-05-28   6
ad    6               2020-05-29   10
ad    70              2020-05-28   21

Body:
Try the following query:

SELECT t.name, t.total_revenue, t.created_at, t2.total_sessions
FROM
  (SELECT name, date(created_at) created_at, sum(revenue) total_revenue
   FROM fb_data
   GROUP BY name,
            date(created_at)) t
INNER JOIN
  (SELECT name, date(created_at) created_at, sum(sessions) total_sessions
   FROM google_data
   GROUP BY name,
            date(created_at)) t2 ON t2.created_at = t.created_at
AND t2.name = t.name;


问:
ReferenceError: Cannot access 'embed' before initialization
Here is my code, but I don't know to where should I put that "const embed = new Discord.RichEmbed()" line.

```<code>    const Discord = require("discord.js");

module.exports = {
  name: "events",
  description: "Display the events!",
  execute(message, bot, args){
    message.channel.sendEmbed(embed);
  const embed = new Discord.RichEmbed()
  .setTitle("Event Times")
  .setDescription("Server's timezone: UTC+3")
  .setThumbnail("https://i.imgur.com/Jk5Wxj3.png")
  .addFields(
      { name: '\u200B', value: '\u200B' },
      { name: 'Monday', value: 'DemaNeR - Start 8AM' }, // Value is the event name and time.
      { name: 'Tuesday', value: 'Spaceball - Start 6PM' }, // value: 'new value'
      { name: 'Wednesday', value: 'JPB- Start 10PM' },
      { name: 'Thursday', value: 'Invasion - Start 9PM' },
      { name: 'Friday', value: 'Hitac - Start 4PM' },
      { name: 'Saturday', value: 'CVC(Infiltration) - All Day' },
      { name: 'Sunday', value: 'JPB - Start 7PM ->> Invasion - Start 10PM' },
  )
  .setColor("#f36639")

}

  }
</code>```

答:
You're referencing embed before you defined it.

```<code>execute(message, bot, args) {
    const embed = new Discord.RichEmbed()
        /* code omitted for brevity */
    message.channel.sendEmbed(embed);
}
</code>```

Body:
Here is my code, but I don't know to where should I put that "const embed = new Discord.RichEmbed()" line.

    const Discord = require("discord.js");

module.exports = {
  name: "events",
  description: "Display the events!",
  execute(message, bot, args){
    message.channel.sendEmbed(embed);
  const embed = new Discord.RichEmbed()
  .setTitle("Event Times")
  .setDescription("Server's timezone: UTC+3")
  .setThumbnail("https://i.imgur.com/Jk5Wxj3.png")
  .addFields(
      { name: '\u200B', value: '\u200B' },
      { name: 'Monday', value: 'DemaNeR - Start 8AM' }, // Value is the event name and time.
      { name: 'Tuesday', value: 'Spaceball - Start 6PM' }, // value: 'new value'
      { name: 'Wednesday', value: 'JPB- Start 10PM' },
      { name: 'Thursday', value: 'Invasion - Start 9PM' },
      { name: 'Friday', value: 'Hitac - Start 4PM' },
      { name: 'Saturday', value: 'CVC(Infiltration) - All Day' },
      { name: 'Sunday', value: 'JPB - Start 7PM ->> Invasion - Start 10PM' },
  )
  .setColor("#f36639")

}

  }

Body:
You're referencing embed before you defined it.

execute(message, bot, args) {
    const embed = new Discord.RichEmbed()
        /* code omitted for brevity */
    message.channel.sendEmbed(embed);
}


问:
"NoPermissionsInAccessToken" when trying to get user profile photo using Microsoft Graph API + react-adal
I'm trying to fetch the user's profile photo using https://graph.microsoft.com/v1.0/me/photo/$value endpoint and by following these instructions. In our React app we're using react-adal, so I first got an access token using adalGetToken(authContext, "https://graph.microsoft.com/") and then made the call with

```<code>axios.get("https://graph.microsoft.com/v1.0/me/photo/$value", {
  headers: {
    Authorization: `Bearer ${token}`,
  },
})
</code>```

However, the response is

```<code>{
  "error": {
    "code": "NoPermissionsInAccessToken",
    "message": "The token contains no permissions, or permissions can not be understood.",
    "innerError": {
      "request-id": "d2ed76f0-7f35-4014-bc53-xxxxxxxxxxxx",
      "date": "2020-05-29T09:27:12"
    }
  }
}
</code>```

When I make a call to https://graph.microsoft.com/v1.0/me using the same token, I get a proper response, eg

```<code>{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
  "id": "<id>",
  ...
}
</code>```

In Azure Portal I have delegated User.Read permissions for the application: Image of the permissions

What could be the problem?

答:
You are validating the token by calling a different endpoint locally (v1.0/me) than your app is calling (v1.0/me/photo/$value).

You can manually validate access tokens using tools like https://jwt.io/ and https://jwt.ms/

Per the comment by @sruthi-j-msft-identity, v1.0/me/photo is not available for personal accounts. Try using beta/me/photo/$value in your React app if you are working with personal accounts. ref: https://learn.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-beta#permissions

The beta API contains preview features and should not be used for production systems.

Body:
I'm trying to fetch the user's profile photo using https://graph.microsoft.com/v1.0/me/photo/$value endpoint and by following these instructions. In our React app we're using react-adal, so I first got an access token using adalGetToken(authContext, "https://graph.microsoft.com/") and then made the call with

axios.get("https://graph.microsoft.com/v1.0/me/photo/$value", {
  headers: {
    Authorization: `Bearer ${token}`,
  },
})

However, the response is

{
  "error": {
    "code": "NoPermissionsInAccessToken",
    "message": "The token contains no permissions, or permissions can not be understood.",
    "innerError": {
      "request-id": "d2ed76f0-7f35-4014-bc53-xxxxxxxxxxxx",
      "date": "2020-05-29T09:27:12"
    }
  }
}

When I make a call to https://graph.microsoft.com/v1.0/me using the same token, I get a proper response, eg

{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
  "id": "<id>",
  ...
}

In Azure Portal I have delegated User.Read permissions for the application: Image of the permissions

What could be the problem?