问:
Can't get Start Time of a process
I'm trying to get the Start Time of a running process on Windows. I did some searching and a couple of people suggested getting the Creation Time of a process with GetProcessTimes() but this doesn't seem to return accurate information. After converting the time to systemtime, it seems to return 23 for the hour instead of the correct time. How do I get the correct time? Surely there has to be a way if Process Explorer can do it. </p>

```<code>// Returns the wrong time
SYSTEMTIME ftime;
FILETIME creationTime;
GetProcessTimes(hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
FileTimeToSystemTime(&creationTime, &ftime);
</code>```

答:
FileTimeToSystemTime() gets the time in UTC time. 23 is the right answer for another 10 minutes :)

You can use SystemTimeToTzSpecificLocalTime() to convert the UTC time to the local time zone (by passing NULL as the first parameter), or to any other time zone you want.

Title: Can't get Start Time of a process

Body:
I'm trying to get the Start Time of a running process on Windows. I did some searching and a couple of people suggested getting the Creation Time of a process with GetProcessTimes() but this doesn't seem to return accurate information. After converting the time to systemtime, it seems to return 23 for the hour instead of the correct time. How do I get the correct time? Surely there has to be a way if Process Explorer can do it.

// Returns the wrong time
SYSTEMTIME ftime;
FILETIME creationTime;
GetProcessTimes(hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
FileTimeToSystemTime(&creationTime, &ftime);


来源: stackexchange

问:
Dataframe Groupby to combine multiple rows, summing float-type columns
Terrible title, but Here goes.  I have a 13,000 x 91 dataframe.  26 of the columns are numeric.  The rows are individual projects, with project performance split by year.  Like this:

```<code>| Year | Control | Description   | USD_Cost | USD_Profit |
|------|---------|---------------|----------|------------|
| 1991 | A1      | A description | 1        | 2          |
| 1992 | A1      | A Description | 100      | 300        |
| 1991 | B1      | B Description | 3        | 50         |
| 1995 | C1      | C Description | 5        | 10         |
| 1990 | D1      | D Description | 2        | 1          |
| 1996 | D1      | D Description | 1        | 1          |
</code>```

Rather than recording how each project performed in each particular year, I just want to record how long each project lasted, and the overall project performance:

```<code>| Years | Control | Description   | USD_Cost | USDProfit |
|-------|---------|---------------|----------|-----------|
| 2     | A1      | A description | 101      | 302       |
| 1     | B1      | B Description | 3        | 50        |
| 1     | C1      | C Description | 5        | 10        |
| 2     | D1      | D Description | 3        | 2         |
</code>```

Control and Description aren't changed, but the numeric columns beginning with USD are summed across rows.  And there are 26 USD columns for different performance aspects. There are about 8000 unique Control Numbers but 13000 total Year-ControlNumber combos.

I know how to groupby for one element (e.g. print(dft.groupby(['Control'])['USD_Cost', 'USD_Profit'].sum() ) but when I do that, I think I am losing all the non-numeric columns.  Also, I would like to avoid typing in the names of all 26 USD columns.

Can this be done with groupby?

答:
So my solution would be to group by "Control" and then apply a function to each group, which takes all non-numeric data from the first row (I'm assuming all rows are the same for non-numeric data), but takes the sum for all numeric data. Years are treated separately since you don't want to sum the number of years.

My code:

```<code>import pandas as pd
import numpy as np

def sum_project(project):
    # Since only numeric data and years are different,
    # we just take the first row
    project_summed = project.iloc[0, :]

    # sum all numeric data but exclude "Year"
    cols_numeric = project.select_dtypes([np.number]).columns
    cols_numeric = cols_numeric.drop(["Year"])
    project_summed[cols_numeric] = project[cols_numeric].sum()

    # Get year number
    project_summed["Year"] = len(project)

    return project_summed

df = pd.DataFrame({
    "Year": [1991, 1992, 1991, 1995, 1990, 1996],
    "Control": ["A1", "A1", "B1", "C1", "D1", "D1"],
    "Description": [
        "A description",
        "A description",
        "B description",
        "C description",
        "D description",
        "D description"
    ],
    "USD_Cost": [1, 100, 3, 5, 2, 1],
    "USD_Profit": [2, 300, 50, 10, 1, 1],
})

findal_df = df.groupby(["Control"]).apply(sum_project)
</code>```

this gives final_df:

```<code>         Year Control    Description  USD_Cost  USD_Profit
Control
A1          2      A1  A description       101         302
B1          1      B1  B description         3          50
C1          1      C1  C description         5          10
D1          2      D1  D description         3           2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Terrible title, but Here goes.  I have a 13,000 x 91 dataframe.  26 of the columns are numeric.  The rows are individual projects, with project performance split by year.  Like this:

| Year | Control | Description   | USD_Cost | USD_Profit |
|------|---------|---------------|----------|------------|
| 1991 | A1      | A description | 1        | 2          |
| 1992 | A1      | A Description | 100      | 300        |
| 1991 | B1      | B Description | 3        | 50         |
| 1995 | C1      | C Description | 5        | 10         |
| 1990 | D1      | D Description | 2        | 1          |
| 1996 | D1      | D Description | 1        | 1          |

Rather than recording how each project performed in each particular year, I just want to record how long each project lasted, and the overall project performance:

| Years | Control | Description   | USD_Cost | USDProfit |
|-------|---------|---------------|----------|-----------|
| 2     | A1      | A description | 101      | 302       |
| 1     | B1      | B Description | 3        | 50        |
| 1     | C1      | C Description | 5        | 10        |
| 2     | D1      | D Description | 3        | 2         |

Control and Description aren't changed, but the numeric columns beginning with USD are summed across rows.  And there are 26 USD columns for different performance aspects. There are about 8000 unique Control Numbers but 13000 total Year-ControlNumber combos.

I know how to groupby for one element (e.g. print(dft.groupby(['Control'])['USD_Cost', 'USD_Profit'].sum() ) but when I do that, I think I am losing all the non-numeric columns.  Also, I would like to avoid typing in the names of all 26 USD columns.

Can this be done with groupby?

Body:
So my solution would be to group by "Control" and then apply a function to each group, which takes all non-numeric data from the first row (I'm assuming all rows are the same for non-numeric data), but takes the sum for all numeric data. Years are treated separately since you don't want to sum the number of years.

My code:

import pandas as pd
import numpy as np

def sum_project(project):
    # Since only numeric data and years are different,
    # we just take the first row
    project_summed = project.iloc[0, :]

    # sum all numeric data but exclude "Year"
    cols_numeric = project.select_dtypes([np.number]).columns
    cols_numeric = cols_numeric.drop(["Year"])
    project_summed[cols_numeric] = project[cols_numeric].sum()

    # Get year number
    project_summed["Year"] = len(project)

    return project_summed

df = pd.DataFrame({
    "Year": [1991, 1992, 1991, 1995, 1990, 1996],
    "Control": ["A1", "A1", "B1", "C1", "D1", "D1"],
    "Description": [
        "A description",
        "A description",
        "B description",
        "C description",
        "D description",
        "D description"
    ],
    "USD_Cost": [1, 100, 3, 5, 2, 1],
    "USD_Profit": [2, 300, 50, 10, 1, 1],
})

findal_df = df.groupby(["Control"]).apply(sum_project)

this gives final_df:

         Year Control    Description  USD_Cost  USD_Profit
Control
A1          2      A1  A description       101         302
B1          1      B1  B description         3          50
C1          1      C1  C description         5          10
D1          2      D1  D description         3           2


问:
Optional Character in Form Input Text Pattern
Apologies if this is answered elsewhere, please point me in that direction.

Using Node and EJS, I have a form field for capturing the name of a brewery, this comes via an API...

```<code><label>Brewery</label><br>
<input id="formBreweryName" class="form-control" type="text" name="breweryname" ><br>
<label>Beer Name</label><br>
<input id="formBeerName" class="form-control" type="text" name="beername" >
</code>```

Here's the ejs that both displays the brewery name in a
 and contains the onclick handler for populating the form...

```<code> <ul>
    <% BeerList.forEach(function(objsofbeer){ %>
       <li>
          <a onclick="addFormText( '<%= objsofbeer.brewery.brewery_name %>','<%= objsofbeer.beer.beer_name %>')">
          <span><%= objsofbeer.brewery.brewery_name %></span><br>
          <span><%= objsofbeer.beer.beer_name %></span><br>
          </a>
       </li>
</ul>

</code>```

And the javascript for porting the brewery name up to the form...

```<code>var addFormText = function( breweryName, beerName) {
    document.getElementById('formBreweryName').value = breweryName;
    document.getElementById('formBeerName').value = beerName;
      }
</code>```

the API passes me a brewery name like so...

```<code>brewery_name: 'Reuben\'s Brews',
</code>```

I added the beer name in the code above for good measure.

The Issue

When there is an apostrophe in the brewery name, the brewery name will not show in the appropriate form field, BUT the brewery name does show in the  section.

For most examples, the brewery name does not have an apostrophe. So the API brewery name shows up in the form field as expected. But as in the example above, the brewery name has an apostrophe, so the name will not show up in my form field.

I am hoping there is a non-javascript, pattern attribute solution that will let me optionally include apostrophes (or other unforeseen special characters) in the text. If not, then I'm open to javascript or other suggestions.

I see many examples of 'use pattern to exclude certain characters' or 'use pattern to force users to only use this given text pattern'. But I don't see anything that would allow for the optional inclusion of a character like an apostrophe (or any other optional inclusion of special characters).

If it seems like this is an issue beyond my form input field, I am happy to share more of my coding.

答:
Not sure but i think the problem is that you need a double escape character before the accent, one for the ejs on the server and one for the js on the browser. Can you try using <%- instead of <%= (EJS doesn't escape characters).
Sorry i never used ejs... other try, very ugly...:

```<code><ul>
<% BeerList.forEach(function(objsofbeer){ %>
<%   objsofbeer.brewery.brewery_name = objsofbeer.brewery.brewery_name.replace("'","\\'"); %>
<%   objsofbeer.beer.beer_name = objsofbeer.beer.beer_name.replace("'","\\'"); %>
   <li>
      <a onclick="addFormText( '<%= objsofbeer.brewery.brewery_name %>','<%= objsofbeer.beer.beer_name %>')">
      <span><%= objsofbeer.brewery.brewery_name %></span><br>
      <span><%= objsofbeer.beer.beer_name %></span><br>
      </a>
   </li>
</code>```

or try playng with ` character instead " or '

Body:
Apologies if this is answered elsewhere, please point me in that direction.

Using Node and EJS, I have a form field for capturing the name of a brewery, this comes via an API...

Brewery

<input id="formBreweryName" class="form-control" type="text" name="breweryname" >

Beer Name

<input id="formBeerName" class="form-control" type="text" name="beername" >

Here's the ejs that both displays the brewery name in a
 and contains the onclick handler for populating the form...

    <% BeerList.forEach(function(objsofbeer){ %>

          <a onclick="addFormText( '<%= objsofbeer.brewery.brewery_name %>','<%= objsofbeer.beer.beer_name %>')">
          <%= objsofbeer.brewery.brewery_name %>

          <%= objsofbeer.beer.beer_name %>

And the javascript for porting the brewery name up to the form...

var addFormText = function( breweryName, beerName) {
    document.getElementById('formBreweryName').value = breweryName;
    document.getElementById('formBeerName').value = beerName;
      }

the API passes me a brewery name like so...

brewery_name: 'Reuben\'s Brews',

I added the beer name in the code above for good measure.

The Issue

When there is an apostrophe in the brewery name, the brewery name will not show in the appropriate form field, BUT the brewery name does show in the  section.

For most examples, the brewery name does not have an apostrophe. So the API brewery name shows up in the form field as expected. But as in the example above, the brewery name has an apostrophe, so the name will not show up in my form field.

I am hoping there is a non-javascript, pattern attribute solution that will let me optionally include apostrophes (or other unforeseen special characters) in the text. If not, then I'm open to javascript or other suggestions.

I see many examples of 'use pattern to exclude certain characters' or 'use pattern to force users to only use this given text pattern'. But I don't see anything that would allow for the optional inclusion of a character like an apostrophe (or any other optional inclusion of special characters).

If it seems like this is an issue beyond my form input field, I am happy to share more of my coding.

Body:
Not sure but i think the problem is that you need a double escape character before the accent, one for the ejs on the server and one for the js on the browser. Can you try using <%- instead of <%= (EJS doesn't escape characters).
Sorry i never used ejs... other try, very ugly...:

<ul>
<% BeerList.forEach(function(objsofbeer){ %>
<%   objsofbeer.brewery.brewery_name = objsofbeer.brewery.brewery_name.replace("'","\\'"); %>
<%   objsofbeer.beer.beer_name = objsofbeer.beer.beer_name.replace("'","\\'"); %>
   <li>
      <a onclick="addFormText( '<%= objsofbeer.brewery.brewery_name %>','<%= objsofbeer.beer.beer_name %>')">
      <span><%= objsofbeer.brewery.brewery_name %></span><br>
      <span><%= objsofbeer.beer.beer_name %></span><br>
      </a>
   </li>

or try playng with ` character instead " or '


问:
How to access class attributes and functions within modules properly
I'm writing classes in ES6 modules using object literals and I want to set object attributes within a function. Now I know modules are executed in strict mode by default which makes usage of this safe or at least safer, but I'm not sure whether foo() modifies the object I'm accessing in the 'parent' script file or just the local object existing only in Controller.mjs. Do both function calls have the same effect?

```<code>//Controller.mjs
const Controller = {
    someAttr1: [],
    someAttr2: true,

    foo: function () {
        this.someAttr1.push("some value");
        Controller.someAttr1.push("some value");
    }
};

//export Controller's interface...

//SomeOtherFile.mjs
import { Controller } from 'Controller.mjs'

Controller.foo();
</code>```

答:
the object I'm accessing in the 'parent' script file or just the local object existing only in Controller.mjs

There is only a single object in your code. The import declaration really does nothing but create an alias for the const Controller variable in the imported module. There is no second object getting instantiated.

In general, for using this vs Controller to refer to the object, see Javascript: Object Literal reference in own key's function instead of 'this'. It doesn't matter whether the code is spread across modules or not for that.

Body:
I'm writing classes in ES6 modules using object literals and I want to set object attributes within a function. Now I know modules are executed in strict mode by default which makes usage of this safe or at least safer, but I'm not sure whether foo() modifies the object I'm accessing in the 'parent' script file or just the local object existing only in Controller.mjs. Do both function calls have the same effect?

//Controller.mjs
const Controller = {
    someAttr1: [],
    someAttr2: true,

    foo: function () {
        this.someAttr1.push("some value");
        Controller.someAttr1.push("some value");
    }
};

//export Controller's interface...

//SomeOtherFile.mjs
import { Controller } from 'Controller.mjs'

Controller.foo();


问:
How do I use loop in the following problem?
I want to loop through some variables and create nine new variables which are equal to 1 if the first three variables are "433" or "434". I am using the following code but its showing 1 for everything, can someone help</p>

```<code>data icd_dim;
set asg3;
array icd (9) $ ICD9_DGNS_CD_1-ICD9_DGNS_CD_9;
array flag_icd (9) flag_icd_1-flag_icd_9;
do i = 1 to 9;
if icd(i)=substr(icd(i),1,3)="433" OR "434" then flag_icd(i)=1; end;
run;

</code>```

答:
The in: operator is a prefix comparison operator for character values.  You also might want a flag variable name that is more descriptive of the diagnosis.

```<code>occlusion_flag(i) = icd(i) in: ('433', '434');
</code>```

Body:
I want to loop through some variables and create nine new variables which are equal to 1 if the first three variables are "433" or "434". I am using the following code but its showing 1 for everything, can someone help

data icd_dim;
set asg3;
array icd (9) $ ICD9_DGNS_CD_1-ICD9_DGNS_CD_9;
array flag_icd (9) flag_icd_1-flag_icd_9;
do i = 1 to 9;
if icd(i)=substr(icd(i),1,3)="433" OR "434" then flag_icd(i)=1; end;
run;

Body:
The in: operator is a prefix comparison operator for character values.  You also might want a flag variable name that is more descriptive of the diagnosis.

occlusion_flag(i) = icd(i) in: ('433', '434');


问:
How to enable pulse device to allow recording using portaudio
I'm currently working on a code to record voice bqsed on portaudio framework. For the moment, I can't make it works and I have the error code below.

```
0: /dev/dsp
An error occured while using the portaudio stream
Error number: -10000
Error message: PortAudio not initialized
```

I think that my issue is probably linked to a bad audio src which is not a pulse audio device. Is anyone can let me know how to setup a pulse device in order to allow port audio to access to it instead of /dev/dsp

答: Did you call the function Pa_Initialize() before doing whatever else you were trying to do?

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on a code to record voice bqsed on portaudio framework. For the moment, I can't make it works and I have the error code below.

0: /dev/dsp
An error occured while using the portaudio stream
Error number: -10000
Error message: PortAudio not initialized

I think that my issue is probably linked to a bad audio src which is not a pulse audio device. Is anyone can let me know how to setup a pulse device in order to allow port audio to access to it instead of /dev/dsp


问:
How can I extract three characters at a time from a Python string?
I want to write a function that takes a long string of characters (a protein sequence like 'UGGUGUUAUUAAUGGUUU') and extracts three characters at a time from it (i.e. the codons). It can either return each set of three characters one after another, or a list containing all the sets of three characters. Either way would work. But I'm having some trouble figuring out exactly how to do this cleanly.

Here's what I have so far:

```<code>def get_codon_list(codon_string):
    codon_start = 0
    codon_length = 3
    codon_end = 3
    codon_list = []
    for x in range(len(codon_string) // codon_length):
        codon_list.append(codon_string[codon_start:codon_end])
        codon_start += codon_length
        codon_end += codon_length
    return codon_list
</code>```

It works to return a list of the codons, but it seems very inefficient. I don't like using hard-coded numbers and incrementing variables like that if there is a better way. I also don't like using for loops that don't actually use the variable in the loop. It doesn't seem like a proper use of it.

Any suggestions for how to improve this, either with a specific function/module, or just a better Pythonic technique?

Thanks!

答:
With regular expression :</p>

```<code>import re

def get_codon_list(codon_string):
    return list(re.findall(r"(\w{3})", codon_string))
</code>```

Body:
I want to write a function that takes a long string of characters (a protein sequence like 'UGGUGUUAUUAAUGGUUU') and extracts three characters at a time from it (i.e. the codons). It can either return each set of three characters one after another, or a list containing all the sets of three characters. Either way would work. But I'm having some trouble figuring out exactly how to do this cleanly.

Here's what I have so far:

def get_codon_list(codon_string):
    codon_start = 0
    codon_length = 3
    codon_end = 3
    codon_list = []
    for x in range(len(codon_string) // codon_length):
        codon_list.append(codon_string[codon_start:codon_end])
        codon_start += codon_length
        codon_end += codon_length
    return codon_list

It works to return a list of the codons, but it seems very inefficient. I don't like using hard-coded numbers and incrementing variables like that if there is a better way. I also don't like using for loops that don't actually use the variable in the loop. It doesn't seem like a proper use of it.

Any suggestions for how to improve this, either with a specific function/module, or just a better Pythonic technique?

Thanks!

Body:
With regular expression :

import re

def get_codon_list(codon_string):
    return list(re.findall(r"(\w{3})", codon_string))


问:
Can I display lists (<ol>, <ul>) as inline items?
I know they are block elements, but I'm sure there is a way, maybe with CSS? I tried to use the span tag but it doesn't work. What did I do wrong? I would like to put the second element next to the first one on the website. Not under it, but next.</p>

```<code>  <span>
        <section>
        <h3>Favourite quotes</h3>
         <ul>
          <li>
              “Pizza is good" ―Me
          </li>
         </ul>
        </section>
  </span>

  <span>
        <section>
        <h3>Favourite series</h3>
         <ul>
          <li> X </li>
          <li> Y </li>
          <li> Z </li>
         </ul>
        </section>
  </span>
</code>```

答:
Using span this way is wrong because span is inline element and you can't wrap section like this and any other block's. You can use
 or flexbox for this case.

.container {
  display: flex;
}

.container section {
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <section>
    <h3>Favourite quotes</h3>
    <ul>
      <li>“Pizza is good" ―Me</li>
    </ul>
  </section>
  <section>
    <h3>Favourite series</h3>
    <ul>
      <li> X </li>
      <li> Y </li>
      <li> Z </li>
    </ul>
  </section>
</div></code>```

Body:
I know they are block elements, but I'm sure there is a way, maybe with CSS? I tried to use the span tag but it doesn't work. What did I do wrong? I would like to put the second element next to the first one on the website. Not under it, but next.

Favourite quotes

              “Pizza is good" ―Me

Favourite series

 X

 Y

 Z

Body:
Using span this way is wrong because span is inline element and you can't wrap section like this and any other block's. You can use <table> or flexbox for this case.

.container {
  display: flex;
}

.container section {
  width: 50%;
}

<div class="container">
  <section>
    <h3>Favourite quotes</h3>
    <ul>
      <li>“Pizza is good" ―Me</li>
    </ul>
  </section>
  <section>
    <h3>Favourite series</h3>
    <ul>
      <li> X </li>
      <li> Y </li>
      <li> Z </li>
    </ul>
  </section>
</div>


问:
Why not all the values in one columns not converted
I have inserted csv file to sql server and doing now casting. there is One column contains value like (166742.9659) as nvarchar and i wanted to convert it to decimal.
my query was like this

```<code>CAST([amount] AS decimal(18,2))     AS [amount]
</code>```

I got the following message:

Error converting data type nvarchar to numeric

then i tried the query just to see which values aws not converted

```<code>TRY_CAST([amount] AS decimal(18,2))     AS [amount]
</code>```

then i got number of NULL values. When i checked this values in the original csv file i found that those numbers have the same format of the value which have been converted successfully.
for example:
this number 17011343.12 was successfully converted
this number **166742.9659 ** get null value

so is there anybody please can understand what happened ??

答:
This suggests that you have unexpected characters in the string.  And that requires debugging.  So this is intended to help you with that.

You need some forensics on the query.  One place to start is:

```<code>select amount, len(amount), len(ltrim(rtrim(amount)))
from staging
where TRY_CAST([amount] AS decimal(18,2)) is null and
      amount is not null;
</code>```

You will need to manually count the characters to see if the lengths match what you see.  If they do, then it suggests that one of the digits is really something else (say a O or l -- capital O or lower case l).  Or perhaps the decimal place is some other period.

If they do not match, then nefarious other characters have found their way into your file.

Body:
I have inserted csv file to sql server and doing now casting. there is One column contains value like (166742.9659) as nvarchar and i wanted to convert it to decimal.
my query was like this

CAST([amount] AS decimal(18,2))     AS [amount]

I got the following message:

Error converting data type nvarchar to numeric

then i tried the query just to see which values aws not converted

TRY_CAST([amount] AS decimal(18,2))     AS [amount]

then i got number of NULL values. When i checked this values in the original csv file i found that those numbers have the same format of the value which have been converted successfully.
for example:
this number 17011343.12 was successfully converted
this number **166742.9659 ** get null value

so is there anybody please can understand what happened ??

Body:
This suggests that you have unexpected characters in the string.  And that requires debugging.  So this is intended to help you with that.

You need some forensics on the query.  One place to start is:

select amount, len(amount), len(ltrim(rtrim(amount)))
from staging
where TRY_CAST([amount] AS decimal(18,2)) is null and
      amount is not null;

You will need to manually count the characters to see if the lengths match what you see.  If they do, then it suggests that one of the digits is really something else (say a O or l -- capital O or lower case l).  Or perhaps the decimal place is some other period.

If they do not match, then nefarious other characters have found their way into your file.


问:
ES6 get path of module inside module
How can i get moudle path inside module? I use babel and webpack to create bundle for browsers.

I expect

/src/someModule/index.js

```<code>console.log(`someModule path is ${process.execPath}`);
</code>```

to output in browser someModule path is /home/user/proj/src/someModule

or someModule path is /src/someModule

答:
The import.meta is now supported in all modern browsers, yay!

// /es6/someFile.js
console.log(import.meta);
```

<p>Outputs:</p>

```{url: "https://yourdomain.com/es6/someFile.js"}
```

(even though OP asked about webpack, I believe this info will be useful for many people coming here)

Title: ES6 get path of module inside module

Body:
How can i get moudle path inside module? I use babel and webpack to create bundle for browsers.

I expect

/src/someModule/index.js

console.log(`someModule path is ${process.execPath}`);

to output in browser someModule path is /home/user/proj/src/someModule

or someModule path is /src/someModule

Body:
The import.meta is now supported in all modern browsers, yay!

// /es6/someFile.js
console.log(import.meta);

Outputs:

{url: "https://yourdomain.com/es6/someFile.js"}

(even though OP asked about webpack, I believe this info will be useful for many people coming here)


问:
Login Form is not rendering
I'm having an issue when i want to render a login form view those issues started when i began to use context api for React. the error that show me right now is:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
  Check the render method of LoginForm.

the error is there:

Index.js:

```<code>    // React
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { LoginPage } from '../src/views/Login';

// 1
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

// Context Provider
import AppProvider from './context/context';
import { LoginForm } from './components/Form';

// 2
const httpLink = createHttpLink({
  uri: 'http://localhost:3000/graphql'
});

// 3
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

// 4
export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
})

ReactDOM.render(

    <ApolloProvider client={client}>
    <BrowserRouter>
      <AppProvider>
        <App />
      </AppProvider>
    </BrowserRouter>
    </ApolloProvider>,
    document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();
</code>```

when i take the line out of the script, the one with Context.Consumer at the LoginForm component the error goes away. i tried to export the component with the default then wihout it with no success.

Login Form:

```<code>        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // import mutations
    import mutations from './mutations';

    // React bootstrap
    import { Container, Row, Form, Button } from 'react-bootstrap';

    // Import Style
    import './style.css';

    // Component
    import NavbarLayout from '../Navbar';

    // Context
    import Context from '../../context/context';

    export class LoginForm extends React.Component {

        render() {

            return(

                <Fragment>
                    <Context.Consumer>
                        {c => {
                            return(
                                <Container>
                                    <Form className="form-container">
                                        <h2 className="text-center pb-4">Ingreso</h2>
                                        <Form.Group controlId="formBasicEmail">
                                            <Form.Control name='email' onChange={e => c.get_data(e)} type="email" placeholder="Email" />
                                        </Form.Group>

                                        <Form.Group controlId="formBasicPassword">
                                            <Form.Control name='password' onChange={e => c.get_data(e)} type="password" placeholder="Contraseña" />
                                        </Form.Group>
                                        <div className="text-center">
                                            <Button className="button-login" variant="primary" onClick={e => c.submit(e)} type="submit">
                                                Ingresa
                                            </Button>
                                        </div>
                                    </Form>
                                </Container>
                            );
                        }}
                    </Context.Consumer>
                </Fragment>
            );
        }
    }
</code>```

This component is called into this view:

```<code>        // React
    import React, { Fragment } from 'react';

    // Component React
    import { LoginForm } from '../../components/Form';

    // React bootstrap
    import { Container, Row } from 'react-bootstrap';

    export const LoginPage = () => {
        return(
            <Fragment>
                <Container style={{marginTop: '2rem'}}>
                    <LoginForm />
                </Container>
            </Fragment>
        );
    }
</code>```

The context Api file is:

```<code>        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // Mutation
    import mutations from './mutations';

    // Context
    const Context = React.createContext();

    class AppProvider extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                // Login & logout states
                login_credentials: {},
                isLogged: false,
                get_data: this.get_data,
                submit: this.submit,
            }
        }

        // Actions

        // Login & Logout

        get_data = async(e) => {
            e.preventDefault();
            const { name, value } = e.target;
            const data = { [name]: value };
            const newData = { ...this.state.login_credentials, ...data };
            this.setState({
                login_credentials: newData
            });

        }

        submit = async(e) => {
            e.preventDefault();
            const { signinUser } = this.props;
            const { login_credentials, isLogged } = this.state;

            try {
                let variables = login_credentials;
                const response = await signinUser({variables});
                const get_token = response.data.signinUser.token;

                // setting localStorage
                localStorage.setItem('token', get_token);
                this.setState({
                    isLogged: true
                });

                this.props.history.push({pathname: '/home', state: {isLogged: this.state.isLogged}});

            } catch(error) {
                console.log(error);
            }

        }

        // END LOGIN & LOGOUT ACTIONS

        render() {
            return(
                <Context.Provider value={this.state}>
                    {this.props.children}
                </Context.Provider>
            );
        }
    }

    export default compose(
        withRouter,
        graphql(mutations.signinUser, { name: 'signinUser' }),
    )(AppProvider)
</code>```

答:
Well i have the answer finally for this bug. the fixed lines shown is this solutions has been inherit from the question at the top

I was not exporting context from context.js so i have to add export:

```<code>// Context
export const Context = React.createContext();
</code>```

I was importing the context as if it were a default export so to fix:

```<code>// Context
import { Context } from '../../context/context';
</code>```

Title: Login Form is not rendering

Body:
I'm having an issue when i want to render a login form view those issues started when i began to use context api for React. the error that show me right now is:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
  Check the render method of LoginForm.

the error is there:

Index.js:

    // React
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { LoginPage } from '../src/views/Login';

// 1
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

// Context Provider
import AppProvider from './context/context';
import { LoginForm } from './components/Form';

// 2
const httpLink = createHttpLink({
  uri: 'http://localhost:3000/graphql'
});

// 3
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

// 4
export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
})

ReactDOM.render(

    <ApolloProvider client={client}>
    <BrowserRouter>
      <AppProvider>
        <App />
      </AppProvider>
    </BrowserRouter>
    </ApolloProvider>,
    document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();

when i take the line out of the script, the one with Context.Consumer at the LoginForm component the error goes away. i tried to export the component with the default then wihout it with no success.

Login Form:

        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // import mutations
    import mutations from './mutations';

    // React bootstrap
    import { Container, Row, Form, Button } from 'react-bootstrap';

    // Import Style
    import './style.css';

    // Component
    import NavbarLayout from '../Navbar';

    // Context
    import Context from '../../context/context';

    export class LoginForm extends React.Component {

        render() {

            return(

                <Fragment>
                    <Context.Consumer>
                        {c => {
                            return(
                                <Container>
                                    <Form className="form-container">

Ingreso

                                        <Form.Group controlId="formBasicEmail">
                                            <Form.Control name='email' onChange={e => c.get_data(e)} type="email" placeholder="Email" />
                                        </Form.Group>

                                        <Form.Group controlId="formBasicPassword">
                                            <Form.Control name='password' onChange={e => c.get_data(e)} type="password" placeholder="Contraseña" />
                                        </Form.Group>

                                            <Button className="button-login" variant="primary" onClick={e => c.submit(e)} type="submit">
                                                Ingresa
                                            </Button>

                                    </Form>
                                </Container>
                            );
                        }}
                    </Context.Consumer>
                </Fragment>
            );
        }
    }

This component is called into this view:

        // React
    import React, { Fragment } from 'react';

    // Component React
    import { LoginForm } from '../../components/Form';

    // React bootstrap
    import { Container, Row } from 'react-bootstrap';

    export const LoginPage = () => {
        return(
            <Fragment>
                <Container style={{marginTop: '2rem'}}>
                    <LoginForm />
                </Container>
            </Fragment>
        );
    }

The context Api file is:

        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // Mutation
    import mutations from './mutations';

    // Context
    const Context = React.createContext();

    class AppProvider extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                // Login & logout states
                login_credentials: {},
                isLogged: false,
                get_data: this.get_data,
                submit: this.submit,
            }
        }

        // Actions

        // Login & Logout

        get_data = async(e) => {
            e.preventDefault();
            const { name, value } = e.target;
            const data = { [name]: value };
            const newData = { ...this.state.login_credentials, ...data };
            this.setState({
                login_credentials: newData
            });

        }

        submit = async(e) => {
            e.preventDefault();
            const { signinUser } = this.props;
            const { login_credentials, isLogged } = this.state;

            try {
                let variables = login_credentials;
                const response = await signinUser({variables});
                const get_token = response.data.signinUser.token;

                // setting localStorage
                localStorage.setItem('token', get_token);
                this.setState({
                    isLogged: true
                });

                this.props.history.push({pathname: '/home', state: {isLogged: this.state.isLogged}});

            } catch(error) {
                console.log(error);
            }

        }

        // END LOGIN & LOGOUT ACTIONS

        render() {
            return(
                <Context.Provider value={this.state}>
                    {this.props.children}
                </Context.Provider>
            );
        }
    }

    export default compose(
        withRouter,
        graphql(mutations.signinUser, { name: 'signinUser' }),
    )(AppProvider)

Body:
Well i have the answer finally for this bug. the fixed lines shown is this solutions has been inherit from the question at the top

I was not exporting context from context.js so i have to add export:

// Context
export const Context = React.createContext();

I was importing the context as if it were a default export so to fix:

// Context
import { Context } from '../../context/context';


问:
Vue.js: What to display when axios returns error
In a page component, I am using "created()" hook to fetch data using Axios, but when axios returns an error(for example resource not found error), currently it results in an ugly UI as the data that UI requires is not available.

My question is: should there be a global error page or should I need to handle the error for specific situations? Or is there any recommendations regarding Axios error handling with a UI feedback to the user?

答: You have to handle each error and show related alert.</p>


问:
How can I get and then add Staccato 222 font to my first website?
I want to make my first website. The logo of my company is written by Staccato 222 font. The only site I know to get fonts is google fonts, but Staccato is not available there. Could you recommend me a site where I can get the font Staccato 222? I want to add the font in a way everybody can see the same font i.e Stacatto 222. And how can I add it to my website?</p>

答:
You might have better luck looking for it using its original name, Mistral.

In the 1980s, Bitstream started selling (authorized, from what I understand) digital versions of many classic fonts, using genericized names. Staccato 222 (Mistral) was one of them.


问:
What 's different between "text frame" and "binary frame" in Websocket?
Text frame(opcode = 0x01) and Binary frame(opcode = 0x02) in RFC 6455. What's different between them and which one is faster?</p>

答:
For some background and perhaps more familiarity in other realms, HTTP/1 relied on an unstructured plaintext protocol while HTTP/2 allowed for faster processing of messages through binary framing. Also, SMTP relies on text while TCP relies on a binary protocol. To sum up, text relies on ASCII ('Hello') while binary, although a confusing term, has no readable representation.  In JavaScript, socket.send(new ArrayBuffer(8)) is a basic binary object and is one example of the format that can be sent.  This allocates a contiguous memory area of 8 bytes and pre-fills it with zeroes.

Hopefully this provides some good context.

0x01 is hexadecimal number (denoted by 0x and represents the integer 1) is the 4 bit opcode for the receiver (client or server) to know what type of "frame" it will receive.  UTF-8 is denoted by 0x01 and raw binary is denoted by 0x02.

Raw binary will be much faster.  Imagine an architecture like so:

If we send textual data (opcode 0x01) via the Websocket, it must translate the received data at the proxy. Before the TCP server responds to the client message, it may have to translate the response to textual data.  Encoding binary data to ASCII text via base64 will increase the size of the message by 20-30%.

With an opcode of 0x02, we can skip 2 steps in the whole request/response cycle and reduce the size of the message we are passing.  In short, we skip interpretation.  Moreover, the Websocket spec has UTF-8 validation rules.  The difference between text and binary might be 2x in favor of binary.


问:
Serving a dynamically generated MS Excel files using django and xlwt fails in Internet Explorer
I am trying to use xlwt to create MS-Excel files from the contents of the database on my django site.

I have seen several solutions here on stackoverflow, in particular this link: django excel xlwt

and this django snippet: http://djangosnippets.org/snippets/2233/

These examples work in firefox, but not in Internet Explorer. Instead of getting prompted to open or save a file, a bunch of wingding junk appears on the screen.  It seems that IE thinks the response is html.

Here is my view function:

```<code>def exportexcel(request):
    from xlwt import Workbook

    wb = Workbook()
    ws = wb.add_sheet('Sheetname')
    ws.write(0, 0, 'Firstname')
    ws.write(0, 1, 'Surname')
    ws.write(1, 0, 'Hans')
    ws.write(1, 1, 'Muster')

    fname = 'testfile.xls'
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename=%s' % fname

    wb.save(response)

    return response
</code>```

I am seeing this behavior in IE 8.

Any suggestions as to why this isn't working in Internet Explorer?

Thanks.

答:
The mimetype you're using application/ms-excel is invalid for .xls files.

The standard one is application/vnd.ms-excel

Look here Setting mime type for excel document for more informations.

Body:
I am trying to use xlwt to create MS-Excel files from the contents of the database on my django site.

I have seen several solutions here on stackoverflow, in particular this link: django excel xlwt

and this django snippet: http://djangosnippets.org/snippets/2233/

These examples work in firefox, but not in Internet Explorer. Instead of getting prompted to open or save a file, a bunch of wingding junk appears on the screen.  It seems that IE thinks the response is html.

Here is my view function:

def exportexcel(request):
    from xlwt import Workbook

    wb = Workbook()
    ws = wb.add_sheet('Sheetname')
    ws.write(0, 0, 'Firstname')
    ws.write(0, 1, 'Surname')
    ws.write(1, 0, 'Hans')
    ws.write(1, 1, 'Muster')

    fname = 'testfile.xls'
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename=%s' % fname

    wb.save(response)

    return response

I am seeing this behavior in IE 8.

Any suggestions as to why this isn't working in Internet Explorer?

Thanks.


问:
Conventional Routing in ASP.NET Core API
Problem:

I'm creating an API Application with NET Core 3.1.
I'd like to avoid to set route attribute over every ApiControllers and Actions. I tryed a lot of combinations over UseEndpoints to set a conventional route, but i'm failing.

With some configuration I can't get the Api working, with some others I get this exception during startup:

InvalidOperationException: Action 'ApiIsWorking' does not have an
  attribute route. Action methods on controllers annotated with
  ApiControllerAttribute must be attribute routed.

How can i set the startup.cs to auto map controllers with their class name and actions with their method name?

Thank you!

Some code:

startup.cs

```<code>...
services.AddControllers()
...

app.UseHttpsRedirection()
   .UseRouting()
   .UseAuthentication()
   .UseEndpoints(endpoints => ?? )
   .UseCoreHttpContext()
   .UseServerConfiguration();
</code>```

controller.cs

```<code>[ApiController]
public class BaseAPI : ControllerBase
{
        [HttpGet]
        public string ApiIsWorking()
        {
            return "API is working!";
        }
}
</code>```

Solution:

As Reza Aghaei says in the solution, the error was to add the ApiController attribute. After I removed it, the command UseEndpoints start to work.

My mistake was to add the attribute to be able to recognize which classes should be exposed via API. It wasn't necessary because UseEndpoints maps only the classes that inherit from ControllerBase.

Warning:

1) Conventional Routing require [FromBody] attribute in actions params.

2) I highlight Zinov's response about conventional routing problems with Swashbuckle in .NET Core

答:
To have conventional routing for your controllers and action, you need to remove [ApiController] attribute and [Route] attribute from your controller and actions and setup route in UseEndpoints.

It's already mentioned in the documentations:

The [ApiController] attribute makes attribute routing a requirement.

Actions are inaccessible via conventional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in Startup.Configure.

Example

This is the working setup that I have for Startup:

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
</code>```

And a sample API controller:

```<code>public class ValuesController : ControllerBase
{
    // values/getall
    [HttpGet]
    public IEnumerable<string> GetAll()
    {
        return new string[] { "value1", "value2" };
    }

    // values/getitem/1
    [HttpGet]
    public string GetItem(int id)
    {
        return "value";
    }
}
</code>```

Body:
Problem:

I'm creating an API Application with NET Core 3.1.
I'd like to avoid to set route attribute over every ApiControllers and Actions. I tryed a lot of combinations over UseEndpoints to set a conventional route, but i'm failing.

With some configuration I can't get the Api working, with some others I get this exception during startup:

InvalidOperationException: Action 'ApiIsWorking' does not have an
  attribute route. Action methods on controllers annotated with
  ApiControllerAttribute must be attribute routed.

How can i set the startup.cs to auto map controllers with their class name and actions with their method name?

Thank you!

Some code:

startup.cs

...
services.AddControllers()
...

app.UseHttpsRedirection()
   .UseRouting()
   .UseAuthentication()
   .UseEndpoints(endpoints => ?? )
   .UseCoreHttpContext()
   .UseServerConfiguration();

controller.cs

[ApiController]
public class BaseAPI : ControllerBase
{
        [HttpGet]
        public string ApiIsWorking()
        {
            return "API is working!";
        }
}

Solution:

As Reza Aghaei says in the solution, the error was to add the ApiController attribute. After I removed it, the command UseEndpoints start to work.

My mistake was to add the attribute to be able to recognize which classes should be exposed via API. It wasn't necessary because UseEndpoints maps only the classes that inherit from ControllerBase.

Warning:

1) Conventional Routing require [FromBody] attribute in actions params.

2) I highlight Zinov's response about conventional routing problems with Swashbuckle in .NET Core

Body:
To have conventional routing for your controllers and action, you need to remove [ApiController] attribute and [Route] attribute from your controller and actions and setup route in UseEndpoints.

It's already mentioned in the documentations:

The [ApiController] attribute makes attribute routing a requirement.

Actions are inaccessible via conventional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in Startup.Configure.

Example

This is the working setup that I have for Startup:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

And a sample API controller:

public class ValuesController : ControllerBase
{
    // values/getall
    [HttpGet]
    public IEnumerable<string> GetAll()
    {
        return new string[] { "value1", "value2" };
    }

    // values/getitem/1
    [HttpGet]
    public string GetItem(int id)
    {
        return "value";
    }
}


问:
Generic interface with wildcard. '? extends Class' is not 'Class'
I'm learning Java and trying to implement a command bus but I'm really stuck on generics and wildcards.

Here's the CommandHandler interface:

```<code>public interface CommandHandler<C extends Command> {

    boolean supports(Command command);

    void handle(C command);
}
</code>```

CommandBus interface:

```<code>public interface CommandBus {

    void register(CommandHandler<? extends Command> handler);

    void handle(Command command);
}
</code>```

And the implementation of CommandBus:

```<code>public class SimpleCommandBus implements CommandBus {

    private List<CommandHandler<? extends Command>> handlers = new ArrayList<>();

    @Override
    public void register(CommandHandler<? extends Command> handler) {
        handlers.add(handler);
    }

    @Override
    public void handle(Command command) {
        for (CommandHandler<? extends Command> handler : handlers) {
            if (handler.supports(command)) {
                handler.handle(command); // <- problem here

                return;
            }
        }
    }
}
</code>```

The problem lies on this line: handler.handle(command);.

? extends Command is not Command.
I've tried many things. The only solution that worked is casting:

```<code>public void handle(Command command) {
    for (CommandHandler<? extends Command> handler : handlers) {
        CommandHandler<Command> castedHandler = (CommandHandler<Command>) handler;

        if (castedHandler.supports(command)) {
            castedHandler.handle(command);

            return;
        }
    }
}
</code>```

But I think there must be better way to do it.

答:
The problem is that generics only happen at compile-time (in the static type system), but the run-time call to supports does not give the compiler information that the type of the handler can now be narrowed. Just like you still have to cast inside of an if (a instanceof X){ (and that is even a built-in language feature).

Living with the cast is a perfectly pragmatic solution, as you know it is safe, even if the compiler does not.

But if you want to push it further into typesafe country, how about something like this (pseudo-code):

```<code>public void <C extends Command> handle(C command) {
  handlers.toStream().flatMap(h -> h.adapt(command)).first.handle(command);
}
</code>```

For this you need to make a method on CommandHandler (to replace supports)

```<code><D extends Command> Optional<CommandHandler<D>> adapt(D command);
</code>```

which returns the handler itself with the narrowed type (if it supports that) or an empty Optional if it does not.

That way, the result of the supports/adapt runtime check is expressed in the static type of that result, and the compiler can make use of that.

Body:
I'm learning Java and trying to implement a command bus but I'm really stuck on generics and wildcards.

Here's the CommandHandler interface:

public interface CommandHandler<C extends Command> {

    boolean supports(Command command);

    void handle(C command);
}

CommandBus interface:

public interface CommandBus {

    void register(CommandHandler<? extends Command> handler);

    void handle(Command command);
}

And the implementation of CommandBus:

public class SimpleCommandBus implements CommandBus {

    private List<CommandHandler<? extends Command>> handlers = new ArrayList<>();

    @Override
    public void register(CommandHandler<? extends Command> handler) {
        handlers.add(handler);
    }

    @Override
    public void handle(Command command) {
        for (CommandHandler<? extends Command> handler : handlers) {
            if (handler.supports(command)) {
                handler.handle(command); // <- problem here

                return;
            }
        }
    }
}

The problem lies on this line: handler.handle(command);.

? extends Command is not Command.
I've tried many things. The only solution that worked is casting:

public void handle(Command command) {
    for (CommandHandler<? extends Command> handler : handlers) {
        CommandHandler<Command> castedHandler = (CommandHandler<Command>) handler;

        if (castedHandler.supports(command)) {
            castedHandler.handle(command);

            return;
        }
    }
}

But I think there must be better way to do it.

Body:
The problem is that generics only happen at compile-time (in the static type system), but the run-time call to supports does not give the compiler information that the type of the handler can now be narrowed. Just like you still have to cast inside of an if (a instanceof X){ (and that is even a built-in language feature).

Living with the cast is a perfectly pragmatic solution, as you know it is safe, even if the compiler does not.

But if you want to push it further into typesafe country, how about something like this (pseudo-code):

public void <C extends Command> handle(C command) {
  handlers.toStream().flatMap(h -> h.adapt(command)).first.handle(command);
}

For this you need to make a method on CommandHandler (to replace supports)

<D extends Command> Optional<CommandHandler<D>> adapt(D command);

which returns the handler itself with the narrowed type (if it supports that) or an empty Optional if it does not.

That way, the result of the supports/adapt runtime check is expressed in the static type of that result, and the compiler can make use of that.


问:
Firebase/Angular: auth-user-not found
I have read all posts regarding this issue but i cant' apply the solutions to my implementation.
I have the following nodes in firebase:

The service atached to a regular reactive form to register the user

```<code>export class UserService {

  constructor(private db: AngularFireDatabase) { }

createUser(user:User){
   this.db.list('/users').push(user)
}
</code>```

And then the login:

```<code>constructor(private afAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router) { }

  emailLogin(email:string, password:string) {

    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
    .then((user) => {
       console.log("user details:",user);
       this.router.navigate(['/home']);
       console.log('Successfully Signed In');
     }).catch((error) => console.log(error));
   }
</code>```

And I get the message: There is no user record corresponding to this identifier. etc
But as I read this is some kind of security feature from firebase. So what can I do work this around?

EDIT @Andrei

AuthService:

```<code>  createUser(email:string, password:string){
    this.afAuth.auth.createUserWithEmailAndPassword(email, password)
    .then((user)=>{
      this.router.navigate(['/login']);
      console.log('Successfully registered');

    }).catch(error=>console.log(error))
  }

  emailLogin(email:string, password:string) {

    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
    .then((user) => {
      localStorage.setItem('currentUser', JSON.stringify(user));
       console.log("user details:",user);
       this.router.navigate(['/home']);
       console.log('Successfully Signed In');
     }).catch((error) => console.log(error));
   }
</code>```

The error message remains the same, plus, i dont see any node created on the firebase console

答:
AngularFireAuth stores users in some other internal collection, not users collection that you've created. you should create users with

```<code> this.afAuth.auth.createUserWithEmailAndPassword(email, passwors)
</code>```

not with filling your custom table

Title: Firebase/Angular: auth-user-not found

Body:
I have read all posts regarding this issue but i cant' apply the solutions to my implementation.
I have the following nodes in firebase:

The service atached to a regular reactive form to register the user

export class UserService {

  constructor(private db: AngularFireDatabase) { }

createUser(user:User){
   this.db.list('/users').push(user)
}

And then the login:

constructor(private afAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router) { }

  emailLogin(email:string, password:string) {

    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
    .then((user) => {
       console.log("user details:",user);
       this.router.navigate(['/home']);
       console.log('Successfully Signed In');
     }).catch((error) => console.log(error));
   }

And I get the message: There is no user record corresponding to this identifier. etc
But as I read this is some kind of security feature from firebase. So what can I do work this around?

EDIT @Andrei

AuthService:

  createUser(email:string, password:string){
    this.afAuth.auth.createUserWithEmailAndPassword(email, password)
    .then((user)=>{
      this.router.navigate(['/login']);
      console.log('Successfully registered');

    }).catch(error=>console.log(error))
  }

  emailLogin(email:string, password:string) {

    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
    .then((user) => {
      localStorage.setItem('currentUser', JSON.stringify(user));
       console.log("user details:",user);
       this.router.navigate(['/home']);
       console.log('Successfully Signed In');
     }).catch((error) => console.log(error));
   }

The error message remains the same, plus, i dont see any node created on the firebase console

Body:
AngularFireAuth stores users in some other internal collection, not users collection that you've created. you should create users with

 this.afAuth.auth.createUserWithEmailAndPassword(email, passwors)

not with filling your custom table


问:
R: Dynamically Splitting A Data Frame
I have a one column data frame.  The length varies between 60,000 and 500,000 rows.

I would like to split the data frame into smaller data frames with 45,000 rows plus an additional data frame with any remaining rows.  For example, if my starting data frame has 90,100 rows, the result should be 3 data frames - 2 with 45000 rows and 1 with 100 rows.

I would like to be able to subsequently process each of the resulting data frames in a for loop.

Is there a way to do this in R?

答:
Another base R solution using split+%/%

```<code>r <- split(df,seq(nrow(df))%/%45000)
</code>```

Title: R: Dynamically Splitting A Data Frame

Body:
Another base R solution using split+%/%

r <- split(df,seq(nrow(df))%/%45000)


问:
Display Double as Int if it is a whole number in Swift
I am trying to write a method that will check to see if the Double ends in .0 vs anything else. So for example checking if it is 2.0 vs 2.12345.

If it is 2.0 then I want it to display just 2, but if it is 2.12345 then show 2.12345.

I had the idea of writing a func that took the Double as a parameter and returned an Int, but if the input turns out to be .12345 it cannot return it.

So I was wondering if the way I was thinking would work with tweaking or if there is a much similar means.

I was thinking maybe the return type could somehow be both Int & Double, but I do not know how that would work.

This is what I have so far

```<code>  private func checkIfWholeNumber(displayedDouble: Double) -> Int {
    if displayedDouble.truncatingRemainder(dividingBy: 1) == 0 {
      return Int(displayedDouble)
    } else {
      return //
    }
  }
</code>```

答:
Swift 4+

```<code>let i = 2.0
let j = 2.12345

let nf = NumberFormatter()
nf.maximumFractionDigits = 6

let a = nf.string(for: i) ?? "" // 2
let b = nf.string(for: j) ?? "" // 2.12345
</code>```

For another option, this example uses NumberFormatter(). I just subjectively set the max digits to 6.

Body:
I am trying to write a method that will check to see if the Double ends in .0 vs anything else. So for example checking if it is 2.0 vs 2.12345.

If it is 2.0 then I want it to display just 2, but if it is 2.12345 then show 2.12345.

I had the idea of writing a func that took the Double as a parameter and returned an Int, but if the input turns out to be .12345 it cannot return it.

So I was wondering if the way I was thinking would work with tweaking or if there is a much similar means.

I was thinking maybe the return type could somehow be both Int & Double, but I do not know how that would work.

This is what I have so far

  private func checkIfWholeNumber(displayedDouble: Double) -> Int {
    if displayedDouble.truncatingRemainder(dividingBy: 1) == 0 {
      return Int(displayedDouble)
    } else {
      return //
    }
  }

Body:
Swift 4+

let i = 2.0
let j = 2.12345

let nf = NumberFormatter()
nf.maximumFractionDigits = 6

let a = nf.string(for: i) ?? "" // 2
let b = nf.string(for: j) ?? "" // 2.12345

For another option, this example uses NumberFormatter(). I just subjectively set the max digits to 6.


问:
Java priority queue
Java's priority queue is a data structure with O(log n) complexity for put (insertion) and O(log n) for poll (retrieval and removal of the min element).

C++ STL's multimap has the same functionality but O(1) complexity for retrieval and removal of the min element (begin and erase). Is there an equivalent in Java ?

答: Google Collections provides a Multimap implementation. Specifically, a TreeMultimap can use comparators to sort based on either keys, values or both.</p>

OwnerDisplayName: Helltone

Title: Java priority queue

OwnerDisplayName: Mark

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mark


问:
how to get tab index by tab name in jquery?
how to get tab index by tab name in jquery?

i need to remove a certain tab by this command:

$(tabContainer).tabs('remove', index);

the index must contain the correct order of the tab to be closed. the problem is, i'm generating the tabs programmatically so chances of having the wrong index is likely.

答:
I think this is what you want ("name" is the name of your tab) :</p>

```<code>// close tab with a given name
function removeTab(name) {

    var tab = $('#tabs a').filter(function(){
        return $(this).text() == name;
    }).parent();

    var index = $( "li", $tabs ).index(tab);
    if (index>=0) {
        $tabs.tabs( "remove", index );
    }
}
</code>```

Body:
I think this is what you want ("name" is the name of your tab) :

// close tab with a given name
function removeTab(name) {

    var tab = $('#tabs a').filter(function(){
        return $(this).text() == name;
    }).parent();

    var index = $( "li", $tabs ).index(tab);
    if (index>=0) {
        $tabs.tabs( "remove", index );
    }
}


问:
linker ignores library linking
I have a simple linker script, that links for armv7 processor. I didnt have a need for libc yet, so it was not really linked in. But now when i tried to compile some C sources i came across undefined references to memset which should be in libc.a that ships with compiler.

So what i did was ld -Llib -lc (i moved libc in to project's lib folder). and it still gave me undefined reference to memset.

Next i directly specified to use libc.a in linking with INPUT(libc.a), and still i get undefined reference.

And what finally worked is ld $(objects) lib/libc.a, and that linked it no problem. i looked at disassembly and everything is fine, it uses memset.

Can somebody explain to me what is happening here, i am still new to all this stuff :)

答:
I found the solution and would be interesting for everyone new to armv7 programming.

First of all, even if it links fine you will end up in HardFault handler since ld will use libgcc which was not built for thumb.

Solution:
instead of a linker (ld) use gcc, for example

arm-none-eabi-gcc -T linker.ld -O1 -nostartfiles -mthumb -o bin/prog.elf src/obj/boot.o src/obj/stm32f746_startup.o

Very important here is -mthumb so your linker picks up the right libc/libgcc, or compile your own libc with thumb and link it with ld.

Title: linker ignores library linking


问:
How to add new line in MemoEdit (DevExpress)
```<code>int maxLength = 90;
var sb = new StringBuilder();
DevExpress.XtraEditors.MemoEdit edit = sender as DevExpress.XtraEditors.MemoEdit;
foreach(string str in edit.Lines) {
   if(str.Length > maxLength) {
      e.Cancel = true;
      sb.AppendLine(memoShipMark.Text);
      return;
   }
}
</code>```

This not add new line it focus first line

答:
You can change this line

```<code>sb.AppendLine(memoShipMark.Text);
</code>```

to

```<code>sb.AppendLine($"{memoShipMark.Text}\r\n");
</code>```

or you can use Environment.NewLine which is better for cross-platform programs as it will use the proper newline character(s) for the current operating system/character set.

```<code>sb.AppendLine(memoShipMark.Text + Environment.NewLine);
</code>```

Body:
int maxLength = 90;
var sb = new StringBuilder();
DevExpress.XtraEditors.MemoEdit edit = sender as DevExpress.XtraEditors.MemoEdit;
foreach(string str in edit.Lines) {
   if(str.Length > maxLength) {
      e.Cancel = true;
      sb.AppendLine(memoShipMark.Text);
      return;
   }
}

This not add new line it focus first line

Body:
You can change this line

sb.AppendLine(memoShipMark.Text);

to

sb.AppendLine($"{memoShipMark.Text}\r\n");

or you can use Environment.NewLine which is better for cross-platform programs as it will use the proper newline character(s) for the current operating system/character set.

sb.AppendLine(memoShipMark.Text + Environment.NewLine);


问:
Prolog jargon: id(X,X). fact or rule?
In Prolog, this is unambiguously a fact:

```<code>foo(bar).
</code>```

And this is unambiguously a rule:

```<code>foo(X) :- bar(X).
</code>```

But what about a clause that has both non-singleton variables and no :- such as

```<code>identity(X,X).
</code>```

or more realistically something like

```<code>my_member(X, [X|_]).
</code>```

I've been calling these rules since I learned Prolog, but now that I've tried to check to be 100% sure, I can't seem to find any source making a stronger distinction than what I have in the first two examples.

So is a rule:

a clause that defines a variable logical relationship, i.e. a clause that will not always succeed.

a clause that that defines a relationship between predicates (or possibly a predicate and itself).

答:
The truth is that there is an argument over Prolog's terminology, but i' ll try to make a brief review which will hopefully lead to some answers.

Generally speaking, a Prolog program consists of objects and the relations between them.

The relations are called predicates and the objects are called arguments of the predicate. The number of the arguments is the predicate's arity.

Describing the objects and their relations is being done with clauses. There are three types of clauses: facts, rules and queries.

A fact denotes a relation between objects. This relation is unambiguously true. Syntactically, a fact consists of a name describing a relation, followed by one or more comma separated objects in parenthesis and a period. Example:

```<code>male(john).
father_of(adam, cain).
</code>```

Combining facts, we can define new relations between objects. This is done with a rule, which consists of two parts: a condition section (also called body of the rule) and a conclusion (also called head of the rule). While facts denote relations that are unambiguously true, rules denote relations that are true only if certain conditions are true. These conditions are also relations between objects. Syntactically, the head of the rule is separated from the body with the neck operator (:-) which can be read as if. The conditions of the rule, if more than one, are separated by commas which can be read as and. Example:

```<code>father_of(X,Y) :-
    parent(X,Y),
    male(X).
</code>```

In conclusion, rules and facts are clauses. A rule has the form Head :- Body. and a fact has the form Head. Predicates are relations defined by a name and number of arguments and there can be multiple facts or rules for the same predicate. Ultimately:

father_of/2 is a predicate named father_of with arity 2

father_of(adam, cain). is a fact

father_of(adam, abel). is another fact

father_of(A,B) :- parent(A,B), male(A). is a rule

Title: Prolog jargon: id(X,X). fact or rule?

Body:
In Prolog, this is unambiguously a fact:

foo(bar).

And this is unambiguously a rule:

foo(X) :- bar(X).

But what about a clause that has both non-singleton variables and no :- such as

identity(X,X).

or more realistically something like

my_member(X, [X|_]).

I've been calling these rules since I learned Prolog, but now that I've tried to check to be 100% sure, I can't seem to find any source making a stronger distinction than what I have in the first two examples.

So is a rule:

a clause that defines a variable logical relationship, i.e. a clause that will not always succeed.

a clause that that defines a relationship between predicates (or possibly a predicate and itself).

Body:
The truth is that there is an argument over Prolog's terminology, but i' ll try to make a brief review which will hopefully lead to some answers.

Generally speaking, a Prolog program consists of objects and the relations between them.

The relations are called predicates and the objects are called arguments of the predicate. The number of the arguments is the predicate's arity.

Describing the objects and their relations is being done with clauses. There are three types of clauses: facts, rules and queries.

A fact denotes a relation between objects. This relation is unambiguously true. Syntactically, a fact consists of a name describing a relation, followed by one or more comma separated objects in parenthesis and a period. Example:

male(john).
father_of(adam, cain).

Combining facts, we can define new relations between objects. This is done with a rule, which consists of two parts: a condition section (also called body of the rule) and a conclusion (also called head of the rule). While facts denote relations that are unambiguously true, rules denote relations that are true only if certain conditions are true. These conditions are also relations between objects. Syntactically, the head of the rule is separated from the body with the neck operator (:-) which can be read as if. The conditions of the rule, if more than one, are separated by commas which can be read as and. Example:

father_of(X,Y) :-
    parent(X,Y),
    male(X).

In conclusion, rules and facts are clauses. A rule has the form Head :- Body. and a fact has the form Head. Predicates are relations defined by a name and number of arguments and there can be multiple facts or rules for the same predicate. Ultimately:

father_of/2 is a predicate named father_of with arity 2

father_of(adam, cain). is a fact

father_of(adam, abel). is another fact

father_of(A,B) :- parent(A,B), male(A). is a rule


问:
Why do I get dependency-error trying to install package "tidytext" in RStudio
I tried to install tidytext package and received below dependency-ERROR.  Please help.

ERROR: dependency ‘ISOcodes’ is not available for package ‘stopwords’
ERROR: dependency ‘stopwords’ is not available for package ‘tidytext’

答:
Looks like you need to install the ISOcodes package. Try that out:

install.packages("ISOcodes")
```


问:
How do I improve the time it takes to load and parse files
So I 'm trying to load some data that my website can use in order to display some items.
Each item is in a json format and this is what I'm doing.

When the user sends a request to load the page, it then tries to load 400 items (there are in total 26000, i'm just using 400 to test)
and obviously 400 is going to take a lot of time, and it does that when the user clicks next as well since it's using pagination.

And my idea was that maybe I could load like 50 at a time, which would make it way more efficient!
But I'm not sure what I could do in order to implement that thought.
I tried using foreach skip and take but I couldnt really come up with a decent algorithm.
Each file is between 1 and 2KB.

Would it improve the speed a lot if I just made it one file? Seeing how it would try to load it each time I click next or another page number.

```<code>public ActionResult Items(int? page)
        {
            var items = new List<ItemModel>();
            var path = @"C:\Users\MyUser\Desktop\items-json";
            var itemFiles = Directory.GetFiles(path);

            for (int i = 0; i < 400; i++)
            {
                try
                {
                    var json = System.IO.File.ReadAllText(itemFiles[i]);

                    var itemObject = JsonConvert.DeserializeObject<ItemModel>(json);
                    items.Add(itemObject);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            var pageNumber = page ?? 1;
            var onePageOfItems = items.ToPagedList(pageNumber, 10);
            //ViewBag.OnePageProducts = onePageOfProducts;
            return View(onePageOfItems);
        }
</code>```

答:
(My answer is assuming that you have to read individual files from-disk instead of storing data in a different medium such as a SQLite database file).

First-off, there's a huge bug in your code: the Directory.GetFiles() method does not guarantee any specific ordering of files - and pagination is meaningless without a defined ordering.

https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?redirectedfrom=MSDN&view=netframework-4.8#System_IO_Directory_GetFiles_System_String_

The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required.

Assuming that you want to order by filename, then we can use that as the basis of paging, and then read only those files.

The code below uses real async file IO (by creating a FileStream with async: true) which means it uses Windows' built-in Overlapped IO to handle asynchronous file-reads from multiple files - which should be much faster than serially synchronously reading from other files.

```<code>using System.Linq;
using System.Collections.Generic;
using System.IO;

public async Task<ActionResult> Items( Int32? page )
{
    const String path = @"C:\Users\MyUser\Desktop\items-json\";
    const Int32 pageSize = 50;
    Int32 pageIndex = ( ( page ?? 1 ) - 1 ); // 0-based indexing!

    IReadOnlyList<FileInfo> files = new DirectoryInfo( path ).GetFiles("*.json");

    List<FileInfo> filesToRead = files
        .OrderBy( fi => fi.Name, StringComparer.OrdinalIgnoreCase )
        .Skip( pageSize * pageIndex )
        .Take( pageSize )
        .ToList();

    IReadOnlyList<ItemModel> items = await ReadJsonFilesAsync<ItemModel>( filesToRead ).ConfigureAwait(false);

    return this.View( items );
}

private static async Task<IReadOnlyList<T>> ReadJsonFilesAsync<T>( IEnumerable<FileInfo> jsonFiles )
{
    // Asynchronously read from all the files at once and let Windows' Overlapped-IO take care of it:
    List<Task<T>> tasks = jsonFiles
        .Select( fi => ReadJsonFileAsync<T>( fi.FullName ) )
        .ToList();

    T[] items = await Task.WhenAll( tasks ).ConfigureAwait(false);
    return items;
}

private static async Task<T> ReadJsonFileAsync<T>( String path )
{
    const Int32 asyncFileStreamBufferSize = 1 * 1024 * 1024; // Adjust this to be a reasonably sized multiple of 4096 that's at least larger than any file you'll process.

    using( FileStream fs = new FileStream( path: path, mode: FileMode.Open, access: FileAccess.Read, share: FileShare.Read, bufferSize: asyncFileStreamBufferSize, useAsync: true )
    using( StreamReader rdr = new StreamReader( fs ) )
    {
        // Annoyingly, JsonTextReader and JsonSerializer doesn't support true async deserialization - but the entire file will be buffered into a string anyway so it's moot - so we great perf at the cost of somewhat higher memory usage.
        String fileText = await rdr.ReadToEndAsync().ConfigureAwait(false);
        return JsonConvert.DeserializeObject<T>( fileText );
    }
}
</code>```

Body:
So I 'm trying to load some data that my website can use in order to display some items.
Each item is in a json format and this is what I'm doing.

When the user sends a request to load the page, it then tries to load 400 items (there are in total 26000, i'm just using 400 to test)
and obviously 400 is going to take a lot of time, and it does that when the user clicks next as well since it's using pagination.

And my idea was that maybe I could load like 50 at a time, which would make it way more efficient!
But I'm not sure what I could do in order to implement that thought.
I tried using foreach skip and take but I couldnt really come up with a decent algorithm.
Each file is between 1 and 2KB.

Would it improve the speed a lot if I just made it one file? Seeing how it would try to load it each time I click next or another page number.

public ActionResult Items(int? page)
        {
            var items = new List<ItemModel>();
            var path = @"C:\Users\MyUser\Desktop\items-json";
            var itemFiles = Directory.GetFiles(path);

            for (int i = 0; i < 400; i++)
            {
                try
                {
                    var json = System.IO.File.ReadAllText(itemFiles[i]);

                    var itemObject = JsonConvert.DeserializeObject<ItemModel>(json);
                    items.Add(itemObject);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            var pageNumber = page ?? 1;
            var onePageOfItems = items.ToPagedList(pageNumber, 10);
            //ViewBag.OnePageProducts = onePageOfProducts;
            return View(onePageOfItems);
        }

Body:
(My answer is assuming that you have to read individual files from-disk instead of storing data in a different medium such as a SQLite database file).

First-off, there's a huge bug in your code: the Directory.GetFiles() method does not guarantee any specific ordering of files - and pagination is meaningless without a defined ordering.

https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?redirectedfrom=MSDN&view=netframework-4.8#System_IO_Directory_GetFiles_System_String_

The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required.

Assuming that you want to order by filename, then we can use that as the basis of paging, and then read only those files.

The code below uses real async file IO (by creating a FileStream with async: true) which means it uses Windows' built-in Overlapped IO to handle asynchronous file-reads from multiple files - which should be much faster than serially synchronously reading from other files.

using System.Linq;
using System.Collections.Generic;
using System.IO;

public async Task<ActionResult> Items( Int32? page )
{
    const String path = @"C:\Users\MyUser\Desktop\items-json\";
    const Int32 pageSize = 50;
    Int32 pageIndex = ( ( page ?? 1 ) - 1 ); // 0-based indexing!

    IReadOnlyList<FileInfo> files = new DirectoryInfo( path ).GetFiles("*.json");

    List<FileInfo> filesToRead = files
        .OrderBy( fi => fi.Name, StringComparer.OrdinalIgnoreCase )
        .Skip( pageSize * pageIndex )
        .Take( pageSize )
        .ToList();

    IReadOnlyList<ItemModel> items = await ReadJsonFilesAsync<ItemModel>( filesToRead ).ConfigureAwait(false);

    return this.View( items );
}

private static async Task<IReadOnlyList<T>> ReadJsonFilesAsync<T>( IEnumerable<FileInfo> jsonFiles )
{
    // Asynchronously read from all the files at once and let Windows' Overlapped-IO take care of it:
    List<Task<T>> tasks = jsonFiles
        .Select( fi => ReadJsonFileAsync<T>( fi.FullName ) )
        .ToList();

    T[] items = await Task.WhenAll( tasks ).ConfigureAwait(false);
    return items;
}

private static async Task<T> ReadJsonFileAsync<T>( String path )
{
    const Int32 asyncFileStreamBufferSize = 1 * 1024 * 1024; // Adjust this to be a reasonably sized multiple of 4096 that's at least larger than any file you'll process.

    using( FileStream fs = new FileStream( path: path, mode: FileMode.Open, access: FileAccess.Read, share: FileShare.Read, bufferSize: asyncFileStreamBufferSize, useAsync: true )
    using( StreamReader rdr = new StreamReader( fs ) )
    {
        // Annoyingly, JsonTextReader and JsonSerializer doesn't support true async deserialization - but the entire file will be buffered into a string anyway so it's moot - so we great perf at the cost of somewhat higher memory usage.
        String fileText = await rdr.ReadToEndAsync().ConfigureAwait(false);
        return JsonConvert.DeserializeObject<T>( fileText );
    }
}


问:
Why does clang require a function to be declared before it's called in a template?
I have the following code example (available online at coliru):

#include <iostream>
#include <utility>

struct Bar {
    int a;
};

template <class T>
void print_arg(const T& arg) {
    std::cout << arg << std::endl;
}

std::ostream& operator<<(std::ostream& os, const Bar& b) {
    os << b.a;
    return os;
}

template <class T1, class T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& pair) {
    os << "Pair(" << pair.first << ',' << pair.second << ")";
    return os;
}

int main()
{
    auto bar = Bar{1};
    print_arg(bar);
    print_arg(std::make_pair(bar, bar));
    print_arg(std::make_pair(bar, 1));
    print_arg(std::make_pair(0, 1));
}
```

<p>The last line in the main function is what's giving me trouble. Compilation with g++ works just fine (with the exact same options as below), I launch the executable and it prints everything as expected. However, Clang++ gives me the following error:</p>

```$ clang++ -std=c++17 -O2 -Wall -Werror -Wpedantic main.cpp && ./a.out
main.cpp:10:15: error: call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup
    std::cout << arg << std::endl;
              ^
main.cpp:29:5: note: in instantiation of function template specialization 'print_arg<std::pair<int, int> >' requested here
    print_arg(std::make_pair(0, 1));
    ^
main.cpp:19:15: note: 'operator<<' should be declared prior to the call site
std::ostream& operator<<(std::ostream& os, const std::pair<T, T>& pair) {
              ^
1 error generated.
```

Furthermore, removing the last line (commenting it out) results in Clang++ compiling everything correctly. Which, as far as I can tell, means that std::pair<int, int> is qualitatively different from other parameter types.

My question is, why does g++ compile it eitherway? And more importantly, why does clang think it is ok to declare operator<<(ostream, pair<Bar, Bar>) later, but it's not ok for operator<<(ostream, pair<int, int>). Is it because the latter only includes standard and basic types?

To me the (somewhat) logical thing seems to be that defining functions only over standard/basic types is UB, but g++ silently ignores it and clang++ gives a weird-looking error message. However, that doesn't make a whole lot of sense to me and I can't find the relevant standard clause.

Note: I understand that moving the declaration up is what clang is asking for, but I don't understand why. I want to provide print_arg function in a separate header and allow the person that includes that header to specialize operator<< while using print_arg.

答:
The relevant text in the Standard is C++17 [temp.dep.res]/1:

In resolving dependent names, names from the following sources are considered:

Declarations that are visible at the point of definition of the template.

Declarations from namespaces associated with the types of the function arguments both from the instantiation context and from the definition context.

(This is elaborated on by temp.dep.candidate/1).

The problem situation in this code is the call std::cout << arg inside print_arg.  The name being looked up is operator<<. This is a dependent name because it's a function call with an argument whose type depends on a template parameter.

The definition context is the context where this expression occurs, i.e. inside print_arg.  Any declaration visible at this point is considered.

The instantiation context is defined by [temp.point]; in this code print_arg was called from main() so the instantiation context is at namespace scope after the end of main(). However , as covered by the second bullet point above,  the only names considered from the instantiation context are those found by argument-dependent lookup.

The argument of std::pair<Bar, int> or std::pair<Bar, Bar> has ADL classes of pair (therefore namespace std), and Bar (therefore the global namespace). ADL of a template type does include any template parameter types.

However in the case std::pair<int, int> the only ADL namespace is std, therefore ::operator<< is not found.

Important point to understand: the operator<<(ostream, pair) function was found due to the  global namespace being searched by ADL, which happened because Bar's use added the global namespace to the search list, even though this function doesn't mention Bar specifically.  If Bar were in some other namespace then all three calls should fail to compile.

Because of the reasons covered here, it's normally recommended to not add operator overloads unless at least one parameter is in a namespace defined by the user. Then it will always be found by ADL for the corresponding arguments.  It would be preferable to define your library in such a way that it does not overload for (ostream, pair) .

Body:
I have the following code example (available online at coliru):

#include <iostream>
#include <utility>

struct Bar {
    int a;
};

template <class T>
void print_arg(const T& arg) {
    std::cout << arg << std::endl;
}

std::ostream& operator<<(std::ostream& os, const Bar& b) {
    os << b.a;
    return os;
}

template <class T1, class T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& pair) {
    os << "Pair(" << pair.first << ',' << pair.second << ")";
    return os;
}

int main()
{
    auto bar = Bar{1};
    print_arg(bar);
    print_arg(std::make_pair(bar, bar));
    print_arg(std::make_pair(bar, 1));
    print_arg(std::make_pair(0, 1));
}

The last line in the main function is what's giving me trouble. Compilation with g++ works just fine (with the exact same options as below), I launch the executable and it prints everything as expected. However, Clang++ gives me the following error:

$ clang++ -std=c++17 -O2 -Wall -Werror -Wpedantic main.cpp && ./a.out
main.cpp:10:15: error: call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup
    std::cout << arg << std::endl;
              ^
main.cpp:29:5: note: in instantiation of function template specialization 'print_arg<std::pair<int, int> >' requested here
    print_arg(std::make_pair(0, 1));
    ^
main.cpp:19:15: note: 'operator<<' should be declared prior to the call site
std::ostream& operator<<(std::ostream& os, const std::pair<T, T>& pair) {
              ^
1 error generated.

Furthermore, removing the last line (commenting it out) results in Clang++ compiling everything correctly. Which, as far as I can tell, means that std::pair<int, int> is qualitatively different from other parameter types.

My question is, why does g++ compile it eitherway? And more importantly, why does clang think it is ok to declare operator<<(ostream, pair<Bar, Bar>) later, but it's not ok for operator<<(ostream, pair<int, int>). Is it because the latter only includes standard and basic types?

To me the (somewhat) logical thing seems to be that defining functions only over standard/basic types is UB, but g++ silently ignores it and clang++ gives a weird-looking error message. However, that doesn't make a whole lot of sense to me and I can't find the relevant standard clause.

Note: I understand that moving the declaration up is what clang is asking for, but I don't understand why. I want to provide print_arg function in a separate header and allow the person that includes that header to specialize operator<< while using print_arg.