问:
PHP: DatePeriod with last day of month
I'd like to work with PHP DateInterval to iterate through months:

```<code>$from = new DateTime();
$from->setDate(2014, 1, 31);

$period = new DatePeriod($from, new DateInterval('P1M'), 12);
</code>```

I'd expect it to returns 31 January, 28 February (as the DateInterval is 1 month), but it actually returns 31 January, 3 March, 3 of April... hence skipping February.

Is there any way to do this simply?

Thanks!

EDIT : as a refernece, here is a solution that seems to cover most use cases:

```<code>$date = new DateTime('2014-01-31');
$start = $date->format('n');

for ($i = 0; $i < 28; $i++) {
  $current = clone $date;
  $current->modify('+'.$i.' month');

  if ($current->format('n') > ($start % 12) && $start !== 12) {
    $current->modify('last day of last month');
  }

  $start++;

  echo $current->format('Y-m-d').PHP_EOL;
}
</code>```

答:
The issue is cause by the variance between the last day in each of the months within the range. ie. February ending on 28 instead of 31 and the addition of 1 month from the last day 2014-01-31 + 1 month = 2014-03-03 https://3v4l.org/Y42QJ

To resolve the issue with DatePeriod and simplify it a bit, adjust the initial date by resetting the specified date to the first day of the specified month, by using first day of this month.

Then during iteration, you can modify the date period date by using last day of this month to retrieve the bounds of the currently iterated month.

Example: https://3v4l.org/889mB

```<code>$from = new DateTime('2014-01-31');
$from->modify('first day of this month'); //2014-01-01

$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
    echo $date->modify('last day of this month')->format('Y-m-d');
}
</code>```

Result:

```<code>2014-01-31
2014-02-28
2014-03-31
2014-04-30
2014-05-31
2014-06-30
2014-07-31
2014-08-31
2014-09-30
2014-10-31
2014-11-30
2014-12-31
2015-01-31
</code>```

Then to expand on this approach, in order to retrieve the desired day from the specified date, such as the 29th. You can extract the specified day and adjust the currently iterated month as needed when the day is out of bounds for that month.

Example: https://3v4l.org/SlEJc

```<code>$from = new DateTime('2014-01-29');
$day = $from->format('j');
$from->modify('first day of this month'); //2014-01-01

$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
    $lastDay = clone $date;
    $lastDay->modify('last day of this month');
    $date->setDate($date->format('Y'), $date->format('n'), $day);
    if ($date > $lastDay) {
       $date = $lastDay;
    }
    echo $date->format('Y-m-d');
}
</code>```

Result:

```<code>2014-01-29
2014-02-28 #notice the last day of february is used
2014-03-29
2014-04-29
2014-05-29
2014-06-29
2014-07-29
2014-08-29
2014-09-29
2014-10-29
2014-11-29
2014-12-29
2015-01-29
</code>```

Title: PHP: DatePeriod with last day of month

Body:
I'd like to work with PHP DateInterval to iterate through months:

$from = new DateTime();
$from->setDate(2014, 1, 31);

$period = new DatePeriod($from, new DateInterval('P1M'), 12);

I'd expect it to returns 31 January, 28 February (as the DateInterval is 1 month), but it actually returns 31 January, 3 March, 3 of April... hence skipping February.

Is there any way to do this simply?

Thanks!

EDIT : as a refernece, here is a solution that seems to cover most use cases:

$date = new DateTime('2014-01-31');
$start = $date->format('n');

for ($i = 0; $i < 28; $i++) {
  $current = clone $date;
  $current->modify('+'.$i.' month');

  if ($current->format('n') > ($start % 12) && $start !== 12) {
    $current->modify('last day of last month');
  }

  $start++;

  echo $current->format('Y-m-d').PHP_EOL;
}

Body:
The issue is cause by the variance between the last day in each of the months within the range. ie. February ending on 28 instead of 31 and the addition of 1 month from the last day 2014-01-31 + 1 month = 2014-03-03 https://3v4l.org/Y42QJ

To resolve the issue with DatePeriod and simplify it a bit, adjust the initial date by resetting the specified date to the first day of the specified month, by using first day of this month.

Then during iteration, you can modify the date period date by using last day of this month to retrieve the bounds of the currently iterated month.

Example: https://3v4l.org/889mB

$from = new DateTime('2014-01-31');
$from->modify('first day of this month'); //2014-01-01

$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
    echo $date->modify('last day of this month')->format('Y-m-d');
}

Result:

2014-01-31
2014-02-28
2014-03-31
2014-04-30
2014-05-31
2014-06-30
2014-07-31
2014-08-31
2014-09-30
2014-10-31
2014-11-30
2014-12-31
2015-01-31

Then to expand on this approach, in order to retrieve the desired day from the specified date, such as the 29th. You can extract the specified day and adjust the currently iterated month as needed when the day is out of bounds for that month.

Example: https://3v4l.org/SlEJc

$from = new DateTime('2014-01-29');
$day = $from->format('j');
$from->modify('first day of this month'); //2014-01-01

$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
    $lastDay = clone $date;
    $lastDay->modify('last day of this month');
    $date->setDate($date->format('Y'), $date->format('n'), $day);
    if ($date > $lastDay) {
       $date = $lastDay;
    }
    echo $date->format('Y-m-d');
}

Result:

2014-01-29
2014-02-28 #notice the last day of february is used
2014-03-29
2014-04-29
2014-05-29
2014-06-29
2014-07-29
2014-08-29
2014-09-29
2014-10-29
2014-11-29
2014-12-29
2015-01-29


来源: stackexchange

问:
Critical loop containing many "if" whose output is constant : How to save on condition tests?
I have a critical loop in my code with this shape :

```<code>int myloop(int a, .....){

   /* some stuff */

   // Critical loop
   while(...){
       /* Some Stuff */
       if(a == 1){
          // .....
       }
       else if(a == 2){
          // .....
       }
       else if(a == 3){
          // .....
       }
       else{
          // ....
       }
   }
}
</code>```

As the loop never touches the value of "a" the branch taken will never change, but as this loop is really heavy it will require to test the value of "a" many times, which is totally unnecessary. The best thing is probably to duplicate the loop, so that the "if" can be tested before the loop begins, but this would mean copying a lot of stuff common to both situations and will result in a very ugly code...

Is there any way to ask GCC/G++ to duplicate this code when it compiles it ? Or any other trick to avoid testing the value so many times ?

Thank you for your help !

Nathann

答:
You can use an array with pointer to functions, if your conditions are mostly adjacent.

```<code>typedef void ( *case_func )( type1 param1, type2 param2 );

void case_func1( type1 param1, type2 param2 );
void case_func2( type1 param1, type2 param2 );
void case_func3( type1 param1, type2 param2 );
void case_func5( type1 param1, type2 param2 );

case_func    func_array[] =
{
    &case_func1,
    &case_func2,
    &case_func3,
    NULL,        // Just a place holder, for non-contiguous values.
    &case_func5
};

int myloop(int a, .....){

   /* some stuff */

   // Critical loop
   while(...)
   {
       if ( func_array[ a ] && a < sizeof( func_array ) )
           func_array[ a ]( .... );
   }
}
</code>```

If you can be assure that you'll have no holes in your array and a will never be outside array bounds you can omit if ( func_array[ a ] && a < sizeof( func_array ) ), reducing the code to no comparison at all.

Anyway, this approach can be a bit clearer, and may be worth even if it gives no big performance gain.

ContentLicense: CC BY-SA 2.5

Body:
I have a critical loop in my code with this shape :

int myloop(int a, .....){

   /* some stuff */

   // Critical loop
   while(...){
       /* Some Stuff */
       if(a == 1){
          // .....
       }
       else if(a == 2){
          // .....
       }
       else if(a == 3){
          // .....
       }
       else{
          // ....
       }
   }
}

As the loop never touches the value of "a" the branch taken will never change, but as this loop is really heavy it will require to test the value of "a" many times, which is totally unnecessary. The best thing is probably to duplicate the loop, so that the "if" can be tested before the loop begins, but this would mean copying a lot of stuff common to both situations and will result in a very ugly code...

Is there any way to ask GCC/G++ to duplicate this code when it compiles it ? Or any other trick to avoid testing the value so many times ?

Thank you for your help !

Nathann

Body:
You can use an array with pointer to functions, if your conditions are mostly adjacent.

typedef void ( *case_func )( type1 param1, type2 param2 );

void case_func1( type1 param1, type2 param2 );
void case_func2( type1 param1, type2 param2 );
void case_func3( type1 param1, type2 param2 );
void case_func5( type1 param1, type2 param2 );

case_func    func_array[] =
{
    &case_func1,
    &case_func2,
    &case_func3,
    NULL,        // Just a place holder, for non-contiguous values.
    &case_func5
};

int myloop(int a, .....){

   /* some stuff */

   // Critical loop
   while(...)
   {
       if ( func_array[ a ] && a < sizeof( func_array ) )
           func_array[ a ]( .... );
   }
}

If you can be assure that you'll have no holes in your array and a will never be outside array bounds you can omit if ( func_array[ a ] && a < sizeof( func_array ) ), reducing the code to no comparison at all.

Anyway, this approach can be a bit clearer, and may be worth even if it gives no big performance gain.

ContentLicense: CC BY-SA 3.0


问:
Prevent trailing zero with pandas "to_csv"
I'm trying to export a CSV string to a D3 web application, but the command to_csv insists on adding a trailing 0 to the data, which prevents a proper use by D3.

Here's a minimal example to illustrate the problem.

My (simplified) dataframe is:

```<code>>>> df = pd.DataFrame([['Alex',20.0000, 50.650]],columns=['Name','Age', 'Weight'])
   Name   Age  Weight
0  Alex  20.0   50.65
</code>```

df['Age'] contains a float, as indicated by:

```<code>>>> df['Age']
0    20.0
Name: Age, dtype: float64
</code>```

Then based on this answer I run .astype(object) to get the format I would like:

```<code>>>> df=df.astype(object)
   Name Age Weight
0  Alex  20  50.65
</code>```

Now, df['Age'] contains an object, with no trailing zero:

```<code>>>> df['Age']
0    20
Name: Age, dtype: object
</code>```

That's what I would like to export with to_csv, but this command reappends a trailing 0 to the number, which I want to avoid:

```<code>>>> df_csv = df.to_csv(sep=',', index = False)
>>> df_csv
'Name,Age,Weight\nAlex,20.0,50.65\n'
</code>```

I tried using df_csv = df.to_csv(sep=',', index = False, float_format='%.0f') based on this answer, but that doesn't work because there are other floats in my dataframe for which I wish to keep non-zero decimals.

How could I prevent this trailing 0 to appear for numbers with no decimals?

答:
Here is one way that will work as long as you don't have spaces within your string columns.

Use to_string() after astype(object) instead of to_csv(). This will preserve the numeric formats, but it will use spaces as the separator. As long as you don't have spaces in any of your other fields, you can use regular expressions to convert the spaces to commas.

import re
df = df.astype(object)
df_string = re.sub(" +", ",", df.to_string(index=False))
print(df_string)
#Name,Age,Weight
#Alex,20,50.65
```
<p>Now write <code>df_string</code> to your file:</p>
<pre class="lang-py prettyprint-override"><code>with open('path/to/some/file.csv', 'w') as f:
    f.write(df_string)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to export a CSV string to a D3 web application, but the command to_csv insists on adding a trailing 0 to the data, which prevents a proper use by D3.

Here's a minimal example to illustrate the problem.

My (simplified) dataframe is:

>>> df = pd.DataFrame([['Alex',20.0000, 50.650]],columns=['Name','Age', 'Weight'])
   Name   Age  Weight
0  Alex  20.0   50.65

df['Age'] contains a float, as indicated by:

>>> df['Age']
0    20.0
Name: Age, dtype: float64

Then based on this answer I run .astype(object) to get the format I would like:

>>> df=df.astype(object)
   Name Age Weight
0  Alex  20  50.65

Now, df['Age'] contains an object, with no trailing zero:

>>> df['Age']
0    20
Name: Age, dtype: object

That's what I would like to export with to_csv, but this command reappends a trailing 0 to the number, which I want to avoid:

>>> df_csv = df.to_csv(sep=',', index = False)
>>> df_csv
'Name,Age,Weight\nAlex,20.0,50.65\n'

I tried using df_csv = df.to_csv(sep=',', index = False, float_format='%.0f') based on this answer, but that doesn't work because there are other floats in my dataframe for which I wish to keep non-zero decimals.

How could I prevent this trailing 0 to appear for numbers with no decimals?

Body:
Here is one way that will work as long as you don't have spaces within your string columns.

Use to_string() after astype(object) instead of to_csv(). This will preserve the numeric formats, but it will use spaces as the separator. As long as you don't have spaces in any of your other fields, you can use regular expressions to convert the spaces to commas.

import re
df = df.astype(object)
df_string = re.sub(" +", ",", df.to_string(index=False))
print(df_string)
#Name,Age,Weight
#Alex,20,50.65

Now write df_string to your file:

with open('path/to/some/file.csv', 'w') as f:
    f.write(df_string)


问:
Create writable combobox with vba
I want to create a combobox on the cell the user click, and permit the user to write and/or choose (an autocompletion similar to google), set it to the cell and close combobox.

I have this code which create the box :

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim lst
If Not Intersect([4:7], Target) Is Nothing And Target.Count = 1 Then
        Me.DropDowns.Delete
        With Worksheets("Listing")
            lst = "'" & .Name & "'!" & _
              .Range(.Range("a1"), _
              .Cells(.Rows.Count, 1).End(xlUp)).Address()
         End With
        With Me.Shapes.AddFormControl(xlDropDown, Left:=Target.Left, _
                                  Top:=Target.Top, Width:=60, Height:=15)
             .Name = "CB"
            .OnAction = "CB_Change"
            .ControlFormat.ListFillRange = lst

        End With
    End If
End Sub
</code>```

The problem is that the Comboboxes created only allow user to select and not to write into

答:
If possible, use Data Validation instead. This will create a writable combo, based on the values in cells J3:J5</p>

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect([4:7], Target) Is Nothing And Target.Count = 1 Then
        With Target.Validation
            .Delete
            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=$J$3:$J$5"
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = ""
            .ErrorTitle = ""
            .InputMessage = ""
            .ErrorMessage = ""
            .ShowInput = True
            .ShowError = False
        End With

        ' This will expand the list
        Target.Select
        SendKeys "%{DOWN}"
    End If
End Sub
</code>```

Title: Create writable combobox with vba

Body:
I want to create a combobox on the cell the user click, and permit the user to write and/or choose (an autocompletion similar to google), set it to the cell and close combobox.

I have this code which create the box :

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim lst
If Not Intersect([4:7], Target) Is Nothing And Target.Count = 1 Then
        Me.DropDowns.Delete
        With Worksheets("Listing")
            lst = "'" & .Name & "'!" & _
              .Range(.Range("a1"), _
              .Cells(.Rows.Count, 1).End(xlUp)).Address()
         End With
        With Me.Shapes.AddFormControl(xlDropDown, Left:=Target.Left, _
                                  Top:=Target.Top, Width:=60, Height:=15)
             .Name = "CB"
            .OnAction = "CB_Change"
            .ControlFormat.ListFillRange = lst

        End With
    End If
End Sub

The problem is that the Comboboxes created only allow user to select and not to write into

Body:
If possible, use Data Validation instead. This will create a writable combo, based on the values in cells J3:J5

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect([4:7], Target) Is Nothing And Target.Count = 1 Then
        With Target.Validation
            .Delete
            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=$J$3:$J$5"
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = ""
            .ErrorTitle = ""
            .InputMessage = ""
            .ErrorMessage = ""
            .ShowInput = True
            .ShowError = False
        End With

        ' This will expand the list
        Target.Select
        SendKeys "%{DOWN}"
    End If
End Sub


问:
How to remove ' ' in a list in python?
I'm still a noob when it comes to python. I have this list that contains strings. My problem is to remove ''(empty string) from the list.

I've tried to use .remove() in python but it still does not work.

For example, I have a list that contains next data:

```<code>a = ['', 'word', 'three', '', 'five']
</code>```

I just want the output to be:

```<code>a = ['word', 'three', 'five']
</code>```

答:
You can apply list comprehension to rewrite original list missing zero-length strings.

Code:

```<code>a = ['', 'word', 'three', '', 'five']
a = [item for item in a if item]
</code>```

Output:

```<code>['word', 'three', 'five']
</code>```

Title: How to remove ' ' in a list in python?

Body:
I'm still a noob when it comes to python. I have this list that contains strings. My problem is to remove ''(empty string) from the list.

I've tried to use .remove() in python but it still does not work.

For example, I have a list that contains next data:

a = ['', 'word', 'three', '', 'five']

I just want the output to be:

a = ['word', 'three', 'five']

Body:
You can apply list comprehension to rewrite original list missing zero-length strings.

Code:

a = ['', 'word', 'three', '', 'five']
a = [item for item in a if item]

Output:

['word', 'three', 'five']


问:
How to rename a CSV file from a value in the CSV file
I have 100 1-line CSV files. The files are currently labeled AAA.txt, AAB.txt, ABB.txt (after I used split -l 1 on them). The first field in each of these files is what I want to rename the file as, so instead of AAA, AAB and ABB it would be the first value.

Input CSV (filename AAA.txt)

```<code>1234ABC, stuff, stuff
</code>```

Desired Output (filename 1234ABC.csv)

```<code>1234ABC, stuff, stuff
</code>```

I don't want to edit the content of the CSV itself, just change the filename

答:
This will store the whole input file into the colum1.csv of the inputfile.

```<code>awk -F, '{print $0 > $1".csv" }' aaa.txt
</code>```

Body:
I have 100 1-line CSV files. The files are currently labeled AAA.txt, AAB.txt, ABB.txt (after I used split -l 1 on them). The first field in each of these files is what I want to rename the file as, so instead of AAA, AAB and ABB it would be the first value.

Input CSV (filename AAA.txt)

1234ABC, stuff, stuff

Desired Output (filename 1234ABC.csv)

1234ABC, stuff, stuff

I don't want to edit the content of the CSV itself, just change the filename

Body:
This will store the whole input file into the colum1.csv of the inputfile.

awk -F, '{print $0 > $1".csv" }' aaa.txt


问:
What is the difference between Angular ngOnInit() and ngOnChanges()?
Angular provides lifecycle hook ngOnInit() and ngOnChanges() by default.
Why should ngOnInit be used, if we already have a ngOnChanges? And constructor also.</p>

答: ngOnInit and ngOnChanges are functions belonging to a component life-cycle method groups and they are executed in a different moment of our component (that's why name life-cycle). Here is a list of all of them:


问:
How to send Product Selected Custom Option Sku Field to cart page in Magento
I am working in a scenario I want to send Product selected Custom Option SKU in cart page  have founded the array which is sent to cart in case of custom options.

Here is a Function called getProductOptions() in which Product Option Array is created and sent to cart. At this point, I want to send selected Custom Option SKU field to cart.

I have the following code:

```<code>public function getProductOptions()
{
    $options = array();
    if ($optionIds = $this->getItem()->getOptionByCode('option_ids')) {
        $options = array();
        foreach (explode(',', $optionIds->getValue()) as $optionId) {
            if ($option = $this->getProduct()->getOptionById($optionId)) {

//echo $optionId;
                echo "hhhhhhhhhhhhh";
//print_r( $option->getId());
//echo Mage::getModel('catalog/product')->getOptionSku($option);
//die();
//print_r( $option->getOptionSku());
//echo Mage_Catalog_Model_Product_Option_Type_Select::getOptionSku());

                $quoteItemOption = $this->getItem()->getOptionByCode('option_' . $option->getId());
//echo $option->getQuoteItemOption($quoteItemOption);
                $group = $option->groupFactory($option->getType())
                    ->setOption($option)
                    ->setQuoteItemOption($quoteItemOption);
                $options[] = array(
                    'label' => $option->getTitle(),
                    'value' => $group->getFormattedOptionValue($quoteItemOption->getValue()),
                    'print_value' => $group->getPrintableOptionValue($quoteItemOption->getValue()),
                    'option_id' => $option->getId(),
                    'option_type' => $option->getType(),
                    'custom_view' => $group->isCustomizedView(),
                    'option_sku'=>//What should i call here to send Selected option SKU to this Array
                );
            }
        }
        if ($addOptions = $this->getItem()->getOptionByCode('additional_options')) {
            $options = array_merge($options, unserialize($addOptions->getValue()));
        }
    }
    return $options;
}
</code>```

答:
It looks like the bit you're missing is</p>

```<code>'option_sku' => $this->getItem()->getSku()
</code>```

Body:
I am working in a scenario I want to send Product selected Custom Option SKU in cart page  have founded the array which is sent to cart in case of custom options.

Here is a Function called getProductOptions() in which Product Option Array is created and sent to cart. At this point, I want to send selected Custom Option SKU field to cart.

I have the following code:

public function getProductOptions()
{
    $options = array();
    if ($optionIds = $this->getItem()->getOptionByCode('option_ids')) {
        $options = array();
        foreach (explode(',', $optionIds->getValue()) as $optionId) {
            if ($option = $this->getProduct()->getOptionById($optionId)) {

//echo $optionId;
                echo "hhhhhhhhhhhhh";
//print_r( $option->getId());
//echo Mage::getModel('catalog/product')->getOptionSku($option);
//die();
//print_r( $option->getOptionSku());
//echo Mage_Catalog_Model_Product_Option_Type_Select::getOptionSku());

                $quoteItemOption = $this->getItem()->getOptionByCode('option_' . $option->getId());
//echo $option->getQuoteItemOption($quoteItemOption);
                $group = $option->groupFactory($option->getType())
                    ->setOption($option)
                    ->setQuoteItemOption($quoteItemOption);
                $options[] = array(
                    'label' => $option->getTitle(),
                    'value' => $group->getFormattedOptionValue($quoteItemOption->getValue()),
                    'print_value' => $group->getPrintableOptionValue($quoteItemOption->getValue()),
                    'option_id' => $option->getId(),
                    'option_type' => $option->getType(),
                    'custom_view' => $group->isCustomizedView(),
                    'option_sku'=>//What should i call here to send Selected option SKU to this Array
                );
            }
        }
        if ($addOptions = $this->getItem()->getOptionByCode('additional_options')) {
            $options = array_merge($options, unserialize($addOptions->getValue()));
        }
    }
    return $options;
}

Body:
It looks like the bit you're missing is

'option_sku' => $this->getItem()->getSku()


问:
Why is the assignment in a function ignored?
Consider following code:

```<code>zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz
</code>```

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

答:
Because $(...) runs in a subshell. Changes from a subshell are not visible in the parent shell.

From bash manual:

Bash performs the expansion by executing command in a subshell environment ...

and a subshell creates a separate process, which has a separate command execution environment.

It's the same as:

```<code>(
   f
)
</code>```

The ( .. ) also creates a subshell, but does not capture stdout.

Body:
Consider following code:

zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

Body:
Because $(...) runs in a subshell. Changes from a subshell are not visible in the parent shell.

From bash manual:

Bash performs the expansion by executing command in a subshell environment ...

and a subshell creates a separate process, which has a separate command execution environment.

It's the same as:

(
   f
)

The ( .. ) also creates a subshell, but does not capture stdout.


问:
How to produce a stream of guesses for the root of f?
I would like to produce a stream of guesses for the root of f with 3 arguments f fx and x with f = sin(x) and x = 3. I tried some code but i don't get it. I would appreciate it if you could provide me some help. </p>

```<code>(define (stream f fx x)
(let ((x (3))
((f x) (sin x))
((fx x) (cos x)))
(cons-stream (x (stream f fx (x (- x (/ (f x) (fx x)))))))))

(stream f fx 3)
</code>```

答:
Your code is this (I've applied indentation to make the bracketing clearer):

```<code>(define (stream f fx x)
  (let ((x (3))
        ((f x) (sin x))
        ((fx x) (cos x)))
    (cons-stream (x (stream f fx (x (- x (/ (f x) (fx x))))
                            ))
                 )))

(stream f fx 3)
</code>```

You have a few mistakes in this:

(3) treats 3 as a procedure and tries to call it. You should have 3 instead.

You have put specific arguments 3, sin, cos inside the general function. It should be outside instead.

You have done (x (stream ...)) and (x (- x ..)) both treat x like a function, but it's a number.

So clearing up these mistakes the code will be more like this:

```<code>(define (stream f fx x)
    (cons-stream x (stream f fx (- x (/ (f x) (fx x))))))

(let ((x 3)
      (f (lambda (x) (sin x)))
      (fx (lambda (x) (cos x))))
  (stream f fx x))
</code>```

lambda was used to define a local function. Hope that helps, Feel free to ask follow up questions if anything was unclear.

Body:
I would like to produce a stream of guesses for the root of f with 3 arguments f fx and x with f = sin(x) and x = 3. I tried some code but i don't get it. I would appreciate it if you could provide me some help.

(define (stream f fx x)
(let ((x (3))
((f x) (sin x))
((fx x) (cos x)))
(cons-stream (x (stream f fx (x (- x (/ (f x) (fx x)))))))))

(stream f fx 3)

Body:
Your code is this (I've applied indentation to make the bracketing clearer):

(define (stream f fx x)
  (let ((x (3))
        ((f x) (sin x))
        ((fx x) (cos x)))
    (cons-stream (x (stream f fx (x (- x (/ (f x) (fx x))))
                            ))
                 )))

(stream f fx 3)

You have a few mistakes in this:

(3) treats 3 as a procedure and tries to call it. You should have 3 instead.

You have put specific arguments 3, sin, cos inside the general function. It should be outside instead.

You have done (x (stream ...)) and (x (- x ..)) both treat x like a function, but it's a number.

So clearing up these mistakes the code will be more like this:

(define (stream f fx x)
    (cons-stream x (stream f fx (- x (/ (f x) (fx x))))))

(let ((x 3)
      (f (lambda (x) (sin x)))
      (fx (lambda (x) (cos x))))
  (stream f fx x))

lambda was used to define a local function. Hope that helps, Feel free to ask follow up questions if anything was unclear.


问:
C# with SQL: Populating multiple comboboxes each with different columns of same table
as stated in the title, I would appreciate some help with populating comboboxes with different columns of the same table

I don't have the actual source codes with me but I was able to populate one combobox with something like

```<code>SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt;
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;
</code>```

but I have 5 comboboxes, and I didn't want to repeat the same blocks of code 5 times just for that. so I looked around and found some answers, including changing datasource to bindingsource, like so:

```<code>myCMB.DataSource = new BindingSource(da, "Column_Name");
</code>```

but doing so would populate the combobox with each letter of the first item of the specified column (ie. if the first item in "Column_Name" is ABCD, my combobox options would be A,B,C,D)

So, I tried looking for more answers but I can't find any. is there a more efficient way of populating my comboboxes or do I really have to repeat essentially the same lines of code for each of them? if anyone can help, it would be greatly appreciated.

答:
Try this:</p>

```<code>DataTable dt = new DataTable();
dt.Columns.Add("Value");
dt.Columns.Add("Display");

string query = @"SELECT ID AS ID, Description AS CODE FROM [Tender] ORDER BY ID";
SqlDataReader sqlReader = new SqlCommand(query, DB.SQLConnection).ExecuteReader();

while (sqlReader.Read())
{
    if (!string.IsNullOrEmpty(sqlReader["CODE"].ToString()))
        dt.Rows.Add(sqlReader["ID"].ToString(), sqlReader["CODE"].ToString());
}

cbPayment1.DisplayMember = "display";
cbPayment1.ValueMember = "value";
cbPayment1.DataSource = dt;
</code>```

Body:
as stated in the title, I would appreciate some help with populating comboboxes with different columns of the same table

I don't have the actual source codes with me but I was able to populate one combobox with something like

SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt;
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;

but I have 5 comboboxes, and I didn't want to repeat the same blocks of code 5 times just for that. so I looked around and found some answers, including changing datasource to bindingsource, like so:

myCMB.DataSource = new BindingSource(da, "Column_Name");

but doing so would populate the combobox with each letter of the first item of the specified column (ie. if the first item in "Column_Name" is ABCD, my combobox options would be A,B,C,D)

So, I tried looking for more answers but I can't find any. is there a more efficient way of populating my comboboxes or do I really have to repeat essentially the same lines of code for each of them? if anyone can help, it would be greatly appreciated.

Body:
Try this:

DataTable dt = new DataTable();
dt.Columns.Add("Value");
dt.Columns.Add("Display");

string query = @"SELECT ID AS ID, Description AS CODE FROM [Tender] ORDER BY ID";
SqlDataReader sqlReader = new SqlCommand(query, DB.SQLConnection).ExecuteReader();

while (sqlReader.Read())
{
    if (!string.IsNullOrEmpty(sqlReader["CODE"].ToString()))
        dt.Rows.Add(sqlReader["ID"].ToString(), sqlReader["CODE"].ToString());
}

cbPayment1.DisplayMember = "display";
cbPayment1.ValueMember = "value";
cbPayment1.DataSource = dt;


问:
How does an incoming request to a nodejs server get handled when the event loop is waiting for a DB operation
I have a route in my API, as an example lets call it /users/:userId/updateBalance. This route will fetch the users current balance, add whatever comes from the request and then update the balance with the newly calculated balance. A request like this comes into the server for a specific user every 30 minutes, so until recently, I thought a concurrency issue to be impossible.

What ended up happening is that somewhere, a sent request failed and was only sent again 30 minutes later, about within a second of the other request. The result was that, as I can see it in the database, both of these requests fetched the same balance from the DB and both added their respective amounts. Essentially, the second request actually read a stale balance, as normally it should execute after request 1 has executed.

To give a numerical example for some more clarity, lets say request 1 was to add $2 to the balance, and request 2 was to add $5, and the user had a balance of $10. If the requests act in parallel, the users balance would end at either $12 or $15 depending on whether request 1 or request 2 finished first respectively, because both requests fetch a balance of $10 from the DB. However, obviously the expected behaviour is that we want request 1 to execute, update the users balance to $12, and then request 2 to execute and update the balance from $12 to $17.

To give some better perspective of the overall execution of this process: the request is received, a function is called, the function has to wait for the balance from the DB, the function then calculates the new balance and updates the db, after which execution is completed.

So I have a few questions on this. The first being, how does node handle incoming requests when it is waiting for an asynchronous request like a MySQL database read. Given the results I have observed, I assume that when the first request is waiting for the DB, the second request can commence being processed? Otherwise I am uncertain of how such asynchronous behaviour is experienced within a single threaded environment like node.

Secondly, how do I go about controlling this and preventing it. I had wanted to use a MySQL transaction with a forUpdate lock, but it turns out it seems not possible due to the way the code is currently written. Is there a way to tell node that a certain block of code can not be executed "in parallel"? Or any other alternatives?

答:
The first being, how does node handle incoming requests when it is waiting for an asynchronous request like a MySQL database read

The event loop of nodejs makes this happens, otherwise you'll have a totally sync programm with super-low performances.

Every single async function invocked in a context will be executed after the context itself has been executed.

Between the finish of execution of the context and the execution of the async function, other async functions can be scheduled for been executed (this "insertion" is managed by the event loop).

If an async function is awaited, the remaining code of the context is scheduled somewhere after the execution of the async function.

Is more clear when playing with it. Example 1:

```<code>// Expected result: 1, 3, 4, 2

function asyncFunction(x) {
  // setTimeout as example of async operation
  setTimeout(() => console.log(x), 10)
}

function context() {
  console.log(1)
  asyncFunction(2)
  console.log(3)
}

context()

console.log(4)
</code>```

Example 2:

```<code>// Expected result: 1, 2, 3

function asyncFunction(x) {
  // Promise as example of async operation
  return new Promise((resolve) => {
    console.log(x)
    resolve()
  })
}

async function context() {
  console.log(1)

  await asyncFunction(2)

  console.log(3)
}

context()
</code>```

Example 3 (more similar to your situation):

```<code>// Expected result: 1, 2, 4, 5, 3, 6

function asyncFunction(x) {
  // Promise as example of async operation
  return new Promise((resolve) => {
    console.log(x)
    resolve()
  })
}

async function context(a, b, c) {
  console.log(a)

  await asyncFunction(b)

  console.log(c)
}

context(1, 2, 3)
context(4, 5, 6)
</code>```

In your example:

when the server receive a connection, the execution of the handler is scheduled

when the handler is executed, it schedule the execution of the query, and the remaining portion of the handler context is scheduled after that

In between scheduled executions everything can happen.

Body:
The first being, how does node handle incoming requests when it is waiting for an asynchronous request like a MySQL database read

The event loop of nodejs makes this happens, otherwise you'll have a totally sync programm with super-low performances.

Every single async function invocked in a context will be executed after the context itself has been executed.

Between the finish of execution of the context and the execution of the async function, other async functions can be scheduled for been executed (this "insertion" is managed by the event loop).

If an async function is awaited, the remaining code of the context is scheduled somewhere after the execution of the async function.

Is more clear when playing with it. Example 1:

// Expected result: 1, 3, 4, 2

function asyncFunction(x) {
  // setTimeout as example of async operation
  setTimeout(() => console.log(x), 10)
}

function context() {
  console.log(1)
  asyncFunction(2)
  console.log(3)
}

context()

console.log(4)

Example 2:

// Expected result: 1, 2, 3

function asyncFunction(x) {
  // Promise as example of async operation
  return new Promise((resolve) => {
    console.log(x)
    resolve()
  })
}

async function context() {
  console.log(1)

  await asyncFunction(2)

  console.log(3)
}

context()

Example 3 (more similar to your situation):

// Expected result: 1, 2, 4, 5, 3, 6

function asyncFunction(x) {
  // Promise as example of async operation
  return new Promise((resolve) => {
    console.log(x)
    resolve()
  })
}

async function context(a, b, c) {
  console.log(a)

  await asyncFunction(b)

  console.log(c)
}

context(1, 2, 3)
context(4, 5, 6)

In your example:

when the server receive a connection, the execution of the handler is scheduled

when the handler is executed, it schedule the execution of the query, and the remaining portion of the handler context is scheduled after that

In between scheduled executions everything can happen.


问:
Replace dataframe multiple columns with id from another dataframe
I have Pandas Dataframe df1 as:

```<code>ID | c1 | c2 | c3
-----------------
1  | A  | B  | 32
2  | C  | D  | 34
3  | A  | B  | 11
4  | E  | F  | 3
</code>```

And df2:

```<code>ID | c1 | c2
------------
1  | A  | B
2  | C  | D
3  | E  | F
</code>```

There is foreign key between df1 and df2 on columns (c1, c2). Join look like:

```<code>pd.merge(df1, df2, left_on=['c1','c2'], right_on = ['c1','c2'])
</code>```

Result is:

```<code>ID_x| c1 | c2 | c3 | ID_y
-------------------------
1   | A  | B  | 32 | 1
2   | C  | D  | 34 | 2
3   | A  | B  | 11 | 1
4   | E  | F  | 3  | 3
</code>```

I want to replace (c1,c2) in df1 with df2.id.
Expected FINAL df1 is:

```<code>ID| c3 | df2_id
---------------
1 | 32 | 1
2 | 34 | 2
3 | 11 | 1
4 | 3  | 3
</code>```

In other words I want to add column 'df2_id' in df1(filled with df2.id value for this row) and drop columns (c1,c2)(they are not necessary anymore).

I have idea to do that by:

save result from merge in df1

drop unnecessary columns (c1,c2)

rename 'ID_y' to 'df2_id' and 'ID_x' to 'ID'

Is there any better solution?

答:
We could make a one liner out of your steps by making use of suffixes argument and on instead of left_on, right_on plus using method chaining with drop:

```<code>df1.merge(df2, on=['c1','c2'], suffixes=['_1', '_2']).drop(['c1', 'c2'], axis=1)
</code>```

Output

```<code>   ID_1  c3  ID_2
0     1  32     1
1     3  11     1
2     2  34     2
3     4   3     3
</code>```

To make it exactly like OP's output:

```<code>df1.merge(df2, on=['c1','c2'], suffixes=['', '_2']).drop(['c1', 'c2'], axis=1).rename(columns={"id_2": "df2_id"})
</code>```

Body:
I have Pandas Dataframe df1 as:

ID | c1 | c2 | c3
-----------------
1  | A  | B  | 32
2  | C  | D  | 34
3  | A  | B  | 11
4  | E  | F  | 3

And df2:

ID | c1 | c2
------------
1  | A  | B
2  | C  | D
3  | E  | F

There is foreign key between df1 and df2 on columns (c1, c2). Join look like:

pd.merge(df1, df2, left_on=['c1','c2'], right_on = ['c1','c2'])

Result is:

ID_x| c1 | c2 | c3 | ID_y
-------------------------
1   | A  | B  | 32 | 1
2   | C  | D  | 34 | 2
3   | A  | B  | 11 | 1
4   | E  | F  | 3  | 3

I want to replace (c1,c2) in df1 with df2.id.
Expected FINAL df1 is:

ID| c3 | df2_id
---------------
1 | 32 | 1
2 | 34 | 2
3 | 11 | 1
4 | 3  | 3

In other words I want to add column 'df2_id' in df1(filled with df2.id value for this row) and drop columns (c1,c2)(they are not necessary anymore).

I have idea to do that by:

save result from merge in df1

drop unnecessary columns (c1,c2)

rename 'ID_y' to 'df2_id' and 'ID_x' to 'ID'

Is there any better solution?

Body:
We could make a one liner out of your steps by making use of suffixes argument and on instead of left_on, right_on plus using method chaining with drop:

df1.merge(df2, on=['c1','c2'], suffixes=['_1', '_2']).drop(['c1', 'c2'], axis=1)

Output

   ID_1  c3  ID_2
0     1  32     1
1     3  11     1
2     2  34     2
3     4   3     3

To make it exactly like OP's output:

df1.merge(df2, on=['c1','c2'], suffixes=['', '_2']).drop(['c1', 'c2'], axis=1).rename(columns={"id_2": "df2_id"})


问:
How does python map works with torch.tensor?
I am now in python so I am trying to understand this line from pytorch tutorial.

```<code>x_train, y_train, x_valid, y_valid = map(
    torch.tensor, (x_train, y_train, x_valid, y_valid)
)
</code>```

I understand how map works on a single element

```<code>def sqr(a):
    return a * a

a = [1, 2, 3, 4]

a = map(sqr, a)
print(list(a))
</code>```

And here I need to use list(a) to convert map object back to list.

But what I don't understand, is how does it work on multiple variables?

If I try to do this

```<code>def sqr(a):
    return a * a

a = [1, 2, 3, 4]
b = [1, 3, 5, 7]

a, b = map(sqr, (a, b))
print(list(a))
print(list(b))
</code>```

I get an error: TypeError: can't multiply sequence by non-int of type 'list'

Please clarify this for me
Thank you

答:
map works on a single the same way it works on list/tuple of lists, it fetches an element of the given input regardless what is it.

The reason why torch.tensor works, is that it accepts a list as input.

If you unfold the following line you provided:

```<code>x_train, y_train, x_valid, y_valid = map(
    torch.tensor, (x_train, y_train, x_valid, y_valid)
)
</code>```

it's the same as doing:

```<code>x_train, y_train, x_valid, y_valid = [torch.tensor(x_train), torch.tensor(y_train), torch.tensor(x_valid), torch.tensor(y_valid)]
</code>```

On other hand, your sqr function does not accept lists. It expects a scalar type to square, which is not the case for your a an b, they are lists.

However, if you change sqr to:

```<code>def sqr(a):
    return [s * s for s in a]

a = [1, 2, 3, 4]
b = [1, 3, 5, 7]

a, b = map(sqr, (a, b))
</code>```

or as suggested by @Jean, a, b = map(sqr, x) for x in (a, b)

It will work.

Body:
I am now in python so I am trying to understand this line from pytorch tutorial.

x_train, y_train, x_valid, y_valid = map(
    torch.tensor, (x_train, y_train, x_valid, y_valid)
)

I understand how map works on a single element

def sqr(a):
    return a * a

a = [1, 2, 3, 4]

a = map(sqr, a)
print(list(a))

And here I need to use list(a) to convert map object back to list.

But what I don't understand, is how does it work on multiple variables?

If I try to do this

def sqr(a):
    return a * a

a = [1, 2, 3, 4]
b = [1, 3, 5, 7]

a, b = map(sqr, (a, b))
print(list(a))
print(list(b))

I get an error: TypeError: can't multiply sequence by non-int of type 'list'

Please clarify this for me
Thank you

Body:
map works on a single the same way it works on list/tuple of lists, it fetches an element of the given input regardless what is it.

The reason why torch.tensor works, is that it accepts a list as input.

If you unfold the following line you provided:

x_train, y_train, x_valid, y_valid = map(
    torch.tensor, (x_train, y_train, x_valid, y_valid)
)

it's the same as doing:

x_train, y_train, x_valid, y_valid = [torch.tensor(x_train), torch.tensor(y_train), torch.tensor(x_valid), torch.tensor(y_valid)]

On other hand, your sqr function does not accept lists. It expects a scalar type to square, which is not the case for your a an b, they are lists.

However, if you change sqr to:

def sqr(a):
    return [s * s for s in a]

a = [1, 2, 3, 4]
b = [1, 3, 5, 7]

a, b = map(sqr, (a, b))

or as suggested by @Jean, a, b = map(sqr, x) for x in (a, b)

It will work.


问:
How to Show primary key data?
I have two tables: Transactions and Accounts.

Transaction has a foreign key IDAccount from Accounts Table.

I assign datasource property of Datasource property of Datagridview to Transactions Table.

I want to Accounts.description insead of IDAccount in Datagridview.

What must I do?

答:
There is a solution to this problem offered here which involves doing some custom code to inspect each property and determine if it belongs to the main bound object or to a child object.

This looks like a good solution except it doesn't support editing or sorting based on these properties.

Another approach (which I would probably recommend since it is simpler) is to introduce an AccountDescription property to your Transaction object.

```<code>public class Transaction
{
    private Account _account

    public string AccountDescription
    {
        get { return _account.description; }
        set { _account.description = value; }
    }
}
</code>```

You might also need to implement some custom INotifyPropertyChanged code so databinding works nicely.

Title: How to Show primary key data?

Body:
There is a solution to this problem offered here which involves doing some custom code to inspect each property and determine if it belongs to the main bound object or to a child object.

This looks like a good solution except it doesn't support editing or sorting based on these properties.

Another approach (which I would probably recommend since it is simpler) is to introduce an AccountDescription property to your Transaction object.

public class Transaction
{
    private Account _account

    public string AccountDescription
    {
        get { return _account.description; }
        set { _account.description = value; }
    }
}

You might also need to implement some custom INotifyPropertyChanged code so databinding works nicely.


问:
Merging several word Docs dynamically
I need to make a macro that would export automatically data from datagridview to a word report using a template that i created.
the program work just fine, but it generates each row in separate file for that i need all the rows in one file.

I tried to include mail merge, but i got an error "type mismatch"
here's my code

```<code>            private void FindAndReplace(word.Application wordApp, string ToFindText, object replaceWithText)
                {
                    object MatchCase = true;
                    object FindText = true;
                    object MatchWholeWord = true;
                    object MatchWildcards = false;
                    object MatchSoundsLike = false;
                    object MatchAllWordForms = false;
                    object Forward = true;
                    object Format = false;
                    object MatchKashida = false;
                    object MatchDiacritics = false;
                    object MatchAlefHamza = false;
                    object MatchControl = false;
                    object Read_only = false;
                    //   object ReplaceWith = false;
                    object Visible = true;
                    object Replace = 2;
                    object Wrap = 1;
                    //wordApp.Selection.Find.Execute(ToFindText,replaceWithText);

                    wordApp.Selection.Find.Execute(ToFindText,
                        ref MatchCase,
                        ref MatchWholeWord,
                        ref MatchWildcards,
                        ref MatchSoundsLike,
                        ref MatchAllWordForms,
                        ref Forward,
                        ref Wrap,
                        ref Format,
                        ref Replace,
                        ref MatchKashida,
                        ref MatchDiacritics,
                        ref MatchAlefHamza,
                        ref MatchControl);
                    wordApp.Selection.Text = replaceWithText.ToString();

                }

                private void WordDoc(object filename, object SaveAs)
                {
                    word.Application wordApp = new word.Application();
                    object missing = Missing.Value;
                    word.Document myWordDoc = null;

                    object readOnly = false;
                    object IsVisible = false;
                    wordApp.Visible = false;

                    try
                    {

                        foreach (DataGridViewRow selectedRow in dataGridView2.Rows)
                        {
                            myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                            myWordDoc.Activate();

                            string Column1 = selectedRow.Cells[0].Value.ToString();
                            string Column2 = selectedRow.Cells[1].Value.ToString();
                            string Column3 = selectedRow.Cells[2].Value.ToString();
                            string Column4 = selectedRow.Cells[3].Value.ToString();
                            string Column5 = selectedRow.Cells[4].Value.ToString();
                            string Column6 = selectedRow.Cells[5].Value.ToString();
                            string Column7 = selectedRow.Cells[6].Value.ToString();
                            string Column8 = selectedRow.Cells[7].Value.ToString();
                            string Column9 = selectedRow.Cells[8].Value.ToString();
                            string Column10 = selectedRow.Cells[9].Value.ToString();
                            string Column11 = selectedRow.Cells[10].Value.ToString();
                            string Column12 = selectedRow.Cells[11].Value.ToString();
                            string Column13 = selectedRow.Cells[12].Value.ToString();
                            string Column14 = selectedRow.Cells[13].Value.ToString();
                            string Column15 = selectedRow.Cells[14].Value.ToString();
                            string Column16 = selectedRow.Cells[15].Value.ToString();
                            string Column17 = selectedRow.Cells[16].Value.ToString();
                            string Column18 = selectedRow.Cells[17].Value.ToString();
                            string Column19 = selectedRow.Cells[18].Value.ToString();
                            string Column20 = selectedRow.Cells[19].Value.ToString();
                            string Column21 = selectedRow.Cells[20].Value.ToString();

                            this.FindAndReplace(wordApp, "<Type1>", Column1);
                            this.FindAndReplace(wordApp, "<Type2>", Column2);
                            this.FindAndReplace(wordApp, "<Type3>", Column3);
                            this.FindAndReplace(wordApp, "<Type4>", Column4);
                            this.FindAndReplace(wordApp, "<Type5>", Column5);
                            this.FindAndReplace(wordApp, "<Type6>", Column6);
                            this.FindAndReplace(wordApp, "<Type7>", Column7);
                            this.FindAndReplace(wordApp, "<Type8>", Column8);
                            this.FindAndReplace(wordApp, "<Type9>", Column9);
                            this.FindAndReplace(wordApp, "<Type10>", Column10);
                            this.FindAndReplace(wordApp, "<Type11>", Column11);
                            this.FindAndReplace(wordApp, "<Type12>", Column12);
                            this.FindAndReplace(wordApp, "<Type13>", Column13);
                            this.FindAndReplace(wordApp, "<Type14>", Column14);
                            this.FindAndReplace(wordApp, "<Type15>", Column15);
                            this.FindAndReplace(wordApp, "<Type16>", Column16);
                            this.FindAndReplace(wordApp, "<Type17>", Column17);
                            this.FindAndReplace(wordApp, "<Type18>", Column18);
                            this.FindAndReplace(wordApp, "<Type19>", Column19);
                            this.FindAndReplace(wordApp, "<Type20>", Column20);
                            this.FindAndReplace(wordApp, "<Type21>", Column21);

                            //Saving file

                            myWordDoc.SaveAs(SaveAs.ToString() + selectedRow.ToString() + ".docx", ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing);

                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error : " + ex.Message);
                    }

                    myWordDoc.Close();
                    wordApp.Quit();
                    MessageBox.Show("File Created!");
                }

                private void AddButton_Click(object sender, EventArgs e)
                {
                    WordDoc(filename: Getfilepath, SaveAs: Savingpath);
                }
</code>```

I don't know what i need to change in order to get all rows's data into one file

答:
Try creating and saving the doc file outside foreach clause.

myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
myWordDoc.Activate();

try
{
    foreach (DataGridViewRow selectedRow in dataGridView2.Rows)
    {
        string Column1 = selectedRow.Cells[0].Value.ToString();
        string Column2 = selectedRow.Cells[1].Value.ToString();
        string Column3 = selectedRow.Cells[2].Value.ToString();
        string Column4 = selectedRow.Cells[3].Value.ToString();
        string Column5 = selectedRow.Cells[4].Value.ToString();
        string Column6 = selectedRow.Cells[5].Value.ToString();
        string Column7 = selectedRow.Cells[6].Value.ToString();
        string Column8 = selectedRow.Cells[7].Value.ToString();
        string Column9 = selectedRow.Cells[8].Value.ToString();
        string Column10 = selectedRow.Cells[9].Value.ToString();
        string Column11 = selectedRow.Cells[10].Value.ToString();
        string Column12 = selectedRow.Cells[11].Value.ToString();
        string Column13 = selectedRow.Cells[12].Value.ToString();
        string Column14 = selectedRow.Cells[13].Value.ToString();
        string Column15 = selectedRow.Cells[14].Value.ToString();
        string Column16 = selectedRow.Cells[15].Value.ToString();
        string Column17 = selectedRow.Cells[16].Value.ToString();
        string Column18 = selectedRow.Cells[17].Value.ToString();
        string Column19 = selectedRow.Cells[18].Value.ToString();
        string Column20 = selectedRow.Cells[19].Value.ToString();
        string Column21 = selectedRow.Cells[20].Value.ToString();

        this.FindAndReplace(wordApp, "<Type1>", Column1);
        this.FindAndReplace(wordApp, "<Type2>", Column2);
        this.FindAndReplace(wordApp, "<Type3>", Column3);
        this.FindAndReplace(wordApp, "<Type4>", Column4);
        this.FindAndReplace(wordApp, "<Type5>", Column5);
        this.FindAndReplace(wordApp, "<Type6>", Column6);
        this.FindAndReplace(wordApp, "<Type7>", Column7);
        this.FindAndReplace(wordApp, "<Type8>", Column8);
        this.FindAndReplace(wordApp, "<Type9>", Column9);
        this.FindAndReplace(wordApp, "<Type10>", Column10);
        this.FindAndReplace(wordApp, "<Type11>", Column11);
        this.FindAndReplace(wordApp, "<Type12>", Column12);
        this.FindAndReplace(wordApp, "<Type13>", Column13);
        this.FindAndReplace(wordApp, "<Type14>", Column14);
        this.FindAndReplace(wordApp, "<Type15>", Column15);
        this.FindAndReplace(wordApp, "<Type16>", Column16);
        this.FindAndReplace(wordApp, "<Type17>", Column17);
        this.FindAndReplace(wordApp, "<Type18>", Column18);
        this.FindAndReplace(wordApp, "<Type19>", Column19);
        this.FindAndReplace(wordApp, "<Type20>", Column20);
        this.FindAndReplace(wordApp, "<Type21>", Column21);

        //Saving file
        myWordDoc.SaveAs(SaveAs.ToString() + selectedRow.ToString() + ".docx",         ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing);
    }

}
catch (Exception ex)
{
    MessageBox.Show("Error : " + ex.Message);
}

```

Title: Merging several word Docs dynamically

Body:
I need to make a macro that would export automatically data from datagridview to a word report using a template that i created.
the program work just fine, but it generates each row in separate file for that i need all the rows in one file.

I tried to include mail merge, but i got an error "type mismatch"
here's my code

            private void FindAndReplace(word.Application wordApp, string ToFindText, object replaceWithText)
                {
                    object MatchCase = true;
                    object FindText = true;
                    object MatchWholeWord = true;
                    object MatchWildcards = false;
                    object MatchSoundsLike = false;
                    object MatchAllWordForms = false;
                    object Forward = true;
                    object Format = false;
                    object MatchKashida = false;
                    object MatchDiacritics = false;
                    object MatchAlefHamza = false;
                    object MatchControl = false;
                    object Read_only = false;
                    //   object ReplaceWith = false;
                    object Visible = true;
                    object Replace = 2;
                    object Wrap = 1;
                    //wordApp.Selection.Find.Execute(ToFindText,replaceWithText);

                    wordApp.Selection.Find.Execute(ToFindText,
                        ref MatchCase,
                        ref MatchWholeWord,
                        ref MatchWildcards,
                        ref MatchSoundsLike,
                        ref MatchAllWordForms,
                        ref Forward,
                        ref Wrap,
                        ref Format,
                        ref Replace,
                        ref MatchKashida,
                        ref MatchDiacritics,
                        ref MatchAlefHamza,
                        ref MatchControl);
                    wordApp.Selection.Text = replaceWithText.ToString();

                }

                private void WordDoc(object filename, object SaveAs)
                {
                    word.Application wordApp = new word.Application();
                    object missing = Missing.Value;
                    word.Document myWordDoc = null;

                    object readOnly = false;
                    object IsVisible = false;
                    wordApp.Visible = false;

                    try
                    {

                        foreach (DataGridViewRow selectedRow in dataGridView2.Rows)
                        {
                            myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                            myWordDoc.Activate();

                            string Column1 = selectedRow.Cells[0].Value.ToString();
                            string Column2 = selectedRow.Cells[1].Value.ToString();
                            string Column3 = selectedRow.Cells[2].Value.ToString();
                            string Column4 = selectedRow.Cells[3].Value.ToString();
                            string Column5 = selectedRow.Cells[4].Value.ToString();
                            string Column6 = selectedRow.Cells[5].Value.ToString();
                            string Column7 = selectedRow.Cells[6].Value.ToString();
                            string Column8 = selectedRow.Cells[7].Value.ToString();
                            string Column9 = selectedRow.Cells[8].Value.ToString();
                            string Column10 = selectedRow.Cells[9].Value.ToString();
                            string Column11 = selectedRow.Cells[10].Value.ToString();
                            string Column12 = selectedRow.Cells[11].Value.ToString();
                            string Column13 = selectedRow.Cells[12].Value.ToString();
                            string Column14 = selectedRow.Cells[13].Value.ToString();
                            string Column15 = selectedRow.Cells[14].Value.ToString();
                            string Column16 = selectedRow.Cells[15].Value.ToString();
                            string Column17 = selectedRow.Cells[16].Value.ToString();
                            string Column18 = selectedRow.Cells[17].Value.ToString();
                            string Column19 = selectedRow.Cells[18].Value.ToString();
                            string Column20 = selectedRow.Cells[19].Value.ToString();
                            string Column21 = selectedRow.Cells[20].Value.ToString();

                            this.FindAndReplace(wordApp, "<Type1>", Column1);
                            this.FindAndReplace(wordApp, "<Type2>", Column2);
                            this.FindAndReplace(wordApp, "<Type3>", Column3);
                            this.FindAndReplace(wordApp, "<Type4>", Column4);
                            this.FindAndReplace(wordApp, "<Type5>", Column5);
                            this.FindAndReplace(wordApp, "<Type6>", Column6);
                            this.FindAndReplace(wordApp, "<Type7>", Column7);
                            this.FindAndReplace(wordApp, "<Type8>", Column8);
                            this.FindAndReplace(wordApp, "<Type9>", Column9);
                            this.FindAndReplace(wordApp, "<Type10>", Column10);
                            this.FindAndReplace(wordApp, "<Type11>", Column11);
                            this.FindAndReplace(wordApp, "<Type12>", Column12);
                            this.FindAndReplace(wordApp, "<Type13>", Column13);
                            this.FindAndReplace(wordApp, "<Type14>", Column14);
                            this.FindAndReplace(wordApp, "<Type15>", Column15);
                            this.FindAndReplace(wordApp, "<Type16>", Column16);
                            this.FindAndReplace(wordApp, "<Type17>", Column17);
                            this.FindAndReplace(wordApp, "<Type18>", Column18);
                            this.FindAndReplace(wordApp, "<Type19>", Column19);
                            this.FindAndReplace(wordApp, "<Type20>", Column20);
                            this.FindAndReplace(wordApp, "<Type21>", Column21);

                            //Saving file

                            myWordDoc.SaveAs(SaveAs.ToString() + selectedRow.ToString() + ".docx", ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing);

                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error : " + ex.Message);
                    }

                    myWordDoc.Close();
                    wordApp.Quit();
                    MessageBox.Show("File Created!");
                }

                private void AddButton_Click(object sender, EventArgs e)
                {
                    WordDoc(filename: Getfilepath, SaveAs: Savingpath);
                }

I don't know what i need to change in order to get all rows's data into one file


问:
How can I get Vim to recognize Python3 syntax?
I've scoured related posts and have tried several things, but I'm still receiving a syntax error in Vim when using Python3 syntax.

The code that is receiving the error:

```<code>types_of_people = 10; f"There are {types_of_people} types of people."
</code>```

The output of running $ vim --version:

```<code>$ vim --version
VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Sep 17 2017 10:39:50)
MacOS X (unix) version
Included patches: 1-1100
Compiled by Homebrew
Huge version without GUI.  Features included (+) or not (-):
+acl             +file_in_path    +mouse_sgr       +tag_old_static
+arabic          +find_in_path    -mouse_sysmouse  -tag_any_white
+autocmd         +float           +mouse_urxvt     -tcl
-balloon_eval    +folding         +mouse_xterm     +termguicolors
-browse          -footer          +multi_byte      +terminal
++builtin_terms  +fork()          +multi_lang      +terminfo
+byte_offset     -gettext         -mzscheme        +termresponse
+channel         -hangul_input    +netbeans_intg   +textobjects
+cindent         +iconv           +num64           +timers
-clientserver    +insert_expand   +packages        +title
+clipboard       +job             +path_extra      -toolbar
+cmdline_compl   +jumplist        +perl            +user_commands
+cmdline_hist    +keymap          +persistent_undo +vertsplit
+cmdline_info    +lambda          +postscript      +virtualedit
+comments        +langmap         +printer         +visual
+conceal         +libcall         +profile         +visualextra
+cryptv          +linebreak       -python          +viminfo
+cscope          +lispindent      +python3         +vreplace
+cursorbind      +listcmds        +quickfix        +wildignore
+cursorshape     +localmap        +reltime         +wildmenu
+dialog_con      -lua             +rightleft       +windows
+diff            +menu            +ruby            +writebackup
+digraphs        +mksession       +scrollbind      -X11
-dnd             +modify_fname    +signs           -xfontset
-ebcdic          +mouse           +smartindent     -xim
+emacs_tags      -mouseshape      +startuptime     -xpm
+eval            +mouse_dec       +statusline      -xsmp
+ex_extra        -mouse_gpm       -sun_workshop    -xterm_clipboard
+extra_search    -mouse_jsbterm   +syntax          -xterm_save
+farsi           +mouse_netterm   +tag_binary
system vimrc file: "$VIM/vimrc"
 user vimrc file: "$HOME/.vimrc"
2nd user vimrc file: "~/.vim/vimrc"
  user exrc file: "$HOME/.exrc"
   defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/usr/local/share/vim"
Compilation: clang -c -I. -Iproto -DHAVE_CONFIG_H   -DMACOS_X_UNIX  -g -O2 -
U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: clang   -L. -fstack-protector -L/usr/local/lib -
L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -
L/usr/local/opt/readline/lib  -L/usr/local/lib -o vim        -lncurses -liconv
-framework Cocoa   -mmacosx-version-min=10.11 -fstack-protector-strong -
L/usr/local/lib  -L/usr/local/Cellar/perl/5.26.0/lib/perl5/5.26.0/darwin-
thread-multi-2level/CORE -lperl -lm -lutil -lc  -
L/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/config-3.6m-
darwin -lpython3.6m -framework CoreFoundation  -lruby.2.4.2 -lobjc
</code>```

You may notice above that Vim is including python3 but not python

I have reinstalled Vim using:

```<code>$ brew uninstall vim
$ brew install vim --with-python3
</code>```

I have also tried aliasing python to my Python3 version:

$ alias python='python3.6'

My PATH:

```<code>$ echo $PATH
/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/garythegoat/.rbenv/shims:/usr/bin/python:/usr/local/heroku/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/usr/local/go/bin:/Users/garythegoat/golang/bin
</code>```

:echo has('python')  returns 1

:echo has('python3') returns 0

Any suggestions appreciated

答:
This is a difficult question, because this is related to the default python configured by your OS.

The most useful related question I found is this one.

Both solutions worked for me :

Setting up a Virtual Environment using virtualenv. This is exhausting as you will have to launch the virtual env each time you need to open vim.

Adding let g:syntastic_python_python_exec = 'python3' to .vimrc configuration file. I'm not sure if your configuration is based on the syntastic plugin, but this is something worst looking into.

Body:
I've scoured related posts and have tried several things, but I'm still receiving a syntax error in Vim when using Python3 syntax.

The code that is receiving the error:

types_of_people = 10; f"There are {types_of_people} types of people."

The output of running $ vim --version:

$ vim --version
VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Sep 17 2017 10:39:50)
MacOS X (unix) version
Included patches: 1-1100
Compiled by Homebrew
Huge version without GUI.  Features included (+) or not (-):
+acl             +file_in_path    +mouse_sgr       +tag_old_static
+arabic          +find_in_path    -mouse_sysmouse  -tag_any_white
+autocmd         +float           +mouse_urxvt     -tcl
-balloon_eval    +folding         +mouse_xterm     +termguicolors
-browse          -footer          +multi_byte      +terminal
++builtin_terms  +fork()          +multi_lang      +terminfo
+byte_offset     -gettext         -mzscheme        +termresponse
+channel         -hangul_input    +netbeans_intg   +textobjects
+cindent         +iconv           +num64           +timers
-clientserver    +insert_expand   +packages        +title
+clipboard       +job             +path_extra      -toolbar
+cmdline_compl   +jumplist        +perl            +user_commands
+cmdline_hist    +keymap          +persistent_undo +vertsplit
+cmdline_info    +lambda          +postscript      +virtualedit
+comments        +langmap         +printer         +visual
+conceal         +libcall         +profile         +visualextra
+cryptv          +linebreak       -python          +viminfo
+cscope          +lispindent      +python3         +vreplace
+cursorbind      +listcmds        +quickfix        +wildignore
+cursorshape     +localmap        +reltime         +wildmenu
+dialog_con      -lua             +rightleft       +windows
+diff            +menu            +ruby            +writebackup
+digraphs        +mksession       +scrollbind      -X11
-dnd             +modify_fname    +signs           -xfontset
-ebcdic          +mouse           +smartindent     -xim
+emacs_tags      -mouseshape      +startuptime     -xpm
+eval            +mouse_dec       +statusline      -xsmp
+ex_extra        -mouse_gpm       -sun_workshop    -xterm_clipboard
+extra_search    -mouse_jsbterm   +syntax          -xterm_save
+farsi           +mouse_netterm   +tag_binary
system vimrc file: "$VIM/vimrc"
 user vimrc file: "$HOME/.vimrc"
2nd user vimrc file: "~/.vim/vimrc"
  user exrc file: "$HOME/.exrc"
   defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/usr/local/share/vim"
Compilation: clang -c -I. -Iproto -DHAVE_CONFIG_H   -DMACOS_X_UNIX  -g -O2 -
U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: clang   -L. -fstack-protector -L/usr/local/lib -
L/usr/local/opt/libyaml/lib -L/usr/local/opt/openssl/lib -
L/usr/local/opt/readline/lib  -L/usr/local/lib -o vim        -lncurses -liconv
-framework Cocoa   -mmacosx-version-min=10.11 -fstack-protector-strong -
L/usr/local/lib  -L/usr/local/Cellar/perl/5.26.0/lib/perl5/5.26.0/darwin-
thread-multi-2level/CORE -lperl -lm -lutil -lc  -
L/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/config-3.6m-
darwin -lpython3.6m -framework CoreFoundation  -lruby.2.4.2 -lobjc

You may notice above that Vim is including python3 but not python

I have reinstalled Vim using:

$ brew uninstall vim
$ brew install vim --with-python3

I have also tried aliasing python to my Python3 version:

$ alias python='python3.6'

My PATH:

$ echo $PATH
/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/garythegoat/.rbenv/shims:/usr/bin/python:/usr/local/heroku/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/usr/local/go/bin:/Users/garythegoat/golang/bin

:echo has('python')  returns 1

:echo has('python3') returns 0

Any suggestions appreciated


问:
Access kubernetes web ui from remote computer
I installed Web UI for kubernetes on master node. I am using Ubuntu Server 18.04.2. Following this tutorial and it states that you must access dashboard from localhost. I need to access it from remote PC.

UPDATE:
I executed a dashboard with following command:

kubectl proxy --accept-hosts='.*' --address='100.180.3.11'

100.180.3.11 is external machine IP. I am able to get to sign in page. When I provide a token, nothing happens. Hint: seems like a cookie is not written and not being redirected.

答:
Assuming you your cluster is on VM's in bridged mode or that you can just access the node's IP from remote machine in the same network you can just change the type of service to NodePort and then access the dashboard on your node IP and access it on https://NODEIP:PORT.

Probably the reason that nothing happens after you add the token is the fact that you are using kubectl proxy which only allows HTTP connections. You won't be able to access it from any other place than localhost address. More information here.


问:
How to set space on Enum
I want to set the space on my enum. Here is my code sample:

```<code>public enum category
{
    goodBoy=1,
    BadBoy
}
</code>```

I want to set

```<code>public enum category
{
    Good Boy=1,
    Bad Boy
}
</code>```

When I retrieve I want to see Good Boy result from the enum

答:
I used Regex to split the values by capital letter and then immediately join into a string with a space between each string in the returned array.

```<code>string.Join(" ", Regex.Split(v.ToString(), @"(?<!^)(?=[A-Z])"));
</code>```

First get the values of the enum:

```<code>var values = Enum.GetValues(typeof(Category));
</code>```

Then loop through the values and use the code above to get the values:

```<code>var ret = new Dictionary<int, string>();

foreach (Category v in values)
{
   ret.Add((int)v, string.Join(" ", Regex.Split(v.ToString(), @"(?<!^)(?=[A-Z])")));
}
</code>```

In my case I needed a dictionary with the value and display name so that it why I have the variable "ret"

OwnerDisplayName: jame

Title: How to set space on Enum

Body:
I want to set the space on my enum. Here is my code sample:

public enum category
{
    goodBoy=1,
    BadBoy
}

I want to set

public enum category
{
    Good Boy=1,
    Bad Boy
}

When I retrieve I want to see Good Boy result from the enum

Body:
I used Regex to split the values by capital letter and then immediately join into a string with a space between each string in the returned array.

string.Join(" ", Regex.Split(v.ToString(), @"(?<!^)(?=[A-Z])"));

First get the values of the enum:

var values = Enum.GetValues(typeof(Category));

Then loop through the values and use the code above to get the values:

var ret = new Dictionary<int, string>();

foreach (Category v in values)
{
   ret.Add((int)v, string.Join(" ", Regex.Split(v.ToString(), @"(?<!^)(?=[A-Z])")));
}

In my case I needed a dictionary with the value and display name so that it why I have the variable "ret"


问:
Difference between two .csv file using Powershell
First Exported .csv file (Report of First Day)

```<code>id                                      principalName       licenseDisplayName

4b3556f1-df58-6c3c-848b-022fc6a8668d    abc@my.com         Basic
5b3556f1-df58-6c3c-848b-022fc6a8668d    xyz@my.com         Stackholder
6b3556f1-ff58-6c3c-848b-022fc6a8668d    pqr@my.com         Admin
</code>```

Another Day export .csv file (Report of Second Day)

```<code>id                                      principalName       licenseDisplayName

4b3556f1-df58-6c3c-848b-022fc6a8668d    abc@my.com         Stackholder
5b3556f1-df58-6c3c-848b-022fc6a8668d    xyz@my.com         Stackholder
8b3556f1-ff58-6c3c-848b-022fc6a8668d    yz@my.com          Basic
</code>```

Scenario, there is daily export report using PowerShell. In above Report 1 and Report 2 shows the records. So, I wanted difference between two .csv files.

In Report2, the first record is changed from Basic to Stackholder and the third record is missing 6b3556f1-ff58-6c3c-848b-022fc6a8668d and a new record  8b3556f1-ff58-6c3c-848b-022fc6a8668d is added

I wanted the following output (Difference of the two .csv files)

```<code>id                                     principalName       licenseDisplayName       Status
4b3556f1-df58-6c3c-848b-022fc6a8668d    abc@my.com         Stackholder     Updated from Basic to Stackholder
6b3556f1-ff58-6c3c-848b-022fc6a8668d    pqr@my.com         Admin             Deleted
8b3556f1-ff58-6c3c-848b-022fc6a8668d    yz@my.com          Basic               New
</code>```

My code:

```<code>$reference = Import-Csv -Path C:\Documents\Daily_Report\Daily_Export_jsonold.csv
$lookup = $reference | Group-Object -AsHashTable -AsString -Property Server
$results = Import-Csv -Path C:\Documents\Daily_Report\Daily_Export_jsonnew.csv | foreach {
    $server = $_.id
    Write-Verbose "Looking for $server"
    if ($lookup.value.ContainsKey($server))
    {
        $oldState = ($lookup[$server]).Access_Level
    }

    if ($_.State -ne $oldState)
    {
        [PSCustomObject]@{
            id = $server
            Username = $_.Username
            OldState = $oldState
            NewState = $_.Access_Level
        }
    }
}
</code>```

But I get the following output

```<code>id                                   Username                  OldState NewState
--                                   --------                  -------- --------
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com                Unknown  Stakeholder
5b3556f1-df58-6c3c-848b-022fc6a8668d xyz@my.com                Unknown  Stakeholder
</code>```

I wanted it to be like below:

```<code>id                                   Username             OldState     NewState
--                                   --------             --------     --------
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com           Basic        Stakeholder
5b3556f1-df58-6c3c-848b-022fc6a8668d xyz@my.com           Stakeholder  Stakeholder
</code>```

答:
I suggest to let the cmdlet Compare-Object do the core of the work.

```<code>$Reference = Import-Csv '.\Daily_Export_jsonold.csv'
$Difference= Import-Csv '.\Daily_Export_jsonnew.csv'

Compare-Object -Ref $Reference -Diff $Difference `
               -Property id,principalName,licenseDisplayName
</code>```

Sample output:

```<code>id                                   principalName licenseDisplayName SideIndicator
--                                   ------------- ------------------ -------------
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com    Stackholder        =>
8b3556f1-ff58-6c3c-848b-022fc6a8668d yz@my.com     Basic              =>
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com    Basic              <=
6b3556f1-ff58-6c3c-848b-022fc6a8668d pqr@my.com    Admin              <=
</code>```

That's quite near your desired result, grouping this by the property id yields:

```<code>Count Name                      Group
----- ----                      -----
    2 4b3556f1-df58-6c3c-848... {@{id=4b3556f1-df58-6c3c-848b-022fc6a8668d; principalName=abc@my.com; licenseDisplayName=Stackho...
    1 8b3556f1-ff58-6c3c-848... {@{id=8b3556f1-ff58-6c3c-848b-022fc6a8668d; principalName=yz@my.com; licenseDisplayName=Basic; S...
    1 6b3556f1-ff58-6c3c-848... {@{id=6b3556f1-ff58-6c3c-848b-022fc6a8668d; principalName=pqr@my.com; licenseDisplayName=Admin; ...
</code>```

Here:

Count greater one denotes a change

Count of 1 and a SideIndicator '<=' denotes 'Deleted'

Count of 1 and a SideIndicator '=>' denotes 'New'

So this script:

```<code>## Q:\Test\2019\05\28\SO_56341395.ps1
$Reference = Import-Csv '.\Daily_Export_jsonOld.csv'
$Difference= Import-Csv '.\Daily_Export_jsonNew.csv'

$Result = Compare-Object -Ref $Reference -Diff $Difference `
               -Property id,principalName,licenseDisplayName |
    Group-Object id | ForEach-Object {
        if ($_.Count -gt 1){
            $Status = 'Updated from {0}' -f $_.Group[1].licenseDisplayName
        } elseif ($_.Group[0].SideIndicator -eq '<='){
            $Status = 'Deleted'
        } else {
            $Status = 'New'
        }
        [PSCustomObject]@{
            id                 = $_.Group[0].id
            principalName      = $_.Group[0].principalName
            licenseDisplayName = $_.Group[0].licenseDisplayName
            Status             = $Status
        }
    }

$Result | Sort-Object id
$Result | Sort-Object id| Export-Csv '.\Daily_Export_jsonDif.csv' -NoTypeInformation
</code>```

Yields this output:

```<code>> Q:\Test\2019\05\28\SO_56341395.ps1

id                                   principalName licenseDisplayName Status
--                                   ------------- ------------------ ------
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com    Stackholder        Updated from Basic
6b3556f1-ff58-6c3c-848b-022fc6a8668d pqr@my.com    Admin              Deleted
8b3556f1-ff58-6c3c-848b-022fc6a8668d yz@my.com     Basic              New
</code>```

Body:
First Exported .csv file (Report of First Day)

id                                      principalName       licenseDisplayName

4b3556f1-df58-6c3c-848b-022fc6a8668d    abc@my.com         Basic
5b3556f1-df58-6c3c-848b-022fc6a8668d    xyz@my.com         Stackholder
6b3556f1-ff58-6c3c-848b-022fc6a8668d    pqr@my.com         Admin

Another Day export .csv file (Report of Second Day)

id                                      principalName       licenseDisplayName

4b3556f1-df58-6c3c-848b-022fc6a8668d    abc@my.com         Stackholder
5b3556f1-df58-6c3c-848b-022fc6a8668d    xyz@my.com         Stackholder
8b3556f1-ff58-6c3c-848b-022fc6a8668d    yz@my.com          Basic

Scenario, there is daily export report using PowerShell. In above Report 1 and Report 2 shows the records. So, I wanted difference between two .csv files.

In Report2, the first record is changed from Basic to Stackholder and the third record is missing 6b3556f1-ff58-6c3c-848b-022fc6a8668d and a new record  8b3556f1-ff58-6c3c-848b-022fc6a8668d is added

I wanted the following output (Difference of the two .csv files)

id                                     principalName       licenseDisplayName       Status
4b3556f1-df58-6c3c-848b-022fc6a8668d    abc@my.com         Stackholder     Updated from Basic to Stackholder
6b3556f1-ff58-6c3c-848b-022fc6a8668d    pqr@my.com         Admin             Deleted
8b3556f1-ff58-6c3c-848b-022fc6a8668d    yz@my.com          Basic               New

My code:

$reference = Import-Csv -Path C:\Documents\Daily_Report\Daily_Export_jsonold.csv
$lookup = $reference | Group-Object -AsHashTable -AsString -Property Server
$results = Import-Csv -Path C:\Documents\Daily_Report\Daily_Export_jsonnew.csv | foreach {
    $server = $_.id
    Write-Verbose "Looking for $server"
    if ($lookup.value.ContainsKey($server))
    {
        $oldState = ($lookup[$server]).Access_Level
    }

    if ($_.State -ne $oldState)
    {
        [PSCustomObject]@{
            id = $server
            Username = $_.Username
            OldState = $oldState
            NewState = $_.Access_Level
        }
    }
}

But I get the following output

id                                   Username                  OldState NewState
--                                   --------                  -------- --------
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com                Unknown  Stakeholder
5b3556f1-df58-6c3c-848b-022fc6a8668d xyz@my.com                Unknown  Stakeholder

I wanted it to be like below:

id                                   Username             OldState     NewState
--                                   --------             --------     --------
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com           Basic        Stakeholder
5b3556f1-df58-6c3c-848b-022fc6a8668d xyz@my.com           Stakeholder  Stakeholder

Body:
I suggest to let the cmdlet Compare-Object do the core of the work.

$Reference = Import-Csv '.\Daily_Export_jsonold.csv'
$Difference= Import-Csv '.\Daily_Export_jsonnew.csv'

Compare-Object -Ref $Reference -Diff $Difference `
               -Property id,principalName,licenseDisplayName

Sample output:

id                                   principalName licenseDisplayName SideIndicator
--                                   ------------- ------------------ -------------
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com    Stackholder        =>
8b3556f1-ff58-6c3c-848b-022fc6a8668d yz@my.com     Basic              =>
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com    Basic              <=
6b3556f1-ff58-6c3c-848b-022fc6a8668d pqr@my.com    Admin              <=

That's quite near your desired result, grouping this by the property id yields:

Count Name                      Group
----- ----                      -----
    2 4b3556f1-df58-6c3c-848... {@{id=4b3556f1-df58-6c3c-848b-022fc6a8668d; principalName=abc@my.com; licenseDisplayName=Stackho...
    1 8b3556f1-ff58-6c3c-848... {@{id=8b3556f1-ff58-6c3c-848b-022fc6a8668d; principalName=yz@my.com; licenseDisplayName=Basic; S...
    1 6b3556f1-ff58-6c3c-848... {@{id=6b3556f1-ff58-6c3c-848b-022fc6a8668d; principalName=pqr@my.com; licenseDisplayName=Admin; ...

Here:

Count greater one denotes a change

Count of 1 and a SideIndicator '<=' denotes 'Deleted'

Count of 1 and a SideIndicator '=>' denotes 'New'

So this script:

## Q:\Test\2019\05\28\SO_56341395.ps1
$Reference = Import-Csv '.\Daily_Export_jsonOld.csv'
$Difference= Import-Csv '.\Daily_Export_jsonNew.csv'

$Result = Compare-Object -Ref $Reference -Diff $Difference `
               -Property id,principalName,licenseDisplayName |
    Group-Object id | ForEach-Object {
        if ($_.Count -gt 1){
            $Status = 'Updated from {0}' -f $_.Group[1].licenseDisplayName
        } elseif ($_.Group[0].SideIndicator -eq '<='){
            $Status = 'Deleted'
        } else {
            $Status = 'New'
        }
        [PSCustomObject]@{
            id                 = $_.Group[0].id
            principalName      = $_.Group[0].principalName
            licenseDisplayName = $_.Group[0].licenseDisplayName
            Status             = $Status
        }
    }

$Result | Sort-Object id
$Result | Sort-Object id| Export-Csv '.\Daily_Export_jsonDif.csv' -NoTypeInformation

Yields this output:

> Q:\Test\2019\05\28\SO_56341395.ps1

id                                   principalName licenseDisplayName Status
--                                   ------------- ------------------ ------
4b3556f1-df58-6c3c-848b-022fc6a8668d abc@my.com    Stackholder        Updated from Basic
6b3556f1-ff58-6c3c-848b-022fc6a8668d pqr@my.com    Admin              Deleted
8b3556f1-ff58-6c3c-848b-022fc6a8668d yz@my.com     Basic              New


问:
MSVC 1 bit enum type equals -1 and equality test fails
I have defined a bitfield of enum types to match a set of bits in an embedded system. I'm trying to write a test harness in MSVC for the code, but comparing what should be equal values fails.

The definition looks like this:

typedef enum { SERIAL, PARALLEL } MODE_e;
typedef union {
    struct {
        TYPE_e      Type    : 1;    // 1
        POSITION_e  1Pos    : 1;    // 2
        POSITION_e  2Pos    : 1;    // 3
        bool        Enable  : 1;    // 4
        NET_e       Net     : 1;    // 5
        TYPE_e      Type    : 1;    // 6
        bool        En      : 1;    // 7
        TIME_e      Time    : 3;    // 8-10
        MODE_e      Mode    : 1;    // 11
        bool        TestEn  : 1;    // 12
        bool        DelayEn : 1;    // 13
        MODE_e      Mode    : 1;    // 14
        bool        xEn     : 1;    // 15
        MODE_e      yMode   : 1;    // 16
        bool        zEnable : 1;    // 17
    } Bits;
    uint32_t Word;
} BITS_t;
```
<p>Later the following comparison fails:</p>
<pre class="lang-none prettyprint-override"><code>Store.Bits.Mode = PARALLEL;
if (store.Bits.Mode == PARALLEL)
    ...
</code>```

I examined the Mode bool in the debugger, and it looked odd. The value of Mode is -1.

It's as if MSVC considers the value to be a two's complement number, but 1 bit wide, so 0b1 is decimal -1. The enum sets PARALLEL to 1, so the two do not match.

The comparison works fine on the embedded side using LLVM or GCC.

Which behavior is correct? I assume GCC and LLVM have better support for the C standards than MSVC in areas such as bit fields. More importantly, can I work around this difference without making major changes to the embedded code?

答:
I would use the following approach.

```<code>typedef enum { SERIAL_TEST_MODE = 0, PARALLEL_TEST_MODE = 1 } TEST_MODE_e;
</code>```

Then set the value and test the value as follows.

```<code>config.jumpers.Bits.TestMode = PARALLEL_TEST_MODE;
if (config.jumpers.Bits.TestMode & PARALLEL_TEST_MODE)
    ...
</code>```

The value of 1 will have the least significant bit turned on and the value of 0 would have the least significant bit turned off.

And this should be portable across multiple compilers.

Body:
I have defined a bitfield of enum types to match a set of bits in an embedded system. I'm trying to write a test harness in MSVC for the code, but comparing what should be equal values fails.

The definition looks like this:

typedef enum { SERIAL, PARALLEL } MODE_e;
typedef union {
    struct {
        TYPE_e      Type    : 1;    // 1
        POSITION_e  1Pos    : 1;    // 2
        POSITION_e  2Pos    : 1;    // 3
        bool        Enable  : 1;    // 4
        NET_e       Net     : 1;    // 5
        TYPE_e      Type    : 1;    // 6
        bool        En      : 1;    // 7
        TIME_e      Time    : 3;    // 8-10
        MODE_e      Mode    : 1;    // 11
        bool        TestEn  : 1;    // 12
        bool        DelayEn : 1;    // 13
        MODE_e      Mode    : 1;    // 14
        bool        xEn     : 1;    // 15
        MODE_e      yMode   : 1;    // 16
        bool        zEnable : 1;    // 17
    } Bits;
    uint32_t Word;
} BITS_t;

Later the following comparison fails:

Store.Bits.Mode = PARALLEL;
if (store.Bits.Mode == PARALLEL)
    ...

I examined the Mode bool in the debugger, and it looked odd. The value of Mode is -1.

It's as if MSVC considers the value to be a two's complement number, but 1 bit wide, so 0b1 is decimal -1. The enum sets PARALLEL to 1, so the two do not match.

The comparison works fine on the embedded side using LLVM or GCC.

Which behavior is correct? I assume GCC and LLVM have better support for the C standards than MSVC in areas such as bit fields. More importantly, can I work around this difference without making major changes to the embedded code?

Body:
I would use the following approach.

typedef enum { SERIAL_TEST_MODE = 0, PARALLEL_TEST_MODE = 1 } TEST_MODE_e;

Then set the value and test the value as follows.

config.jumpers.Bits.TestMode = PARALLEL_TEST_MODE;
if (config.jumpers.Bits.TestMode & PARALLEL_TEST_MODE)
    ...

The value of 1 will have the least significant bit turned on and the value of 0 would have the least significant bit turned off.

And this should be portable across multiple compilers.


答:
something like this should work:

```<code>for f in ./* ; do new_name=$(head -1 $f | cut -d, -f1); cp $f dir/$new_name
</code>```

move them into a new dir just in case something goes wrong, or you need the original file names.

Title: How to rename a CSV file from a value in the CSV file

Body:
I have 100 1-line CSV files. The files are currently labeled AAA.txt, AAB.txt, ABB.txt (after I used split -l 1 on them). The first field in each of these files is what I want to rename the file as, so instead of AAA, AAB and ABB it would be the first value.

Input CSV (filename AAA.txt)

1234ABC, stuff, stuff

Desired Output (filename 1234ABC.csv)

1234ABC, stuff, stuff

I don't want to edit the content of the CSV itself, just change the filename

Body:
something like this should work:

for f in ./* ; do new_name=$(head -1 $f | cut -d, -f1); cp $f dir/$new_name

move them into a new dir just in case something goes wrong, or you need the original file names.


问:
regexp to match simple markdown
I'm trying to figure out the regexp to match all the occurences of *this kind of strings*. Two additional rules unfortunately made this thing more complicated than I thought:

tagged string should start with * followed by non-whitespace character (so * this one* should not be matched

tagged string should end with non-whitespace followed by * followed by whitespace (so *this one * and *this o*ne should not be matched

I started with simplest regexp \*\S([^\*]+)?\* which for my testing string:

*foo 1 * 2 bar* foo *b* azz *qu **ux*

matches places in square brackets:

[*foo 1 *] 2 bar* foo [*b*] azz [*qu *][*ux*]

and this is what I'd like to achieve:

[*foo 1 * 2 bar*] foo [*b*] azz [*qu **ux*]

so 2 problems appear:

how to express in a regexp a rule from 2. "search till first non-whitespace followed * followed by whitespace appears"? positive lookahead?

how to match whitespace from rule 2. but not include it into result, which \*\S([^\*]+)?\*\s would do?

答:
You can use this regex:

```<code>\*(?!\s)(.*?)(?<!\s|\*)\*(?=\s|$)
</code>```

how to express in a regexp a rule from 2. "search till first non-whitespace followed * followed by whitespace appears"? positive lookahead?

You can use a negative lookbehind to match the final asterisk only when it's preceded by a non-whitespace character and a positive lookahead to match the asterisk when it's followed by a whitespace character or the end of the string.

how to match whitespace from rule 2. but not include it into result, which *\S([^*]+)?*\s would do?

If you want to check if a pattern is followed by a character without consuming it you can use a lookahead, e.g. pattern(?=\s) will not consume the \s as opposed to pattern\s.

Title: regexp to match simple markdown

Body:
You can use this regex:

\*(?!\s)(.*?)(?<!\s|\*)\*(?=\s|$)

how to express in a regexp a rule from 2. "search till first non-whitespace followed * followed by whitespace appears"? positive lookahead?

You can use a negative lookbehind to match the final asterisk only when it's preceded by a non-whitespace character and a positive lookahead to match the asterisk when it's followed by a whitespace character or the end of the string.

how to match whitespace from rule 2. but not include it into result, which *\S([^*]+)?*\s would do?

If you want to check if a pattern is followed by a character without consuming it you can use a lookahead, e.g. pattern(?=\s) will not consume the \s as opposed to pattern\s.