问:
Replacing part of a string in pandas column with `and` condition
I have a pandas dataframe that looks like this:

```<code>    Size    Measure     Location    Messages
    Small     1         Washington  TXT0123 TXT0875 TXT874 TXT0867 TXT0875 TXT0874
    Medium    2         California  TXT020 TXT017 TXT120 TXT012
    Large     3         Texas       TXT0123 TXT0123 TXT0123 TXT0123 TXT0217 TXT0206
    Small     4         California  TXT020 TXT0217 TXT006
    Tiny      5         Nevada      TXT0206 TXT0217 TXT0206
</code>```

I am trying to remove the 0 from the individual words in the Messages column if the length equals 7 and the fourth character is 0.

I've tried for loop, but it's removing all 0's:

```<code>for line in df.Messages:
    for message in line.split():
        if len(message) == 7 and message[3] == '0':
            print(message.replace('0', ''))
</code>```

I also tried .map which gave me some errors:

```<code>df.Messages = df.Messages.map(lambda x: x.replace('0', '') for message in line.split() for line in df.Messages if (len(message) == 7 and message[3] == '0'))

TypeError: 'generator' object is not callable
</code>```

Is there a way to do this with .map that includes the if and and conditionals?

答:
Given you want to do this for each word, first split your column with str.split, call apply, and then re-join with str.join:

```<code>def f(l):
    return [w.replace('0', '') if len(w) == 7 and w[3] == '0' else w for w in l]

df.Messages.str.split().apply(f).str.join(' ')

0    TXT123 TXT875 TXT874 TXT867 TXT875 TXT874
1                  TXT020 TXT017 TXT120 TXT012
2     TXT123 TXT123 TXT123 TXT123 TXT217 TXT26
3                         TXT020 TXT217 TXT006
4                           TXT26 TXT217 TXT26
Name: Messages, dtype: object
</code>```

If you want to replace just the single 0 (and not all of them), use w.replace('0', '', 1) in function f instead.

Body:
I have a pandas dataframe that looks like this:

    Size    Measure     Location    Messages
    Small     1         Washington  TXT0123 TXT0875 TXT874 TXT0867 TXT0875 TXT0874
    Medium    2         California  TXT020 TXT017 TXT120 TXT012
    Large     3         Texas       TXT0123 TXT0123 TXT0123 TXT0123 TXT0217 TXT0206
    Small     4         California  TXT020 TXT0217 TXT006
    Tiny      5         Nevada      TXT0206 TXT0217 TXT0206

I am trying to remove the 0 from the individual words in the Messages column if the length equals 7 and the fourth character is 0.

I've tried for loop, but it's removing all 0's:

for line in df.Messages:
    for message in line.split():
        if len(message) == 7 and message[3] == '0':
            print(message.replace('0', ''))

I also tried .map which gave me some errors:

df.Messages = df.Messages.map(lambda x: x.replace('0', '') for message in line.split() for line in df.Messages if (len(message) == 7 and message[3] == '0'))

TypeError: 'generator' object is not callable

Is there a way to do this with .map that includes the if and and conditionals?

Body:
Given you want to do this for each word, first split your column with str.split, call apply, and then re-join with str.join:

def f(l):
    return [w.replace('0', '') if len(w) == 7 and w[3] == '0' else w for w in l]

df.Messages.str.split().apply(f).str.join(' ')

0    TXT123 TXT875 TXT874 TXT867 TXT875 TXT874
1                  TXT020 TXT017 TXT120 TXT012
2     TXT123 TXT123 TXT123 TXT123 TXT217 TXT26
3                         TXT020 TXT217 TXT006
4                           TXT26 TXT217 TXT26
Name: Messages, dtype: object

If you want to replace just the single 0 (and not all of them), use w.replace('0', '', 1) in function f instead.


来源: stackexchange

问:
Why do I get a blank return during this SQL query?
```<code>SELECT dependents.[Dependent_name],
       "Child of " + employee.[Lname] + "," + employee.[Fname] AS Dependence
FROM dependents, employees AS employee
WHERE employee.[Lname] LIKE 'W%'
  AND employee.Ssn = dependents.Essn
  AND NOT dependents.Relationship = "Spouse"
ORDER BY employee.[Lname], dependents.[Dependent_name];
</code>```

<p>I'm attempting to create a query that will return a table with 2 fields. Those being dependent_name and Dependence. The only thing that is not properly functioning is the LIKE condition and I do not know why. It causes the whole table to not return anything. It should return 2 entries </p>

答:
MS Access uses * as the wildcard in LIKE, not %.  So, try this WHERE condition:

```<code>WHERE employee.[Lname] LIKE 'W*' AND
      . . .
</code>```

ContentLicense: CC BY-SA 3.0

Body:
SELECT dependents.[Dependent_name],
       "Child of " + employee.[Lname] + "," + employee.[Fname] AS Dependence
FROM dependents, employees AS employee
WHERE employee.[Lname] LIKE 'W%'
  AND employee.Ssn = dependents.Essn
  AND NOT dependents.Relationship = "Spouse"
ORDER BY employee.[Lname], dependents.[Dependent_name];

I'm attempting to create a query that will return a table with 2 fields. Those being dependent_name and Dependence. The only thing that is not properly functioning is the LIKE condition and I do not know why. It causes the whole table to not return anything. It should return 2 entries

Body:
MS Access uses * as the wildcard in LIKE, not %.  So, try this WHERE condition:

WHERE employee.[Lname] LIKE 'W*' AND
      . . .


问:
Javascript Replace All words
I need to replace all the words in a DOM (web page in memory) using jquery and javascript.
I need to transform this:

```<code><html>
<head>
    Hi to all
</head>
<body>
    Hi to all
</body>
</html>
</code>```

Into this:

```<code><html>
    <head>
        Bye to all
    </head>
    <body>
        Bye to all
    </body>
</html>
</code>```

But without modifying the tags (ONLY THE VALUES IN THERE)

One try is:

```<code>jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}
</code>```

But it continue replacing the tag values and breaks the page if I put it.

Help!!!

答:
if you don't want it to change your tags, why do you modify the "html"and not just the text?</p>

```
jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).text( $(this).text().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}
```

ContentLicense: CC BY-SA 2.5

Title: Javascript Replace All words

Body:
I need to replace all the words in a DOM (web page in memory) using jquery and javascript.
I need to transform this:

    Hi to all

    Hi to all

Into this:

        Bye to all

        Bye to all

But without modifying the tags (ONLY THE VALUES IN THERE)

One try is:

jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}

But it continue replacing the tag values and breaks the page if I put it.

Help!!!

Body:
if you don't want it to change your tags, why do you modify the "html"and not just the text?

jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).text( $(this).text().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}


问:
(R, dplyr) select multiple columns starts with same string and summarise mean (90% CI) by group
I am new to tidyverse, conceptually I would like to calculate mean and 90% CI of all columns starts with "ab", grouped by "case". Tried many ways but none seem to work, my actual data has many columns so explicitly list them out is not an option.

test data below

```<code>library(tidyverse)

dat <- tibble(case= c("case1", "case1", "case2", "case2", "case3"),
              abc = c(1, 2, 3, 1, 2),
              abe = c(1, 3, 2, 3, 4),
              bca = c(1, 6, 3, 8, 9))
</code>```

below code is what i would like to do conceptually, but doesn't work, obviously

```<code>dat %>% group_by(`case`) %>%
  summarise(mean=mean(select(starts_with("ab"))),
            qt=quantile(select(starts_with("ab"), prob=c(0.05, 0.95))))
</code>```

what I would like to get is something like below

```<code>case abc_mean abe_mean abc_lb abc_ub abe_lb abe_ub

  <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 case1      1.5      2.0   1.05   1.95   1.10   2.90
2 case2      2.0      2.5   1.10   2.90   2.05   2.95
3 case3      2.0      4.0   2.00   2.00   4.00   4.00
</code>```

答:
Another option is summarise_at. vars(starts_with("ab")) is for selecting columns, funs(...) is to apply summarzing functions.

```<code>library(tidyverse)

dat2 <- dat %>%
  group_by(case) %>%
  summarise_at(vars(starts_with("ab")), funs(mean = mean(.),
                                             lb = quantile(., prob = 0.05),
                                             ub = quantile(., prob = 0.95)))
dat2
# # A tibble: 3 x 7
#    case abc_mean abe_mean abc_lb abe_lb abc_ub abe_ub
#   <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
# 1 case1      1.5      2.0   1.05   1.10   1.95   2.90
# 2 case2      2.0      2.5   1.10   2.05   2.90   2.95
# 3 case3      2.0      4.0   2.00   4.00   2.00   4.00
</code>```

Body:
I am new to tidyverse, conceptually I would like to calculate mean and 90% CI of all columns starts with "ab", grouped by "case". Tried many ways but none seem to work, my actual data has many columns so explicitly list them out is not an option.

test data below

library(tidyverse)

dat <- tibble(case= c("case1", "case1", "case2", "case2", "case3"),
              abc = c(1, 2, 3, 1, 2),
              abe = c(1, 3, 2, 3, 4),
              bca = c(1, 6, 3, 8, 9))

below code is what i would like to do conceptually, but doesn't work, obviously

dat %>% group_by(`case`) %>%
  summarise(mean=mean(select(starts_with("ab"))),
            qt=quantile(select(starts_with("ab"), prob=c(0.05, 0.95))))

what I would like to get is something like below

case abc_mean abe_mean abc_lb abc_ub abe_lb abe_ub

  <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 case1      1.5      2.0   1.05   1.95   1.10   2.90
2 case2      2.0      2.5   1.10   2.90   2.05   2.95
3 case3      2.0      4.0   2.00   2.00   4.00   4.00

Body:
Another option is summarise_at. vars(starts_with("ab")) is for selecting columns, funs(...) is to apply summarzing functions.

library(tidyverse)

dat2 <- dat %>%
  group_by(case) %>%
  summarise_at(vars(starts_with("ab")), funs(mean = mean(.),
                                             lb = quantile(., prob = 0.05),
                                             ub = quantile(., prob = 0.95)))
dat2
# # A tibble: 3 x 7
#    case abc_mean abe_mean abc_lb abe_lb abc_ub abe_ub
#   <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
# 1 case1      1.5      2.0   1.05   1.10   1.95   2.90
# 2 case2      2.0      2.5   1.10   2.05   2.90   2.95
# 3 case3      2.0      4.0   2.00   4.00   2.00   4.00


问:
Bash: How can I cut ignoring the delimiters found in between " "?
Consider the following file

```<code>col1 col2 col3 col4 col5
3 5 "Hello World" 2 8
20 NA "Alice" 1 6
1 1 "A B C" 1 154
</code>```

I would like select the first three columns. The expected output is

```<code>col1 col2 col3
3 5 "Hello World"
20 NA "Alice"
1 1 "A B C"
</code>```

I naively tried

```<code>$cut -d" " -f -3 myFile.txt
col1 col2 col3
3 5 "Hello
20 NA "Alice"
1 1 "A
</code>```

I am having difficulties due to the spaces in between " ". How can I cut ignoring the delimiters found in between " "?

答:
Probably not the most elegant solution but here is what I came up with</p>

```<code>cat myfile | awk '
{
    split($0, chars, "")
    nbQuotes=0
    nbColumns=1
    for (i=1 ; i <= length($0); i++)
    {
        if (chars[i] == "\"")
        {
            nbQuotes++
        } else
        {
            if (nbQuotes%2 == 0)
            {
                if (chars[i] == " ")
                {
                    nbColumns++
                }
            }
        }
        if (nbColumns > 3)
        {
            break
        }
        printf chars[i]
    }
    print ""
}
'

col1 col2 col3
3 5 "Hello World"
20 NA "Alice"
1 1 "A B C"
</code>```

Body:
Consider the following file

col1 col2 col3 col4 col5
3 5 "Hello World" 2 8
20 NA "Alice" 1 6
1 1 "A B C" 1 154

I would like select the first three columns. The expected output is

col1 col2 col3
3 5 "Hello World"
20 NA "Alice"
1 1 "A B C"

I naively tried

$cut -d" " -f -3 myFile.txt
col1 col2 col3
3 5 "Hello
20 NA "Alice"
1 1 "A

I am having difficulties due to the spaces in between " ". How can I cut ignoring the delimiters found in between " "?

Body:
Probably not the most elegant solution but here is what I came up with

cat myfile | awk '
{
    split($0, chars, "")
    nbQuotes=0
    nbColumns=1
    for (i=1 ; i <= length($0); i++)
    {
        if (chars[i] == "\"")
        {
            nbQuotes++
        } else
        {
            if (nbQuotes%2 == 0)
            {
                if (chars[i] == " ")
                {
                    nbColumns++
                }
            }
        }
        if (nbColumns > 3)
        {
            break
        }
        printf chars[i]
    }
    print ""
}
'

col1 col2 col3
3 5 "Hello World"
20 NA "Alice"
1 1 "A B C"


问:
List of possible combinations of characters with OR statement
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?  </p>

```<code>items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
</code>```

答:
like this for example</p>

```<code>items = ['a', 'b', 'c','d']
from itertools import permutations
for p in permutations(items):
     print(p)

items = ['a', 'b', 'c','f']
from itertools import permutations
for p in permutations(items):
     print(p)
</code>```

Body:
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?

items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

Body:
like this for example

items = ['a', 'b', 'c','d']
from itertools import permutations
for p in permutations(items):
     print(p)

items = ['a', 'b', 'c','f']
from itertools import permutations
for p in permutations(items):
     print(p)


问:
Customer Search with data from database
we're trying to create a search feature for our site.
The products are in the database and the goal would be to have the search feature use words that are in the title and description of the products inside the database. I was wondering if they where tools out there to build this kind of features. Meaning having some framework that can remove useless words from the description like 'the', 'for', 'and' etc

Without going overboard with big servers like ElastiqSearch.

答:
Well i am not sure what you mean? Can't you use linq or sth like that?
you can use the .Contains() that .net provides for strings.</p>

ContentLicense: CC BY-SA 4.0

Title: Customer Search with data from database


问:
2D map with Java streams
I am learning Java Streams and want to replace the below code with java 8 features.

I have a list of points with X and Y coordinates and a direction arrow:

```<code>final List<PathStep> path;
</code>```

and I want to convert the above list to a map of maps like in the following Java 7 code:

```<code>    final Map<Integer, Map<Integer, Direction>> map = new HashMap<>();

    for (final PathStep pathStep : path) {
        final Coordinate coordinate = pathStep.getCoordinate();
        final int y = coordinate.getY();

        if (!map.containsKey(y)) {
            map.put(y, new HashMap<>());
        }

        final Map<Integer, Direction> mapY = map.get(y);
        mapY.put(coordinate.getX(), pathStep.getDirection());
    }
</code>```

I was able to use stream.filter() and stream.map features, but I could not replace the above code with java 8 features.

Any pointers would be highly appreciated!

答:
You can collect with groupingBy() and a nested toMap(). Assuming path is a Collection<PathStep>:

```<code>final Map<Integer, Map<Integer, Direction>> map = path.stream().collect(
        Collectors.groupingBy(
                step -> step.getCoordinate().getY(),
                Collectors.toMap(
                        step -> step.getCoordinate().getX(),
                        step -> step.getDirection())));
</code>```

Title: 2D map with Java streams

Body:
I am learning Java Streams and want to replace the below code with java 8 features.

I have a list of points with X and Y coordinates and a direction arrow:

final List<PathStep> path;

and I want to convert the above list to a map of maps like in the following Java 7 code:

    final Map<Integer, Map<Integer, Direction>> map = new HashMap<>();

    for (final PathStep pathStep : path) {
        final Coordinate coordinate = pathStep.getCoordinate();
        final int y = coordinate.getY();

        if (!map.containsKey(y)) {
            map.put(y, new HashMap<>());
        }

        final Map<Integer, Direction> mapY = map.get(y);
        mapY.put(coordinate.getX(), pathStep.getDirection());
    }

I was able to use stream.filter() and stream.map features, but I could not replace the above code with java 8 features.

Any pointers would be highly appreciated!

Body:
You can collect with groupingBy() and a nested toMap(). Assuming path is a Collection<PathStep>:

final Map<Integer, Map<Integer, Direction>> map = path.stream().collect(
        Collectors.groupingBy(
                step -> step.getCoordinate().getY(),
                Collectors.toMap(
                        step -> step.getCoordinate().getX(),
                        step -> step.getDirection())));


问:
Highlight rough mistakes in JavaScript files in Visual Studio Code?
Is there a way to get syntax highlighting for rough mistakes in JavaScript in Visual Studio Code?

By rough mistakes I mean things like an attempt to use a variable which doesn't exist.

答:
You can try adding this comment at the start of your js file:

// @ts-check
```


问:
local variable access by workers in julia
Let's say I have some data :: Vector{Float64} and a function f!(data::Vector{Float64}, i::Int) that calculates some value from it, modifying it in the process.

```<code>answers = pmap([1,2,3,4]) do i
    f!(data, i)
end
</code>```

Is this safe to do?  Does each worker have its own copy of data, or should I explicitly copy(data) on all workers?

答: That is safe to do and will create a closure that puts the data in the function and sends the function with the data to each process. If you use a CachingPool it will make sure that data is only sent to each worker once (in Julia v0.7 and 1.0 this will be done by default).

Body:
Let's say I have some data :: Vector{Float64} and a function f!(data::Vector{Float64}, i::Int) that calculates some value from it, modifying it in the process.

answers = pmap([1,2,3,4]) do i
    f!(data, i)
end

Is this safe to do?  Does each worker have its own copy of data, or should I explicitly copy(data) on all workers?


问:
Java: ternary operator with single line if stmt
Could you help me to write efficient Java code.

The logic is:
I have to read the first valid record in a file and generate a file name. The invalid/valid records are identified by the first 2 chars of the line. Invalid record first 2 chars are populated in an ArrayList named ignoreTrans(passed as arguments).

There are 2 scenarios:-
Scenario 1: all the records in a file are valid in this case ignoreTrans will be empty
Scenario 2: File has invalid records where ignoreTrans is populated from the passed arguments.

I wanted to write a ternary operator like below:

```<code>FileName = ignoreTrans.isEmpty() ? getFileName(pos) : (if (!ignoreTrans.contains(line.substring(0,2))) getFieldName(pos));
</code>```

This statement is erroring. Could you suggest how to use ternary with if.

Thank you,

答:
Try

```<code>FileName = ignoreTrans.isEmpty() ? getFileName(pos) : !ignoreTrans.contains(line.substring(0,2))) ? getFieldName(pos) : "";
</code>```

Just like how you can have a nested if structure, you can nest ternary operators too.

Body:
Could you help me to write efficient Java code.

The logic is:
I have to read the first valid record in a file and generate a file name. The invalid/valid records are identified by the first 2 chars of the line. Invalid record first 2 chars are populated in an ArrayList named ignoreTrans(passed as arguments).

There are 2 scenarios:-
Scenario 1: all the records in a file are valid in this case ignoreTrans will be empty
Scenario 2: File has invalid records where ignoreTrans is populated from the passed arguments.

I wanted to write a ternary operator like below:

FileName = ignoreTrans.isEmpty() ? getFileName(pos) : (if (!ignoreTrans.contains(line.substring(0,2))) getFieldName(pos));

This statement is erroring. Could you suggest how to use ternary with if.

Thank you,

Body:
Try

FileName = ignoreTrans.isEmpty() ? getFileName(pos) : !ignoreTrans.contains(line.substring(0,2))) ? getFieldName(pos) : "";

Just like how you can have a nested if structure, you can nest ternary operators too.


问:
Any openssl command line to verify ECDSA prime256v1 certificate and private key match?
I'm now testing the hyperledger/fabric/core/comm/testdata/certs/generate.go to get the ECDSA prime256v1 certificate(Org1-cert.pem) and private key(Org1-key.pem).
I want to use a openssl command line to test if the Org1-cert.pem mathes the Org1-key.pem, but don't know how? Any help appreciated.
I've used the command, but the results don't match the same.

```<code># openssl x509 -pubkey -in Org1-cert.pem -noout | openssl md5
</code>```

(stdin)= 4f8782bbec9d258553f0c0c7c6879fef

```<code># openssl pkey -pubout -in Org1-key.pem | openssl md5
</code>```

(stdin)= 98c3ec3c2971648f2721915ff7e80479

more info about Org1-cert.pem and Org1-key.pem below:

```<code># openssl x509 -in Org1-cert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            50:0a:7a:e4:31:6e:1b:57:68:48:26:d7:a0:c5:9c:da
    Signature Algorithm: ecdsa-with-SHA256
        Issuer: C = US, ST = California, L = San Francisco, O = Org1, CN = Org1
        Validity
            Not Before: Nov 13 09:09:06 2017 GMT
            Not After : Nov 11 09:09:06 2027 GMT
        Subject: C = US, ST = California, L = San Francisco, O = Org1, CN = Org1
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:ac:bb:17:91:91:1e:72:38:d2:aa:9a:2d:17:c8:
                    50:80:18:58:4a:a8:6a:40:0a:a8:2a:a8:58:33:46:
                    ae:2c:48:67:28:c7:af:59:09:92:01:68:15:cd:e5:
                    c0:84:d1:1e:3e:03:60:25:8b:55:89:3e:e9:e2:f1:
                    23:3e:e4:c4:c8
                ASN1 OID: prime256v1
                NIST CURVE: P-256
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment, Certificate Sign, CRL Sign
            X509v3 Extended Key Usage:
                Any Extended Key Usage
            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Subject Key Identifier:
                01:02:03:04
    Signature Algorithm: ecdsa-with-SHA256
         30:46:02:21:00:b4:81:76:75:fe:a1:1c:14:94:3e:d6:eb:b3:
         43:02:27:32:46:2e:c0:6d:b7:94:3b:9d:a9:05:ad:c9:10:29:
         34:02:21:00:80:31:3c:00:18:b3:c0:be:1d:73:dc:ab:9b:aa:
         28:75:86:bc:2a:97:64:9d:65:5f:6f:6f:a0:c8:38:aa:2c:35

    # more Org1-key.pem

-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDgnuzTIxFYZorg/lKBQxwpyXWH7zREzuO8Gle9p8CzQoAoGCCqGSM49
AwEHoUQDQgAEsYeTGiApHX1SJAZ7HmroVR1YNBH6wc0WqiNWO/N3XG/aWxksYLA8
s2asE88Z5EOWs1qMLig2nyv3CL0H2VI0zg==
-----END EC PRIVATE KEY-----

    # more Org1-cert.pem

-----BEGIN CERTIFICATE-----
MIIB8jCCAZegAwIBAgIQUAp65DFuG1doSCbXoMWc2jAKBggqhkjOPQQDAjBYMQsw
CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy
YW5jaXNjbzENMAsGA1UEChMET3JnMTENMAsGA1UEAxMET3JnMTAeFw0xNzExMTMw
OTA5MDZaFw0yNzExMTEwOTA5MDZaMFgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpD
YWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMQ0wCwYDVQQKEwRPcmcx
MQ0wCwYDVQQDEwRPcmcxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAErLsXkZEe
cjjSqpotF8hQgBhYSqhqQAqoKqhYM0auLEhnKMevWQmSAWgVzeXAhNEePgNgJYtV
iT7p4vEjPuTEyKNDMEEwDgYDVR0PAQH/BAQDAgGmMA8GA1UdJQQIMAYGBFUdJQAw
DwYDVR0TAQH/BAUwAwEB/zANBgNVHQ4EBgQEAQIDBDAKBggqhkjOPQQDAgNJADBG
AiEAtIF2df6hHBSUPtbrs0MCJzJGLsBtt5Q7nakFrckQKTQCIQCAMTwAGLPAvh1z
3Kubqih1hrwql2SdZV9vb6DIOKosNQ==
-----END CERTIFICATE-----
</code>```

答:
You can verify that a certificate and any supported key (including an ECDSA prime256v1 key) match using OpenSSL.

This command will get the public key from the certificate:

```<code>openssl x509 -noout -pubkey -in Org1-cert.pem
</code>```

This command will get the public key from the key:

```<code>openssl pkey -pubout -in Org1-key.pem
</code>```

You can compare them visually...

OR you can automate the comparison of any cert and key as follows with Bash:

Create a script called verify-cert-key:

```<code>#!/usr/bin/env bash
certFile="${1}"
keyFile="${2}"
certPubKey="$(openssl x509 -noout -pubkey -in "${certFile}")"
keyPubKey="$(openssl pkey -pubout -in "${keyFile}")"
if [[ "${certPubKey}" == "${keyPubKey}" ]]
then
  echo "PASS: key and cert match"
else
  echo "FAIL: key and cert DO NOT match"
fi
</code>```

Make the script executable:

```<code>chmod +x verify-cert-key
</code>```

Run it:

```<code>./verify-cert-key Org1-cert.pem Org1-key.pem
</code>```

CAVEAT: openssl on macOS Sierra doesn't have pkey

On macOS Sierra, the script may say "FAIL: key and cert DO NOT match" even if they do.

Verify that pkey is missing:

```<code>openssl pkey -in
</code>```

If it is missing, you will see this:

```<code>openssl:Error: 'pkey' is an invalid command.
</code>```

Followed by tons of other usage summary output from OpenSSL.

You may also see "openssl:Error: 'pkey' is an invalid command."

If pkey is missing, you'll need install a newer openssl and set your PATH accordingly.

I installed a newer OpenSSL with Homebrew and set my PATH like this:

```<code>export PATH=/usr/local/Cellar/openssl/1.0.2m/bin/:$PATH
</code>```

Verify that pkey is available:

```<code>openssl pkey -in
</code>```

This should show pkey usage summary:

```<code>Usage pkey [options]
where options are
</code>```

Now the script should work as expected.

Body:
I'm now testing the hyperledger/fabric/core/comm/testdata/certs/generate.go to get the ECDSA prime256v1 certificate(Org1-cert.pem) and private key(Org1-key.pem).
I want to use a openssl command line to test if the Org1-cert.pem mathes the Org1-key.pem, but don't know how? Any help appreciated.
I've used the command, but the results don't match the same.

# openssl x509 -pubkey -in Org1-cert.pem -noout | openssl md5

(stdin)= 4f8782bbec9d258553f0c0c7c6879fef

# openssl pkey -pubout -in Org1-key.pem | openssl md5

(stdin)= 98c3ec3c2971648f2721915ff7e80479

more info about Org1-cert.pem and Org1-key.pem below:

# openssl x509 -in Org1-cert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            50:0a:7a:e4:31:6e:1b:57:68:48:26:d7:a0:c5:9c:da
    Signature Algorithm: ecdsa-with-SHA256
        Issuer: C = US, ST = California, L = San Francisco, O = Org1, CN = Org1
        Validity
            Not Before: Nov 13 09:09:06 2017 GMT
            Not After : Nov 11 09:09:06 2027 GMT
        Subject: C = US, ST = California, L = San Francisco, O = Org1, CN = Org1
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:ac:bb:17:91:91:1e:72:38:d2:aa:9a:2d:17:c8:
                    50:80:18:58:4a:a8:6a:40:0a:a8:2a:a8:58:33:46:
                    ae:2c:48:67:28:c7:af:59:09:92:01:68:15:cd:e5:
                    c0:84:d1:1e:3e:03:60:25:8b:55:89:3e:e9:e2:f1:
                    23:3e:e4:c4:c8
                ASN1 OID: prime256v1
                NIST CURVE: P-256
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment, Certificate Sign, CRL Sign
            X509v3 Extended Key Usage:
                Any Extended Key Usage
            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Subject Key Identifier:
                01:02:03:04
    Signature Algorithm: ecdsa-with-SHA256
         30:46:02:21:00:b4:81:76:75:fe:a1:1c:14:94:3e:d6:eb:b3:
         43:02:27:32:46:2e:c0:6d:b7:94:3b:9d:a9:05:ad:c9:10:29:
         34:02:21:00:80:31:3c:00:18:b3:c0:be:1d:73:dc:ab:9b:aa:
         28:75:86:bc:2a:97:64:9d:65:5f:6f:6f:a0:c8:38:aa:2c:35

    # more Org1-key.pem

-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDgnuzTIxFYZorg/lKBQxwpyXWH7zREzuO8Gle9p8CzQoAoGCCqGSM49
AwEHoUQDQgAEsYeTGiApHX1SJAZ7HmroVR1YNBH6wc0WqiNWO/N3XG/aWxksYLA8
s2asE88Z5EOWs1qMLig2nyv3CL0H2VI0zg==
-----END EC PRIVATE KEY-----

    # more Org1-cert.pem

-----BEGIN CERTIFICATE-----
MIIB8jCCAZegAwIBAgIQUAp65DFuG1doSCbXoMWc2jAKBggqhkjOPQQDAjBYMQsw
CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy
YW5jaXNjbzENMAsGA1UEChMET3JnMTENMAsGA1UEAxMET3JnMTAeFw0xNzExMTMw
OTA5MDZaFw0yNzExMTEwOTA5MDZaMFgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpD
YWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMQ0wCwYDVQQKEwRPcmcx
MQ0wCwYDVQQDEwRPcmcxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAErLsXkZEe
cjjSqpotF8hQgBhYSqhqQAqoKqhYM0auLEhnKMevWQmSAWgVzeXAhNEePgNgJYtV
iT7p4vEjPuTEyKNDMEEwDgYDVR0PAQH/BAQDAgGmMA8GA1UdJQQIMAYGBFUdJQAw
DwYDVR0TAQH/BAUwAwEB/zANBgNVHQ4EBgQEAQIDBDAKBggqhkjOPQQDAgNJADBG
AiEAtIF2df6hHBSUPtbrs0MCJzJGLsBtt5Q7nakFrckQKTQCIQCAMTwAGLPAvh1z
3Kubqih1hrwql2SdZV9vb6DIOKosNQ==
-----END CERTIFICATE-----

Body:
You can verify that a certificate and any supported key (including an ECDSA prime256v1 key) match using OpenSSL.

This command will get the public key from the certificate:

openssl x509 -noout -pubkey -in Org1-cert.pem

This command will get the public key from the key:

openssl pkey -pubout -in Org1-key.pem

You can compare them visually...

OR you can automate the comparison of any cert and key as follows with Bash:

Create a script called verify-cert-key:

#!/usr/bin/env bash
certFile="${1}"
keyFile="${2}"
certPubKey="$(openssl x509 -noout -pubkey -in "${certFile}")"
keyPubKey="$(openssl pkey -pubout -in "${keyFile}")"
if [[ "${certPubKey}" == "${keyPubKey}" ]]
then
  echo "PASS: key and cert match"
else
  echo "FAIL: key and cert DO NOT match"
fi

Make the script executable:

chmod +x verify-cert-key

Run it:

./verify-cert-key Org1-cert.pem Org1-key.pem

CAVEAT: openssl on macOS Sierra doesn't have pkey

On macOS Sierra, the script may say "FAIL: key and cert DO NOT match" even if they do.

Verify that pkey is missing:

openssl pkey -in

If it is missing, you will see this:

openssl:Error: 'pkey' is an invalid command.

Followed by tons of other usage summary output from OpenSSL.

You may also see "openssl:Error: 'pkey' is an invalid command."

If pkey is missing, you'll need install a newer openssl and set your PATH accordingly.

I installed a newer OpenSSL with Homebrew and set my PATH like this:

export PATH=/usr/local/Cellar/openssl/1.0.2m/bin/:$PATH

Verify that pkey is available:

openssl pkey -in

This should show pkey usage summary:

Usage pkey [options]
where options are

Now the script should work as expected.


问:
Details on Selenium ChromeDriver options
Here is my code:

```<code>namespace WindowsFormsApplication11
{
public partial class Form1 : Form // Se declara driver, variables.
{

    public  IWebDriver driver = new ChromeDriver()

    public Form1() // Se inicia Form y se minimiza cmd
    {

        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
</code>```

And I can't set ChromeOptions to the WebDriver, and I want to change the Start Page of the driver (it starts on "data:,").

If I try to put ChromeOptions over or above of:

```<code> public  IWebDriver driver = new ChromeDriver();
</code>```

It doesn't let me cause "driver" doesn't exist.

I wish I could post the entire CODE but I'm not allowed, so if this isn't ok, make me know.

Some help?

答:
You can put the instantiation in the loading method of the form. Here you can also create the options and give them to the webdriver :</p>

```<code>private void Form1_Load(object sender, EventArgs e)
{
    ChromeOptions options = new ChromeOptions();
    ...
    driver = new ChromeDriver(options);
}
</code>```

Body:
Here is my code:

namespace WindowsFormsApplication11
{
public partial class Form1 : Form // Se declara driver, variables.
{

    public  IWebDriver driver = new ChromeDriver()

    public Form1() // Se inicia Form y se minimiza cmd
    {

        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

And I can't set ChromeOptions to the WebDriver, and I want to change the Start Page of the driver (it starts on "data:,").

If I try to put ChromeOptions over or above of:

 public  IWebDriver driver = new ChromeDriver();

It doesn't let me cause "driver" doesn't exist.

I wish I could post the entire CODE but I'm not allowed, so if this isn't ok, make me know.

Some help?

Body:
You can put the instantiation in the loading method of the form. Here you can also create the options and give them to the webdriver :

private void Form1_Load(object sender, EventArgs e)
{
    ChromeOptions options = new ChromeOptions();
    ...
    driver = new ChromeDriver(options);
}


问:
How to scale SVG elements separately.
I am making a graph in D3, and I am trying to scale the Y axis of the graph on window resize, without scaling the size of the elements within it. (And I don't want to have to redraw the graph).

To say this another way, I want to be able to use SVG to scale the distance between objects, without changing the size of the objects.

Reading the last part of this article and seems to suggest I can, but I can't seem to get the details right.

Here is an simplified codepen of what I am trying to do:
https://codepen.io/thesuperuser/pen/BmdNwz/

```<code><symbol id="circle" width="20" height="20" preserveAspectRatio="none">
  <circle cx="10" cy="10" r=10></circle>
</symbol>
</code>```

and then I use this symbol, and try and preserve the size of the symbol with d3

```<code>let svg2 = d3.select('svg.scaled')
svg2.selectAll('use')
  .data(data)
  .enter()
  .append('use')
  .attrs({
    class: 'circle',
    href: '#circle2',
    x: d => scale(d),
    y: '50%',
    height: dotR*2,
    width: dotR*2,
  })
</code>```

This seems to just duplicate the behavior in the first example, which scales both size and distance the way you would expect viewBox and preserveAspectRatio to behave.

答:
If you set a viewBox for the svg element, it will scale that viewBox including all content to fit the viewport. What you want is the opposite: a svg element where content positioning can vary, but nothing gets scaled. The key to this is relative (percentage) units.

Here is a working pattern:

```<code><svg width="100%" height="200">
  <symbol viewBox="0 0 20 20" preserveAspectRatio="xMidYMid meet">
    <circle id="circle" cx="10" cy="10" r="10" />
  </symbol>
  <use xlink:href="#circle" x="5%" y="50%" width="10%" height="20" />
  <use xlink:href="#circle" x="15%" y="50%" width="10%" height="20" />
  ...
</svg>
</code>```

This way, when the width of the SVG changes, the viewports of the use elements change their width, but not their height. The circles rendered inside them fit the constant height (as long as the viewports are wider than high). preserveAspectRatio="xMid..." and the viewport x and width result in the circle being centered at 10%, 20%, ... Change these to position the circles as needed.

Here's a codepen to demonstrate with d3.

Title: How to scale SVG elements separately.

Body:
I am making a graph in D3, and I am trying to scale the Y axis of the graph on window resize, without scaling the size of the elements within it. (And I don't want to have to redraw the graph).

To say this another way, I want to be able to use SVG to scale the distance between objects, without changing the size of the objects.

Reading the last part of this article and seems to suggest I can, but I can't seem to get the details right.

Here is an simplified codepen of what I am trying to do:
https://codepen.io/thesuperuser/pen/BmdNwz/

<symbol id="circle" width="20" height="20" preserveAspectRatio="none">
  <circle cx="10" cy="10" r=10></circle>
</symbol>

and then I use this symbol, and try and preserve the size of the symbol with d3

let svg2 = d3.select('svg.scaled')
svg2.selectAll('use')
  .data(data)
  .enter()
  .append('use')
  .attrs({
    class: 'circle',
    href: '#circle2',
    x: d => scale(d),
    y: '50%',
    height: dotR*2,
    width: dotR*2,
  })

This seems to just duplicate the behavior in the first example, which scales both size and distance the way you would expect viewBox and preserveAspectRatio to behave.

Body:
If you set a viewBox for the svg element, it will scale that viewBox including all content to fit the viewport. What you want is the opposite: a svg element where content positioning can vary, but nothing gets scaled. The key to this is relative (percentage) units.

Here is a working pattern:

<svg width="100%" height="200">
  <symbol viewBox="0 0 20 20" preserveAspectRatio="xMidYMid meet">
    <circle id="circle" cx="10" cy="10" r="10" />
  </symbol>
  <use xlink:href="#circle" x="5%" y="50%" width="10%" height="20" />
  <use xlink:href="#circle" x="15%" y="50%" width="10%" height="20" />
  ...
</svg>

This way, when the width of the SVG changes, the viewports of the use elements change their width, but not their height. The circles rendered inside them fit the constant height (as long as the viewports are wider than high). preserveAspectRatio="xMid..." and the viewport x and width result in the circle being centered at 10%, 20%, ... Change these to position the circles as needed.

Here's a codepen to demonstrate with d3.


问:
ASP.NET MVC - Easy way to temporarily require authorisation for whole site except one page
I am building a site with a mixture of public and member-only pages.  The login system works fine as it is.

However I'd like to launch a closed, invite-only preview and temporarily require visitors log in for all actions except the welcome page.

Currently I have [Authorize] attributes on certain action methods.  I could add additional attributes to the other action methods too, but this feels a bit hacky and will make it harder to remove them correctly later when I want to revert to having more open content.

So, how can I effectively add a site-wide authorisation requirement?  Recall that I want the single /Home/Index route to remain public as well, so that people I've invited can read some information before activating their invites.

答:
Add a custom filter - here's my implementation for a similar requirement. The main difference from what you describe is that it requires a role set from the invite page rather than letting in any logged in user.</p>

```<code>public class PreviewAuthAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // if site is live, show page
        if (Data.Settings.IsLive) return;

        // if request is from localhost or build server, show page
        if (filterContext.HttpContext.Request.IsLocal) return;
        if (filterContext.HttpContext.Request.UserHostAddress.StartsWith("192.168.0")) return;

        // if user has has alpha or admin role, show page
        if (filterContext.HttpContext.Request.IsAuthenticated && (filterContext.HttpContext.User.IsInRole("Alpha") || filterContext.HttpContext.User.IsInRole("Admin"))) return;

        // site is not live and user does not have access - show placeholder

        filterContext.Result = new ViewResult()
        {
            ViewName="Placeholder",
            ViewData = filterContext.Controller.ViewData,
            TempData = filterContext.Controller.TempData
        };
    }

}
</code>```

Body:
Add a custom filter - here's my implementation for a similar requirement. The main difference from what you describe is that it requires a role set from the invite page rather than letting in any logged in user.

public class PreviewAuthAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // if site is live, show page
        if (Data.Settings.IsLive) return;

        // if request is from localhost or build server, show page
        if (filterContext.HttpContext.Request.IsLocal) return;
        if (filterContext.HttpContext.Request.UserHostAddress.StartsWith("192.168.0")) return;

        // if user has has alpha or admin role, show page
        if (filterContext.HttpContext.Request.IsAuthenticated && (filterContext.HttpContext.User.IsInRole("Alpha") || filterContext.HttpContext.User.IsInRole("Admin"))) return;

        // site is not live and user does not have access - show placeholder

        filterContext.Result = new ViewResult()
        {
            ViewName="Placeholder",
            ViewData = filterContext.Controller.ViewData,
            TempData = filterContext.Controller.TempData
        };
    }

}


问:
Pruning old Git commits without rebasing
Suppose I have a Git repository with huge trees (~60 GiB) and some history, where old versions contain many deleted files.

I now want to prune old history, but without rebaseing all the commits after the prune point, because that would take several hours for each commit.

Can I just delete the first commit object to remove, and hope for git gc to delete all (now unreferenced) older ones? Or will this cause panic because of missing objects?

Can I use git replace to replace the first commit I want to remove with a dummy commit and then call git gc?

Is there some other method to remove my old commits in-place?

答:
without rebasing all the commits after the prune point, because that would take several hours for each commit.

After Git 2.18 (Q2 2018)

Since Git 2.18, graft has been superseded by git ref/replace/): see "What are .git/info/grafts for?".

As noted by in the comments, you would use instead

git replace --convert-graft-file :

Creates graft commits for all entries in $GIT_DIR/info/grafts and deletes that file upon success.

The purpose is to help users with transitioning off of the now-deprecated graft file.

So after git rev-parse HEAD~100 > .git/info/grafts.

And git filter-branch or BFG are obsolete after Git 2.22

Install git filter-repo and use git filter-repo --force

Before Git 2.18 (Q2 2018):

That is what graft point is for (better in that particular case than git replace, as I detail here)

The file .git/info/grafts with only one line with a commit id, says that the commit doesn't have a parent.

To keep the last 100 commits, using git rev-parse:

```<code> git rev-parse HEAD~100 > .git/info/grafts
</code>```

Then:

```<code> git filter-branch -- --all
</code>```

Finally:

```<code>rm -Rf .git/refs/original
</code>```

Then you can prune the rest:

```<code>git reflog expire --expire=now --all
git gc --prune=now
git gc --aggressive --prune=now
git repack -Ad      # kills in-pack garbage
git prune           # kills loose garbage
</code>```

Body:
without rebasing all the commits after the prune point, because that would take several hours for each commit.

After Git 2.18 (Q2 2018)

Since Git 2.18, graft has been superseded by git ref/replace/): see "What are .git/info/grafts for?".

As noted by in the comments, you would use instead

git replace --convert-graft-file :

Creates graft commits for all entries in $GIT_DIR/info/grafts and deletes that file upon success.

The purpose is to help users with transitioning off of the now-deprecated graft file.

So after git rev-parse HEAD~100 > .git/info/grafts.

And git filter-branch or BFG are obsolete after Git 2.22

Install git filter-repo and use git filter-repo --force

Before Git 2.18 (Q2 2018):

That is what graft point is for (better in that particular case than git replace, as I detail here)

The file .git/info/grafts with only one line with a commit id, says that the commit doesn't have a parent.

To keep the last 100 commits, using git rev-parse:

 git rev-parse HEAD~100 > .git/info/grafts

Then:

 git filter-branch -- --all

Finally:

rm -Rf .git/refs/original

Then you can prune the rest:

git reflog expire --expire=now --all
git gc --prune=now
git gc --aggressive --prune=now
git repack -Ad      # kills in-pack garbage
git prune           # kills loose garbage


问:
Cant findAll if you are a sibling in Beautiful soup
I have some HTLML that I am trying to parse that is formatted with almost no class identifiers so I have very little to have BeautifulSoup to latch on. It looks sort of like this:

```<code><h3>I am an important section of the list</h3>
<ul>
    <li><a href="commonStuff/newThing1">Important text in here</a></li>
    <li><a href="commonStuff/newThing2">Differentmportant text in here</a></li>
    ...
</ul>
<h3>I am another section of the list but I am not important</h3>
<ul>
    <li><a href="I look like I could be important">Cool looking info in here></li>
    <li><a href="I look like I could be important">Cool looking info in here></li>
</ul>
</code>```

I only care about the a elements in-between the h3 tags I care about. Naturally the way I am currently doing this is:

```<code>sections = part.select('h3')
        for section in sections:
            if "I am an important section of the list" in section:
</code>```

The problem is I dont know what to do afterward because at that point I am looking for the stuff after the header tag. The only way I have seen to do that is with some sort of get children function. So I am doing this:

```<code>for body in section.next_siblings:
</code>```

There are two things bad about this

There should only ever be one sibiling after it. I dont really understadn in what case there would be multiple

I cant do for links in body.find_all("a"): because the siblings aren't the same as the original html soup I was parsing earlier

How would you suggest getting to the href link as well as the text inside the  tag only if it is directly under a
 tag I care about?

The trouble here seems to be that I want the content directly after the
 tag. It would be nice if I could somehow split the document by the content between such tags.

答:
next_siblings exists without plural, to find the first next sibling :

```<code>res = []
sections = part.find_all('h3',
                         string=lambda s:'I am an important section of the list' in s)
for section in sections:
    for item in section.next_sibling.next_sibling.find_all('a'):
        res.append(item.get('href'))

print(res)

>>>['commonStuff/newThing1', 'commonStuff/newThing2']
</code>```

Explanations about next_sibling:

If your html source contains no linebreak after
, you'd need only one next_sibling. BeautifulSoup interprets it as a NavigableString.

In this first example, we get the linebreak :

```<code>html = """
<h3>I am an important section of the list</h3>
<ul>
    <li><a href="commonStuff/newThing1">Important text in here</a></li>
    <li><a href="commonStuff/newThing2">Differentmportant text in here</a></li>
</ul>
 """
soup = soup(html, 'html.parser')

sections = soup.find_all('h3')
for section in sections:
    print('next sibling : ', section.next_sibling)
    print(type(section.next_sibling))
</code>```

result :

```<code>next sibling :

<class 'bs4.element.NavigableString'>
</code>```

In this one, without linebreak after
, we obtain directly the tag we are searching :

```<code>html = """
<h3>I am an important section of the list</h3><ul>
    <li><a href="commonStuff/newThing1">Important text in here</a></li>
    <li><a href="commonStuff/newThing2">Differentmportant text in here</a></li>
</ul>
 """
soup = soup(html, 'html.parser')

sections = soup.find_all('h3')
for section in sections:
    print('next sibling : ', section.next_sibling)
    print(type(section.next_sibling))
</code>```

result :

```<code>next sibling :  <ul>
<li><a href="commonStuff/newThing1">Important text in here</a></li>
<li><a href="commonStuff/newThing2">Differentmportant text in here</a></li>
</ul>
<class 'bs4.element.Tag'>
</code>```

Body:
I have some HTLML that I am trying to parse that is formatted with almost no class identifiers so I have very little to have BeautifulSoup to latch on. It looks sort of like this:

I am an important section of the list

Important text in here

Differentmportant text in here

    ...

I am another section of the list but I am not important

Cool looking info in here>

Cool looking info in here>

I only care about the a elements in-between the h3 tags I care about. Naturally the way I am currently doing this is:

sections = part.select('h3')
        for section in sections:
            if "I am an important section of the list" in section:

The problem is I dont know what to do afterward because at that point I am looking for the stuff after the header tag. The only way I have seen to do that is with some sort of get children function. So I am doing this:

for body in section.next_siblings:

There are two things bad about this

There should only ever be one sibiling after it. I dont really understadn in what case there would be multiple

I cant do for links in body.find_all("a"): because the siblings aren't the same as the original html soup I was parsing earlier

How would you suggest getting to the href link as well as the text inside the  tag only if it is directly under a
 tag I care about?

The trouble here seems to be that I want the content directly after the
 tag. It would be nice if I could somehow split the document by the content between such tags.

Body:
next_siblings exists without plural, to find the first next sibling :

res = []
sections = part.find_all('h3',
                         string=lambda s:'I am an important section of the list' in s)
for section in sections:
    for item in section.next_sibling.next_sibling.find_all('a'):
        res.append(item.get('href'))

print(res)

>>>['commonStuff/newThing1', 'commonStuff/newThing2']

Explanations about next_sibling:

If your html source contains no linebreak after <h3>, you'd need only one next_sibling. BeautifulSoup interprets it as a NavigableString.

In this first example, we get the linebreak :

html = """
<h3>I am an important section of the list</h3>
<ul>
    <li><a href="commonStuff/newThing1">Important text in here</a></li>
    <li><a href="commonStuff/newThing2">Differentmportant text in here</a></li>
</ul>
 """
soup = soup(html, 'html.parser')

sections = soup.find_all('h3')
for section in sections:
    print('next sibling : ', section.next_sibling)
    print(type(section.next_sibling))

result :

next sibling :

<class 'bs4.element.NavigableString'>

In this one, without linebreak after <h3>, we obtain directly the tag we are searching :

html = """
<h3>I am an important section of the list</h3><ul>
    <li><a href="commonStuff/newThing1">Important text in here</a></li>
    <li><a href="commonStuff/newThing2">Differentmportant text in here</a></li>
</ul>
 """
soup = soup(html, 'html.parser')

sections = soup.find_all('h3')
for section in sections:
    print('next sibling : ', section.next_sibling)
    print(type(section.next_sibling))

result :

next sibling :  <ul>
<li><a href="commonStuff/newThing1">Important text in here</a></li>
<li><a href="commonStuff/newThing2">Differentmportant text in here</a></li>
</ul>
<class 'bs4.element.Tag'>


问:
Java code style for open stream try/finally block
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

```<code>InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}
</code>```

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

```<code>InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}
</code>```

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

答:
The answer is, no, there is no hidden error with doing it your way. It is purely a style thing.
I typically never have a try catch finally block, only try catch blocks and try finally blocks.

They tend to end up looking like this:

```<code>try {
    InputStream in = acquireStream();
    try {
        ...
    } finally {
        in.close();
    }
} catch (IOException e) {
    ... handle exception
}
</code>```

There is no reason to put acquireStream() in the try finally block. If in is never assigned to a valid stream, you can never close it. An explicit null check is totally unnecessary. Additionally, it is rare that you want to handle an exception on the close() differently than an exception in the main processing block.

Body:
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

Body:
The answer is, no, there is no hidden error with doing it your way. It is purely a style thing.
I typically never have a try catch finally block, only try catch blocks and try finally blocks.

They tend to end up looking like this:

try {
    InputStream in = acquireStream();
    try {
        ...
    } finally {
        in.close();
    }
} catch (IOException e) {
    ... handle exception
}

There is no reason to put acquireStream() in the try finally block. If in is never assigned to a valid stream, you can never close it. An explicit null check is totally unnecessary. Additionally, it is rare that you want to handle an exception on the close() differently than an exception in the main processing block.


问:
Flask: get current blueprint webroot
I am building a Flask app with a blueprint mounted on two different endpoint (one is a legacy alias to the other).

In my blueprint class:

```<code>ldp = Blueprint('ldp', __name__)

@ldp.route('/<path:uuid>', methods=['GET'])
@ldp.route('/', defaults={'uuid': None}, methods=['GET'],
        strict_slashes=False)

def get_resource(uuid):
    # Route code...
</code>```

In my main server code:

```<code>app = Flask(__name__)
app.config.update(config['flask'])

app.register_blueprint(ldp, url_prefix='/new_ep')
# Legacy endpoint. @TODO Deprecate.
app.register_blueprint(ldp, url_prefix='/old_ep')
</code>```

How can I get the actual URL of the request up to the /old_ep or /new_ep part in the route method, e.g. http://localhost:5000/new_ep?

So far I have used

```<code>request.host_url + request.path.split('/')[1]
</code>```

but it looks quite inelegant and possibly error-prone. I would like to use the information from the blueprint setup if possible.

Thanks for your help.

EDIT: I could get to the Blueprint instance from within the request with

```<code>current_app.blueprints[request.blueprint]
</code>```

and I was hoping that the url_prefix attribute that I set when registering the blueprint was there, but it is None instead. As I read from the documentation for the supposedly related iter_blueprints() method, apparently these blueprints are listed without regard of how many times and with which parameters they were registered. Too bad.

答:
Here is a full working example to get the idea based off issue 612

```<code>from flask import Flask, Blueprint, url_for, request, g

bp = Blueprint('whatever', __name__)

@bp.url_defaults
def bp_url_defaults(endpoint, values):
    url_prefix = getattr(g, 'url_prefix', None)
    if url_prefix is not None:
        values.setdefault('url_prefix', url_prefix)

@bp.url_value_preprocessor
def bp_url_value_preprocessor(endpoint, values):
    g.url_prefix = values.pop('url_prefix')

@bp.route('/something')
def index():
    return 'host prefix is %s%s' % (request.host_url, g.url_prefix)

app = Flask(__name__)

app.register_blueprint(bp, url_prefix='/new_ep', url_defaults={'url_prefix': 'new_ep'})
app.register_blueprint(bp, url_prefix='/old_ep', url_defaults={'url_prefix': 'old_ep'})
</code>```

Title: Flask: get current blueprint webroot

Body:
I am building a Flask app with a blueprint mounted on two different endpoint (one is a legacy alias to the other).

In my blueprint class:

ldp = Blueprint('ldp', __name__)

@ldp.route('/<path:uuid>', methods=['GET'])
@ldp.route('/', defaults={'uuid': None}, methods=['GET'],
        strict_slashes=False)

def get_resource(uuid):
    # Route code...

In my main server code:

app = Flask(__name__)
app.config.update(config['flask'])

app.register_blueprint(ldp, url_prefix='/new_ep')
# Legacy endpoint. @TODO Deprecate.
app.register_blueprint(ldp, url_prefix='/old_ep')

How can I get the actual URL of the request up to the /old_ep or /new_ep part in the route method, e.g. http://localhost:5000/new_ep?

So far I have used

request.host_url + request.path.split('/')[1]

but it looks quite inelegant and possibly error-prone. I would like to use the information from the blueprint setup if possible.

Thanks for your help.

EDIT: I could get to the Blueprint instance from within the request with

current_app.blueprints[request.blueprint]

and I was hoping that the url_prefix attribute that I set when registering the blueprint was there, but it is None instead. As I read from the documentation for the supposedly related iter_blueprints() method, apparently these blueprints are listed without regard of how many times and with which parameters they were registered. Too bad.

Body:
Here is a full working example to get the idea based off issue 612

from flask import Flask, Blueprint, url_for, request, g

bp = Blueprint('whatever', __name__)

@bp.url_defaults
def bp_url_defaults(endpoint, values):
    url_prefix = getattr(g, 'url_prefix', None)
    if url_prefix is not None:
        values.setdefault('url_prefix', url_prefix)

@bp.url_value_preprocessor
def bp_url_value_preprocessor(endpoint, values):
    g.url_prefix = values.pop('url_prefix')

@bp.route('/something')
def index():
    return 'host prefix is %s%s' % (request.host_url, g.url_prefix)

app = Flask(__name__)

app.register_blueprint(bp, url_prefix='/new_ep', url_defaults={'url_prefix': 'new_ep'})
app.register_blueprint(bp, url_prefix='/old_ep', url_defaults={'url_prefix': 'old_ep'})


问:
Automatic Binding Redirects
Running VS 2017, latest update.

The documentation states that to enable automatic binding redirection you modify the csproj file and add the following under the appropriate <PropertyGroup>:

```<code><AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</code>```

Historically my project has had a few binding redirect entries in the app.config. I recently updated all nuget packages for the solutions and in the commit it modified several of the binding redirect entries to match the new version.

I wanted to make sure that everything was good to go for QA so I deleted all entries in the App.Config thinking that they would be regenerated on the next build (as the docs suggest they will).

To my surprise nothing has been added to the app.config on a clean / build.

So my question is, is it safe to assume that by consolidating dependencies in the solutions I no longer need them?

Or is there something wrong and VS should be generating the redirects and its failing.

答:
This is because the source app.config is not modified, only output (the one created in a compilation step and placed in your Debug / Release folder) application configuration file is.

Starting with Visual Studio 2013, new desktop apps that target the .NET Framework 4.5.1 use automatic binding redirection. This means that if two components reference different versions of the same strong-named assembly, the runtime automatically adds a binding redirection to the newer version of the assembly in the output app configuration (app.config) file. This redirection overrides the assembly unification that might otherwise take place. The source app.config file is not modified.

Source

Redirects in your source app.config were generated by Nuget itself. You have triggered it by making changes to the packages.

Title: Automatic Binding Redirects

Body:
Running VS 2017, latest update.

The documentation states that to enable automatic binding redirection you modify the csproj file and add the following under the appropriate <PropertyGroup>:

<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>

Historically my project has had a few binding redirect entries in the app.config. I recently updated all nuget packages for the solutions and in the commit it modified several of the binding redirect entries to match the new version.

I wanted to make sure that everything was good to go for QA so I deleted all entries in the App.Config thinking that they would be regenerated on the next build (as the docs suggest they will).

To my surprise nothing has been added to the app.config on a clean / build.

So my question is, is it safe to assume that by consolidating dependencies in the solutions I no longer need them?

Or is there something wrong and VS should be generating the redirects and its failing.


问:
Is there a universal config file for .Net Standard 2.0 Class Library?
I have a Class Library that I'm converting to a .Net Standard 2 class library in order to also use in ASP.Net Core 2.0 projects.

The library has always read from a config file items such as SMTP settings, connection strings etc.

In Web Projects it finds these values in web.config.

In Console/WinForms it finds these values in app.config.

Is there an equivalent config file for .Net Core 2.0 projects that "just works" like the previous examples?

I assume the answer is no, but looking for best way to handle this given the library is used across the organization, so maintaining backwards compatibility is important.

答:
.Net Core revised configuration approach greatly.

You don't call ConfigurationManager.AppSettings["someSetting"] anymore whenever you need value for some setting. Instead you load configuration on application startup with ConfigurationBuilder. There could be multiple configuration sources (json or/and xml configuration file, environment variables, command line, Azure Key Vault, ...).

Then you build your configuration and pass strongly typed setting objects wrapped into IOption<T> to consuming classes.

Here is a basic idea of how it works:

```<code>//  Application boostrapping

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("AppSettings.json");
var configuration = configurationBuilder.Build();

//  IServiceCollection services

services.AddOptions();
services.Configure<SomeSettings>(configuration.GetSection("SomeSection"));

//  Strongly typed settings

public class SomeSettings
{
    public string SomeHost { get; set; }

    public int SomePort { get; set; }
}

//  Settings consumer

public class SomeClient : ISomeClient
{
    public SomeClient(IOptions<SomeSettings> someSettings)
    {
        var host = someSettings.Value.SomeHost;
        var port = someSettings.Value.SomePort;
    }
}

//  AppSettings.json

{
  "SomeSection": {
    "SomeHost": "localhost",
    "SomePort": 25
  }
}
</code>```

For more details check article Configure an ASP.NET Core App.

I'm afraid that it will be difficult (trying to avoid word 'impossible') to maintain backward compatibility.

Body:
.Net Core revised configuration approach greatly.

You don't call ConfigurationManager.AppSettings["someSetting"] anymore whenever you need value for some setting. Instead you load configuration on application startup with ConfigurationBuilder. There could be multiple configuration sources (json or/and xml configuration file, environment variables, command line, Azure Key Vault, ...).

Then you build your configuration and pass strongly typed setting objects wrapped into IOption<T> to consuming classes.

Here is a basic idea of how it works:

//  Application boostrapping

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("AppSettings.json");
var configuration = configurationBuilder.Build();

//  IServiceCollection services

services.AddOptions();
services.Configure<SomeSettings>(configuration.GetSection("SomeSection"));

//  Strongly typed settings

public class SomeSettings
{
    public string SomeHost { get; set; }

    public int SomePort { get; set; }
}

//  Settings consumer

public class SomeClient : ISomeClient
{
    public SomeClient(IOptions<SomeSettings> someSettings)
    {
        var host = someSettings.Value.SomeHost;
        var port = someSettings.Value.SomePort;
    }
}

//  AppSettings.json

{
  "SomeSection": {
    "SomeHost": "localhost",
    "SomePort": 25
  }
}

For more details check article Configure an ASP.NET Core App.

I'm afraid that it will be difficult (trying to avoid word 'impossible') to maintain backward compatibility.


问:
How to call function after submit form aspx
I want callback alert after submit form, but doesn't worked. Submit not execute.

Only $("#formImpressao").submit(); worked fine.

I try too use $(document).ready(function () { ... :( No Success

Whats wrong?

Sorry for my bad english

```<code><div id="HiddenFormTarget" style="display:none;">
    <form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>
</div>
<iframe id="frmPrint" name="frmPrint" width="0" height="0" runat="server">
</iframe>

<script language="javascript" type="text/javascript">
    $("#formImpressao").submit(function () {
       alert('Test');
    });
    $("#formImpressao").submit();

</script>
</code>```

答:
```<code>$("#formImpressao").submit(function (e) {
    e.preventDefault();
    alert('Test');
    //Insert AJAX to submit form data
});
</code>```

e.preventDefault() will prevent the default action of the submit event, and then run your alert, but it will NOT submit the form. For that, you will need to use AJAX. It's simple enough to understand, and there are plenty of SO topics on the use of it, so I won't reiterate. But preventDefault() will get you started.

Body:
I want callback alert after submit form, but doesn't worked. Submit not execute.

Only $("#formImpressao").submit(); worked fine.

I try too use $(document).ready(function () { ... :( No Success

Whats wrong?

Sorry for my bad english

    <form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>

Body:
$("#formImpressao").submit(function (e) {
    e.preventDefault();
    alert('Test');
    //Insert AJAX to submit form data
});

e.preventDefault() will prevent the default action of the submit event, and then run your alert, but it will NOT submit the form. For that, you will need to use AJAX. It's simple enough to understand, and there are plenty of SO topics on the use of it, so I won't reiterate. But preventDefault() will get you started.


问:
static object inside template class
I have been asked several times about the uses of static object and I guess I understand the crux behind using them, but one particular case confusing me, I know that in the code they are trying to make a factorial like mechanism using recursive call but did not able to understand different stages the code will go through.

```<code>#include<iostream>

using namespace std;

template<short N> class C
{
  private:
     static C<N-1>c;
  public:
     static int const n = N*c.n;
};

template<> class C<0>
{
    public:
    static int const n =1;
};

int main()
{
    cout<<C<5>::n<<endl;
    return 0;
}
</code>```

See the live demo here please.

This code is generating an output 120.

What exactly is happening here?

答:
It's unfortunate that the line

```<code>static C<N-1>c;
</code>```

exists at all. It obfuscates the logic a little bit.

The functionality could have been as easily implemented as:

```<code>template<short N> class C
{
   public:
     static int const n = N*C<N-1>::n;
};

template<> class C<0>
{
  public:
    static int const n = 1;
};
</code>```

which is a little bit easier to follow.

The net effect is same:

```<code>C<5>::n = 5*C<4>::n
C<4>::n = 4*C<3>::n
C<3>::n = 3*C<2>::n
C<2>::n = 2*C<1>::n
C<1>::n = 1*C<0>::n
C<0>::n = 1
</code>```

Now you can follow how the program produces the output.

Title: static object inside template class

Body:
I have been asked several times about the uses of static object and I guess I understand the crux behind using them, but one particular case confusing me, I know that in the code they are trying to make a factorial like mechanism using recursive call but did not able to understand different stages the code will go through.

#include<iostream>

using namespace std;

template<short N> class C
{
  private:
     static C<N-1>c;
  public:
     static int const n = N*c.n;
};

template<> class C<0>
{
    public:
    static int const n =1;
};

int main()
{
    cout<<C<5>::n<<endl;
    return 0;
}

See the live demo here please.

This code is generating an output 120.

What exactly is happening here?

Body:
It's unfortunate that the line

static C<N-1>c;

exists at all. It obfuscates the logic a little bit.

The functionality could have been as easily implemented as:

template<short N> class C
{
   public:
     static int const n = N*C<N-1>::n;
};

template<> class C<0>
{
  public:
    static int const n = 1;
};

which is a little bit easier to follow.

The net effect is same:

C<5>::n = 5*C<4>::n
C<4>::n = 4*C<3>::n
C<3>::n = 3*C<2>::n
C<2>::n = 2*C<1>::n
C<1>::n = 1*C<0>::n
C<0>::n = 1

Now you can follow how the program produces the output.


问:
Why does fgetpos() return a negative offset?
When I am using fgetpos(fp,&pos), the call is setting pos to a negative value where pos is of type fpos_t. Can some one explain why this is happening?

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

#define TRUE 1
#define FALSE 0

#define MAX_TAG_LEN 50

char filename[1000] = "d:\\ire\\a.xml";

//extract each tag from the xml file
int getTag(char * tag, FILE *fp)
{
    //skip until a beginning of a next
    while(!feof(fp))
        if((char)fgetc(fp) == '<')break;

    if(!feof(fp)){
        char temp[MAX_TAG_LEN]={0};
        char *ptr;
        int len;
        fpos_t b;
        fgetpos(fp,&b);   // here the b is containing -ve values.....???
        fread(temp,sizeof(char),MAX_TAG_LEN - 1,fp);
        temp[MAX_TAG_LEN-1] = 0;
        ptr = strchr(temp,'>');  //search of ending tag bracket
        len = ptr - temp + 1;
        sprintf(tag,"<%.*s",len,temp); //copy the tag
        printf("%s",tag); //print the tag
        b += len;         //reset the position of file pointer to just after the tag character.
        fsetpos(fp,&b);

        return TRUE;
    }
    else{
        return FALSE;
    }
}

int main()
{
    int ch;
    char tag[100]={0};
    FILE *fp = fopen(filename,"r");

    while(getTag(tag,fp)){
    }

    fclose(fp);

    return 0;
}
</code>```

where a.xml is a very basic xml file

```<code><file>
  <page>
    <title>AccessibleComputing</title>
    <id>10</id>
    <redirect />
    <revision>
      <id>133452289</id>
      <timestamp>2007-05-25T17:12:12Z</timestamp>
      <contributor>
        <username>Gurch</username>
        <id>241822</id>
      </contributor>
      <minor />
      <comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Rory096|Rory096]]</comment>
      <text xml:space="preserve">#REDIRECT [[Computer accessibility]] {{R from CamelCase}}</text>
    </revision>
  </page>

  </file>
</code>```

The code is working for some xml files but for the above xml file it is stoping after printing the first  tag.

答:
Finally I found the error....

msdn says

You can use fseek to reposition the
  pointer anywhere in a file. The
  pointer can also be positioned beyond
  the end of the file. fseek clears the
  end-of-file indicator and negates the
  effect of any prior ungetc calls
  against stream.

When a file is opened for appending
  data, the current file position is
  determined by the last I/O operation,
  not by where the next write would
  occur. If no I/O operation has yet
  occurred on a file opened for
  appending, the file position is the
  start of the file.

For streams opened in text mode, fseek has limited use, because
  carriage return–linefeed translations
  can cause fseek to produce unexpected
  results. The only fseek operations
  guaranteed to work on streams opened
  in text mode are:

Seeking with an offset of 0 relative
  to any of the origin values. Seeking
  from the beginning of the file with an
  offset value returned from a call to
  ftell.

once fopen call is modified from "r" to "rb" it worked fine....

thanks

Body:
When I am using fgetpos(fp,&pos), the call is setting pos to a negative value where pos is of type fpos_t. Can some one explain why this is happening?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define TRUE 1
#define FALSE 0

#define MAX_TAG_LEN 50

char filename[1000] = "d:\\ire\\a.xml";

//extract each tag from the xml file
int getTag(char * tag, FILE *fp)
{
    //skip until a beginning of a next
    while(!feof(fp))
        if((char)fgetc(fp) == '<')break;

    if(!feof(fp)){
        char temp[MAX_TAG_LEN]={0};
        char *ptr;
        int len;
        fpos_t b;
        fgetpos(fp,&b);   // here the b is containing -ve values.....???
        fread(temp,sizeof(char),MAX_TAG_LEN - 1,fp);
        temp[MAX_TAG_LEN-1] = 0;
        ptr = strchr(temp,'>');  //search of ending tag bracket
        len = ptr - temp + 1;
        sprintf(tag,"<%.*s",len,temp); //copy the tag
        printf("%s",tag); //print the tag
        b += len;         //reset the position of file pointer to just after the tag character.
        fsetpos(fp,&b);

        return TRUE;
    }
    else{
        return FALSE;
    }
}

int main()
{
    int ch;
    char tag[100]={0};
    FILE *fp = fopen(filename,"r");

    while(getTag(tag,fp)){
    }

    fclose(fp);

    return 0;
}

where a.xml is a very basic xml file

<file>
  <page>
    <title>AccessibleComputing</title>
    <id>10</id>
    <redirect />
    <revision>
      <id>133452289</id>
      <timestamp>2007-05-25T17:12:12Z</timestamp>
      <contributor>
        <username>Gurch</username>
        <id>241822</id>
      </contributor>
      <minor />
      <comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Rory096|Rory096]]</comment>
      <text xml:space="preserve">#REDIRECT [[Computer accessibility]] {{R from CamelCase}}</text>
    </revision>
  </page>

  </file>

The code is working for some xml files but for the above xml file it is stoping after printing the first  tag.


问:
How to disable scrolling header in table on concrete example?
Could you help me disable scrolling header of table in this concrete example, I have a problem with this. Being honestly I have no idea how to do it.

Construction of my very simple code is:

```<code><div id="container">
  <table border="1">
      <thead>
          <th>Short fs [dsa]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Short fs[dsadas]</th>
          <th>Very long long long long long</th>
       </thead>
  </table>
</div>
</code>```

https://jsfiddle.net/2avm4a6n/109/

答:
Pretty common thing to do, Checkout this pen - I did not write this

.fixed_headers {
  width: 750px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed_headers th {
  text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
  padding: 5px;
  text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
  min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
  min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
  width: 350px;
}
.fixed_headers thead {
  background-color: #333;
  color: #FDFDFD;
}
.fixed_headers thead tr {
  display: block;
  position: relative;
}
.fixed_headers tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
  background-color: #DDD;
}
.old_ie_wrapper {
  height: 300px;
  width: 750px;
  overflow-x: hidden;
  overflow-y: auto;
}
.old_ie_wrapper tbody {
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- IE < 10 does not like giving a tbody a height.  The workaround here applies the scrolling to a wrapped <div>. -->
<!--[if lte IE 9]>
<div class="old_ie_wrapper">
<!--<![endif]-->

<table class="fixed_headers">
  <thead>
    <tr>
      <th>Name</th>
      <th>Color</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Apple</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Pear</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Grape</td>
      <td>Purple / Green</td>
      <td>These are purple and green.</td>
    </tr>
    <tr>
      <td>Orange</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Banana</td>
      <td>Yellow</td>
      <td>These are yellow.</td>
    </tr>
    <tr>
      <td>Kiwi</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Plum</td>
      <td>Purple</td>
      <td>These are Purple</td>
    </tr>
    <tr>
      <td>Watermelon</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Tomato</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Cherry</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Cantelope</td>
      <td>Orange</td>
      <td>These are orange inside.</td>
    </tr>
    <tr>
      <td>Honeydew</td>
      <td>Green</td>
      <td>These are green inside.</td>
    </tr>
    <tr>
      <td>Papaya</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Raspberry</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Blueberry</td>
      <td>Blue</td>
      <td>These are blue.</td>
    </tr>
    <tr>
      <td>Mango</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Passion Fruit</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
  </tbody>
</table>

<!--[if lte IE 9]>
</div>
<!--<![endif]--></code>```

Body:
Could you help me disable scrolling header of table in this concrete example, I have a problem with this. Being honestly I have no idea how to do it.

Construction of my very simple code is:

          Short fs [dsa]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Short fs[dsadas]
          Very long long long long long

https://jsfiddle.net/2avm4a6n/109/

Body:
Pretty common thing to do, Checkout this pen - I did not write this

.fixed_headers {
  width: 750px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed_headers th {
  text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
  padding: 5px;
  text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
  min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
  min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
  width: 350px;
}
.fixed_headers thead {
  background-color: #333;
  color: #FDFDFD;
}
.fixed_headers thead tr {
  display: block;
  position: relative;
}
.fixed_headers tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
  background-color: #DDD;
}
.old_ie_wrapper {
  height: 300px;
  width: 750px;
  overflow-x: hidden;
  overflow-y: auto;
}
.old_ie_wrapper tbody {
  height: auto;
}

<!-- IE < 10 does not like giving a tbody a height.  The workaround here applies the scrolling to a wrapped <div>. -->
<!--[if lte IE 9]>
<div class="old_ie_wrapper">
<!--<![endif]-->

<table class="fixed_headers">
  <thead>
    <tr>
      <th>Name</th>
      <th>Color</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Apple</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Pear</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Grape</td>
      <td>Purple / Green</td>
      <td>These are purple and green.</td>
    </tr>
    <tr>
      <td>Orange</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Banana</td>
      <td>Yellow</td>
      <td>These are yellow.</td>
    </tr>
    <tr>
      <td>Kiwi</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Plum</td>
      <td>Purple</td>
      <td>These are Purple</td>
    </tr>
    <tr>
      <td>Watermelon</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Tomato</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Cherry</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Cantelope</td>
      <td>Orange</td>
      <td>These are orange inside.</td>
    </tr>
    <tr>
      <td>Honeydew</td>
      <td>Green</td>
      <td>These are green inside.</td>
    </tr>
    <tr>
      <td>Papaya</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
    <tr>
      <td>Raspberry</td>
      <td>Red</td>
      <td>These are red.</td>
    </tr>
    <tr>
      <td>Blueberry</td>
      <td>Blue</td>
      <td>These are blue.</td>
    </tr>
    <tr>
      <td>Mango</td>
      <td>Orange</td>
      <td>These are orange.</td>
    </tr>
    <tr>
      <td>Passion Fruit</td>
      <td>Green</td>
      <td>These are green.</td>
    </tr>
  </tbody>
</table>

<!--[if lte IE 9]>
</div>
<!--<![endif]-->


问:
How to prevent DateComponents from updating for time zone
I am trying to get date components from a date value from an API endpoint. I need to preserve the date values as they are already adjusted for time zone. Unfortunately, I have no control over how the API returns a date value.

When I get the date value (sessionTime) from the API, it is returned as follows:

```<code>2017-12-05 08:00:00 +0000
</code>```

I need to set up a local notification based on that time, however, when I try to extract components from that date object with the following code:

```<code>let notifyTime = Calendar.current.dateComponents(
     [.year, .month, .day, .hour, .minute, .second], from: sessionTime)
</code>```

I get this:

```<code>year: 2017 month: 12 day: 5 hour: 2 minute: 0 second: 0 isLeapMonth: false
</code>```

I am six hours from GMT so it is obvious what is going on, but I wish I could prevent it and extract the date components exactly as they are. The desired output would be:

```<code>year: 2017 month: 12 day: 5 hour: 8 minute: 0 second: 0 isLeapMonth: false
</code>```

Can anyone help? Thanks!

答:
You can specify the timeZone that DateComponents uses.

Like this:

```<code>let notifyTime = Calendar.current.dateComponents(in: TimeZone.current, from: sessionTime)
</code>```

Body:
I am trying to get date components from a date value from an API endpoint. I need to preserve the date values as they are already adjusted for time zone. Unfortunately, I have no control over how the API returns a date value.

When I get the date value (sessionTime) from the API, it is returned as follows:

2017-12-05 08:00:00 +0000

I need to set up a local notification based on that time, however, when I try to extract components from that date object with the following code:

let notifyTime = Calendar.current.dateComponents(
     [.year, .month, .day, .hour, .minute, .second], from: sessionTime)

I get this:

year: 2017 month: 12 day: 5 hour: 2 minute: 0 second: 0 isLeapMonth: false

I am six hours from GMT so it is obvious what is going on, but I wish I could prevent it and extract the date components exactly as they are. The desired output would be:

year: 2017 month: 12 day: 5 hour: 8 minute: 0 second: 0 isLeapMonth: false

Can anyone help? Thanks!

Body:
You can specify the timeZone that DateComponents uses.

Like this:

let notifyTime = Calendar.current.dateComponents(in: TimeZone.current, from: sessionTime)


问:
Powershell can not call ImageMagick commands - IM Montage
I wrote a script in PowerShell and I am having various success calling Image Magick's montage.exe on different computers. The computer on which I wrote the script has no problem executing the 'montage' command, however on another computer with IM Installed the script errors out:

```<code>montage : The term 'montage' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\Server\Contact_Sheet_Local.ps1:51 char:9
+         montage -verbose -label %t -pointsize 20 -background '#FFFFFF ...
+         ~~~~~~~
+ CategoryInfo          : ObjectNotFound: (montage:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code>```

I have tried using montage.exe and even tried the entire path C:\Program Files\ImageMagick-7.0.3-Q16\montage.exe. Additionally I tried setting the directory first:

```<code>Set-Location -Path 'C:\Program Files\ImageMagick-7.0.3-Q16'
montage...
</code>```

Each time on a particular computer this fails. I have tried with IM versions 7.0.3-Q16 and 6.9.1-6-Q8 both x64 as both computers are x64

In the past, I have created scripts in .bat that use ImageMagick and I had to define the full path to the .exe as I mentioned above. But this doesn't seem to help in PowerShell.

Does anyone have any advice or experience with this problem?

答:
PowerShell does not execute programs in the current directory by default. If you want to run an executable that's sitting in the current directory, prefix the executable's name with .\ or ./. Example:

```<code>Set-Location "C:\Program Files\ImageMagick-7.0.3-Q16"
.\montage.exe ...
</code>```

If you have an executable's name in a string or string variable and you want to execute it, you can do so using the & (call or invocation) operator:

```<code>& "C:\Program Files\ImageMagick-7.0.3-Q16\montage.exe" ...
</code>```

If you specify a path and filename that doesn't contain spaces, the & operator isn't required; example:

```<code>C:\ImageMagick\montage.exe ...
</code>```

You could also write it this way:

```<code>& C:\ImageMagick\montage.exe ...
</code>```

If you have an executable's filename in a string variable and you want to execute it, use &; example:

```<code>$execName = "C:\Program Files\ImageMagick-7.0.3-Q16\montage.exe"
& $execName ...
</code>```

Body:
I wrote a script in PowerShell and I am having various success calling Image Magick's montage.exe on different computers. The computer on which I wrote the script has no problem executing the 'montage' command, however on another computer with IM Installed the script errors out:

montage : The term 'montage' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\Server\Contact_Sheet_Local.ps1:51 char:9
+         montage -verbose -label %t -pointsize 20 -background '#FFFFFF ...
+         ~~~~~~~
+ CategoryInfo          : ObjectNotFound: (montage:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

I have tried using montage.exe and even tried the entire path C:\Program Files\ImageMagick-7.0.3-Q16\montage.exe. Additionally I tried setting the directory first:

Set-Location -Path 'C:\Program Files\ImageMagick-7.0.3-Q16'
montage...

Each time on a particular computer this fails. I have tried with IM versions 7.0.3-Q16 and 6.9.1-6-Q8 both x64 as both computers are x64

In the past, I have created scripts in .bat that use ImageMagick and I had to define the full path to the .exe as I mentioned above. But this doesn't seem to help in PowerShell.

Does anyone have any advice or experience with this problem?

Body:
PowerShell does not execute programs in the current directory by default. If you want to run an executable that's sitting in the current directory, prefix the executable's name with .\ or ./. Example:

Set-Location "C:\Program Files\ImageMagick-7.0.3-Q16"
.\montage.exe ...

If you have an executable's name in a string or string variable and you want to execute it, you can do so using the & (call or invocation) operator:

& "C:\Program Files\ImageMagick-7.0.3-Q16\montage.exe" ...

If you specify a path and filename that doesn't contain spaces, the & operator isn't required; example:

C:\ImageMagick\montage.exe ...

You could also write it this way:

& C:\ImageMagick\montage.exe ...

If you have an executable's filename in a string variable and you want to execute it, use &; example:

$execName = "C:\Program Files\ImageMagick-7.0.3-Q16\montage.exe"
& $execName ...


问:
Nested React list not working
I am trying to recursively render JSON data to nested list using React. Right now I am using simple data object like this:

```<code>[{"id": "1",
 "name": "Luke"
},
{"id": "2",
 "name": "Jim",
  "childNodes":[{
    "id": "3",
    "name": "Lola"
   }]
}]
</code>```

using this class:

```<code>export default class NestedList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = (child) => {
    if (child.childNodes) {
      return (
        <ul>
          {child.myData.map(item => {
            return this.renderChild(item);
          })}
        </ul>
      );
    }
    else if (child.name) {
      return <input type="checkbox"><Child name={child.name}/></input>;
    }
    return null;
  }

  render() {
    return (
      <aside>
        <div>
          <h4>Data Sets</h4>
          <ul>
            {this.renderChild(this.props.myData)}
          </ul>
        </div>
      </aside>
    );
  }
}
</code>```

which calls a Child class that creates list element:

```<code>export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (
      <li>{name}</li>
    );
  }
}
</code>```

but it doesn't print anything. I have tried removing attribute childNodes altogether and tried to print the list but it doesn't work still. I don't understand where I am doing wrong. I would appreciate some help regarding how to fix this.

答:
You need to map through myData first so the rendering process begins:

```<code><ul>
  {this.props.myData.map(data => this.renderChild(data))}
</ul>
</code>```

Also, on childNodes you need to loop through child.childNodes:

```<code>if (child.childNodes) {
  return (
    <ul>
      {child.childNodes.map(node => this.renderChild(node))}
    </ul>
  );
}
</code>```

Title: Nested React list not working

Body:
I am trying to recursively render JSON data to nested list using React. Right now I am using simple data object like this:

[{"id": "1",
 "name": "Luke"
},
{"id": "2",
 "name": "Jim",
  "childNodes":[{
    "id": "3",
    "name": "Lola"
   }]
}]

using this class:

export default class NestedList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = (child) => {
    if (child.childNodes) {
      return (

          {child.myData.map(item => {
            return this.renderChild(item);
          })}

      );
    }
    else if (child.name) {
      return <input type="checkbox"><Child name={child.name}/></input>;
    }
    return null;
  }

  render() {
    return (

Data Sets

            {this.renderChild(this.props.myData)}

    );
  }
}

which calls a Child class that creates list element:

export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (

{name}

    );
  }
}

but it doesn't print anything. I have tried removing attribute childNodes altogether and tried to print the list but it doesn't work still. I don't understand where I am doing wrong. I would appreciate some help regarding how to fix this.

Body:
You need to map through myData first so the rendering process begins:

<ul>
  {this.props.myData.map(data => this.renderChild(data))}
</ul>

Also, on childNodes you need to loop through child.childNodes:

if (child.childNodes) {
  return (
    <ul>
      {child.childNodes.map(node => this.renderChild(node))}
    </ul>
  );
}