问:
Bootstrap css not working on dynamically injected components in angular
I have a code block like:

```<code>  <div class="col-md-12">
    <div class="row">
      <ng-template dynamicComponents></ng-template>
    </div>
  </div>
</code>```

dynamicComponents is a directive using which I inject dynamic components.

All the application is using Bootstrap and is working fine but the dynamically injected components are shrinking or not working with bootstrap css, I even tried using encapsulation: ViewEncapsulation.None but it doesn't seem to work.

Please refer the screenshots below:

Here everything works fine till class=row and it is taing the full width, but once a dynamic component named app-from-builder-components-editor is injected it breaks up the bootstrap properties, please see below:

What can I do to get the bootstrap properties to work ?

答:
The problem is your component host (app-form-builder-components-editor) that sits between your row and col divs. To make it work, your 'col-md-12' div should be a direct child of your 'row' div.

What you could do is putting the
 inside your app-form-builder component's template to work around this issue.

Body:
I have a code block like:

      <ng-template dynamicComponents></ng-template>

dynamicComponents is a directive using which I inject dynamic components.

All the application is using Bootstrap and is working fine but the dynamically injected components are shrinking or not working with bootstrap css, I even tried using encapsulation: ViewEncapsulation.None but it doesn't seem to work.

Please refer the screenshots below:

Here everything works fine till class=row and it is taing the full width, but once a dynamic component named app-from-builder-components-editor is injected it breaks up the bootstrap properties, please see below:

What can I do to get the bootstrap properties to work ?

Body:
The problem is your component host (app-form-builder-components-editor) that sits between your row and col divs. To make it work, your 'col-md-12' div should be a direct child of your 'row' div.

What you could do is putting the <div class="row"> inside your app-form-builder component's template to work around this issue.


来源: stackexchange

问:
Calculating percentages with GROUP BY query
I have a table with 3 columns which looks like this:

```<code>File    User     Rating (1-5)
------------------------------
00001    1        3
00002    1        4
00003    2        2
00004    3        5
00005    4        3
00005    3        2
00006    2        3
Etc.
</code>```

I want to generate a query that outputs the following (for each user and rating, display the number of files as well as percentage of files):

```<code>User    Rating   Count   Percentage
-----------------------------------
1       1         3      .18
1       2         6      .35
1       3         8      .47
2       5         12     .75
2       3         4      .25
</code>```

With Postgresql, I know how to create a query that includes the first 3 columns using the following query, but I can't figure out how to calculate percentage within the GROUP BY:

```<code>SELECT
    User,
    Rating,
    Count(*)
FROM
    Results
GROUP BY
    User, Rating
ORDER BY
    User, Rating
</code>```

Here I want the percentage calculation to apply to each user/rating group.

答:
```<code>WITH t1 AS
 (SELECT User, Rating, Count(*) AS n
  FROM your_table
  GROUP BY User, Rating)
SELECT User, Rating, n,
       (0.0+n)/(COUNT(*) OVER (PARTITION BY User)) -- no integer divide!
FROM t1;
</code>```

Or

```<code>SELECT User, Rating, Count(*) OVER w_user_rating AS n,
        (0.0+Count(*) OVER w_user_rating)/(Count(*) OVER (PARTITION BY User)) AS pct
FROM your_table
WINDOW w_user_rating AS (PARTITION BY User, Rating);
</code>```

I would see if one of these or the other yields a better query plan with the appropriate tool for your RDBMS.

ContentLicense: CC BY-SA 3.0

Body:
I have a table with 3 columns which looks like this:

File    User     Rating (1-5)
------------------------------
00001    1        3
00002    1        4
00003    2        2
00004    3        5
00005    4        3
00005    3        2
00006    2        3
Etc.

I want to generate a query that outputs the following (for each user and rating, display the number of files as well as percentage of files):

User    Rating   Count   Percentage
-----------------------------------
1       1         3      .18
1       2         6      .35
1       3         8      .47
2       5         12     .75
2       3         4      .25

With Postgresql, I know how to create a query that includes the first 3 columns using the following query, but I can't figure out how to calculate percentage within the GROUP BY:

SELECT
    User,
    Rating,
    Count(*)
FROM
    Results
GROUP BY
    User, Rating
ORDER BY
    User, Rating

Here I want the percentage calculation to apply to each user/rating group.

Body:
WITH t1 AS
 (SELECT User, Rating, Count(*) AS n
  FROM your_table
  GROUP BY User, Rating)
SELECT User, Rating, n,
       (0.0+n)/(COUNT(*) OVER (PARTITION BY User)) -- no integer divide!
FROM t1;

Or

SELECT User, Rating, Count(*) OVER w_user_rating AS n,
        (0.0+Count(*) OVER w_user_rating)/(Count(*) OVER (PARTITION BY User)) AS pct
FROM your_table
WINDOW w_user_rating AS (PARTITION BY User, Rating);

I would see if one of these or the other yields a better query plan with the appropriate tool for your RDBMS.

ContentLicense: CC BY-SA 4.0


问:
What does "hashable" mean in Python?
What exactly does it mean to say that an object in Python code is hashable?

答:
In Python, any immutable object (such as an integer, boolean, string, tuple) is hashable, meaning its value does not change during its lifetime. This allows Python to create a unique hash value to identify it, which can be used by dictionaries to track unique keys and sets to track unique values.

This is why Python requires us to use immutable datatypes for the keys in a dictionary.

Title: What does "hashable" mean in Python?


问:
best way to find substring using regex in python 3
I was trying to find out the best way to find the specific substring in key value pair using re for the following:

```<code>some_string-variable_length/some_no_variable_digit/some_no1_variable_digit/some_string1/some_string2
eg: aba/101/11111/cde/xyz or aaa/111/1119/cde/xzx or ada/21111/5/cxe/yyz
</code>```

here everything is variable and what I was looking for is something like below in key value pair:

```<code>`cde: 2` as there are two entries for cde

cxe: 1 as there is only one cxe
</code>```

Note: everything is variable here except /. ie cde or cxe or some string will be there exactly after two / in each case

```<code>input:aba/101/11111/cde/xyz/blabla
output: cde:xyz/blabla
input: aaa/111/1119/cde/xzx/blabla
output: cde:xzx/blabla
input: aahjdsga/11231/1119/gfts/sjhgdshg/blabla
output: gfts:sjhgdshg/blabla
</code>```

If you notice here, my key is always the first string after 3rd / and value is always the substring after key

答:
Others have already posted various regexes; a more broad question — is this problem best solved using a regex? Depending on how the data is formatted overall, it may be better parsed using

the .split('/') method on the string; or

csv.reader(..., delimiter='/') or csv.DictReader(..., delimiter='/') in the csv module.

Body:
I was trying to find out the best way to find the specific substring in key value pair using re for the following:

some_string-variable_length/some_no_variable_digit/some_no1_variable_digit/some_string1/some_string2
eg: aba/101/11111/cde/xyz or aaa/111/1119/cde/xzx or ada/21111/5/cxe/yyz

here everything is variable and what I was looking for is something like below in key value pair:

`cde: 2` as there are two entries for cde

cxe: 1 as there is only one cxe

Note: everything is variable here except /. ie cde or cxe or some string will be there exactly after two / in each case

input:aba/101/11111/cde/xyz/blabla
output: cde:xyz/blabla
input: aaa/111/1119/cde/xzx/blabla
output: cde:xzx/blabla
input: aahjdsga/11231/1119/gfts/sjhgdshg/blabla
output: gfts:sjhgdshg/blabla

If you notice here, my key is always the first string after 3rd / and value is always the substring after key


问:
php split a file into $key=>$value pairs with duplicate keys
I've been trying to wrap my head around this and I'm just brain frozen.

I have a file with multiple lines, each line is delimited by "=" into separate pieces of data:

```<code>// Example file. Syntax: <key>=<Value>
key1=value1
key1=value2
key1=value3
key2=value1
key2=value2
key3=value1
key3=value2
key3=value3
key3=value4
</code>```

I need to explode this file into separate lines, and throw them all in an array such that key1 holds an array of value1, 2, 3, key2 has its values, key3 has its values, so on and so forth. Kind of like this:

```<code>Array
(
    [key1] => Array
        (
        [0] => value1
        [1] => value2
        [2] => value3
        )
    [key2] => Array
        (
        [0] => value1
        [1] => value2
        )
    [key3] => Array
        (
        [0] => value1
        [1] => value2
        [2] => value3
        [3] => value4
        )
)
</code>```

So far I have the following code:

```<code>$loadFile = file('file.txt');
$returnArray = array();
foreach ($loadFile as $line) {
  $startWith = substr(trim($line), 0, 2);
    if (empty($line) || $startWith == '//') {
          continue;
  }
  list($key, $value) = explode('=', $line);
  $returnArray[$key] = $value;
}
return $returnArray;
</code>```

However all I'm getting back is:

```<code>Array ( [key1] => value3 [key2] => value2 [key3] => value4 )
</code>```

I've also tried

```<code>$loadFile = file('file.txt');
$returnArray = array();
foreach ($loadFile as $line) {
  $startWith = substr(trim($line), 0, 2);
    if (empty($line) || $startWith == '//') {
          continue;
  }
  $exp = explode('=', $line);
  $returnArray[$exp[0]] = $exp[1];
}
return $returnArray;
</code>```

Which also gives me the same result. I've also tried an array_merge which just shoved everything into an array with a numeric value as the key.

答:
you should  append your values to a subarray
of  $returnArray[$key] </p>

```<code>array_push($returnArray[$key],$value) ;
</code>```

Body:
I've been trying to wrap my head around this and I'm just brain frozen.

I have a file with multiple lines, each line is delimited by "=" into separate pieces of data:

// Example file. Syntax: <key>=<Value>
key1=value1
key1=value2
key1=value3
key2=value1
key2=value2
key3=value1
key3=value2
key3=value3
key3=value4

I need to explode this file into separate lines, and throw them all in an array such that key1 holds an array of value1, 2, 3, key2 has its values, key3 has its values, so on and so forth. Kind of like this:

Array
(
    [key1] => Array
        (
        [0] => value1
        [1] => value2
        [2] => value3
        )
    [key2] => Array
        (
        [0] => value1
        [1] => value2
        )
    [key3] => Array
        (
        [0] => value1
        [1] => value2
        [2] => value3
        [3] => value4
        )
)

So far I have the following code:

$loadFile = file('file.txt');
$returnArray = array();
foreach ($loadFile as $line) {
  $startWith = substr(trim($line), 0, 2);
    if (empty($line) || $startWith == '//') {
          continue;
  }
  list($key, $value) = explode('=', $line);
  $returnArray[$key] = $value;
}
return $returnArray;

However all I'm getting back is:

Array ( [key1] => value3 [key2] => value2 [key3] => value4 )

I've also tried

$loadFile = file('file.txt');
$returnArray = array();
foreach ($loadFile as $line) {
  $startWith = substr(trim($line), 0, 2);
    if (empty($line) || $startWith == '//') {
          continue;
  }
  $exp = explode('=', $line);
  $returnArray[$exp[0]] = $exp[1];
}
return $returnArray;

Which also gives me the same result. I've also tried an array_merge which just shoved everything into an array with a numeric value as the key.

Body:
you should  append your values to a subarray
of  $returnArray[$key]

array_push($returnArray[$key],$value) ;


问:
How do you change column names to lowercase with linux and store the file as it is?
I am trying to change the column names to lowercase in a csv file. I found the code to do that online but I dont know how to replace the old column names(uppercase) with new column names(lowercase) in the original file. I did something like this:
$cat head -n1 xxx.csv | tr "[A-Z]" "[a-z]"

But it simply just prints out the column names in lowercase, which is not enough for me.
I tried to add sed -i but it did not do any good. Thanks!!

答:
Using awk (readability winner) :

concise way:

```<code>awk 'NR==1{print tolower($0);next}1' file.csv
</code>```

or using ternary operator:

```<code>awk '{print (NR==1) ? tolower($0): $0}' file.csv
</code>```

or using if/else statements:

```<code>awk '{if (NR==1) {print tolower($0)} else {print $0}}' file.csv
</code>```

To change the file for real:

```<code>awk 'NR==1{print tolower($0);next}1' file.csv | tee /tmp/temp
mv /tmp/temp file.csv
</code>```

For your information, sed using the in place edit switch -i do the same: it use a temporary file under the hood.

You can check this by using :

```<code>strace -f -s 800 sed -i'' '...' file
</code>```

Body:
Using awk (readability winner) :

concise way:

awk 'NR==1{print tolower($0);next}1' file.csv

or using ternary operator:

awk '{print (NR==1) ? tolower($0): $0}' file.csv

or using if/else statements:

awk '{if (NR==1) {print tolower($0)} else {print $0}}' file.csv

To change the file for real:

awk 'NR==1{print tolower($0);next}1' file.csv | tee /tmp/temp
mv /tmp/temp file.csv

For your information, sed using the in place edit switch -i do the same: it use a temporary file under the hood.

You can check this by using :

strace -f -s 800 sed -i'' '...' file


问:
Extract string between two characters in a string
I have a set of strings that has datetime values and I would like to extract them. I am not sure if this is even possible using T-SQL.

```<code>CREATE TABLE #Temp (
BLOB_NM VARCHAR(100)
);

INSERT INTO #Temp
SELECT 'products_country_20200528102030.txt'
UNION ALL
SELECT 'products_territory_20190528102030.txt'
UNION ALL
SELECT 'products_country_2020-05-20_20200528102030.txt'
;
</code>```

Expected Results:

```<code>20200528102030
20190528102030
20200528102030
</code>```

答:
For this dataset, string functions should do it:

```<code>select blob_nm, substring(blob_nm, len(blob_nm) - 17, 14) res from #temp
</code>```

The idea is to count backwards from the end of the string, and capture the 14 characters that preced the extension (represented by the last 4 characters of the string).

Demo on DB Fiddle:

```
blob_nm                                        | res
:--------------------------------------------- | :-------------
products_country_20200528102030.txt            | 20200528102030
products_territory_20190528102030.txt          | 20190528102030
products_country_2020-05-20_20200528102030.txt | 20200528102030
```

Body:
I have a set of strings that has datetime values and I would like to extract them. I am not sure if this is even possible using T-SQL.

CREATE TABLE #Temp (
BLOB_NM VARCHAR(100)
);

INSERT INTO #Temp
SELECT 'products_country_20200528102030.txt'
UNION ALL
SELECT 'products_territory_20190528102030.txt'
UNION ALL
SELECT 'products_country_2020-05-20_20200528102030.txt'
;

Expected Results:

20200528102030
20190528102030
20200528102030

Body:
For this dataset, string functions should do it:

select blob_nm, substring(blob_nm, len(blob_nm) - 17, 14) res from #temp

The idea is to count backwards from the end of the string, and capture the 14 characters that preced the extension (represented by the last 4 characters of the string).

Demo on DB Fiddle:

blob_nm                                        | res
:--------------------------------------------- | :-------------
products_country_20200528102030.txt            | 20200528102030
products_territory_20190528102030.txt          | 20190528102030
products_country_2020-05-20_20200528102030.txt | 20200528102030


问:
Remote JMX connection
I'm trying to open a JMX connection to java application running on a remote machine.

The application JVM is configured with the following options:

com.sun.management.jmxremote

com.sun.management.jmxremote.port=1088

com.sun.management.jmxremote.authenticate=false

com.sun.management.jmxremote.ssl=false

I'm able to connect using localhost:1088 using jconsole or jvisualvm.
But I'm not able to connect using xxx.xxx.xxx.xxx:1088 from a remote machine.

There is no firewall between the servers, or on the OS. But to eliminate this possibility I telnet xxx.xxx.xxx.xxx 1088 and I think it connects, as the console screen turns blank.

Both servers are Windows Server 2008 x64. Tried with 64-bit JVM and 32-bit, neither work.

答:
Try this, I tested to access JMX inside docker container

-Dcom.sun.management.jmxremote=true
  -Djava.rmi.server.hostname=localhost
  -Dcom.sun.management.jmxremote.port=16000
  -Dcom.sun.management.jmxremote.rmi.port=16000
  -Dcom.sun.management.jmxremote.authenticate=false
  -Dcom.sun.management.jmxremote.ssl=false

Then

$ jconsole localhost:16000

ContentLicense: CC BY-SA 2.5

Title: Remote JMX connection


问:
Count of NSMutableArray is 0 after adding object
hi
i have an object (objectA) with tow instance variables, NSString and NSDate.
and i have two other objects
one with tableView and add button (objectB)
and one presented modally when you press the add button (objectC) and in this object view you can type name and date and when this object (objectC) dismissed i create new object (objectA) with name and date.

objectB have NSMutableArray and i want to add objectA to this array so it can be appear in tableView and i do it like this in objectC.m

```<code>- (IBAction)saveButtonPressed {
   objectA *a = [[objectA alloc] init];
   [a setName:[myUITextField text]];
   [a setDate:[myDatePicker date]];

   objectB *b = [[objectB alloc] init];
   [[b myMutableArray] addObject:a]];
   [[b myMutableArray] count]; // count == 1 here but when i go back to objectB implementation it will be 0

}
</code>```

and the app crash here

any ideas ?

thanks,

edit:
crash is gone i just edit the init method of objectA
but myMutableArray still 0

in objectB.m

```<code>- (id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

        UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                             target:self
                                                                             action:@selector(addBarButton:)];
        [navItem setRightBarButtonItem:bbi];
        [bbi release];

        myMutableArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)addBarButton:(id)sender {
    myObjectC = [[objectC alloc] init];
    [self presentModalViewController:myObjectC animated:YES];

}
</code>```

i also have in objectB.h

```<code>@property (nonatomic, retain) NSMutableArray *myMutableArray;
</code>```

the count of myMutableArray in objectC in saveButtonPressed method is now 1
but when i back to objectB tableView where i want to display the myMutableArray is still 0

Edit2 :
after i put a lot of NSLog
i found that when i make new objectB in saveButtonPressed: method the count of myMutableArray will be 1
but when i go back to my tableView (objectB) myMutableArray is back to 0
maybe because i create new and separate object of objectB in objectC (saveButtonPressed:)
also
if i don't alloc and init the objectB in saveButtonPressed: method
objectB will be nil and i cant put objectA in myMutableArray

so i guess i have to get pointer to original objectB but how?

答:
Since count == 0 after you added an object, I'm guessing it's one of two things:

[b myMutableArray] is returning nil because you forgot to allocate myMutableArray in the init function for objectB (e.g. myMutableArray = [[NSMutableArray alloc] initWithCapacity:10];)

[b myMutableArray] is returning a new mutable array each time it's called. Perhaps you are doing something like:

- (NSMutableArray *)myMutableArray {
  return [NSMutableArray arrayWithCapacity:10];
}
```

Sounds like (1) is probably the likely cause but it still doesn't explain the crashing. What error messages do you see in the debug console when the crash happens?

Body:
hi
i have an object (objectA) with tow instance variables, NSString and NSDate.
and i have two other objects
one with tableView and add button (objectB)
and one presented modally when you press the add button (objectC) and in this object view you can type name and date and when this object (objectC) dismissed i create new object (objectA) with name and date.

objectB have NSMutableArray and i want to add objectA to this array so it can be appear in tableView and i do it like this in objectC.m

- (IBAction)saveButtonPressed {
   objectA *a = [[objectA alloc] init];
   [a setName:[myUITextField text]];
   [a setDate:[myDatePicker date]];

   objectB *b = [[objectB alloc] init];
   [[b myMutableArray] addObject:a]];
   [[b myMutableArray] count]; // count == 1 here but when i go back to objectB implementation it will be 0

}

and the app crash here

any ideas ?

thanks,

edit:
crash is gone i just edit the init method of objectA
but myMutableArray still 0

in objectB.m

- (id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

        UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                             target:self
                                                                             action:@selector(addBarButton:)];
        [navItem setRightBarButtonItem:bbi];
        [bbi release];

        myMutableArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)addBarButton:(id)sender {
    myObjectC = [[objectC alloc] init];
    [self presentModalViewController:myObjectC animated:YES];

}

i also have in objectB.h

@property (nonatomic, retain) NSMutableArray *myMutableArray;

the count of myMutableArray in objectC in saveButtonPressed method is now 1
but when i back to objectB tableView where i want to display the myMutableArray is still 0

Edit2 :
after i put a lot of NSLog
i found that when i make new objectB in saveButtonPressed: method the count of myMutableArray will be 1
but when i go back to my tableView (objectB) myMutableArray is back to 0
maybe because i create new and separate object of objectB in objectC (saveButtonPressed:)
also
if i don't alloc and init the objectB in saveButtonPressed: method
objectB will be nil and i cant put objectA in myMutableArray

so i guess i have to get pointer to original objectB but how?

Body:
Since count == 0 after you added an object, I'm guessing it's one of two things:

[b myMutableArray] is returning nil because you forgot to allocate myMutableArray in the init function for objectB (e.g. myMutableArray = [[NSMutableArray alloc] initWithCapacity:10];)

[b myMutableArray] is returning a new mutable array each time it's called. Perhaps you are doing something like:

- (NSMutableArray *)myMutableArray {
  return [NSMutableArray arrayWithCapacity:10];
}

Sounds like (1) is probably the likely cause but it still doesn't explain the crashing. What error messages do you see in the debug console when the crash happens?


问:
Why are common websites' HTML/CSS/Javascript code so complicated?
Here's an example. Here's the first line of Google.com's source code:

<!doctype html><meta charset="UTF-8"><meta content="origin" name="referrer"><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><meta content="origin" name="referrer"><title>Google</title>

 About Store

Gmail

Images

答:
It's called minification.

Typically production deployment of code will go through multiple processes -  one of them being bundling which will almost always have a step for minifying all the scripts file.

And, you're right that it's harder to read. But this code that's deployed on production is not meant to be read. The developers will be having access to the un-minified development codebase (which they can deploy to intranet servers to test and develop).

All the JavaScript that is found in the code could be for many things, including ads. These script are probably not entirely for cookies because, to write a cookie, you only need to add document.cookie = "username: johndoe", or something similar.


问:
group list of dict by tuple value
I tried to solve this with list comprehension, itemgetter and groupby but I don't seem close.  Given this type of list of dict:

```<code>test_list = [{'text': "Hi",'bbox': (0,0)},
          {'text': "There.",'bbox': (1,0)},
          {'text': "Im",'bbox': (0,1)},
          {'text': "John.",'bbox': (1,1)},
         ]
</code>```

I am looking for this result:

```<code>[['Hi',"There."],['Im','John.']]
</code>```

Where the 'text' values are grouped by the second tuple element in the 'bbox'.  Thanks

答:
Sorry for double posting, I can not comment yet.
In cases, in which the elements are not sorted already, the library-free solution of @Chiheb Nexus will contain the correct groupings but not necessarily in the correct order. As the order criterion is discarded in the operation, this might be unfavourable but the question did not specify this. The same holds for the ordering of the elements within each grouping.
Ordering the out dictionary by key before converting to a list would order the groupings and keeping the first entry of the bbox attribute would enable sorting each grouping by that entry.

Title: group list of dict by tuple value

Body:
I tried to solve this with list comprehension, itemgetter and groupby but I don't seem close.  Given this type of list of dict:

test_list = [{'text': "Hi",'bbox': (0,0)},
          {'text': "There.",'bbox': (1,0)},
          {'text': "Im",'bbox': (0,1)},
          {'text': "John.",'bbox': (1,1)},
         ]

I am looking for this result:

[['Hi',"There."],['Im','John.']]

Where the 'text' values are grouped by the second tuple element in the 'bbox'.  Thanks


问:
Adjust spacing around paragraph (within a div) so that the space on either side is always equal between divs on the right and left
I have three divs, aligned on a single row as columns, using a flex container.

The first and third columns have a small amount of text in each, the middle column has a large paragraph.

What I would like to do is to align the text in the middle div so that the space around between it and the first and third divs is always equal, even when the width of the page changes and the words wrap to the next line.

By default, the word wrapping behaviour means that you can end up with a lot of whitespace on the right of the div, which isn't equal to the whitespace on the left (because of the varying length of words). How do I ensure the spacing adjusts based on the longest word (I assume the longest word), so it it always equal?

Here is some example code:

.container {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="column1">
    <p>
      Some content
    </p>
  </div>

  <div class="column2">
    <p>
      There is more content in this div than the other divs. Blah, blah, blah, blah, blah, blah...
    </p>
  </div>

  <div class="column3">
    <p>
      Some content
    </p>
  </div>

</div></code>```

If you expand and shrink the window, you can see that as the middle column's words get closer to wrapping, the spacing isn't equal on either side of the div; there is less space on the right than the left. This what I would like to resolve, so the spacing is always equal between the divs.

答:
```<code>.container {
    display: flex;
    justify-content: space-between;
}
</code>```

Body:
I have three divs, aligned on a single row as columns, using a flex container.

The first and third columns have a small amount of text in each, the middle column has a large paragraph.

What I would like to do is to align the text in the middle div so that the space around between it and the first and third divs is always equal, even when the width of the page changes and the words wrap to the next line.

By default, the word wrapping behaviour means that you can end up with a lot of whitespace on the right of the div, which isn't equal to the whitespace on the left (because of the varying length of words). How do I ensure the spacing adjusts based on the longest word (I assume the longest word), so it it always equal?

Here is some example code:

.container {
  display: flex;
}

      Some content

      There is more content in this div than the other divs. Blah, blah, blah, blah, blah, blah...

      Some content

If you expand and shrink the window, you can see that as the middle column's words get closer to wrapping, the spacing isn't equal on either side of the div; there is less space on the right than the left. This what I would like to resolve, so the spacing is always equal between the divs.


问:
What is an easy way to put an element in the middle of a PHP array?
Say you have a 10 element indexed array and you want to place an element somewhere in the middle (say index 3). Then I want to have the rest of the array shift and thus be 11 elements long. Is there an easy way to do this?

I am surprised there is no put() function or something.

I know it would be easy enough to do this with a combination of array_splice and array_merge but I was just wondering if there an easier way.

答:
No PHP function can currently handle this. It is not too difficult to whip up your own, however:

```<code>function array_insert(&$array, $insert, $position) {
    $c = count($array);
    $slice = array_merge($insert, array_slice($array, $position));
    array_splice($array, $position, $c, $slice);
}

$array = array('a','b','d','e');
print_r($array);
array_insert($array, array('c'), 2);
print_r($array);
</code>```

Will result in:

```<code>Array
(
    [0] => a
    [1] => b
    [2] => d
    [3] => e
)
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)
</code>```

You can probably add checks if the position is bigger than the array, the insert is not an array, etc.

OwnerDisplayName: Andrew

LastEditorDisplayName: Andrew

Body:
No PHP function can currently handle this. It is not too difficult to whip up your own, however:

function array_insert(&$array, $insert, $position) {
    $c = count($array);
    $slice = array_merge($insert, array_slice($array, $position));
    array_splice($array, $position, $c, $slice);
}

$array = array('a','b','d','e');
print_r($array);
array_insert($array, array('c'), 2);
print_r($array);

Will result in:

Array
(
    [0] => a
    [1] => b
    [2] => d
    [3] => e
)
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)

You can probably add checks if the position is bigger than the array, the insert is not an array, etc.

OwnerDisplayName: Paolo Bergantino


问:
Mongoose - entering data in 2 collections in single transaction
I am trying to create Saas model where the user who signs up creates a Company. So when a user registers, my function is supposed to create a Company and put the company id in User collections reference.

Now, if the user email is already registered, my mongoose schema rejects that entry. I can't create a User first because Company id is a required field to create a User.

What I need to do is create these two documents in different collections atomically. If User save fails, I want to abort that transaction so that it removes the Company data too.

Here's my code:

```<code>const mSession = await mongoose.startSession();
mSession.startTransaction();
try{
    var company=new Company({
        name: companyName,
        website: companyWebsite
    });

    company= await company.save();

    this.company= mongoose.Types.ObjectId(company._id);
    this.emailVerificationCode = Random.alphanumeric();
    let user = await this.save();
    await mSession.commitTransaction();
    console.log("User on success:", user);
    return user;
}catch(err){
    await mSession.abortTransaction();
    return false;
}finally{
    mSession.endSession();
}
</code>```

In this, abortTransaction() does not seem to work as the Company data persists anyway.

答:
Now, if the user email is already registered, my mongoose schema rejects that entry. I can't create a User first because Company id is a required field to create a User.

You can create a User first and set its user.comp_id to a locally generated ObjectId:

```<code>var mongoose = require('mongoose');
var company_id = mongoose.Types.ObjectId();

var user = new User({
    comp_id: company_id
});
</code>```

If the email is okay and the User is properly saved, you can then create your Company with its _id being set to the locally generated ObjectId company_id that was generated beforehand:

```<code>var company = new Company({
    _id = company_id,
    name: companyName,
    website: companyWebsite
});
</code>```

Body:
I am trying to create Saas model where the user who signs up creates a Company. So when a user registers, my function is supposed to create a Company and put the company id in User collections reference.

Now, if the user email is already registered, my mongoose schema rejects that entry. I can't create a User first because Company id is a required field to create a User.

What I need to do is create these two documents in different collections atomically. If User save fails, I want to abort that transaction so that it removes the Company data too.

Here's my code:

const mSession = await mongoose.startSession();
mSession.startTransaction();
try{
    var company=new Company({
        name: companyName,
        website: companyWebsite
    });

    company= await company.save();

    this.company= mongoose.Types.ObjectId(company._id);
    this.emailVerificationCode = Random.alphanumeric();
    let user = await this.save();
    await mSession.commitTransaction();
    console.log("User on success:", user);
    return user;
}catch(err){
    await mSession.abortTransaction();
    return false;
}finally{
    mSession.endSession();
}

In this, abortTransaction() does not seem to work as the Company data persists anyway.

Body:
Now, if the user email is already registered, my mongoose schema rejects that entry. I can't create a User first because Company id is a required field to create a User.

You can create a User first and set its user.comp_id to a locally generated ObjectId:

var mongoose = require('mongoose');
var company_id = mongoose.Types.ObjectId();

var user = new User({
    comp_id: company_id
});

If the email is okay and the User is properly saved, you can then create your Company with its _id being set to the locally generated ObjectId company_id that was generated beforehand:

var company = new Company({
    _id = company_id,
    name: companyName,
    website: companyWebsite
});


问:
Python searching lists with lists, all and any
I am having trouble for some reason with a certain if statement. Let's say I have three lists:

```<code>list1 = [1,2,3,4,5]
list2 = [1,2,4,5]
list3 = [4,5,6,7,8]
</code>```

I evaluate each. I want to flag it if the list has both 4 AND 5, but does not have either 2 OR 3. I thought this would work:

```<code>if all(q in [4,5] for q in the_list_name) and not any(q in [2,3] for q in the_list_name)
</code>```

I would expect this to flag only list3. However it returns false on all of the lists. I wonder what I am doing wrong?

答:
If we look at all(q in [4,5] for q in the_list_name), so only half of that if, we can see that it returns False for all the lists. That statement actually tests if all the elements in a list are either 4 or 5. Same for the other one, it tests if all the elements are 3 or 4, so it makes sense for all of them to be False.

To properly test if the list contains 4 and 5 but doesn't have 3 OR 4, you can change your code to:

```<code>inc = [4, 5]
exc = [2, 3]
testList = lambda l, inc, exc: all(i in l for i in inc) and not any(e in exc for e in l)
</code>```

having the results:

```<code>>>> testList(list1, [4, 5], [2, 3])
False
>>> testList(list2, [4, 5], [2, 3])
False
>>> testList(list3, [4, 5], [2, 3])
True
</code>```

Taking a closer look:

all(i in l for i in inc): all the elements from inc (elements that need to be included) are part of the given list l

not any(e in exc for e in l): for every element in the given list l, non of them should be in he exc list (elements that need to be excluded)

Edit:

If you want to use the @ekhumoro answers from the commends (that is more elegant) but also have parameters for elements that need to be included/excluded, you can use:

```<code>testList = lambda l, i, e: {*i}.issubset(l) and not {*e}.intersection(l)
</code>```

Body:
I am having trouble for some reason with a certain if statement. Let's say I have three lists:

list1 = [1,2,3,4,5]
list2 = [1,2,4,5]
list3 = [4,5,6,7,8]

I evaluate each. I want to flag it if the list has both 4 AND 5, but does not have either 2 OR 3. I thought this would work:

if all(q in [4,5] for q in the_list_name) and not any(q in [2,3] for q in the_list_name)

I would expect this to flag only list3. However it returns false on all of the lists. I wonder what I am doing wrong?

Body:
If we look at all(q in [4,5] for q in the_list_name), so only half of that if, we can see that it returns False for all the lists. That statement actually tests if all the elements in a list are either 4 or 5. Same for the other one, it tests if all the elements are 3 or 4, so it makes sense for all of them to be False.

To properly test if the list contains 4 and 5 but doesn't have 3 OR 4, you can change your code to:

inc = [4, 5]
exc = [2, 3]
testList = lambda l, inc, exc: all(i in l for i in inc) and not any(e in exc for e in l)

having the results:

>>> testList(list1, [4, 5], [2, 3])
False
>>> testList(list2, [4, 5], [2, 3])
False
>>> testList(list3, [4, 5], [2, 3])
True

Taking a closer look:

all(i in l for i in inc): all the elements from inc (elements that need to be included) are part of the given list l

not any(e in exc for e in l): for every element in the given list l, non of them should be in he exc list (elements that need to be excluded)

Edit:

If you want to use the @ekhumoro answers from the commends (that is more elegant) but also have parameters for elements that need to be included/excluded, you can use:

testList = lambda l, i, e: {*i}.issubset(l) and not {*e}.intersection(l)


问:
verilog ; can't use "string" type in $display
I'm using a recent master branch build of icarus verilog.

Should I expect the following to run?

```<code>module string_display ();

//reg [10:0][7:0] x = "initial";
string x = "initial";

always @* begin
  $display ("x = %s",x);
end

initial begin

  // Assign new string
  x = "aaaaa";
  #1

  // Assign new string
  x = "bbbb";
  #1

  #1 $finish;
end

endmodule
</code>```

The above gives

```<code>internal error: 18vvp_fun_anyedge_sa: recv_string(initial) not implemented
vvp: vvp_net.cc:2972: virtual void vvp_net_fun_t::recv_string(vvp_net_ptr_t, const string&, vvp_context_t): Assertion `0' failed.
</code>```

However, if I define 'x' as a reg by uncommenting the line above then it works as expected ...

```<code>x =       aaaaa
x =        bbbb
</code>```

答: The error message tells you exactly what's wrong: "not implemented". That means it recognizes what you want to do, but it has not been implemented yet.

Body:
I'm using a recent master branch build of icarus verilog.

Should I expect the following to run?

module string_display ();

//reg [10:0][7:0] x = "initial";
string x = "initial";

always @* begin
  $display ("x = %s",x);
end

initial begin

  // Assign new string
  x = "aaaaa";
  #1

  // Assign new string
  x = "bbbb";
  #1

  #1 $finish;
end

endmodule

The above gives

internal error: 18vvp_fun_anyedge_sa: recv_string(initial) not implemented
vvp: vvp_net.cc:2972: virtual void vvp_net_fun_t::recv_string(vvp_net_ptr_t, const string&, vvp_context_t): Assertion `0' failed.

However, if I define 'x' as a reg by uncommenting the line above then it works as expected ...

x =       aaaaa
x =        bbbb


问:
How to have multiple draggable canvas widgets?
Thus far I have:

Repurposed code from Drag and drop image object to allow multiple custom widgets to be draggable.

Repurposing the code has gone well with the exception of attempting to enforce draggable widgets to only move within the canvas dimensions.

If a single widget is added to the canvas the widget is draggable and bound to the canvas dimensions.

The Problem: If any number of widgets greater than one are added to the canvas, then only the last widget added is draggable and bound to the canvas dimensions. All other widgets fail to move due to logic in the mouse motion callback where the detected mouse motion is unusually large.

The draggable widgets are object-oriented, thus the logic for making a single draggable widget is identical to multiple other instantiations of the same widget type.

The manipulated code that I have thus far is:

```<code>import os
import tkinter as tk

APP_TITLE = "Drag & Drop Tk Canvas Images"
APP_XPOS = 100
APP_YPOS = 100
APP_WIDTH = 300
APP_HEIGHT = 200

class CreateCanvasObject(object):

    def __init__(self, canvas, block_name):
        self.canvas = canvas

        self.block_width = 250
        self.block_height = 250

        self.name = block_name

        self.max_speed = 30

        self.win_width = self.canvas.winfo_width()
        self.win_height = self.canvas.winfo_height()

        self.block_main = tk.Frame(self.canvas, bd=10, relief=tk.RAISED)
        self.block_main.pack(side=tk.TOP, fill=tk.BOTH, expand=False, padx=0, pady=0)

        self.block_name = tk.Label(self.block_main, text=block_name, anchor=tk.CENTER, font='Helvetica 10 bold', cursor='fleur')
        self.block_name.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        self.image_obj = self.canvas.create_window( (0, 0), window=self.block_main, anchor="nw", width=self.block_width, height=self.block_height)

        self.block_name.bind( '<Button1-Motion>', self.move)
        self.block_name.bind( '<ButtonRelease-1>', self.release)
        self.move_flag = False

        self.canvas.bind("<Configure>", self.configure)

    def configure(self, event):
        self.win_width = event.width
        self.win_height = event.height

    def move(self, event):

        print('Moving [%s]'%self.name)
        print(event)

        if self.move_flag:

            dx, dy = event.x, event.y

            abs_coord_x, abs_coord_y = self.canvas.coords( self.image_obj )

            cond_1 = abs_coord_x + dx >= 0
            cond_2 = abs_coord_y + dy >= 0
            cond_3 = (abs_coord_x + self.block_width + dx) <= self.win_width
            cond_4 = (abs_coord_y + self.block_height + dy) <= self.win_height

            print('abs_coord_x = %3.2f ; abs_coord_y = %3.2f'%(abs_coord_x, abs_coord_y))
            print('dx = %3.2f ; dy = %3.2f'%(dx, dy))
            print('self.block_width = %3.2f'%(self.block_width))
            print('self.block_height = %3.2f'%(self.block_height))
            print('Cond 1 = %s; Cond 2 = %s; Cond 3 = %s; Cond 4 = %s\n\n'%(cond_1, cond_2, cond_3, cond_4))

            if cond_1 and cond_2 and cond_3 and cond_4:
                self.canvas.move(self.image_obj, dx, dy)

        else:
            self.move_flag = True
            self.canvas.tag_raise(self.image_obj)

    def release(self, event):
        self.move_flag = False

class Application(tk.Frame):

    def __init__(self, master):
        self.master = master
        self.master.protocol("WM_DELETE_WINDOW", self.close)
        tk.Frame.__init__(self, master)

        self.canvas = tk.Canvas(self, width=800, height=800, bg='steelblue', highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)

        self.block_1 = CreateCanvasObject(canvas=self.canvas, block_name='Thing 1')
        self.block_2 = CreateCanvasObject(canvas=self.canvas, block_name='Thing 2')

    def close(self):
        print("Application-Shutdown")
        self.master.destroy()

def main():
    app_win = tk.Tk()
    app_win.title(APP_TITLE)
    app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS))

    Application(app_win).pack(fill='both', expand=True)

    app_win.mainloop()

if __name__ == '__main__':
    main()
</code>```

答:
The root of the problem is this line of code:

```<code>self.canvas.bind("<Configure>", self.configure)
</code>```

Whenever you call self.canvas.bind, you replace any previous binding on the widget. Thus, when the binding is triggered, only the last CreateCanvasObject will see the event because it will have replaced the bindings created by previous CreateCanvasObject objects.

Because of that, you only ever update self.win_width and self.win_height of the last object created. And because you use those values to compute self.cond3 and self.cond4, those conditions are always false and thus the object never moves.

A simple solution is to remove the binding and remove the configure method, and instead compute the width and height inside your move function. That, or make self.win_width and self.win_height class variables so when you update one you update all. Those aren't the only ways to solve the problem, but they are the simplest.

Body:
Thus far I have:

Repurposed code from Drag and drop image object to allow multiple custom widgets to be draggable.

Repurposing the code has gone well with the exception of attempting to enforce draggable widgets to only move within the canvas dimensions.

If a single widget is added to the canvas the widget is draggable and bound to the canvas dimensions.

The Problem: If any number of widgets greater than one are added to the canvas, then only the last widget added is draggable and bound to the canvas dimensions. All other widgets fail to move due to logic in the mouse motion callback where the detected mouse motion is unusually large.

The draggable widgets are object-oriented, thus the logic for making a single draggable widget is identical to multiple other instantiations of the same widget type.

The manipulated code that I have thus far is:

import os
import tkinter as tk

APP_TITLE = "Drag & Drop Tk Canvas Images"
APP_XPOS = 100
APP_YPOS = 100
APP_WIDTH = 300
APP_HEIGHT = 200

class CreateCanvasObject(object):

    def __init__(self, canvas, block_name):
        self.canvas = canvas

        self.block_width = 250
        self.block_height = 250

        self.name = block_name

        self.max_speed = 30

        self.win_width = self.canvas.winfo_width()
        self.win_height = self.canvas.winfo_height()

        self.block_main = tk.Frame(self.canvas, bd=10, relief=tk.RAISED)
        self.block_main.pack(side=tk.TOP, fill=tk.BOTH, expand=False, padx=0, pady=0)

        self.block_name = tk.Label(self.block_main, text=block_name, anchor=tk.CENTER, font='Helvetica 10 bold', cursor='fleur')
        self.block_name.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        self.image_obj = self.canvas.create_window( (0, 0), window=self.block_main, anchor="nw", width=self.block_width, height=self.block_height)

        self.block_name.bind( '<Button1-Motion>', self.move)
        self.block_name.bind( '<ButtonRelease-1>', self.release)
        self.move_flag = False

        self.canvas.bind("<Configure>", self.configure)

    def configure(self, event):
        self.win_width = event.width
        self.win_height = event.height

    def move(self, event):

        print('Moving [%s]'%self.name)
        print(event)

        if self.move_flag:

            dx, dy = event.x, event.y

            abs_coord_x, abs_coord_y = self.canvas.coords( self.image_obj )

            cond_1 = abs_coord_x + dx >= 0
            cond_2 = abs_coord_y + dy >= 0
            cond_3 = (abs_coord_x + self.block_width + dx) <= self.win_width
            cond_4 = (abs_coord_y + self.block_height + dy) <= self.win_height

            print('abs_coord_x = %3.2f ; abs_coord_y = %3.2f'%(abs_coord_x, abs_coord_y))
            print('dx = %3.2f ; dy = %3.2f'%(dx, dy))
            print('self.block_width = %3.2f'%(self.block_width))
            print('self.block_height = %3.2f'%(self.block_height))
            print('Cond 1 = %s; Cond 2 = %s; Cond 3 = %s; Cond 4 = %s\n\n'%(cond_1, cond_2, cond_3, cond_4))

            if cond_1 and cond_2 and cond_3 and cond_4:
                self.canvas.move(self.image_obj, dx, dy)

        else:
            self.move_flag = True
            self.canvas.tag_raise(self.image_obj)

    def release(self, event):
        self.move_flag = False

class Application(tk.Frame):

    def __init__(self, master):
        self.master = master
        self.master.protocol("WM_DELETE_WINDOW", self.close)
        tk.Frame.__init__(self, master)

        self.canvas = tk.Canvas(self, width=800, height=800, bg='steelblue', highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)

        self.block_1 = CreateCanvasObject(canvas=self.canvas, block_name='Thing 1')
        self.block_2 = CreateCanvasObject(canvas=self.canvas, block_name='Thing 2')

    def close(self):
        print("Application-Shutdown")
        self.master.destroy()

def main():
    app_win = tk.Tk()
    app_win.title(APP_TITLE)
    app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS))

    Application(app_win).pack(fill='both', expand=True)

    app_win.mainloop()

if __name__ == '__main__':
    main()

Body:
The root of the problem is this line of code:

self.canvas.bind("<Configure>", self.configure)

Whenever you call self.canvas.bind, you replace any previous binding on the widget. Thus, when the binding is triggered, only the last CreateCanvasObject will see the event because it will have replaced the bindings created by previous CreateCanvasObject objects.

Because of that, you only ever update self.win_width and self.win_height of the last object created. And because you use those values to compute self.cond3 and self.cond4, those conditions are always false and thus the object never moves.

A simple solution is to remove the binding and remove the configure method, and instead compute the width and height inside your move function. That, or make self.win_width and self.win_height class variables so when you update one you update all. Those aren't the only ways to solve the problem, but they are the simplest.


答:
Please run the code snippet to see if this is your desire output.

.container {
  display: flex;
}

.container div p {
  text-align: justify;
  text-justify: inter-word;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="column1">
    <p>
      Some content
    </p>
  </div>

  <div class="column2">
    <p>
      There is more content in this div than the other divs. Blah, blah, blah, blah, blah, blah...
    </p>
  </div>

  <div class="column3">
    <p>
      Some content
    </p>
  </div>

</div></code>```

Title: Adjust spacing around paragraph (within a div) so that the space on either side is always equal between divs on the right and left

Body:
Please run the code snippet to see if this is your desire output.

.container {
  display: flex;
}

.container div p {
  text-align: justify;
  text-justify: inter-word;
}

<div class="container">

  <div class="column1">
    <p>
      Some content
    </p>
  </div>

  <div class="column2">
    <p>
      There is more content in this div than the other divs. Blah, blah, blah, blah, blah, blah...
    </p>
  </div>

  <div class="column3">
    <p>
      Some content
    </p>
  </div>

</div>


问:
Can one model be passed through multiple editor templates?
I'm trying to display a view model using an editor template that wraps the model in a fieldset before applying a base Object editor template.

My view:

```<code>@model Mvc3VanillaApplication.Models.ContactModel

@using (Html.BeginForm())
{
    @Html.EditorForModel("Fieldset")
}
</code>```

Uses a fieldset template (Views/Shared/EditorTemplates/Fieldset.cshtml):

```<code><fieldset>
    <legend>@ViewData.ModelMetadata.DisplayName</legend>
    @Html.EditorForModel()
</fieldset>
</code>```

Which in turn uses a basic template for all objects (Views/Shared/EditorTemplates/Object.cshtml):

```<code>@foreach (var prop in ViewData.ModelMetadata.Properties.Where(x =>
    x.ShowForEdit && !x.IsComplexType && !ViewData.TemplateInfo.Visited(x)))
{
    @Html.Label(prop.PropertyName, prop.DisplayName)
    @Html.Editor(prop.PropertyName)
}
</code>```

That's my intent anyway. The problem is that while the page renders with a fieldset and a legend, the Object template isn't applied so no input controls are displayed.

If I change the view to not specify the "Fieldset" template then my model's properties are rendered using the Object template, so it's not that my Object template can't be found.

Is it possible to pass the same model through multiple templates?

For what it's worth, the view model looks like this:

```<code>namespace Mvc3VanillaApplication.Models
{
    [System.ComponentModel.DisplayName("Contact Info")]
    public class ContactModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
</code>```

答:
I implemented what you have, and was able to reproduce it.  I set a break point in Object.cshtml so I could inspect it and I was caught off guard to realize that it wasn't even hitting the object template when the fieldset template was being used.  Then I stepped through the fieldset template and saw it was calling the template just fine, so something must be happening in the code which prevents it from displaying the object template.

I opened up the MVC3 source code, searched for EditorForModel and found the correct function.

```<code>public static MvcHtmlString EditorForModel(this HtmlHelper html) {
    return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */));
}
</code>```

Obviously this wasn't it, so I pressed F12 on TemplateHelpers.TemplateHelper, and once there again I pressed F12 on single line call which brings you to the meat of the function.  Here I found this short bit of code starting on line 214 of TemplateHelpers.cs:

```<code>// Normally this shouldn't happen, unless someone writes their own custom Object templates which
// don't check to make sure that the object hasn't already been displayed
object visitedObjectsKey = metadata.Model ?? metadata.RealModelType;
if (html.ViewDataContainer.ViewData.TemplateInfo.VisitedObjects.Contains(visitedObjectsKey)) {    // DDB #224750
    return String.Empty;
}
</code>```

Those comments are actually in the code, and here we have the answer to your question: Can one model be passed through multiple editor templates?, the answer is no*.

That being said, this seems like a very reasonable use case for such a feature, so finding an alternative is probably worth the effort.  I suspected a templated razor delegate would solve this wrapping functionality, so I tried it out.

```<code>@{
    Func<dynamic, object> fieldset = @<fieldset><legend>@ViewData.ModelMetadata.DisplayName</legend>@Html.EditorForModel()</fieldset>;
}

@using (Html.BeginForm())
{
    //@Html.EditorForModel("Fieldset")
    //@Html.EditorForModel()
    @fieldset(Model)
}
</code>```

And viola! It worked!  I'll leave it up to you to implement this as an extension (and much more reusable) method.  Here is a short blog post about templated razor delegates.

* Technically you could rewrite this function and compile your own version of MVC3, but it's probably more trouble than it's worth.  We tried to do this on the careers project when we found out that the Html.ActionLink function is quite slow when you have a few hundred routes defined.  There is a signing issue with the rest of the libraries which we decided was not worth our time to work through now and maintain for future releases of MVC.

Body:
I'm trying to display a view model using an editor template that wraps the model in a fieldset before applying a base Object editor template.

My view:

@model Mvc3VanillaApplication.Models.ContactModel

@using (Html.BeginForm())
{
    @Html.EditorForModel("Fieldset")
}

Uses a fieldset template (Views/Shared/EditorTemplates/Fieldset.cshtml):

<fieldset>
    <legend>@ViewData.ModelMetadata.DisplayName</legend>
    @Html.EditorForModel()
</fieldset>

Which in turn uses a basic template for all objects (Views/Shared/EditorTemplates/Object.cshtml):

@foreach (var prop in ViewData.ModelMetadata.Properties.Where(x =>
    x.ShowForEdit && !x.IsComplexType && !ViewData.TemplateInfo.Visited(x)))
{
    @Html.Label(prop.PropertyName, prop.DisplayName)
    @Html.Editor(prop.PropertyName)
}

That's my intent anyway. The problem is that while the page renders with a fieldset and a legend, the Object template isn't applied so no input controls are displayed.

If I change the view to not specify the "Fieldset" template then my model's properties are rendered using the Object template, so it's not that my Object template can't be found.

Is it possible to pass the same model through multiple templates?

For what it's worth, the view model looks like this:

namespace Mvc3VanillaApplication.Models
{
    [System.ComponentModel.DisplayName("Contact Info")]
    public class ContactModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Body:
I implemented what you have, and was able to reproduce it.  I set a break point in Object.cshtml so I could inspect it and I was caught off guard to realize that it wasn't even hitting the object template when the fieldset template was being used.  Then I stepped through the fieldset template and saw it was calling the template just fine, so something must be happening in the code which prevents it from displaying the object template.

I opened up the MVC3 source code, searched for EditorForModel and found the correct function.

public static MvcHtmlString EditorForModel(this HtmlHelper html) {
    return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */));
}

Obviously this wasn't it, so I pressed F12 on TemplateHelpers.TemplateHelper, and once there again I pressed F12 on single line call which brings you to the meat of the function.  Here I found this short bit of code starting on line 214 of TemplateHelpers.cs:

// Normally this shouldn't happen, unless someone writes their own custom Object templates which
// don't check to make sure that the object hasn't already been displayed
object visitedObjectsKey = metadata.Model ?? metadata.RealModelType;
if (html.ViewDataContainer.ViewData.TemplateInfo.VisitedObjects.Contains(visitedObjectsKey)) {    // DDB #224750
    return String.Empty;
}

Those comments are actually in the code, and here we have the answer to your question: Can one model be passed through multiple editor templates?, the answer is no*.

That being said, this seems like a very reasonable use case for such a feature, so finding an alternative is probably worth the effort.  I suspected a templated razor delegate would solve this wrapping functionality, so I tried it out.

@{
    Func<dynamic, object> fieldset = @<fieldset><legend>@ViewData.ModelMetadata.DisplayName</legend>@Html.EditorForModel()</fieldset>;
}

@using (Html.BeginForm())
{
    //@Html.EditorForModel("Fieldset")
    //@Html.EditorForModel()
    @fieldset(Model)
}

And viola! It worked!  I'll leave it up to you to implement this as an extension (and much more reusable) method.  Here is a short blog post about templated razor delegates.

* Technically you could rewrite this function and compile your own version of MVC3, but it's probably more trouble than it's worth.  We tried to do this on the careers project when we found out that the Html.ActionLink function is quite slow when you have a few hundred routes defined.  There is a signing issue with the rest of the libraries which we decided was not worth our time to work through now and maintain for future releases of MVC.


问:
NLog seems to ignore config file location in .NET Core 3.1 Windows Service
Type: Bug

NLog version: 4.7.2

NLog.Web/NLog.Web.AspNetCore version: 4.9.2

NLog.Extensions.Logging version: N/A

Platform: .NET Core 3.1

Current NLog config (xml or C#, if relevant)

```<code><nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        autoReload="true"
        internalLogLevel="Warn"
        internalLogFile="internal.txt">
  <extensions>
    <!--enable NLog.Web for ASP.NET Core-->
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- define various log targets -->
  <targets>
    <target xsi:type="File"
            name="allOutput"
            fileName="${startupdir}\logs\SkyJack-Agent-All-${shortdate}.log"
            layout="${longdate} ${logger} ${uppercase:${level}} ${message} ${exception}" />
    <target xsi:type="File"
            name="ourOutput"
            fileName="${startupdir}\logs\SkyJack-Agent-OurOutput-${shortdate}.log"
            layout="${longdate} ${logger} ${uppercase:${level}} ${message} ${exception}" />
    <target xsi:type="File"
            name="errorsOnly"
            fileName="${startupdir}\logs\SkyJack-Agent-ErrorsOnly-${shortdate}.log"
            layout="${longdate} ${logger} ${uppercase:${level}} ${message} ${exception}" />
    <target name="console" xsi:type="ColoredConsole" layout="${longdate} ${pad:padding=5:inner=-${level}-} ${message}"
                useDefaultRowHighlightingRules="false" >
      <highlight-row condition="level==LogLevel.Trace" foregroundColor="Gray" />
      <highlight-row condition="level==LogLevel.Debug" foregroundColor="DarkGray" />
      <highlight-word text="-Info-"  foregroundColor="DarkGreen" />
      <highlight-word text="-Warn-"  foregroundColor="DarkYellow" />
      <highlight-word text="-Error-"  foregroundColor="DarkMagenta" />
      <highlight-word text="-Fatal-"  foregroundColor="DarkRed" backgroundColor="White"/>
    </target>
  </targets>

  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Debug" writeTo="console" />
    <logger name="*" minlevel="Trace" writeTo="allOutput" />
    <logger name="*" minlevel="Error" writeTo="errorsOnly" />

    <!--Skip Microsoft logs - no writeTo attribute-->
    <logger name="Microsoft.*" minlevel="Trace" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ourOutput" />
  </rules>
</nlog>
</code>```

I am using NLog in a .NET Core web service published as single file and attempting to install it as a service. NLog works fine when I run it normally, however when running as a service it needs to be told where to find the config file, which I am accomplishing with:

            var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);

            NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(Path.Combine(pathToContentRoot, "nlog.config"));
            var logger = NLog.Web.NLogBuilder.ConfigureNLog(NLog.LogManager.Configuration).GetCurrentClassLogger();
```

<p>And the content root with:</p>

```                builder.UseWindowsService().UseContentRoot(pathToContentRoot);
```

<p>This appears to work, at least at first, and generates some log output, enough to see that I am setting the content root successfully:</p>

```2020-05-28 15:42:20.5932 SkyJack.Agent.Program INFO ... Initializing SkyJack Agent with content root G:\MSGPS2\SkyJack\SkyJack\src\SkyJack.Agent\bin\Release\netcoreapp3.1\publish...
2020-05-28 15:42:20.6373 SkyJack.Agent.Program TRACE Entering CreateWebHostBuilder()
2020-05-28 15:42:20.8023 SkyJack.Agent.Program TRACE Returned from CreateWebHostBuilder()
2020-05-28 15:42:20.8023 SkyJack.Agent.Program TRACE Entering builder.Build()
2020-05-28 15:42:20.9446 SkyJack.Agent.Program TRACE Returned from builder.Build()
```

<p>Eventually, however, it throws an exception:</p>

```Log Name:      Application
Source:        ServerManagerAgent
Date:          5/28/2020 3:54:04 PM
Event ID:      6
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      HPZEE.redmond.corp.microsoft.com
Description:
Category: Microsoft.AspNetCore.Hosting.Diagnostics
EventId: 6

Application startup exception

Exception:
System.IO.FileNotFoundException: Failed to load NLog LoggingConfiguration. Searched the following locations:
- C:\WINDOWS\TEMP\.net\ServerManagerAgent\31dyvwga.rkl\nlog.config

File name: 'nlog.config'
   at NLog.LogFactory.LoadConfiguration(String configFile, Boolean optional)
   at NLog.LogFactory.LoadConfiguration(String configFile)
   at NLog.LogManager.LoadConfiguration(String configFile)
   at NLog.Web.NLogBuilder.ConfigureNLog(String configFileName)
   at WebAppService.Startup.Configure(IApplicationBuilder app)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
   at Microsoft.Extensions.DependencyInjection.AutoRegisterMiddleware.<>c__DisplayClass4_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)

Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="ServerManagerAgent" />
    <EventID Qualifiers="0">6</EventID>
    <Version>0</Version>
    <Level>2</Level>
    <Task>0</Task>
    <Opcode>0</Opcode>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2020-05-28T22:54:04.0041305Z" />
    <EventRecordID>61154</EventRecordID>
    <Correlation />
    <Execution ProcessID="0" ThreadID="0" />
    <Channel>Application</Channel>
    <Computer>HPZEE.redmond.corp.microsoft.com</Computer>
    <Security />
  </System>
  <EventData>
    <Data>Category: Microsoft.AspNetCore.Hosting.Diagnostics
EventId: 6

Application startup exception

Exception:
System.IO.FileNotFoundException: Failed to load NLog LoggingConfiguration. Searched the following locations:
- C:\WINDOWS\TEMP\.net\ServerManagerAgent\31dyvwga.rkl\nlog.config

File name: 'nlog.config'
   at NLog.LogFactory.LoadConfiguration(String configFile, Boolean optional)
   at NLog.LogFactory.LoadConfiguration(String configFile)
   at NLog.LogManager.LoadConfiguration(String configFile)
   at NLog.Web.NLogBuilder.ConfigureNLog(String configFileName)
   at WebAppService.Startup.Configure(IApplicationBuilder app)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
   at Microsoft.Extensions.DependencyInjection.AutoRegisterMiddleware.<>c__DisplayClass4_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
</Data>
  </EventData>
</Event>
```

WebAppService.Startup.Configure() is calling NLog.Web.NLogBuilder.ConfigureNLog() again, presumably with just "nlog.config" instead of the location or LoggerConfiguration object that I passed in to begin with.

Is there any way to get it to use the location or configuration that I've already specified and loaded?

答:
I got it working with:

NLog.LogManager.LogFactory.SetCandidateConfigFilePaths(new List<string> { $"{Path.Combine(pathToContentRoot, "nlog.config")}" });
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
```

Body:
Type: Bug

NLog version: 4.7.2

NLog.Web/NLog.Web.AspNetCore version: 4.9.2

NLog.Extensions.Logging version: N/A

Platform: .NET Core 3.1

Current NLog config (xml or C#, if relevant)

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        autoReload="true"
        internalLogLevel="Warn"
        internalLogFile="internal.txt">
  <extensions>

    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <targets>
    <target xsi:type="File"
            name="allOutput"
            fileName="${startupdir}\logs\SkyJack-Agent-All-${shortdate}.log"
            layout="${longdate} ${logger} ${uppercase:${level}} ${message} ${exception}" />
    <target xsi:type="File"
            name="ourOutput"
            fileName="${startupdir}\logs\SkyJack-Agent-OurOutput-${shortdate}.log"
            layout="${longdate} ${logger} ${uppercase:${level}} ${message} ${exception}" />
    <target xsi:type="File"
            name="errorsOnly"
            fileName="${startupdir}\logs\SkyJack-Agent-ErrorsOnly-${shortdate}.log"
            layout="${longdate} ${logger} ${uppercase:${level}} ${message} ${exception}" />
    <target name="console" xsi:type="ColoredConsole" layout="${longdate} ${pad:padding=5:inner=-${level}-} ${message}"
                useDefaultRowHighlightingRules="false" >
      <highlight-row condition="level==LogLevel.Trace" foregroundColor="Gray" />
      <highlight-row condition="level==LogLevel.Debug" foregroundColor="DarkGray" />
      <highlight-word text="-Info-"  foregroundColor="DarkGreen" />
      <highlight-word text="-Warn-"  foregroundColor="DarkYellow" />
      <highlight-word text="-Error-"  foregroundColor="DarkMagenta" />
      <highlight-word text="-Fatal-"  foregroundColor="DarkRed" backgroundColor="White"/>
    </target>
  </targets>

  <rules>

    <logger name="*" minlevel="Debug" writeTo="console" />
    <logger name="*" minlevel="Trace" writeTo="allOutput" />
    <logger name="*" minlevel="Error" writeTo="errorsOnly" />

    <logger name="Microsoft.*" minlevel="Trace" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ourOutput" />
  </rules>
</nlog>

I am using NLog in a .NET Core web service published as single file and attempting to install it as a service. NLog works fine when I run it normally, however when running as a service it needs to be told where to find the config file, which I am accomplishing with:

            var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);

            NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(Path.Combine(pathToContentRoot, "nlog.config"));
            var logger = NLog.Web.NLogBuilder.ConfigureNLog(NLog.LogManager.Configuration).GetCurrentClassLogger();

And the content root with:

                builder.UseWindowsService().UseContentRoot(pathToContentRoot);

This appears to work, at least at first, and generates some log output, enough to see that I am setting the content root successfully:

2020-05-28 15:42:20.5932 SkyJack.Agent.Program INFO ... Initializing SkyJack Agent with content root G:\MSGPS2\SkyJack\SkyJack\src\SkyJack.Agent\bin\Release\netcoreapp3.1\publish...
2020-05-28 15:42:20.6373 SkyJack.Agent.Program TRACE Entering CreateWebHostBuilder()
2020-05-28 15:42:20.8023 SkyJack.Agent.Program TRACE Returned from CreateWebHostBuilder()
2020-05-28 15:42:20.8023 SkyJack.Agent.Program TRACE Entering builder.Build()
2020-05-28 15:42:20.9446 SkyJack.Agent.Program TRACE Returned from builder.Build()

Eventually, however, it throws an exception:

Log Name:      Application
Source:        ServerManagerAgent
Date:          5/28/2020 3:54:04 PM
Event ID:      6
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      HPZEE.redmond.corp.microsoft.com
Description:
Category: Microsoft.AspNetCore.Hosting.Diagnostics
EventId: 6

Application startup exception

Exception:
System.IO.FileNotFoundException: Failed to load NLog LoggingConfiguration. Searched the following locations:
- C:\WINDOWS\TEMP\.net\ServerManagerAgent\31dyvwga.rkl\nlog.config

File name: 'nlog.config'
   at NLog.LogFactory.LoadConfiguration(String configFile, Boolean optional)
   at NLog.LogFactory.LoadConfiguration(String configFile)
   at NLog.LogManager.LoadConfiguration(String configFile)
   at NLog.Web.NLogBuilder.ConfigureNLog(String configFileName)
   at WebAppService.Startup.Configure(IApplicationBuilder app)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
   at Microsoft.Extensions.DependencyInjection.AutoRegisterMiddleware.<>c__DisplayClass4_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)

Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="ServerManagerAgent" />
    <EventID Qualifiers="0">6</EventID>
    <Version>0</Version>
    <Level>2</Level>
    <Task>0</Task>
    <Opcode>0</Opcode>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2020-05-28T22:54:04.0041305Z" />
    <EventRecordID>61154</EventRecordID>
    <Correlation />
    <Execution ProcessID="0" ThreadID="0" />
    <Channel>Application</Channel>
    <Computer>HPZEE.redmond.corp.microsoft.com</Computer>
    <Security />
  </System>
  <EventData>
    <Data>Category: Microsoft.AspNetCore.Hosting.Diagnostics
EventId: 6

Application startup exception

Exception:
System.IO.FileNotFoundException: Failed to load NLog LoggingConfiguration. Searched the following locations:
- C:\WINDOWS\TEMP\.net\ServerManagerAgent\31dyvwga.rkl\nlog.config

File name: 'nlog.config'
   at NLog.LogFactory.LoadConfiguration(String configFile, Boolean optional)
   at NLog.LogFactory.LoadConfiguration(String configFile)
   at NLog.LogManager.LoadConfiguration(String configFile)
   at NLog.Web.NLogBuilder.ConfigureNLog(String configFileName)
   at WebAppService.Startup.Configure(IApplicationBuilder app)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
   at Microsoft.Extensions.DependencyInjection.AutoRegisterMiddleware.<>c__DisplayClass4_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
</Data>
  </EventData>
</Event>

WebAppService.Startup.Configure() is calling NLog.Web.NLogBuilder.ConfigureNLog() again, presumably with just "nlog.config" instead of the location or LoggerConfiguration object that I passed in to begin with.

Is there any way to get it to use the location or configuration that I've already specified and loaded?


问:
Can I safely remove await Task.CompletedTask call at the end of a method?
I was looking over some old code and I found an async method doing some async stuff and at the end calling await Task.CompletedTask; like below:

```<code>    public async Task SomeMethod()
    {
        //some code
        //...

        await _someService.DoStuffAsync();
        await Task.CompletedTask;
    }
</code>```

From what I read it seems safe to remove the last line, as it does not have a functional impact over the method execution, since the Task.CompletedTask will return a task that is already completed so it will not await it, but I have second thoughts about this.

Is it safe to delete the last line? Is it redundant?

答:
Adding the line await Task.CompletedTask; is an easy way to suppress the compiler warning CS1998:

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Other than that it does nothing. So it is quite possible to add it while designing the API of a class, and then forget to remove it after writting the implementation. Feel free to remove it. Removing it will not cause any side-effects at all.

Body:
I was looking over some old code and I found an async method doing some async stuff and at the end calling await Task.CompletedTask; like below:

    public async Task SomeMethod()
    {
        //some code
        //...

        await _someService.DoStuffAsync();
        await Task.CompletedTask;
    }

From what I read it seems safe to remove the last line, as it does not have a functional impact over the method execution, since the Task.CompletedTask will return a task that is already completed so it will not await it, but I have second thoughts about this.

Is it safe to delete the last line? Is it redundant?


问:
Quickest way of checking if a csv column consists of a particular value in python
What is the quickest way to get the row that contains the column having a particular value 'X'. For example, if I have a csv having the following columns :

```<code>item_no.,item_Name,item_price
</code>```

What is the best way (in terms of execution time) to get the record having item_name = 'X'? I know we can iterate over the whole csv to get this, but it seems expensive in terms of execution time.

Thanks a lot in advance for your help.

答:
Fast file search/find of text

Optimizations

Process file in binary (removes the overhead of binary to text conversions)

Search a buffer at a time rather than line by line

Convert found line from binary to text

Code

Inspired by

```<code>def find_line(fname, goal):
    " Generator of lines containing goal string "

    def str_to_bytes(s):
        ' String to byte array '
        result = bytearray()
        result.extend(map(ord, s))
        return result

    def find_buffer(fname, goal, start=0, bsize=2**17):
        """
            Processing file in binary to find goal string
                - removes overhead of binary to text conversions
            Uses find method on a buffer of data at a time
                - faster than check each line by line
        """
        bgoal = str_to_bytes(goal)            # convert goal string to binary
        bnew_line = str_to_bytes(os.linesep)  # line separator as byte array

        if bsize < len(bgoal):
            raise ValueError("The buffer size must be larger than the string being searched for.")
        with open(fname, 'rb') as f:
            if start > 0:
                f.seek(start)
            overlap = len(bgoal) - 1
            while True:
                buffer = f.read(bsize)
                pos = buffer.find(bgoal)

                if pos >= 0:
                    start_line = buffer.rfind(bnew_line, 0, pos)
                    end_line = buffer.find(bnew_line, pos)
                    yield buffer[start_line+len(bnew_line):end_line] #f.tell() - len(buffer) + pos
                if not buffer:
                    return None
                f.seek(f.tell() - overlap)

    # Find line in file
    os_encoding = locale.getpreferredencoding()
    delimiter = str_to_bytes(',')  # column delimiter in bytes
    bgoal = str_to_bytes(goal)

    for line in find_buffer(fname, goal):
        # convert to text
        # Insure it's in 2nd column
        columns = line.split(str_to_bytes(','))
        if columns[1] == bgoal:
            return line.decode(os_encoding)

    else:
        return None
</code>```

Usage

```<code>line = find_buffer_method(filename, search_string)
</code>```

Performance Testing

Generate 1M row text file similar to posters format

File Generation Code

Inspired by

Create CSV file with 1 million rows

```<code>import csv
import random

records= 100000   # number of rows to generate
print("Making %d records\n" % records)

fieldnames = ['item_no.','item_Name','item_price']

with open("data.csv", "w", newline='') as my_file:
    writer = csv.DictWriter(my_file, fieldnames=fieldnames)

    writer.writeheader()
    for i in range(records):
        writer.writerow(
            {
                'item_no.': i,
                'item_Name': "X{}".format(i),
                'item_price': random.randint(1, 100)
            })
</code>```

Line by Line Method (to provide a speed baseline)

```<code>def line_by_line(fname, goal):
   " Line by line search for goal string "
    with open(fname, 'r') as f:
        for line in f:
            if goal in line:
                # Insure found in 2nd column
                columns = line.split(',')
                if columns[1] == goal:
                    return line
        return None
</code>```

Timing using Timeit

```<code># Rows           find_line_method                 find_buffer_method          Speed Up
10,000           2.99 ms (7 runs/100 loops)       295 µs (7 runs/1000 loops)     10X
100,000         30.40 ms (7 runs/10 loops)        1.78 ms (7 runs/1000 loops)    17X
1M             321.00 ms (7 runs/1 loop)          19.7 ms (7 runs/10 loops)      17X
</code>```

We note that the buffer is ~17X faster for larger files.

Note: Row in the table above is based upon what row the goal string is located in the 1M row file for the test.

Body:
What is the quickest way to get the row that contains the column having a particular value 'X'. For example, if I have a csv having the following columns :

item_no.,item_Name,item_price

What is the best way (in terms of execution time) to get the record having item_name = 'X'? I know we can iterate over the whole csv to get this, but it seems expensive in terms of execution time.

Thanks a lot in advance for your help.

Body:
Fast file search/find of text

Optimizations

Process file in binary (removes the overhead of binary to text conversions)

Search a buffer at a time rather than line by line

Convert found line from binary to text

Code

Inspired by

def find_line(fname, goal):
    " Generator of lines containing goal string "

    def str_to_bytes(s):
        ' String to byte array '
        result = bytearray()
        result.extend(map(ord, s))
        return result

    def find_buffer(fname, goal, start=0, bsize=2**17):
        """
            Processing file in binary to find goal string
                - removes overhead of binary to text conversions
            Uses find method on a buffer of data at a time
                - faster than check each line by line
        """
        bgoal = str_to_bytes(goal)            # convert goal string to binary
        bnew_line = str_to_bytes(os.linesep)  # line separator as byte array

        if bsize < len(bgoal):
            raise ValueError("The buffer size must be larger than the string being searched for.")
        with open(fname, 'rb') as f:
            if start > 0:
                f.seek(start)
            overlap = len(bgoal) - 1
            while True:
                buffer = f.read(bsize)
                pos = buffer.find(bgoal)

                if pos >= 0:
                    start_line = buffer.rfind(bnew_line, 0, pos)
                    end_line = buffer.find(bnew_line, pos)
                    yield buffer[start_line+len(bnew_line):end_line] #f.tell() - len(buffer) + pos
                if not buffer:
                    return None
                f.seek(f.tell() - overlap)

    # Find line in file
    os_encoding = locale.getpreferredencoding()
    delimiter = str_to_bytes(',')  # column delimiter in bytes
    bgoal = str_to_bytes(goal)

    for line in find_buffer(fname, goal):
        # convert to text
        # Insure it's in 2nd column
        columns = line.split(str_to_bytes(','))
        if columns[1] == bgoal:
            return line.decode(os_encoding)

    else:
        return None

Usage

line = find_buffer_method(filename, search_string)

Performance Testing

Generate 1M row text file similar to posters format

File Generation Code

Inspired by

Create CSV file with 1 million rows

import csv
import random

records= 100000   # number of rows to generate
print("Making %d records\n" % records)

fieldnames = ['item_no.','item_Name','item_price']

with open("data.csv", "w", newline='') as my_file:
    writer = csv.DictWriter(my_file, fieldnames=fieldnames)

    writer.writeheader()
    for i in range(records):
        writer.writerow(
            {
                'item_no.': i,
                'item_Name': "X{}".format(i),
                'item_price': random.randint(1, 100)
            })

Line by Line Method (to provide a speed baseline)

def line_by_line(fname, goal):
   " Line by line search for goal string "
    with open(fname, 'r') as f:
        for line in f:
            if goal in line:
                # Insure found in 2nd column
                columns = line.split(',')
                if columns[1] == goal:
                    return line
        return None

Timing using Timeit

# Rows           find_line_method                 find_buffer_method          Speed Up
10,000           2.99 ms (7 runs/100 loops)       295 µs (7 runs/1000 loops)     10X
100,000         30.40 ms (7 runs/10 loops)        1.78 ms (7 runs/1000 loops)    17X
1M             321.00 ms (7 runs/1 loop)          19.7 ms (7 runs/10 loops)      17X

We note that the buffer is ~17X faster for larger files.

Note: Row in the table above is based upon what row the goal string is located in the 1M row file for the test.


问:
How to generate a function with a name pre-determined by an algorithm through a JavaScript function?
Let's say I need to input an X number of strings. The letters of each string must be separated in a variable that has the name that follows the following pattern: (PositionOfTheCharacterInTheString)+String+(OrdinaryPositionOfTheString).

For example, we have strings:

1="ABC"

string 2="XYZ"

string Y="HIJ"

I need that a function when called create the following variables:

```<code>1String1="A"
2String1="B"
3String1="C"
1String2="X"
2String2="Y"
3String2="Z"
1String3="H"
2String3="I"
3String3="J"
</code>```

How would I go about doing it?

I also would like to know how to generate through a function variables with names like "1","2","3"... and "A","B", "C", "D"...

Thanks.

答:
There's really no reason to do this. JavaScript does not support variable variables. Maybe you want to do is something like:

function Organizer(){
  const a = [];
  for(let i=0,s,l=arguments.length; i<l; i++){
    a.push([]);
  }
  a.forEach((v, i)=>{
    s = arguments[i].split('');
    s.forEach((r, q)=>{
      a[q].push(r);
    });
  });
  this.getArray = ()=>{
    return a;
  }
  this.getWeird = fakeVar=>{
    const s = fakeVar.split(/string/i);
    return a[s[0]-1][s[1]-1];
  }
}
const org = new Organizer('ABC', 'XYZ', 'HIJ');
console.log(org.getWeird('3String2'));
console.log(org.getWeird('2String3'));```

Of course, I would just use Array access, instead.

Body:
Let's say I need to input an X number of strings. The letters of each string must be separated in a variable that has the name that follows the following pattern: (PositionOfTheCharacterInTheString)+String+(OrdinaryPositionOfTheString).

For example, we have strings:

1="ABC"

string 2="XYZ"

string Y="HIJ"

I need that a function when called create the following variables:

1String1="A"
2String1="B"
3String1="C"
1String2="X"
2String2="Y"
3String2="Z"
1String3="H"
2String3="I"
3String3="J"

How would I go about doing it?

I also would like to know how to generate through a function variables with names like "1","2","3"... and "A","B", "C", "D"...

Thanks.

Body:
There's really no reason to do this. JavaScript does not support variable variables. Maybe you want to do is something like:

function Organizer(){
  const a = [];
  for(let i=0,s,l=arguments.length; i<l; i++){
    a.push([]);
  }
  a.forEach((v, i)=>{
    s = arguments[i].split('');
    s.forEach((r, q)=>{
      a[q].push(r);
    });
  });
  this.getArray = ()=>{
    return a;
  }
  this.getWeird = fakeVar=>{
    const s = fakeVar.split(/string/i);
    return a[s[0]-1][s[1]-1];
  }
}
const org = new Organizer('ABC', 'XYZ', 'HIJ');
console.log(org.getWeird('3String2'));
console.log(org.getWeird('2String3'));

Of course, I would just use Array access, instead.


问:
jquery how to figure out what the JSON Object contains
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

```<code>$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});
</code>```

If I do this - I get an object, but I don't know what it contains.

答:
In your code to return the Json object you should be setting certain properties of an object, or dynamically creating an object, or something along those lines.

Can we see the method that returns the Json?

Say you are returning an object with the property Id, you should just be able to get that by accessing:

```<code>parent.Id
</code>```

on the client side.

Body:
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});

If I do this - I get an object, but I don't know what it contains.

Body:
In your code to return the Json object you should be setting certain properties of an object, or dynamically creating an object, or something along those lines.

Can we see the method that returns the Json?

Say you are returning an object with the property Id, you should just be able to get that by accessing:

parent.Id

on the client side.


问:
for loop only takes last value in python aws dynamodb
I am trying to insert records into a table, but only last record(result data) from the loop is inserting into the table

Here is the code i tried:

```<code>CDates = ['2020-05-10','2020-05-12','2020-05-13','2020-05-16','2020-05-20']

ResultData = {}
for date in CDates:
   filterDate = Key('Date').eq(id)
   appResponse = appTable.scan(FilterExpression = filterDate)
   accResp = table.query(KeyConditionExpression = Key('PrimaryId').eq('Key'),FilterExpression = Key('Date').eq(date))
   if len(accResp['Items']) == 0:
       ResultData['PrimaryId'] = 'Key'
       ResultData['CreatedDate'] = date
       ResultData['Type'] = 'Appt'
       ResultData['Id'] = str(uuid.uuid4())
       print(ResultData)
       table.put_item(Item=ResultData)

</code>```

Not getting where did I go wrong

答:
You assigned ResultData outside of the loop and changed the values for the same keys every time the loop ran. Try this:

CDates = ['2020-05-10', '2020-05-12', '2020-05-13', '2020-05-16', '2020-05-20']

for date in CDates:
    filterDate = Key('Date').eq(id)
    appResponse = appTable.scan(FilterExpression=filterDate)
    accResp = table.query(
        KeyConditionExpression=Key('PrimaryId').eq('Key'),
        FilterExpression=Key('Date').eq(date))
    if len(accResp['Items']) == 0:
        ResultData = {
            'PrimaryId': 'Key',
            'CreationDate': date,
            'Type': 'Appt',
            'Id': str(uuid.uuid4())
        }
        print(ResultData)
        table.put_item(Item=ResultData)

```

Body:
I am trying to insert records into a table, but only last record(result data) from the loop is inserting into the table

Here is the code i tried:

CDates = ['2020-05-10','2020-05-12','2020-05-13','2020-05-16','2020-05-20']

ResultData = {}
for date in CDates:
   filterDate = Key('Date').eq(id)
   appResponse = appTable.scan(FilterExpression = filterDate)
   accResp = table.query(KeyConditionExpression = Key('PrimaryId').eq('Key'),FilterExpression = Key('Date').eq(date))
   if len(accResp['Items']) == 0:
       ResultData['PrimaryId'] = 'Key'
       ResultData['CreatedDate'] = date
       ResultData['Type'] = 'Appt'
       ResultData['Id'] = str(uuid.uuid4())
       print(ResultData)
       table.put_item(Item=ResultData)

Not getting where did I go wrong