问:
Matching Zeros and Nulls as equal in dataframes
I have the following dataframe/function which reconciles interest rates and codes between a mainframe system and its rate depositary/warehouse.

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

# Test Dataframe
df = pd.DataFrame([[5551455514,3.5,'GG',3.5,'GG',],
                    [9631475400,0,'GG',np.NaN,'GG',],
                   [8529875405,0,'GG',0,'GG',],
                    [3265415409,np.NaN,'GG',0,'GG',],
                    [9631475405,1.25,'GG',0,'GG',]],
columns = ['Account','Mainframe_System_interest','Mainframe_System_code','Rate_warehouse_interest','Rate_warehouse_code'])

# Function
def matching_func(row):
    if row['Mainframe_System_code'] == row['Rate_warehouse_code'] and row['Mainframe_System_interest'] == row['Rate_warehouse_interest']:
        return 'Match'
    else:
        return 'Mismatch'
# New generated Column
df['Rate_Match'] = df.apply(lambda x: matching_func(x), axis=1)

# Current Output:

Account Mainframe_System_interest   Mainframe_System_code   Rate_warehouse_interest Rate_warehouse_code Rate_Match
0       5551455514  3.50            GG                      3.5                   GG      Match
1       9631475400  0.00            GG                      NaN                   GG      Mismatch
2       8529875405  0.00            GG                      0.0                   GG      Match
3       3265415409  NaN             GG                      0.0                   GG      Mismatch
4       9631475405  1.25            GG                      0.0                   GG      Mismatch

</code>```

When matching the interest rates, I need to add in the factor that if the system has a null rate this can be treated as a zero and vice versa. The same concept is applied to the rate warehouse too. Currently function can only match like for like.

I need to factor in where 0s can be nulls and vice versa. Any ideas how to add this to the function provided?

The expected result should see Line 1 and 3 as matched and not mismatched, and the others should not change.

Any thoughts how to achieve this?

答:
Use fillna before:

```<code>m1 = df['Mainframe_System_interest'].fillna(df['Rate_warehouse_interest'])
         == df['Rate_warehouse_interest'].fillna(df['Mainframe_System_interest'])

m2 = df['Mainframe_System_code'].fillna(df['Rate_warehouse_code']) \
         == df['Rate_warehouse_code'].fillna(df['Mainframe_System_code'])

df['Rate_Match'] = np.where(m1 & m2, 'Match', 'Mismatch')
</code>```

Output:

```<code>>>> df[['Account', 'Rate_Match']]
      Account Rate_Match
0  5551455514      Match
1  9631475400      Match
2  8529875405      Match
3  3265415409      Match
4  9631475405   Mismatch

>>> df
      Account  Mainframe_System_interest Mainframe_System_code  Rate_warehouse_interest Rate_warehouse_code Rate_Match
0  5551455514                       3.50                    GG                      3.5                  GG      Match
1  9631475400                       0.00                    GG                      NaN                  GG      Match
2  8529875405                       0.00                    GG                      0.0                  GG      Match
3  3265415409                        NaN                    GG                      0.0                  GG      Match
4  9631475405                       1.25                    GG                      0.0                  GG   Mismatch
</code>```

Body:
I have the following dataframe/function which reconciles interest rates and codes between a mainframe system and its rate depositary/warehouse.

import pandas as pd
import numpy as np

# Test Dataframe
df = pd.DataFrame([[5551455514,3.5,'GG',3.5,'GG',],
                    [9631475400,0,'GG',np.NaN,'GG',],
                   [8529875405,0,'GG',0,'GG',],
                    [3265415409,np.NaN,'GG',0,'GG',],
                    [9631475405,1.25,'GG',0,'GG',]],
columns = ['Account','Mainframe_System_interest','Mainframe_System_code','Rate_warehouse_interest','Rate_warehouse_code'])

# Function
def matching_func(row):
    if row['Mainframe_System_code'] == row['Rate_warehouse_code'] and row['Mainframe_System_interest'] == row['Rate_warehouse_interest']:
        return 'Match'
    else:
        return 'Mismatch'
# New generated Column
df['Rate_Match'] = df.apply(lambda x: matching_func(x), axis=1)

# Current Output:

Account Mainframe_System_interest   Mainframe_System_code   Rate_warehouse_interest Rate_warehouse_code Rate_Match
0       5551455514  3.50            GG                      3.5                   GG      Match
1       9631475400  0.00            GG                      NaN                   GG      Mismatch
2       8529875405  0.00            GG                      0.0                   GG      Match
3       3265415409  NaN             GG                      0.0                   GG      Mismatch
4       9631475405  1.25            GG                      0.0                   GG      Mismatch

When matching the interest rates, I need to add in the factor that if the system has a null rate this can be treated as a zero and vice versa. The same concept is applied to the rate warehouse too. Currently function can only match like for like.

I need to factor in where 0s can be nulls and vice versa. Any ideas how to add this to the function provided?

The expected result should see Line 1 and 3 as matched and not mismatched, and the others should not change.

Any thoughts how to achieve this?

Body:
Use fillna before:

m1 = df['Mainframe_System_interest'].fillna(df['Rate_warehouse_interest'])
         == df['Rate_warehouse_interest'].fillna(df['Mainframe_System_interest'])

m2 = df['Mainframe_System_code'].fillna(df['Rate_warehouse_code']) \
         == df['Rate_warehouse_code'].fillna(df['Mainframe_System_code'])

df['Rate_Match'] = np.where(m1 & m2, 'Match', 'Mismatch')

Output:

>>> df[['Account', 'Rate_Match']]
      Account Rate_Match
0  5551455514      Match
1  9631475400      Match
2  8529875405      Match
3  3265415409      Match
4  9631475405   Mismatch

>>> df
      Account  Mainframe_System_interest Mainframe_System_code  Rate_warehouse_interest Rate_warehouse_code Rate_Match
0  5551455514                       3.50                    GG                      3.5                  GG      Match
1  9631475400                       0.00                    GG                      NaN                  GG      Match
2  8529875405                       0.00                    GG                      0.0                  GG      Match
3  3265415409                        NaN                    GG                      0.0                  GG      Match
4  9631475405                       1.25                    GG                      0.0                  GG   Mismatch


来源: stackexchange

问:
Query update last record only and value from other table
I have two tables

oc_stock_hpp

```<code>id product_id stock
2  1234       0
3  5678       0
4  1234       0
6  1234       0
9  5678       0
</code>```

oc_product

```<code>id product_id quantity
1  1234       7
23 5678       9
</code>```

My purpose is to update value in the stock field table oc_stock_hpp where id=6 become 7 and id=9 become 9 as in oc_product table

I have tried

```<code>UPDATE oc_stock_hpp t1
    INNER JOIN oc_product t2
         ON t1.product_id = t2.product_id
SET t1.stock = t2.quantity
WHERE t1.id = (SELECT MAX(id) FROM oc_stock_hpp GROUP BY product_id)
</code>```

and got error Subquery returns more than 1 row

答:
You must have as result only 1 id

```<code>CREATE TABLE oc_stock_hpp (
  `id` INTEGER,
  `product_id` INTEGER,
  `stock` INTEGER
);

INSERT INTO oc_stock_hpp
  (`id`, `product_id`, `stock`)
VALUES
  ('2', '1234', '0'),
  ('3', '5678', '0'),
  ('4', '1234', '0'),
  ('6', '1234', '0'),
  ('9', '5678', '0');
</code>```

```<code>CREATE TABLE oc_product (
  `id` INTEGER,
  `product_id` INTEGER,
  `quantity` INTEGER
);

INSERT INTO oc_product
  (`id`, `product_id`, `quantity`)
VALUES
  ('1', '1234', '7'),
  ('23', '5678', '9');
</code>```

```<code>UPDATE oc_stock_hpp t1
    INNER JOIN oc_product t2
         ON t1.product_id = t2.product_id
SET t1.stock = t2.quantity
WHERE t1.id = (SELECT MAX(id) FROM (SELECT * FROM oc_stock_hpp) o1 WHERE product_id = t2.product_id)
</code>```

```<code>SELECT * FROM oc_stock_hpp
</code>```
```
id | product_id | stock
-: | ---------: | ----:
 2 |       1234 |     0
 3 |       5678 |     0
 4 |       1234 |     0
 6 |       1234 |     7
 9 |       5678 |     9
```

db<>fiddle here

ContentLicense: CC BY-SA 4.0

Body:
I have two tables

oc_stock_hpp

id product_id stock
2  1234       0
3  5678       0
4  1234       0
6  1234       0
9  5678       0

oc_product

id product_id quantity
1  1234       7
23 5678       9

My purpose is to update value in the stock field table oc_stock_hpp where id=6 become 7 and id=9 become 9 as in oc_product table

I have tried

UPDATE oc_stock_hpp t1
    INNER JOIN oc_product t2
         ON t1.product_id = t2.product_id
SET t1.stock = t2.quantity
WHERE t1.id = (SELECT MAX(id) FROM oc_stock_hpp GROUP BY product_id)

and got error Subquery returns more than 1 row

Body:
You must have as result only 1 id

CREATE TABLE oc_stock_hpp (
  `id` INTEGER,
  `product_id` INTEGER,
  `stock` INTEGER
);

INSERT INTO oc_stock_hpp
  (`id`, `product_id`, `stock`)
VALUES
  ('2', '1234', '0'),
  ('3', '5678', '0'),
  ('4', '1234', '0'),
  ('6', '1234', '0'),
  ('9', '5678', '0');

CREATE TABLE oc_product (
  `id` INTEGER,
  `product_id` INTEGER,
  `quantity` INTEGER
);

INSERT INTO oc_product
  (`id`, `product_id`, `quantity`)
VALUES
  ('1', '1234', '7'),
  ('23', '5678', '9');

UPDATE oc_stock_hpp t1
    INNER JOIN oc_product t2
         ON t1.product_id = t2.product_id
SET t1.stock = t2.quantity
WHERE t1.id = (SELECT MAX(id) FROM (SELECT * FROM oc_stock_hpp) o1 WHERE product_id = t2.product_id)

SELECT * FROM oc_stock_hpp

id | product_id | stock
-: | ---------: | ----:
 2 |       1234 |     0
 3 |       5678 |     0
 4 |       1234 |     0
 6 |       1234 |     7
 9 |       5678 |     9

db<>fiddle here


问:
How to get ApplicationContext in Micronaut CLI application into Httpclient class?
I am running a Micronaut CLI application via Picocli runner wanted to use applicationContext for injecting/getting the bean during application execution.

```<code>@HttpRetryable
@Client("SERVICE_ID")
interface TestHttpClient {

}
@Inject
lateinit var applicationContext: ApplicationContext

private class AuthenticationFilter() : HttpClientFilter {
    // calling appcontext here
    println("appContext is Running " + appContext.isRunning)
}
</code>```

But getting this error on the execution

```<code>kotlin.UninitializedPropertyAccessException: lateinit property applicationContext has not been initialized```
How this can be fixed ?
```

答: The property needs to be in the AuthenticationFilter class. That class should be annotated with jakarta.inject.Singleton and should not be private

Body:
I am running a Micronaut CLI application via Picocli runner wanted to use applicationContext for injecting/getting the bean during application execution.

@HttpRetryable
@Client("SERVICE_ID")
interface TestHttpClient {

}
@Inject
lateinit var applicationContext: ApplicationContext

private class AuthenticationFilter() : HttpClientFilter {
    // calling appcontext here
    println("appContext is Running " + appContext.isRunning)
}

But getting this error on the execution

kotlin.UninitializedPropertyAccessException: lateinit property applicationContext has not been initialized```
How this can be fixed ?


问:
UWP: Fetch data in the background after page rendering and then refresh the UI
I am new to UWP and trying to call data from the internet which needs around 5 seconds to be loaded. The data will then be displayed in a grid. The problem I am facing is that the whole application is blocked until the data arrives.
(the logic exists in Home.xaml which is a page that will be rendered inside a frame in the MainPage.xaml)

I added so far:

```<code>private void WeatherGrid_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    var weatherService = new WeatherService();
    var weather = weatherService.GetCurrentWeather(); // this takes around 5 seconds to be fetched
    this.TemperatureTextBlock.Text = weather.Main.Temp.ToString();
}
</code>```

and my XAML Code:

```<code><Grid Loaded="WeatherGrid_Loaded">
        <TextBlock x:Name="TemperatureTextBlock"></TextBlock>
 </Grid>
</code>```

What I am trying to achieve is for the main page and the home to be loaded and functional and the weather data to be loaded in a thread and when they are fetched, the value will be displayed inside the textblock. If there is an inturreption (change of page or refresh) the process should stop and/or restart again. I don't know to be honest how to start with it as I am used to web development. Any suggestions?

答:
Unless GetCurrentWeather is async or there is an async overload of it available, you should call it on a background thread using the Task.Run API:

```<code>private async void WeatherGrid_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    var weatherService = new WeatherService();
    var weather = await Task.Run(() => weatherService.GetCurrentWeather());
    this.TemperatureTextBlock.Text = weather.Main.Temp.ToString();
}
</code>```

Body:
I am new to UWP and trying to call data from the internet which needs around 5 seconds to be loaded. The data will then be displayed in a grid. The problem I am facing is that the whole application is blocked until the data arrives.
(the logic exists in Home.xaml which is a page that will be rendered inside a frame in the MainPage.xaml)

I added so far:

private void WeatherGrid_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    var weatherService = new WeatherService();
    var weather = weatherService.GetCurrentWeather(); // this takes around 5 seconds to be fetched
    this.TemperatureTextBlock.Text = weather.Main.Temp.ToString();
}

and my XAML Code:

<Grid Loaded="WeatherGrid_Loaded">
        <TextBlock x:Name="TemperatureTextBlock"></TextBlock>
 </Grid>

What I am trying to achieve is for the main page and the home to be loaded and functional and the weather data to be loaded in a thread and when they are fetched, the value will be displayed inside the textblock. If there is an inturreption (change of page or refresh) the process should stop and/or restart again. I don't know to be honest how to start with it as I am used to web development. Any suggestions?

Body:
Unless GetCurrentWeather is async or there is an async overload of it available, you should call it on a background thread using the Task.Run API:

private async void WeatherGrid_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    var weatherService = new WeatherService();
    var weather = await Task.Run(() => weatherService.GetCurrentWeather());
    this.TemperatureTextBlock.Text = weather.Main.Temp.ToString();
}


问:
Include Percentage In Legend
How would I add the segments percentage to the charts label?

Example
(Percentage values dont reflect the actual chart this is just an example.)

Here's my current template.

```<code><ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>
</code>```

答:
In Chart.js V3 you can use a custom generateLabels function for this:

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }, ]
  },
  options: {
    plugins: {
      legend: {
        labels: {
          generateLabels: function(chart) {
            const data = chart.data;
            if (data.labels.length && data.datasets.length) {
              const {
                labels: {
                  pointStyle
                }
              } = chart.legend.options;

              const max = data.datasets[0].data.reduce((a, b) => (a + b), 0);

              return data.labels.map((label, i) => {
                const meta = chart.getDatasetMeta(0);
                const style = meta.controller.getStyle(i);

                return {
                  text: `${label} (${(data.datasets[0].data[i] * 100 / max).toFixed(2)}%)`,
                  fillStyle: style.backgroundColor,
                  strokeStyle: style.borderColor,
                  lineWidth: style.borderWidth,
                  pointStyle: pointStyle,
                  hidden: !chart.getDataVisibility(i),

                  // Extra data used for toggling the correct item
                  index: i
                };
              });
            }
            return [];
          }
        },
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body></code>```

ContentLicense: CC BY-SA 3.0

Title: Include Percentage In Legend

Body:
How would I add the segments percentage to the charts label?

Example
(Percentage values dont reflect the actual chart this is just an example.)

Here's my current template.

<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%>
<span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%>
<%}%>

Body:
In Chart.js V3 you can use a custom generateLabels function for this:

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }, ]
  },
  options: {
    plugins: {
      legend: {
        labels: {
          generateLabels: function(chart) {
            const data = chart.data;
            if (data.labels.length && data.datasets.length) {
              const {
                labels: {
                  pointStyle
                }
              } = chart.legend.options;

              const max = data.datasets[0].data.reduce((a, b) => (a + b), 0);

              return data.labels.map((label, i) => {
                const meta = chart.getDatasetMeta(0);
                const style = meta.controller.getStyle(i);

                return {
                  text: `${label} (${(data.datasets[0].data[i] * 100 / max).toFixed(2)}%)`,
                  fillStyle: style.backgroundColor,
                  strokeStyle: style.borderColor,
                  lineWidth: style.borderWidth,
                  pointStyle: pointStyle,
                  hidden: !chart.getDataVisibility(i),

                  // Extra data used for toggling the correct item
                  index: i
                };
              });
            }
            return [];
          }
        },
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>


问:
Automatic merging of one page pdfs to two page pdfs
I know there are tools like pdftk or convert or ghostscript. but my searches failing because all of the solutions are build for 2 pdf-files merged into 1 pdf-file.

But I have 30.000 PDF files and want to merge them down to 15.000 two sided PDF files. Because the first page is the front and the second page is the back. And I need them combined in one pdf with front and back.

They are numbered down starting with 00001.pdf and 00002.pdf and they need to combined to a new two pages pdf. And then next, 00003.pdf and 00004.pdf and so on.
Any chance to build a command which automatically grabs the next 2 pdf and merge them?

Alternative, I thougth about a "size-break" every file is near 2,5MB big. A command to build only 5MB pdfs and then head over to the next file.

Thx for any suggestions.

P.S. I have all the files in .jpg, too.

答:
In Bash, something like this:

```<code>#! /bin/bash

fileIndex=1

inputFormat="%05d.pdf"        # change the formats
outputFormat="%05d+%05d.pdf"  # to support other name patterns

while true
do
    file1root=$((fileIndex++))
    file2root=$((fileIndex++))
    printf -v file1 "$inputFormat" "$file1root"
    printf -v file2 "$inputFormat" "$file2root"
    printf -v output "$outputFormat" "$file1root" "$file2root"
    [[ -f $file1 ]] && [[ -f $file2 ]] || break
    echo execute some command $file1 $file2 $output ####
done
</code>```

where the #### line is replaced by a command that merges two PDF into one PDF

Body:
In Bash, something like this:

#! /bin/bash

fileIndex=1

inputFormat="%05d.pdf"        # change the formats
outputFormat="%05d+%05d.pdf"  # to support other name patterns

while true
do
    file1root=$((fileIndex++))
    file2root=$((fileIndex++))
    printf -v file1 "$inputFormat" "$file1root"
    printf -v file2 "$inputFormat" "$file2root"
    printf -v output "$outputFormat" "$file1root" "$file2root"
    [[ -f $file1 ]] && [[ -f $file2 ]] || break
    echo execute some command $file1 $file2 $output ####
done

where the #### line is replaced by a command that merges two PDF into one PDF


问:
Find column with specific name and fill the field with specific text to the last row
I need to find column named "Current" (preferred) or last column in general in the table named "YTD_input1" and fill all rows with text "Current" to the last row of the table.

My suggested code is below but does not work.

```<code> Dim pasteSheet As Worksheet: Set pasteSheet = wb.Worksheets("DPM input YTD_working")
 Dim LastRow As Long, Nxtrw As Long, lCol As Long

 LastRow = copySheet.Cells(Rows.Count, 1).End(xlUp).Row

 lCol = pasteSheet.Cells(1, Columns.Count).End(xlToLeft).Select

 pasteSheet.Range(lCol & LastRow).Value = "Current"
</code>```

Can you please give me some advice how to build the code to be working?

答:
Using Match()

Dim m, ws as worksheet, lr as long

set ws = ActiveSheet                              'or whatever
m = Application.Match("Current", ws.rows(1), 0)   'find the column

If Not IsError(m) Then 'got a match?
    lr = ws.Cells(rows.count, 1).End(xlUp).Row    'last row Col A
    ws.Range(ws.Cells(1, m).Offset(1), ws.Cells(lr, m)).Value = "Current"
End If
```

Body:
I need to find column named "Current" (preferred) or last column in general in the table named "YTD_input1" and fill all rows with text "Current" to the last row of the table.

My suggested code is below but does not work.

 Dim pasteSheet As Worksheet: Set pasteSheet = wb.Worksheets("DPM input YTD_working")
 Dim LastRow As Long, Nxtrw As Long, lCol As Long

 LastRow = copySheet.Cells(Rows.Count, 1).End(xlUp).Row

 lCol = pasteSheet.Cells(1, Columns.Count).End(xlToLeft).Select

 pasteSheet.Range(lCol & LastRow).Value = "Current"

Can you please give me some advice how to build the code to be working?


问:
Angular, Init form inputs are invalid but value is valid
I made an angular form with two inputs number and one select.
I fill these inputs with a model values, but the two numbers inputs is invalid and i need to click inside it to change it to valid.

I use inputs like this :

```<code><input type="text"
  name="price"
  id="price"
  [(ngModel)]="chair.price"
  formControlName="price"
  class="form-control form-control-lg form-control-solid"
  [ngClass]="{
      'is-invalid': editPriceForm.controls['price'].invalid,
      'is-valid':editPriceForm.controls['price'].valid
   }"
/>
</code>```

So in the initial render form, i get the good value in the inputs but the class of the input is 'is-invalid', and i don't know why. I try to trigget a markAllAsTouched but nothing change.

When i click inside the input, and click out, the class change to become valid.

Do you know if something is possible to tell to the form to be rechecked after filling data ?

答: You are mixing two different types of Angular's handling of forms. First, refactor your code to either Template Driven Forms by removing formControlName and only using [(ngModel)] or by removing [(ngModel)] and only use formControlName so that your code is Reactive Forms.

Body:
I made an angular form with two inputs number and one select.
I fill these inputs with a model values, but the two numbers inputs is invalid and i need to click inside it to change it to valid.

I use inputs like this :

<input type="text"
  name="price"
  id="price"
  [(ngModel)]="chair.price"
  formControlName="price"
  class="form-control form-control-lg form-control-solid"
  [ngClass]="{
      'is-invalid': editPriceForm.controls['price'].invalid,
      'is-valid':editPriceForm.controls['price'].valid
   }"
/>

So in the initial render form, i get the good value in the inputs but the class of the input is 'is-invalid', and i don't know why. I try to trigget a markAllAsTouched but nothing change.

When i click inside the input, and click out, the class change to become valid.

Do you know if something is possible to tell to the form to be rechecked after filling data ?


问:
Do modern c++ compilers optimize assignments after type casting?
Take the following code:

```<code>char chars[4] = {0x5B, 0x5B, 0x5B, 0x5B};
int* b = (int*) &chars[0];
</code>```

The (int*) &chars[0] value is going to be used in a loop (a long loop). Is there any advantage in using (int*) &chars[0] over b in my code? Is there any overhead in creating b? Since I only want to use it as an alias and improve code readability.

Also, is it OK to do this kind of type casting as long as I know what I'm doing? Or should I always memcpy() to another array with the correct type and use that? Would I encounter any kind of undefined behavior? because in my testing so far, it works, but I've seen people discouraging this kind of type casting.

答:
If code performs multiple discrete byte operations using a pointer derived from a pointer to a type which requires word alignment, clang will sometimes replace the discrete writes with a word write that would succeed if the original object was aligned for that word type, but would fail on systems that don't support unaligned accesses if the object isn't aligned the way the compiler expects.

Among other things, this means that if one casts a pointer to T into a pointer to a union containing T, code which attempts to use the union pointer to access the original type may fail if the union contains any types that require an alignment stricter than the original type, even if the union is only accessed via the member of the original type.

Body:
Take the following code:

char chars[4] = {0x5B, 0x5B, 0x5B, 0x5B};
int* b = (int*) &chars[0];

The (int*) &chars[0] value is going to be used in a loop (a long loop). Is there any advantage in using (int*) &chars[0] over b in my code? Is there any overhead in creating b? Since I only want to use it as an alias and improve code readability.

Also, is it OK to do this kind of type casting as long as I know what I'm doing? Or should I always memcpy() to another array with the correct type and use that? Would I encounter any kind of undefined behavior? because in my testing so far, it works, but I've seen people discouraging this kind of type casting.


问:
How to find specific span from th class using selenium
I want to pick only one html  element from a  class and print on terminal. I've tried using [1] at the end of the  but it didn't work out.

I've tried this with selenium:

```<code>for element in driver.find_elements(By.XPATH, '//div/table/thead/tr/th/span[1]'):
    print(element.text)
</code>```

The html is the following:

Date	Open	High	Low	Close*	Adj Close**	Volume

```

Needing more information, leave a comment.

答:
The SPAN s are decendents of the TH s. Similarly the TH s are decendents of the TR. So you can use either of the following Locator Strategies:

xpath:

```<code>for element in driver.find_elements(By.XPATH, '//thead/tr//th/span'):
        print(element.text)
</code>```

css-selectors:

```<code>for element in driver.find_elements(By.XPATH, 'thead > tr th > span'):
        print(element.text)
</code>```

Update

To identify the first  you can use either of the following Locator Strategies:

xpath:

```<code>print(driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child(1) > span").text)
</code>```

css-selectors:

```<code>print(driver.find_element(By.XPATH, "//thead/tr//following::th[1]/span").text)
</code>```

Body:
I want to pick only one html  element from a  class and print on terminal. I've tried using [1] at the end of the  but it didn't work out.

I've tried this with selenium:

for element in driver.find_elements(By.XPATH, '//div/table/thead/tr/th/span[1]'):
    print(element.text)

The html is the following:

Date	Open	High	Low	Close*	Adj Close**	Volume

Needing more information, leave a comment.

Body:
The SPAN s are decendents of the TH s. Similarly the TH s are decendents of the TR. So you can use either of the following Locator Strategies:

xpath:

for element in driver.find_elements(By.XPATH, '//thead/tr//th/span'):
        print(element.text)

css-selectors:

for element in driver.find_elements(By.XPATH, 'thead > tr th > span'):
        print(element.text)

Update

To identify the first <span> you can use either of the following Locator Strategies:

xpath:

print(driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child(1) > span").text)

css-selectors:

print(driver.find_element(By.XPATH, "//thead/tr//following::th[1]/span").text)


问:
Loading a pretrained model in PyTorch, error:object not callable
I am trying to load the Efficientnet-b6 weights using PyTorch and Fastai:

```<code>PATH = '../input/EffnetB6/efficientnet_b6.pth'
model = torch.load(PATH)
</code>```

The above model is part of another model:

```<code>class EARUnet(nn.Module):
    def __init__(self, pretrained_net, out_ch=1):
        super(EARUnet, self).__init__()
        # print("EfficientUnet_git_b6_res")
        self.pretrained_net = pretrained_net
        .
        .

</code>```

When I run:

```<code>net = EARUnet(model,1)
learn.fit_flat_cos(10)
</code>```

I get this error:

```<code>TypeError: 'collections.OrderedDict' object is not callable
</code>```

What is the model's format requested?

答:
Given the restrained context, I suspect that the problem resides in model, probably containing an OrderedDict of the EfficientNet model state dict, while the EARUnet expects the EfficientNet nn.Module.

You should instead, try something like:

eff_net = EfficientNetB6()
eff_net_state_dict = torch.load(PATH)
eff_net.load_state_dict(eff_net_state_dict)

net = EARUnet(model, 1)
```

Have a look at this page for more details.

Body:
I am trying to load the Efficientnet-b6 weights using PyTorch and Fastai:

PATH = '../input/EffnetB6/efficientnet_b6.pth'
model = torch.load(PATH)

The above model is part of another model:

class EARUnet(nn.Module):
    def __init__(self, pretrained_net, out_ch=1):
        super(EARUnet, self).__init__()
        # print("EfficientUnet_git_b6_res")
        self.pretrained_net = pretrained_net
        .
        .

When I run:

net = EARUnet(model,1)
learn.fit_flat_cos(10)

I get this error:

TypeError: 'collections.OrderedDict' object is not callable

What is the model's format requested?

Body:
Given the restrained context, I suspect that the problem resides in model, probably containing an OrderedDict of the EfficientNet model state dict, while the EARUnet expects the EfficientNet nn.Module.

You should instead, try something like:

eff_net = EfficientNetB6()
eff_net_state_dict = torch.load(PATH)
eff_net.load_state_dict(eff_net_state_dict)

net = EARUnet(model, 1)

Have a look at this page for more details.


问:
Scaling for spring boot application using spring cloud
I am using spring boot with Kubernetes and Eventhub. To connect with Azure Eventhub i use spring cloud stream. What is the math to determine the number of pods assuming non reactive spring boot application with apache tomcat?

Edit 1: to reframe my question, how do you factor in spring boot performance , request rate , user count, etc while scaling the pods?

答: In general the number of pods can be managed with a Deployment in Kubernetes. For more information you can see here kubernetes.io. In a Deployment you tell Kubernetes how many Replicas you want, which means how many Pods should be running. I don't know what you mean with non reactive spring boot application with apache tomcat. I also don't know about spring cloud stream.</p>


问:
How to run multiple BackgroundService parallel in .net core 3.0?
How is it possible to run multiple IHostedServices in parallel?

I use the WorkerService in .Net Core 3.0 and want both services to run parallel. Currently the second service is waiting for the first one to finish. Both services should run endlessly.

```<code>    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<ServiceA>();
                services.AddHostedService<ServiceB>();
            });
    }
</code>```

A service looks like this:

```<code>public class ServiceA : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        do
        {
            Console.WriteLine("Sample");
            await Task.Delay(5000, stoppingToken);
        } while (!stoppingToken.IsCancellationRequested);
    }
}
</code>```

// edit:
Very reluctantly I would use a Task.Run(() => method()); method like this. But of course this way always works:

```<code>public class ServiceA : BackgroundService
{
    public override Task StartAsync(CancellationToken cancellationToken)
    {
        Task.Factory.StartNew(() => ExecuteAsync(cancellationToken), cancellationToken);
        return Task.CompletedTask;
    }
}
</code>```

答:
No need to manually create a task. The default StartAsync calls ExecuteAsync and returns that task to be awaited somewhere else.

https://github.com/aspnet/Hosting/blob/master/src/Microsoft.Extensions.Hosting.Abstractions/BackgroundService.cs#L30

So, you can do return base.StartAsync(cancellationToken) before returning Task.Completed in StartAsync.

Body:
How is it possible to run multiple IHostedServices in parallel?

I use the WorkerService in .Net Core 3.0 and want both services to run parallel. Currently the second service is waiting for the first one to finish. Both services should run endlessly.

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<ServiceA>();
                services.AddHostedService<ServiceB>();
            });
    }

A service looks like this:

public class ServiceA : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        do
        {
            Console.WriteLine("Sample");
            await Task.Delay(5000, stoppingToken);
        } while (!stoppingToken.IsCancellationRequested);
    }
}

// edit:
Very reluctantly I would use a Task.Run(() => method()); method like this. But of course this way always works:

public class ServiceA : BackgroundService
{
    public override Task StartAsync(CancellationToken cancellationToken)
    {
        Task.Factory.StartNew(() => ExecuteAsync(cancellationToken), cancellationToken);
        return Task.CompletedTask;
    }
}


问:
How to process thousands of records faster in java
I have requirement where I have to fetch 5000 records from database and check the status in mongo for each Id .if status is not active than it should delete that record from SQL table . How to optimise it currently it is taking 4 mins and I am using linked list to fetch data from SQL..</p>

答:
I would advise putting log statements within your code timing how long each task is taking.

```<code>long start=System.currentTimeMillis();
    // fetch records from SQL database
long duration1=System.currentTimeMillis()-start;
System.out.println(duration1 + " ms to fetch from SQL");
</code>```

If your initial fetch is eating up your time, then perhaps you need to add an index to your database.  If you're accessing mongo through a slow network, then running multiple queries in parallel would speed things up.  If mongo itself is slow, then perhaps you need to index the field you're querying in mongo.

Timing each operation will help you narrow down what part of your application is behaving slowly.

Body:
I would advise putting log statements within your code timing how long each task is taking.

long start=System.currentTimeMillis();
    // fetch records from SQL database
long duration1=System.currentTimeMillis()-start;
System.out.println(duration1 + " ms to fetch from SQL");

If your initial fetch is eating up your time, then perhaps you need to add an index to your database.  If you're accessing mongo through a slow network, then running multiple queries in parallel would speed things up.  If mongo itself is slow, then perhaps you need to index the field you're querying in mongo.

Timing each operation will help you narrow down what part of your application is behaving slowly.


问:
Joining tables on 2 conditions caused the creation of a duplicate column. If I try to SELECT that column I get an ''Invalid Identifier'' error
Table: A

```<code>| ID  | Name    |
| --  | ------- |
| 1   | John    |
| 2   | Micheal |
| 3   | Mary    |
</code>```

Table B:

```<code>| ID  | Date     | Bonus |
| --  | -------- | ----- |
| 1   | 01/01/09 | 1200  |
| 1   | 01/07/12 | 4000  |
| 1   | 12/05/14 | 2500  |
| 3   | 01/01/09 | 0     |
| 3   | 11/10/17 | 1850  |
| 2   | 08/01/16 | 2500  |
| ... |    ...   |  ...  |
</code>```

I have these 2 tables. My goal to write a query that retreives the name, the lastest date available for that person and the bonus coresponding to both that date and that name.

Here's the code I have,

```<code>SELECT NAME, date_max, BONUS FROM
((SELECT A.ID, MAX(A.DATE) as date_max FROM
table_A A JOIN table_B B
USING (ID)
GROUP BY ID) C
JOIN table_B D
ON (C.ID = D.ID AND date_max = D.DATE))
</code>```

The problem is that by joining on two conditions (last line) I duplicated the ID column in the result of my inner query and now when I try to execute the outer SELECT I get the invalid identifier error. Please help me fix this

答:
Using pure sql, a way would be this:

```<code>select ta.name, tb.Date, tb.Bonus
from TableA ta
  left join TableB tb
      on ta.ID = tb.ID
  left join (
    select ID, max(b.Date) as Date
    from TableA a
      join TableB b
        on a.ID = b.ID
      group by ID
    ) m
  on ta.ID = m.ID
 and tb.date = m.date
</code>```

Or most voted answer in:
Fetch the row which has the Max value for a column

Using window functions, another way would be:

```<code> select t.name, t.Date, t.Bonus,
 from (
   select ta.name, tb.Date, tb.Bonus,
     max(tb.Date) over (partition by ta.ID) as maxDate
   from TableA ta
     left join TableB tb
       on ta.ID = tb.ID
     ) t
 where t.maxDate = t.Date
</code>```

Body:
Table: A

| ID  | Name    |
| --  | ------- |
| 1   | John    |
| 2   | Micheal |
| 3   | Mary    |

Table B:

| ID  | Date     | Bonus |
| --  | -------- | ----- |
| 1   | 01/01/09 | 1200  |
| 1   | 01/07/12 | 4000  |
| 1   | 12/05/14 | 2500  |
| 3   | 01/01/09 | 0     |
| 3   | 11/10/17 | 1850  |
| 2   | 08/01/16 | 2500  |
| ... |    ...   |  ...  |

I have these 2 tables. My goal to write a query that retreives the name, the lastest date available for that person and the bonus coresponding to both that date and that name.

Here's the code I have,

SELECT NAME, date_max, BONUS FROM
((SELECT A.ID, MAX(A.DATE) as date_max FROM
table_A A JOIN table_B B
USING (ID)
GROUP BY ID) C
JOIN table_B D
ON (C.ID = D.ID AND date_max = D.DATE))

The problem is that by joining on two conditions (last line) I duplicated the ID column in the result of my inner query and now when I try to execute the outer SELECT I get the invalid identifier error. Please help me fix this

Body:
Using pure sql, a way would be this:

select ta.name, tb.Date, tb.Bonus
from TableA ta
  left join TableB tb
      on ta.ID = tb.ID
  left join (
    select ID, max(b.Date) as Date
    from TableA a
      join TableB b
        on a.ID = b.ID
      group by ID
    ) m
  on ta.ID = m.ID
 and tb.date = m.date

Or most voted answer in:
Fetch the row which has the Max value for a column

Using window functions, another way would be:

 select t.name, t.Date, t.Bonus,
 from (
   select ta.name, tb.Date, tb.Bonus,
     max(tb.Date) over (partition by ta.ID) as maxDate
   from TableA ta
     left join TableB tb
       on ta.ID = tb.ID
     ) t
 where t.maxDate = t.Date


问:
Endless loop with std::distance on custom list
For the fun of it, I implemented a std::list similar container by myself.

I will never use it in reality. Just practising . . .

During the comparison of my implemented functionality with the std::list, I found a severe problem.

Testing std::distance with invalid parameters, as part of a simple unit test, shows different results.

Of course I expect UB and indeterminate results, but std::distance on my implementation goes into an endless loop, while it does not with a std::list. Why?

Why is my implementation causing an endles loop with std::distance?

I followd link1 and link2 in CPP reference to the source code of std::distance and tried to reproduce it. But this works also for my implemenation.

Test/driver code:

```<code>int main() {

    // std::list works. No endless loop.
    std::list<int> list1{ 1, 2, 3, 4, 5 };
    std::cout << std::distance(list1.end(), list1.begin()) << '\n';

    // Custom list
    List<int> list2{ 1, 2, 3, 4, 5 };

    // Delta works
    std::cout << list2.begin() - list2.end() << '\n';
    std::cout << list2.end() - list2.begin() << '\n';

    // Hopp Count works
    List<int>::iterator i = list2.end();
    int counter = 0;
    while (i != list2.end()) {
        ++counter;
        ++i;
    }
    std::cout << counter << '\n';

    // Distance will go into endless loop ****************************
    std::cout << std::distance(list2.end(), list2.begin()) << '\n';
}
</code>```

What is wrong with my implementation?

Please see the full source code below.

```<code>#include <iostream>
#include <iterator>
#include <vector>
#include <type_traits>
#include <initializer_list>
#include <algorithm>
#include <list>

// ------------------------------------------------------------------------------------------------
// This would be in a header file -----------------------------------------------------------------

// Type trait helper to identify iterators --------------------------------------------------------
template<typename T, typename = void>
struct is_iterator { static constexpr bool value = false; };
template<typename T>
struct is_iterator<T, typename std::enable_if<!std::is_same<typename std::iterator_traits<T>::value_type, void>::value>::type> {
    static constexpr bool value = true;
};

// The List class ---------------------------------------------------------------------------------
template <typename T>
class List {
    // Sub class for a Node -----------
    struct Node {
        Node* next{};
        Node* previous{};
        T data{};
        Node(Node* const n, Node* const p, const T& d) : next(n), previous(p), data(d) {}
        Node(Node* const n, Node* const p) : next(n), previous(p) {}
        Node() {}
    };

    // Private list data and functions --------
    size_t numberOfElements{};
    Node* head{};
    void init() { head = new Node(); head->next = head; head->previous = head; numberOfElements = 0; }

public:
    struct iterator;    // Forward declaration

    // Constructor --------------------
    List() { init(); }
    explicit List(const size_t count, const T& value) { init(); insert(begin(), count, value); };
    explicit List(const size_t count) { init(); insert(begin(), count); }
    template <typename Iter>
    List(const Iter& first, const Iter& last) { init(); insert(begin(),first, last); }
    List(const List& other) { init(), insert(begin(), other.begin(), other.end()); };
    List(List&& other) : head(other.head), numberOfElements(other.numberOfElements) { other.init(); }
    List(const std::initializer_list<T>& il) { init(); insert(begin(), il.begin(), il.end()); }
    template <int N> List(const T(&other)[N]) { init(); insert(begin(), std::begin(other), std::end(other)); }
    template <int N> List(T(&other)[N]) { init(); insert(begin(), std::begin(other), std::end(other)); }

    // Assignment ---------------------
    List& operator =(const List& other) { clear(); insert(begin(), other.begin(), other.end()); return *this; }
    List& operator =(List&& other) { clear(); head = other.head; numberOfElements = other.numberOfElements; other.init(); return *this; }
    List& operator =(const std::initializer_list<T>& il) { clear(); insert(begin(),il.begin(),il.end()); return *this; }
    template <int N> List& operator =(const T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }
    template <int N> List& operator =(T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this;}

    void assign(const size_t count, const T& value) { clear(); insert(begin(), count, value); }
    void assign(const std::initializer_list<T>& il) { clear(); insert(begin(), il.begin(), il.end()); }
    template <typename Iter> void assign(const Iter& first, const Iter& last) { clear(); insert(begin(), first, last);}
    template <int N> void assign(const T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }
    template <int N> void assign(T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }

    // Destructor ---------------------
    ~List() { clear(); }

    // Element Access -----------------
    T& front() { return *begin(); }
    T& back() { return *(--end()); }

    // Iterators ----------------------
    iterator begin() const { return iterator(head->next, head); }
    iterator end() const { return iterator(head, head); }

    // Capacity -----------------------
    size_t size() const { return numberOfElements; }
    bool empty() { return size() == 0; }

    // Modifiers ----------------------
    void clear();

    iterator insert(const iterator& insertBeforePosition, const T& value);
    iterator insert(const iterator& insertBeforePosition);
    template <class Iter, std::enable_if_t<is_iterator<Iter>::value, bool> = true>
    iterator insert(const iterator& insertBeforePosition, const Iter& first, const Iter& last);
    iterator insert(const iterator& insertBeforePosition, const size_t& count, const T& value);
    iterator insert(const iterator& insertBeforePosition, const std::initializer_list<T>& il);

    iterator erase(const iterator& posToDelete);
    iterator erase(const iterator& first, const iterator& last);

    void push_back(const T& d) { insert(end(), d); }
    void pop_back() { erase(--end()); };

    void push_front(const T& d) { insert(begin(), d); }
    void pop_front() { erase(begin()); };

    void resize(size_t count);
    void resize(size_t count, const T& value);

    void swap(List& other) { std::swap(head, other.head); std::swap(numberOfElements, other.numberOfElements); }

     // Operations --------------------
    void reverse();

    // Non standard inefficient functions --------------------------
    T& operator[](const size_t index) const { return begin()[index]; }

    // ------------------------------------------------------------------------
    // Define iterator capability ---------------------------------------------
    struct iterator {

        // Definitions ----------------
        using iterator_category = std::bidirectional_iterator_tag;
        using difference_type = std::ptrdiff_t;
        using value_type = T;
        using pointer = T*;
        using reference = T&;

        // Data -----------------------
        Node* iter{};
        Node* head{};

        // Constructor ----------------
        iterator(Node*const node, Node* const h) : iter(node), head(h) {};
        iterator() {};

        // Dereferencing --------------
        reference operator*() const { return iter->data; }
        reference operator->() const { return &**this; }

        // Arithmetic operations ------
        iterator operator++() { if (iter != head) iter = iter->next; return *this; }
        iterator operator++(int) { iterator tmp = *this; ++* this; return tmp; }
        iterator operator--() { if (iter != head->next) iter = iter->previous; return *this; }
        iterator operator--(int) { iterator tmp = *this; --* this; return tmp; }

        iterator operator +(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)++temp; else while (k++)--temp; return temp;
        }
        iterator operator +=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)++* this; else while (k++)--* this; return *this;
        };
        iterator operator -(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)--temp; else while (k++)++temp; return temp;
        }
        iterator operator -=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)--* this; else while (k++)++* this; return *this;
        };
        // Comparison -----------------
        bool operator ==(const iterator& other) const { return iter == other.iter; };
        bool operator !=(const iterator& other) const { return iter != other.iter; };
        bool operator < (const iterator& other) const { return other.iter - iter < 0; };
        bool operator <= (const iterator& other) const { return other.iter - iter <= 0; };
        bool operator > (const iterator& other) const { return other.iter - iter > 0; };
        bool operator >= (const iterator& other) const { return other.iter - iter >= 0; };

        // Special non standard functions -----------------
        difference_type operator-(const iterator& other) const;
        reference operator[] (const size_t index);
    };
};

// ------------------------------------------------------------------------------------------------
// Implementation of list functions. This would normally go into a TCC file -----------------------

// List class functions ---------------
template <typename T>
void List<T>::clear() {

    for (Node* nextNode{}, * currentNode(head->next); currentNode != head; currentNode = nextNode) {
        nextNode = currentNode->next;
        delete currentNode;
    }
    init();
}
template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const T& value)
{
    Node* nodeInsertBeforePosition = insertBeforePosition.iter;
    Node* newNode = new Node(nodeInsertBeforePosition, nodeInsertBeforePosition->previous, value);
    nodeInsertBeforePosition->previous = newNode;
    (newNode->previous)->next = newNode;
    ++numberOfElements;
    return iterator(newNode, head);
}
template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition)
{
    Node* nodeInsertBeforePosition = insertBeforePosition.iter;
    Node* newNode = new Node(nodeInsertBeforePosition, nodeInsertBeforePosition->previous);
    nodeInsertBeforePosition->previous = newNode;
    (newNode->previous)->next = newNode;
    ++numberOfElements;
    return iterator(newNode, head);
}

template <typename T>
template <class Iter, std::enable_if_t<is_iterator<Iter>::value, bool>>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const Iter& first, const Iter& last) {
    iterator result(insertBeforePosition.iter, head);
    if (first != last) {
        result = insert(insertBeforePosition, *first);
        Iter i(first);
        for (++i; i != last; ++i)
            insert(insertBeforePosition, *i);
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const size_t& count, const T& value) {

    iterator result(insertBeforePosition.iter, head);
    if (count != 0u) {
        result = insert(insertBeforePosition, value);
        for (size_t i{ 1u }; i < count; ++i)
            insert(insertBeforePosition, value);
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const std::initializer_list<T>& il) {
    return insert(insertBeforePosition, il.begin(), il.end());
}

template <typename T>
typename List<T>::iterator List<T>::erase(const List<T>::iterator& posToDelete) {

    iterator result = posToDelete;
    ++result;

    Node* nodeToDelete = posToDelete.iter;

    if (nodeToDelete != head) {

        nodeToDelete->previous->next = nodeToDelete->next;
        nodeToDelete->next->previous = nodeToDelete->previous;

        delete nodeToDelete;
        --numberOfElements;
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::erase(const List<T>::iterator& first, const List<T>::iterator& last) {
    iterator result{ end() };
    if (first == begin() && last == end())
        clear();
    else {
        while (first != last)
            first = erase(first);
        result = last;
    }
    return result;
}

template <typename T>
void List<T>::resize(size_t count) {
    if (numberOfElements < count)
        for (size_t i{ numberOfElements }; i < count; ++i)
            insert(end());
    else
        while (count--)
            pop_back();
}
template <typename T>
void List<T>::resize(size_t count, const T& value) {
    if (numberOfElements < count)
        for (size_t i{ numberOfElements }; i < count; ++i)
            insert(end(),value);
    else
        while (count--)
            pop_back();
}
template <typename T>
void List<T>::reverse() {
    const Node* oldHead = head;

    for (Node* nptr = head; ; nptr = nptr->previous) {
        std::swap(nptr->next, nptr->previous);
        if (nptr->previous == oldHead) // Previous was the original next
            break;
    }
}

// ------------------------------------
// Iterator functions -----------------
template <typename T>
typename List<T>::iterator::difference_type List<T>::iterator::operator-(const iterator& other) const {

    difference_type result{};
    Node* nptr = head;

    int indexThis{ -1 }, indexOther{ -1 }, index{};

    do {
        nptr = nptr->next;
        if (nptr == iter)
            indexThis = index;
        if (nptr == other.iter)
            indexOther = index;
        ++index;
    } while (nptr != head);

    if (indexThis >= 0 and indexOther >= 0)
        result = indexThis - indexOther;
    return result;
}
template <typename T>
typename List<T>::iterator::reference List<T>::iterator::operator[] (const size_t index) {
    Node* nptr = head->next;
    for (size_t i{}; i < index and nptr != head; ++i, nptr = nptr->next)
        ;
    return nptr->data;
}

// ------------------------------------------------------------------------------------------------
// This would be in a cpp file --------------------------------------------------------------------
int main() {

    // std::list works
    std::list<int> list1{ 1, 2, 3, 4, 5 };
    std::cout << std::distance(list1.end(), list1.begin()) << '\n';

    // Custom list
    List<int> list2{ 1, 2, 3, 4, 5 };

    // Delta works
    std::cout << list2.begin() - list2.end() << '\n';
    std::cout << list2.end() - list2.begin() << '\n';

    // Hopp Count works
    List<int>::iterator i = list2.end();
    int counter = 0;
    while (i != list2.end()) {
        ++counter;
        ++i;
    }
    std::cout << counter << '\n';

    // Distance will go into endless loop ****************************
    std::cout << std::distance(list2.end(), list2.begin()) << '\n';
}
</code>```

答:
Based on the good comment of AlanBirtles, I found the bug.

I build in (already in the first versions) a wrong additional sentinel for the pre increment and pre decrement operator of the iterator.

The correct version is:

```<code>iterator operator++() { iter = iter->next; return *this; }
iterator operator--() { iter = iter->previous; return *this; }
</code>```

I originally planned to delete the question, but because of the superb comments, I will leave it. Thank you.

Body:
For the fun of it, I implemented a std::list similar container by myself.

I will never use it in reality. Just practising . . .

During the comparison of my implemented functionality with the std::list, I found a severe problem.

Testing std::distance with invalid parameters, as part of a simple unit test, shows different results.

Of course I expect UB and indeterminate results, but std::distance on my implementation goes into an endless loop, while it does not with a std::list. Why?

Why is my implementation causing an endles loop with std::distance?

I followd link1 and link2 in CPP reference to the source code of std::distance and tried to reproduce it. But this works also for my implemenation.

Test/driver code:

int main() {

    // std::list works. No endless loop.
    std::list<int> list1{ 1, 2, 3, 4, 5 };
    std::cout << std::distance(list1.end(), list1.begin()) << '\n';

    // Custom list
    List<int> list2{ 1, 2, 3, 4, 5 };

    // Delta works
    std::cout << list2.begin() - list2.end() << '\n';
    std::cout << list2.end() - list2.begin() << '\n';

    // Hopp Count works
    List<int>::iterator i = list2.end();
    int counter = 0;
    while (i != list2.end()) {
        ++counter;
        ++i;
    }
    std::cout << counter << '\n';

    // Distance will go into endless loop ****************************
    std::cout << std::distance(list2.end(), list2.begin()) << '\n';
}

What is wrong with my implementation?

Please see the full source code below.

#include <iostream>
#include <iterator>
#include <vector>
#include <type_traits>
#include <initializer_list>
#include <algorithm>
#include <list>

// ------------------------------------------------------------------------------------------------
// This would be in a header file -----------------------------------------------------------------

// Type trait helper to identify iterators --------------------------------------------------------
template<typename T, typename = void>
struct is_iterator { static constexpr bool value = false; };
template<typename T>
struct is_iterator<T, typename std::enable_if<!std::is_same<typename std::iterator_traits<T>::value_type, void>::value>::type> {
    static constexpr bool value = true;
};

// The List class ---------------------------------------------------------------------------------
template <typename T>
class List {
    // Sub class for a Node -----------
    struct Node {
        Node* next{};
        Node* previous{};
        T data{};
        Node(Node* const n, Node* const p, const T& d) : next(n), previous(p), data(d) {}
        Node(Node* const n, Node* const p) : next(n), previous(p) {}
        Node() {}
    };

    // Private list data and functions --------
    size_t numberOfElements{};
    Node* head{};
    void init() { head = new Node(); head->next = head; head->previous = head; numberOfElements = 0; }

public:
    struct iterator;    // Forward declaration

    // Constructor --------------------
    List() { init(); }
    explicit List(const size_t count, const T& value) { init(); insert(begin(), count, value); };
    explicit List(const size_t count) { init(); insert(begin(), count); }
    template <typename Iter>
    List(const Iter& first, const Iter& last) { init(); insert(begin(),first, last); }
    List(const List& other) { init(), insert(begin(), other.begin(), other.end()); };
    List(List&& other) : head(other.head), numberOfElements(other.numberOfElements) { other.init(); }
    List(const std::initializer_list<T>& il) { init(); insert(begin(), il.begin(), il.end()); }
    template <int N> List(const T(&other)[N]) { init(); insert(begin(), std::begin(other), std::end(other)); }
    template <int N> List(T(&other)[N]) { init(); insert(begin(), std::begin(other), std::end(other)); }

    // Assignment ---------------------
    List& operator =(const List& other) { clear(); insert(begin(), other.begin(), other.end()); return *this; }
    List& operator =(List&& other) { clear(); head = other.head; numberOfElements = other.numberOfElements; other.init(); return *this; }
    List& operator =(const std::initializer_list<T>& il) { clear(); insert(begin(),il.begin(),il.end()); return *this; }
    template <int N> List& operator =(const T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }
    template <int N> List& operator =(T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this;}

    void assign(const size_t count, const T& value) { clear(); insert(begin(), count, value); }
    void assign(const std::initializer_list<T>& il) { clear(); insert(begin(), il.begin(), il.end()); }
    template <typename Iter> void assign(const Iter& first, const Iter& last) { clear(); insert(begin(), first, last);}
    template <int N> void assign(const T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }
    template <int N> void assign(T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }

    // Destructor ---------------------
    ~List() { clear(); }

    // Element Access -----------------
    T& front() { return *begin(); }
    T& back() { return *(--end()); }

    // Iterators ----------------------
    iterator begin() const { return iterator(head->next, head); }
    iterator end() const { return iterator(head, head); }

    // Capacity -----------------------
    size_t size() const { return numberOfElements; }
    bool empty() { return size() == 0; }

    // Modifiers ----------------------
    void clear();

    iterator insert(const iterator& insertBeforePosition, const T& value);
    iterator insert(const iterator& insertBeforePosition);
    template <class Iter, std::enable_if_t<is_iterator<Iter>::value, bool> = true>
    iterator insert(const iterator& insertBeforePosition, const Iter& first, const Iter& last);
    iterator insert(const iterator& insertBeforePosition, const size_t& count, const T& value);
    iterator insert(const iterator& insertBeforePosition, const std::initializer_list<T>& il);

    iterator erase(const iterator& posToDelete);
    iterator erase(const iterator& first, const iterator& last);

    void push_back(const T& d) { insert(end(), d); }
    void pop_back() { erase(--end()); };

    void push_front(const T& d) { insert(begin(), d); }
    void pop_front() { erase(begin()); };

    void resize(size_t count);
    void resize(size_t count, const T& value);

    void swap(List& other) { std::swap(head, other.head); std::swap(numberOfElements, other.numberOfElements); }

     // Operations --------------------
    void reverse();

    // Non standard inefficient functions --------------------------
    T& operator[](const size_t index) const { return begin()[index]; }

    // ------------------------------------------------------------------------
    // Define iterator capability ---------------------------------------------
    struct iterator {

        // Definitions ----------------
        using iterator_category = std::bidirectional_iterator_tag;
        using difference_type = std::ptrdiff_t;
        using value_type = T;
        using pointer = T*;
        using reference = T&;

        // Data -----------------------
        Node* iter{};
        Node* head{};

        // Constructor ----------------
        iterator(Node*const node, Node* const h) : iter(node), head(h) {};
        iterator() {};

        // Dereferencing --------------
        reference operator*() const { return iter->data; }
        reference operator->() const { return &**this; }

        // Arithmetic operations ------
        iterator operator++() { if (iter != head) iter = iter->next; return *this; }
        iterator operator++(int) { iterator tmp = *this; ++* this; return tmp; }
        iterator operator--() { if (iter != head->next) iter = iter->previous; return *this; }
        iterator operator--(int) { iterator tmp = *this; --* this; return tmp; }

        iterator operator +(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)++temp; else while (k++)--temp; return temp;
        }
        iterator operator +=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)++* this; else while (k++)--* this; return *this;
        };
        iterator operator -(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)--temp; else while (k++)++temp; return temp;
        }
        iterator operator -=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)--* this; else while (k++)++* this; return *this;
        };
        // Comparison -----------------
        bool operator ==(const iterator& other) const { return iter == other.iter; };
        bool operator !=(const iterator& other) const { return iter != other.iter; };
        bool operator < (const iterator& other) const { return other.iter - iter < 0; };
        bool operator <= (const iterator& other) const { return other.iter - iter <= 0; };
        bool operator > (const iterator& other) const { return other.iter - iter > 0; };
        bool operator >= (const iterator& other) const { return other.iter - iter >= 0; };

        // Special non standard functions -----------------
        difference_type operator-(const iterator& other) const;
        reference operator[] (const size_t index);
    };
};

// ------------------------------------------------------------------------------------------------
// Implementation of list functions. This would normally go into a TCC file -----------------------

// List class functions ---------------
template <typename T>
void List<T>::clear() {

    for (Node* nextNode{}, * currentNode(head->next); currentNode != head; currentNode = nextNode) {
        nextNode = currentNode->next;
        delete currentNode;
    }
    init();
}
template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const T& value)
{
    Node* nodeInsertBeforePosition = insertBeforePosition.iter;
    Node* newNode = new Node(nodeInsertBeforePosition, nodeInsertBeforePosition->previous, value);
    nodeInsertBeforePosition->previous = newNode;
    (newNode->previous)->next = newNode;
    ++numberOfElements;
    return iterator(newNode, head);
}
template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition)
{
    Node* nodeInsertBeforePosition = insertBeforePosition.iter;
    Node* newNode = new Node(nodeInsertBeforePosition, nodeInsertBeforePosition->previous);
    nodeInsertBeforePosition->previous = newNode;
    (newNode->previous)->next = newNode;
    ++numberOfElements;
    return iterator(newNode, head);
}

template <typename T>
template <class Iter, std::enable_if_t<is_iterator<Iter>::value, bool>>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const Iter& first, const Iter& last) {
    iterator result(insertBeforePosition.iter, head);
    if (first != last) {
        result = insert(insertBeforePosition, *first);
        Iter i(first);
        for (++i; i != last; ++i)
            insert(insertBeforePosition, *i);
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const size_t& count, const T& value) {

    iterator result(insertBeforePosition.iter, head);
    if (count != 0u) {
        result = insert(insertBeforePosition, value);
        for (size_t i{ 1u }; i < count; ++i)
            insert(insertBeforePosition, value);
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const std::initializer_list<T>& il) {
    return insert(insertBeforePosition, il.begin(), il.end());
}

template <typename T>
typename List<T>::iterator List<T>::erase(const List<T>::iterator& posToDelete) {

    iterator result = posToDelete;
    ++result;

    Node* nodeToDelete = posToDelete.iter;

    if (nodeToDelete != head) {

        nodeToDelete->previous->next = nodeToDelete->next;
        nodeToDelete->next->previous = nodeToDelete->previous;

        delete nodeToDelete;
        --numberOfElements;
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::erase(const List<T>::iterator& first, const List<T>::iterator& last) {
    iterator result{ end() };
    if (first == begin() && last == end())
        clear();
    else {
        while (first != last)
            first = erase(first);
        result = last;
    }
    return result;
}

template <typename T>
void List<T>::resize(size_t count) {
    if (numberOfElements < count)
        for (size_t i{ numberOfElements }; i < count; ++i)
            insert(end());
    else
        while (count--)
            pop_back();
}
template <typename T>
void List<T>::resize(size_t count, const T& value) {
    if (numberOfElements < count)
        for (size_t i{ numberOfElements }; i < count; ++i)
            insert(end(),value);
    else
        while (count--)
            pop_back();
}
template <typename T>
void List<T>::reverse() {
    const Node* oldHead = head;

    for (Node* nptr = head; ; nptr = nptr->previous) {
        std::swap(nptr->next, nptr->previous);
        if (nptr->previous == oldHead) // Previous was the original next
            break;
    }
}

// ------------------------------------
// Iterator functions -----------------
template <typename T>
typename List<T>::iterator::difference_type List<T>::iterator::operator-(const iterator& other) const {

    difference_type result{};
    Node* nptr = head;

    int indexThis{ -1 }, indexOther{ -1 }, index{};

    do {
        nptr = nptr->next;
        if (nptr == iter)
            indexThis = index;
        if (nptr == other.iter)
            indexOther = index;
        ++index;
    } while (nptr != head);

    if (indexThis >= 0 and indexOther >= 0)
        result = indexThis - indexOther;
    return result;
}
template <typename T>
typename List<T>::iterator::reference List<T>::iterator::operator[] (const size_t index) {
    Node* nptr = head->next;
    for (size_t i{}; i < index and nptr != head; ++i, nptr = nptr->next)
        ;
    return nptr->data;
}

// ------------------------------------------------------------------------------------------------
// This would be in a cpp file --------------------------------------------------------------------
int main() {

    // std::list works
    std::list<int> list1{ 1, 2, 3, 4, 5 };
    std::cout << std::distance(list1.end(), list1.begin()) << '\n';

    // Custom list
    List<int> list2{ 1, 2, 3, 4, 5 };

    // Delta works
    std::cout << list2.begin() - list2.end() << '\n';
    std::cout << list2.end() - list2.begin() << '\n';

    // Hopp Count works
    List<int>::iterator i = list2.end();
    int counter = 0;
    while (i != list2.end()) {
        ++counter;
        ++i;
    }
    std::cout << counter << '\n';

    // Distance will go into endless loop ****************************
    std::cout << std::distance(list2.end(), list2.begin()) << '\n';
}

Body:
Based on the good comment of AlanBirtles, I found the bug.

I build in (already in the first versions) a wrong additional sentinel for the pre increment and pre decrement operator of the iterator.

The correct version is:

iterator operator++() { iter = iter->next; return *this; }
iterator operator--() { iter = iter->previous; return *this; }

I originally planned to delete the question, but because of the superb comments, I will leave it. Thank you.


问:
Facebook-like photo/video/link posting plugin in BuddyPress
I am working on BuddyPress. I am new in BuddyPress. Is there any plugin, something like Facebook-like photo/video/link posting plugin at the time when we update status?

答:
Yes there is one.

Try http://premium.wpmudev.org/project/media-embeds-for-buddypress-activity


问:
How to find MySQL error log file on Windows?
I just downloaded MySQL on Windows, and I am trying to run MySQl from the command line. When I try to login as root, the server simply freezes and does nothing. If I enter the incorrect password, it denies me access, but when I enter the correct password, it's hanging.

enter image description here

I am trying to figure out where to view the MySQL log/error files, but cannot find them on my system.

答:
From the Manual

The error log is located in the data directory specified in your
my.ini file. The default data directory location is C:\Program
Files\MySQL\MySQL Server 8.0\data, or C:\ProgramData\Mysql on Windows
7 and Windows Server 2008. The C:\ProgramData directory is hidden by
default.


问:
How do units flow through matrix operations?
It seems that there are many useful applications for matrix math where not all entries in a given matrix share the same units. I want to look into type systems that could track these units and ensure we don't make mistakes (similar to a number of libraries and languages that already do dimension checking for scalar arithmetic). I'll give an example of what I am talking about, and then I have a few questions building from there.

(cribbing a random mixed-units linear programming example from here, although this is not a homework question as will hopefully become clear)

Bob’s bakery sells bagel and muffins. To bake a dozen bagels Bob needs 5 cups of flour, 2
eggs, and one cup of sugar. To bake a dozen muffins Bob needs 4 cups of flour, 4
eggs and two cups of sugar. Bob can sell bagels in $10/dozen and muffins in
$12/dozen. Bob has 50 cups of flour, 30 eggs and 20 cups of sugar. How many bagels and muffins should Bob bake in order to maximize his revenue?

So let's put that in matrix form (arbitrary concrete syntax...):

```<code> A = [ [ 5 cups of flour / dozen bagels, 4 cups of flour / dozen muffins ],
       [ 2 eggs          / dozen bagels, 4 eggs          / dozen muffins ],
       [ 1 cups of sugar / dozen bagels, 2 cups of sugar / dozen muffins ] ]

 B = [ [ 10 dollars      / dozen bagels, 12 dollars      / dozen muffins ] ]

 C = [ [ 50 cups of flour ],
       [ 30 eggs          ],
       [ 20 cups of sugar ] ]
</code>```

We now want to maximize the inner product B * X such that A * X <= C and X >= 0, an ordinary linear programming problem.

In a hypothetical language with unit checking, how would we ideally represent the types of these matrices?

I'm thinking that an m by n matrix only needs m + n units and not the full m * n units, because unless the units are distributed in a sensible way into rows and columns then the only sensible operation remaining is to add/subtract the fully general matrix with another of the exact same shape or multiply it by a scalar.

What I mean is that the arrangement of units in A is far more useful than that in:

```<code>WTF = [ [ 6 pigeons,      11 cups of sugar ],
        [ 1 cup of sugar, 27 meters        ],
        [ 2 ohms,         2 meters         ] ]
</code>```

And that furthermore situations like the latter simply don't arise in practice. (Anyone got a counterexample?)

Under this simplifying assumption, we can represent the units of a matrix with m + n units as follows. For each of the m rows, we figure out what units are common to all entries in that row, and similarly for the n columns. Let's put the row units in column vectors and the column units in row vectors because that makes Units(M) = RowUnits(M) * ColUnits(M), which seems like a nice property. So, in the example:

```<code>RowUnits(A) = [ [ cups of flour ],
                [ eggs ],
                [ cups of sugar ] ]
ColUnits(A) = [ [ dozen bagels ^ -1, dozen muffins ^ -1 ] ]

RowUnits(B) = [ [ dollars ] ]
ColUnits(B) = [ [ dozen bagels ^ -1, dozen muffins ^ -1 ] ]

RowUnits(C) = [ [ cups of flour ],
                [ eggs ],
                [ cups of sugar ] ]
ColUnits(C) = [ [ 1 ] ]
</code>```

It seems that (although I'm not sure how to prove it...) the units of M1 * M2 are RowUnits(M1 * M2) = RowUnits(M1), ColUnits(M1 * M2) = ColUnits(M2), and for the multiplication to make sense we require ColUnits(M1) * RowUnits(M2) = 1.

We can now infer units for X, because the expression A * X <= C must mean that A * X and C have the same units. This means that RowUnits(A) = RowUnits(C) (which checks out), ColUnits(X) = ColUnits(C), and RowUnits(X) is the element-wise reciprocal of the transpose of ColUnits(A), in other words RowUnits(X) = [ [ dozen bagels ], [ dozen muffins ] ].

("Hooray", I hear you cheering, "we have just gone around the moon to look at something completely obvious!")

My questions are these:

Can you think of real world examples where elements of a matrix have units that do not fall into "row units" and "column units" like this?

Can you think of an elegant way to deal with situations where the same unit is a factor in every cell, and so it could equivalently be placed in every "row" or in every "column" and thus the row units and column units are not a unique representation? What should the side condition be that holds them in "lowest terms" and removes silliness like multiplying every row by furlongs ^ 17 just so that you can multiply every column by furlongs ^ -17?

Can you prove the rules I mentioned for propagating these unit annotations through matrix multiplications?

Can you discover/show the rule for how these unit annotations propagate through matrix inverse operations? Some hand calculations I did with a 2x2 matrix suggest that the units of Inverse(M) are the element-wise reciprocal of the units of Transpose(M), but I don't know how to show it for the general case or even if it is true for the general case.

Are you aware of any academic work on these issues? Or software that performs this static analysis for programs in some language? I may be using the wrong search terms, but I am having trouble finding anything.

My real-world applications of interest are preventing screw ups in signal processing/controller software by making sure that all the filter gains etc have the correct units everywhere, using matrices like these with different units in different cells is extremely common in those applications.

答:
A very good source of information about the topic is the Book "Multidimensional analysis" by George W. Hart which is also referenced in the comments to the question.
Regarding the individual questions (mathematical results are explained in the book):

First of all, we need to introduce a little notation. The square bracket operator extracts the physical unit(s) of a matrix / matrix entry, i.e.
 gives us the unit of the entry (i, j) in the matrix A. Furthermore, the ~ operator transposes a vector / matrix and inverts its units, i.e

Then we need another result from the book which says that the units in any multipliable matrix A can be written as , i.e. the units of the matrix entries can be described by the outer product of 2 vectors a and b where a is a column vector and b^\sim is a row vector with its units inverted.

Answer to 4): the units of the inverse of a matrix A are given by
which means that the units are the element-wise reciprocal of the original units as already proposed in the original question.

Regarding 3): Yes, your rules regarding matrix multiplication are correct if the inner units are identical and thus cancel out, i.e. .

However, it would also be possible to multiply matrices where the inner column/row units are dimensionally parallel:  (here b/c informally refers to be the common unit factor by which c has to be multiplied to obtain c)

Regarding 2): Usually each row or column of a matrix refers to a specific physical quantity which induces the canonical representation for the row and column units. As an example, consider a (x,y) position covariance matrix in a Kalman Filtering application. There, it is clear that the rows and columns describe x- and y-position in a certain physical unit, e.g. all row and column units are [m], leading to a unit of [m^2] for each of the matrix elements. It would also be possible to use [m/s] and [s*m] as row and column units which would also lead to a unit of [m^2] for each element.

However, it should be clear from the problem description that the first representation is the more meaningful.

Regarding 5): There is the book by George W. Hart and a very short paper with a few key results from the book https://www.georgehart.com/research/tdm.ps . As far as implementations in software are concerned, this talk from Meeting C++ 2021 https://www.youtube.com/watch?v=4LmMwhM8ODI describes the implementation of a library that is capable of annotating matrices and vectors with physical units where all checks are done at compile time. The presented library is also able to fully handle the Discrete Kalman Filter example that is described in one of the other answers.

Body:
It seems that there are many useful applications for matrix math where not all entries in a given matrix share the same units. I want to look into type systems that could track these units and ensure we don't make mistakes (similar to a number of libraries and languages that already do dimension checking for scalar arithmetic). I'll give an example of what I am talking about, and then I have a few questions building from there.

(cribbing a random mixed-units linear programming example from here, although this is not a homework question as will hopefully become clear)

Bob’s bakery sells bagel and muffins. To bake a dozen bagels Bob needs 5 cups of flour, 2
eggs, and one cup of sugar. To bake a dozen muffins Bob needs 4 cups of flour, 4
eggs and two cups of sugar. Bob can sell bagels in $10/dozen and muffins in
$12/dozen. Bob has 50 cups of flour, 30 eggs and 20 cups of sugar. How many bagels and muffins should Bob bake in order to maximize his revenue?

So let's put that in matrix form (arbitrary concrete syntax...):

 A = [ [ 5 cups of flour / dozen bagels, 4 cups of flour / dozen muffins ],
       [ 2 eggs          / dozen bagels, 4 eggs          / dozen muffins ],
       [ 1 cups of sugar / dozen bagels, 2 cups of sugar / dozen muffins ] ]

 B = [ [ 10 dollars      / dozen bagels, 12 dollars      / dozen muffins ] ]

 C = [ [ 50 cups of flour ],
       [ 30 eggs          ],
       [ 20 cups of sugar ] ]

We now want to maximize the inner product B * X such that A * X <= C and X >= 0, an ordinary linear programming problem.

In a hypothetical language with unit checking, how would we ideally represent the types of these matrices?

I'm thinking that an m by n matrix only needs m + n units and not the full m * n units, because unless the units are distributed in a sensible way into rows and columns then the only sensible operation remaining is to add/subtract the fully general matrix with another of the exact same shape or multiply it by a scalar.

What I mean is that the arrangement of units in A is far more useful than that in:

WTF = [ [ 6 pigeons,      11 cups of sugar ],
        [ 1 cup of sugar, 27 meters        ],
        [ 2 ohms,         2 meters         ] ]

And that furthermore situations like the latter simply don't arise in practice. (Anyone got a counterexample?)

Under this simplifying assumption, we can represent the units of a matrix with m + n units as follows. For each of the m rows, we figure out what units are common to all entries in that row, and similarly for the n columns. Let's put the row units in column vectors and the column units in row vectors because that makes Units(M) = RowUnits(M) * ColUnits(M), which seems like a nice property. So, in the example:

RowUnits(A) = [ [ cups of flour ],
                [ eggs ],
                [ cups of sugar ] ]
ColUnits(A) = [ [ dozen bagels ^ -1, dozen muffins ^ -1 ] ]

RowUnits(B) = [ [ dollars ] ]
ColUnits(B) = [ [ dozen bagels ^ -1, dozen muffins ^ -1 ] ]

RowUnits(C) = [ [ cups of flour ],
                [ eggs ],
                [ cups of sugar ] ]
ColUnits(C) = [ [ 1 ] ]

It seems that (although I'm not sure how to prove it...) the units of M1 * M2 are RowUnits(M1 * M2) = RowUnits(M1), ColUnits(M1 * M2) = ColUnits(M2), and for the multiplication to make sense we require ColUnits(M1) * RowUnits(M2) = 1.

We can now infer units for X, because the expression A * X <= C must mean that A * X and C have the same units. This means that RowUnits(A) = RowUnits(C) (which checks out), ColUnits(X) = ColUnits(C), and RowUnits(X) is the element-wise reciprocal of the transpose of ColUnits(A), in other words RowUnits(X) = [ [ dozen bagels ], [ dozen muffins ] ].

("Hooray", I hear you cheering, "we have just gone around the moon to look at something completely obvious!")

My questions are these:

Can you think of real world examples where elements of a matrix have units that do not fall into "row units" and "column units" like this?

Can you think of an elegant way to deal with situations where the same unit is a factor in every cell, and so it could equivalently be placed in every "row" or in every "column" and thus the row units and column units are not a unique representation? What should the side condition be that holds them in "lowest terms" and removes silliness like multiplying every row by furlongs ^ 17 just so that you can multiply every column by furlongs ^ -17?

Can you prove the rules I mentioned for propagating these unit annotations through matrix multiplications?

Can you discover/show the rule for how these unit annotations propagate through matrix inverse operations? Some hand calculations I did with a 2x2 matrix suggest that the units of Inverse(M) are the element-wise reciprocal of the units of Transpose(M), but I don't know how to show it for the general case or even if it is true for the general case.

Are you aware of any academic work on these issues? Or software that performs this static analysis for programs in some language? I may be using the wrong search terms, but I am having trouble finding anything.

My real-world applications of interest are preventing screw ups in signal processing/controller software by making sure that all the filter gains etc have the correct units everywhere, using matrices like these with different units in different cells is extremely common in those applications.


问:
Remapping minus key on numeric keyboard
I'm new to linux and even after after searching for more than an hour and help from my IT friends I didn't find a "name" for minus key on numeric keyboard. I'm searching for something like

```<code> key <PAUS> { [ Home ] };
 key <INS>  { [ End ] };
</code>```

specifically that first part out of the brackets. I've already tried

```<code>key <MNS>, key <MINS>, key <MNUS>
</code>```

but it broke my keyboard (I ended up with EN keyboard), which I assume means, there's a mistake in the code.

Does anybody know the "name"? Thanks.

答:
Open a terminal and:

```<code>xev -event keyboard
</code>```

Press the minus key on numeric keyboard and see the key code.

On my system I obtain this output:

```<code>KeyRelease event, serial 28, synthetic NO, window 0x1c00001,
    root 0x31b, subw 0x0, time 1053670, (75,41), root:(1768,207),
    state 0x0, keycode 82 (keysym 0xffad, KP_Subtract), same_screen YES,
    XLookupString gives 1 bytes: (2d) "-"
    XFilterEvent returns: False
</code>```

The keycode is 82

I see from your tag that you are using Ubuntu 20.04.

You can see that the file /usr/share/X11/xkb/symbols/pc has the line:

```<code>keycode  82 = KP_Subtract KP_Subtract KP_Subtract KP_Subtract KP_Subtract KP_Subtract XF86Prev_VMode
</code>```

Title: Remapping minus key on numeric keyboard

Body:
I'm new to linux and even after after searching for more than an hour and help from my IT friends I didn't find a "name" for minus key on numeric keyboard. I'm searching for something like

 key <PAUS> { [ Home ] };
 key   { [ End ] };

specifically that first part out of the brackets. I've already tried

key <MNS>, key <MINS>, key <MNUS>

but it broke my keyboard (I ended up with EN keyboard), which I assume means, there's a mistake in the code.

Does anybody know the "name"? Thanks.

Body:
Open a terminal and:

xev -event keyboard

Press the minus key on numeric keyboard and see the key code.

On my system I obtain this output:

KeyRelease event, serial 28, synthetic NO, window 0x1c00001,
    root 0x31b, subw 0x0, time 1053670, (75,41), root:(1768,207),
    state 0x0, keycode 82 (keysym 0xffad, KP_Subtract), same_screen YES,
    XLookupString gives 1 bytes: (2d) "-"
    XFilterEvent returns: False

The keycode is 82

I see from your tag that you are using Ubuntu 20.04.

You can see that the file /usr/share/X11/xkb/symbols/pc has the line:

keycode  82 = KP_Subtract KP_Subtract KP_Subtract KP_Subtract KP_Subtract KP_Subtract XF86Prev_VMode


问:
can't delete & update a document in mongodb by id, in express
i work by NODE.JS by express, and mongo , mongodb, and execute CRUD by them.
i can do GET and CREATE new document, BUT i can't execute DELETE & UPDATE using ID by same utilities.

note: this id, is valid and exist in my database. i checked this.

when i try this code, i receive this message in console:

connected to MONGOdb...

null

my DELETE code is in belove:

```<code>const mymongoose = require('mongoose');
mymongoose.connect('mongodb://localhost/mongo-exercises')
.then(() => console.log('connected to MONGOdb...'))
.catch(er => console.error('could not connect to mongodb', er));

const courseSchema = new mymongoose.Schema({
name: String,
author: String,
tags: [String],
date: {type: Date, default: Date.now},
isPublished: Boolean,
price: Number
});

const Course = mymongoose.model('Course', courseSchema);

//Remove code:
async function removeCourse(id) {
const course = await Course.findByIdAndRemove(id);
console.log(course);
}
removeCourse('5a68ff090c553064a218a547');
</code>```

答:
Based on the code removeCourse('5a68ff090c553064a218a547'); The Id is being passed as a string instead of a mongodb object Id.

Try formatting / converting the string Id you have to an object Id like this.

```<code>mongoose.Types.ObjectId('5a68ff090c553064a218a547');
</code>```

Related question And other available answers for this.

Body:
i work by NODE.JS by express, and mongo , mongodb, and execute CRUD by them.
i can do GET and CREATE new document, BUT i can't execute DELETE & UPDATE using ID by same utilities.

note: this id, is valid and exist in my database. i checked this.

when i try this code, i receive this message in console:

connected to MONGOdb...

null

my DELETE code is in belove:

const mymongoose = require('mongoose');
mymongoose.connect('mongodb://localhost/mongo-exercises')
.then(() => console.log('connected to MONGOdb...'))
.catch(er => console.error('could not connect to mongodb', er));

const courseSchema = new mymongoose.Schema({
name: String,
author: String,
tags: [String],
date: {type: Date, default: Date.now},
isPublished: Boolean,
price: Number
});

const Course = mymongoose.model('Course', courseSchema);

//Remove code:
async function removeCourse(id) {
const course = await Course.findByIdAndRemove(id);
console.log(course);
}
removeCourse('5a68ff090c553064a218a547');

Body:
Based on the code removeCourse('5a68ff090c553064a218a547'); The Id is being passed as a string instead of a mongodb object Id.

Try formatting / converting the string Id you have to an object Id like this.

mongoose.Types.ObjectId('5a68ff090c553064a218a547');

Related question And other available answers for this.


问:
Getting Specific Facebook User Data Fields On iPhone iOS
Hi, I am capturing the Facebook details in string format, but I want id and username only. How do I separate this data out. My data is:

the fbString is

```<code>{
    "id":"100002257451995",
    "name":"Mustacheiphone Mustache",
    "first_name":"Mustacheiphone",
    "last_name":"Mustache",
    "link":"http:\/\/www.facebook.com\/profile.php?id=100002257451995",
    "gender":"male","email":"mustacheiphone\u0040gmail.com",
    "timezone":5.5,"locale":"en_US","verified":true,
    "updated_time":"2011-04-11T11:28:22+0000"
}
</code>```

答:
```<code>i got it this way i was capture the userid

SBJsonParser    *parser = [[SBJsonParser alloc]init];
    NSDictionary *facebookInfo = [[parser objectWithString:fbString error:nil]     copy];
    [parser release];

    if(facebookInfo != nil)
    {
        //NSDictionary *data = (NSDictionary *) [facebookInfo objectAtIndex:0];
        NSString *faceBoookID   = (NSString *) [facebookInfo objectForKey:@"id"];
        NSLog(@"the faceBookID is %@",faceBoookID);
    //  appDelegate.FBID        = faceBoookID;
        NSString *useremail     = (NSString *) [facebookInfo objectForKey:@"email"];
        NSLog(@"the faceBookemail is %@",useremail);
    //  appDelegate.FBEMAIL     = useremail;
    }
</code>```

Body:
Hi, I am capturing the Facebook details in string format, but I want id and username only. How do I separate this data out. My data is:

the fbString is

{
    "id":"100002257451995",
    "name":"Mustacheiphone Mustache",
    "first_name":"Mustacheiphone",
    "last_name":"Mustache",
    "link":"http:\/\/www.facebook.com\/profile.php?id=100002257451995",
    "gender":"male","email":"mustacheiphone\u0040gmail.com",
    "timezone":5.5,"locale":"en_US","verified":true,
    "updated_time":"2011-04-11T11:28:22+0000"
}


问:
How to upload video in Shopify
I want to upload video in my shopify store my code has for loop

```<code>   <div class="product-slider-show">
      <div class="owl-carousel">
         {% for image in product.images %}
         <div class="swiper-product-image">
            <a class="cloud-zoom-gallery sub-image" id="product-image-options-" href="{{ image.src  | img_url: 'master' }}" title="{{ featured_img_alt }}"
               rel="useZoom: 'product-cloud-zoom', smallImage: '{{ image.src | img_url: 'master' }}'" data-pos="{{ forloop.index }}">
            <img {% if settings.lazyloading_enable %} class="lazyload" data-{% endif %}src="{{ image.src | img_url: 'master' }}" title="{{ featured_img_alt }}" alt="{{ featured_img_alt }}" />
            </a>
         </div>
         {% endfor %}
      </div>
   </div>
</code>```

When I add video html to this code, video shows up next to each pictures.

What code should I use in this for loop, so that the video can appear alone at the end?

答:
if anyone else is having this problem. This code was my solution</p>
```<code>{% for image in product.images %}
{% if forloop.first == true %}
<figure>
   <img src="{{ image.src | img_url: '1024x1024' }}" alt="{{ image.alt | escape }}" class="product_variant_image">
</figure>
{% else %}
<figure>
   <img src="{{ image.src | img_url: '1024x1024' }}" alt="{{ image.alt | escape }}">
</figure>
{% endif %}
{% endfor %}
{% for media in product.media %}
{% if media.media_type == 'video' %}
{{ media | video_tag: controls: true, preload: true, image_size: "768x" }}
{% endif %}
{% endfor %}
</code>```

Title: How to upload video in Shopify

Body:
I want to upload video in my shopify store my code has for loop

         {% for image in product.images %}

         {% endfor %}

When I add video html to this code, video shows up next to each pictures.

What code should I use in this for loop, so that the video can appear alone at the end?

Body:
if anyone else is having this problem. This code was my solution

{% for image in product.images %}
{% if forloop.first == true %}
<figure>
   <img src="{{ image.src | img_url: '1024x1024' }}" alt="{{ image.alt | escape }}" class="product_variant_image">
</figure>
{% else %}
<figure>
   <img src="{{ image.src | img_url: '1024x1024' }}" alt="{{ image.alt | escape }}">
</figure>
{% endif %}
{% endfor %}
{% for media in product.media %}
{% if media.media_type == 'video' %}
{{ media | video_tag: controls: true, preload: true, image_size: "768x" }}
{% endif %}
{% endfor %}