问:
Why do the items in my ListView.builder move after each interaction with them?
I created a StreamBuilder that displays a document snapshot of Cloud Firestore. This snapshot contains a map that should be displayed in a listview. All items are displayed as planned:

But as soon as I press a button that changes the map in Cloud Firestore, the positions of the items in the list change. That would annoy me as a user, so I want to change that. I don't know how to. . .

Here is the StreamBuilder:

```<code>StreamBuilder(
                        stream: database.count(),
                        builder: (context, AsyncSnapshot snapshot) {
                          if (snapshot.hasData) {
                            if (snapshot.data.data()['Einheiten'] != null) {
                              Map<String, dynamic> Einheiten = snapshot.data.data()['Einheiten']
                                  as Map<String, dynamic>;
                              if (snapshot.data
                                      .data()['Verfügbare Einheiten'] !=
                                  null) {
                                Map<String, dynamic> einheiten = snapshot.data
                                    .data()['Verfügbare Einheiten'] as Map<String, dynamic>;
                                return Column(
                                  mainAxisSize: MainAxisSize.max,
                                  children: [
                                    Text(
                                      'Verfügbare Einheiten: ' +
                                          einheiten['Deine Einheiten'].toString(),
                                      style: TextStyle(
                                          fontSize: 30, color: Colors.white),
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.all(15),
                                      child: ListView.builder(
                                        physics: NeverScrollableScrollPhysics(),
                                          shrinkWrap: true,
                                          itemCount: Einheiten.length,
                                          itemBuilder: (BuildContext, i) {
                                            String key =
                                                Einheiten.keys.elementAt(i);
                                            return Padding(
                                              padding: const EdgeInsets.all(8.0),
                                              child: Einheit(key,
                                                  Einheiten[key], einheiten),
                                            );
                                          }),
                                    ),
                                  ],
                                );
                              } else {
                                return Center(
                                    child: CircularProgressIndicator(
                                  color: Colors.green,
                                  backgroundColor: Colors.green,
                                ));
                              }
                            } else {
                              return Center(
                                  child: CircularProgressIndicator(
                                color: Colors.yellow,
                                backgroundColor: Colors.yellow,
                              ));
                            }
                          }
                          return Center(
                              child: CircularProgressIndicator(
                            backgroundColor: Colors.red,
                            color: Colors.red,
                          ));
                        })
</code>```

And here's the standardized item, which gives the commands that cause the items to be moved:

```<code>class Einheit extends StatefulWidget {
  String Sport;
  int number;
  Map einheiten;

  Einheit(this.Sport, this.number, this.einheiten);

  @override
  State<Einheit> createState() => _EinheitState();
}

class _EinheitState extends State<Einheit> {
  User? user;
  late DatabaseService database;

  Future connect() async {
    user = FirebaseAuth.instance.currentUser;
    database = DatabaseService(user!.email!);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    connect();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(34),
          border: Border.all(width: 2, color: Colors.white),
        ),
        child: ListTile(
          contentPadding: EdgeInsets.symmetric(horizontal: 20),
            trailing: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                InkWell(
                    onTap: () {
                      if (widget.einheiten['Deine Einheiten'] != 0) {
                          final newValue = widget.number + 1;
                          widget.number = newValue;
                          database.addE(widget.Sport, widget.number);
                          database.decreaseECount();
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                          content: Text(
                            'Du hast das von dir vorgegebene Maximum an Einheiten erreicht...',
                            textAlign: TextAlign.center,
                            style: TextStyle(color: Colors.white),
                          ),
                          backgroundColor: Colors.purple,
                        ));
                      }
                    },
                    child: Icon(Icons.add)),
                InkWell(
                    onTap: () {
                      if (widget.number != 0) {
                          final newValue = widget.number - 1;
                          widget.number = newValue;
                          database.addE(widget.Sport, widget.number);
                          database.addECount();
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                          content: Text(
                            'Du hast das von dir vorgegebene Maximum an Einheiten erreicht...',
                            textAlign: TextAlign.center,
                            style: TextStyle(color: Colors.white),
                          ),
                          backgroundColor: Colors.purple,
                        ));
                      }
                    },
                    child: Icon(Icons.remove)),
              ],
            ),
            leading: Text((widget.number).toString(),
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),),
            title: Center(
              child: Padding(
                padding:
                    const EdgeInsets.symmetric(vertical: 20, horizontal: 8),
                child: Text(
                  widget.Sport,
                  style: TextStyle(fontSize: 20, color: Colors.white),
                ),
              ),
            ),
            subtitle: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
              if (widget.Sport == 'Fußball')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Pass-, Schuss-, Dribllingtraining, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Leichtathletik')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Kugestoßen-, Hochsprung-, Sprinttraining...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Turnen')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Reck, Bodenturnen, Klimmzüge, Sprung (Pferd)...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Schwimmen')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    '100 Meter, Kopfsprung, Technikdemonstration (Brust und Kraul), 20 Meter Tauchen...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Volleyball')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Pritschen, Baggern, Aufschlag, Angriffsschlag...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Handball')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Passen, Kreuzen, Sprungwurf, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Hockey')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Passen, Schuss, Annahme, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Basketball')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Korbleger, Sprungwurf, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Tennis')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Grundschläge, Aufschlag, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Badmindton')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Lauf-, Schlagtechnik, Spielidee...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Tischtennis')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Vorhand, Rückhand, Spielverhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Ausdauerlauf')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Intervalltraining, Dauerlauf...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
            ])));
  }
}
</code>```

I hope someone can help me with the problem!
If you need more or more specific information, let me know.

Body:
I created a StreamBuilder that displays a document snapshot of Cloud Firestore. This snapshot contains a map that should be displayed in a listview. All items are displayed as planned:

But as soon as I press a button that changes the map in Cloud Firestore, the positions of the items in the list change. That would annoy me as a user, so I want to change that. I don't know how to. . .

Here is the StreamBuilder:

StreamBuilder(
                        stream: database.count(),
                        builder: (context, AsyncSnapshot snapshot) {
                          if (snapshot.hasData) {
                            if (snapshot.data.data()['Einheiten'] != null) {
                              Map<String, dynamic> Einheiten = snapshot.data.data()['Einheiten']
                                  as Map<String, dynamic>;
                              if (snapshot.data
                                      .data()['Verfügbare Einheiten'] !=
                                  null) {
                                Map<String, dynamic> einheiten = snapshot.data
                                    .data()['Verfügbare Einheiten'] as Map<String, dynamic>;
                                return Column(
                                  mainAxisSize: MainAxisSize.max,
                                  children: [
                                    Text(
                                      'Verfügbare Einheiten: ' +
                                          einheiten['Deine Einheiten'].toString(),
                                      style: TextStyle(
                                          fontSize: 30, color: Colors.white),
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.all(15),
                                      child: ListView.builder(
                                        physics: NeverScrollableScrollPhysics(),
                                          shrinkWrap: true,
                                          itemCount: Einheiten.length,
                                          itemBuilder: (BuildContext, i) {
                                            String key =
                                                Einheiten.keys.elementAt(i);
                                            return Padding(
                                              padding: const EdgeInsets.all(8.0),
                                              child: Einheit(key,
                                                  Einheiten[key], einheiten),
                                            );
                                          }),
                                    ),
                                  ],
                                );
                              } else {
                                return Center(
                                    child: CircularProgressIndicator(
                                  color: Colors.green,
                                  backgroundColor: Colors.green,
                                ));
                              }
                            } else {
                              return Center(
                                  child: CircularProgressIndicator(
                                color: Colors.yellow,
                                backgroundColor: Colors.yellow,
                              ));
                            }
                          }
                          return Center(
                              child: CircularProgressIndicator(
                            backgroundColor: Colors.red,
                            color: Colors.red,
                          ));
                        })

And here's the standardized item, which gives the commands that cause the items to be moved:

class Einheit extends StatefulWidget {
  String Sport;
  int number;
  Map einheiten;

  Einheit(this.Sport, this.number, this.einheiten);

  @override
  State<Einheit> createState() => _EinheitState();
}

class _EinheitState extends State<Einheit> {
  User? user;
  late DatabaseService database;

  Future connect() async {
    user = FirebaseAuth.instance.currentUser;
    database = DatabaseService(user!.email!);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    connect();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(34),
          border: Border.all(width: 2, color: Colors.white),
        ),
        child: ListTile(
          contentPadding: EdgeInsets.symmetric(horizontal: 20),
            trailing: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                InkWell(
                    onTap: () {
                      if (widget.einheiten['Deine Einheiten'] != 0) {
                          final newValue = widget.number + 1;
                          widget.number = newValue;
                          database.addE(widget.Sport, widget.number);
                          database.decreaseECount();
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                          content: Text(
                            'Du hast das von dir vorgegebene Maximum an Einheiten erreicht...',
                            textAlign: TextAlign.center,
                            style: TextStyle(color: Colors.white),
                          ),
                          backgroundColor: Colors.purple,
                        ));
                      }
                    },
                    child: Icon(Icons.add)),
                InkWell(
                    onTap: () {
                      if (widget.number != 0) {
                          final newValue = widget.number - 1;
                          widget.number = newValue;
                          database.addE(widget.Sport, widget.number);
                          database.addECount();
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                          content: Text(
                            'Du hast das von dir vorgegebene Maximum an Einheiten erreicht...',
                            textAlign: TextAlign.center,
                            style: TextStyle(color: Colors.white),
                          ),
                          backgroundColor: Colors.purple,
                        ));
                      }
                    },
                    child: Icon(Icons.remove)),
              ],
            ),
            leading: Text((widget.number).toString(),
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),),
            title: Center(
              child: Padding(
                padding:
                    const EdgeInsets.symmetric(vertical: 20, horizontal: 8),
                child: Text(
                  widget.Sport,
                  style: TextStyle(fontSize: 20, color: Colors.white),
                ),
              ),
            ),
            subtitle: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
              if (widget.Sport == 'Fußball')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Pass-, Schuss-, Dribllingtraining, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Leichtathletik')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Kugestoßen-, Hochsprung-, Sprinttraining...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Turnen')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Reck, Bodenturnen, Klimmzüge, Sprung (Pferd)...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Schwimmen')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    '100 Meter, Kopfsprung, Technikdemonstration (Brust und Kraul), 20 Meter Tauchen...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Volleyball')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Pritschen, Baggern, Aufschlag, Angriffsschlag...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Handball')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Passen, Kreuzen, Sprungwurf, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Hockey')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Passen, Schuss, Annahme, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Basketball')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Korbleger, Sprungwurf, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Tennis')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Grundschläge, Aufschlag, taktisches Verhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Badmindton')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Lauf-, Schlagtechnik, Spielidee...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Tischtennis')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Vorhand, Rückhand, Spielverhalten...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
              if (widget.Sport == 'Ausdauerlauf')
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Intervalltraining, Dauerlauf...',
                    style: TextStyle(fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                ),
            ])));
  }
}

I hope someone can help me with the problem!
If you need more or more specific information, let me know.


来源: stackexchange

问:
Direct Multi-Step Ahead Time Series Forecasting using R
I am building a multivariate model for direct time series forecasting, where the goal is to make 4 and 8-step-ahead forecasts using random forest and SVR.
The results look very similar to my 1 step-ahead forecast and I am wondering whether my code is sensible or not.

```<code>Here is an example for some 4-step-ahead forecasts using random forest in conjunction with the predict function.
As far as I understand the difference between the 1-step-ahead and the 4-step-ahead direct forecast is that instead of the first we feed the fourth row of the test set to the predict function. Meaning in the following example:
</code>```

test <- mydata_2diff[(i+4), ]

```<code>instead of
</code>```

test <- mydata_2diff[(i+1), ]

```<code>
My code looks as follows:

</code>```
```<code>train_end <- 112 # End of the training set
j <- 1 # Loop counter
k_max <- 10  # Number of RF estimations
pred_rf_4Q_dir <- matrix(0,(nrow(mydata_2diff)-train_end-3), k_max) # Prediction matrix

{
  tic()
  for (i in train_end:(nrow(mydata_2diff)-4)) {

    train <- mydata_2diff[1:i, ]     # Training data
    test <- mydata_2diff[(i+4), ]    # Test data

    for (k in 1:k_max){

      rf_RPI <- randomForest(RPI ~ RGDP + CPI + STI + LTI + UE + SER + SPI + ARH,
                             data = train, ntree = 500, importance = T)

      pred_rf = predict(rf_RPI, newdata=test, predict.all = T)

      pred_rf_4Q_dir[j,k] <- pred_rf[["aggregate"]]

    }
    j <- j+1
  }
  toc()
}
</code>```
```<code>
Is this approach correct or not?
I am grateful for any feedback.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am building a multivariate model for direct time series forecasting, where the goal is to make 4 and 8-step-ahead forecasts using random forest and SVR.
The results look very similar to my 1 step-ahead forecast and I am wondering whether my code is sensible or not.

Here is an example for some 4-step-ahead forecasts using random forest in conjunction with the predict function.
As far as I understand the difference between the 1-step-ahead and the 4-step-ahead direct forecast is that instead of the first we feed the fourth row of the test set to the predict function. Meaning in the following example:

test <- mydata_2diff[(i+4), ]

instead of

test <- mydata_2diff[(i+1), ]

My code looks as follows:

train_end <- 112 # End of the training set
j <- 1 # Loop counter
k_max <- 10  # Number of RF estimations
pred_rf_4Q_dir <- matrix(0,(nrow(mydata_2diff)-train_end-3), k_max) # Prediction matrix

{
  tic()
  for (i in train_end:(nrow(mydata_2diff)-4)) {

    train <- mydata_2diff[1:i, ]     # Training data
    test <- mydata_2diff[(i+4), ]    # Test data

    for (k in 1:k_max){

      rf_RPI <- randomForest(RPI ~ RGDP + CPI + STI + LTI + UE + SER + SPI + ARH,
                             data = train, ntree = 500, importance = T)

      pred_rf = predict(rf_RPI, newdata=test, predict.all = T)

      pred_rf_4Q_dir[j,k] <- pred_rf[["aggregate"]]

    }
    j <- j+1
  }
  toc()
}

Is this approach correct or not?
I am grateful for any feedback.


问:
AttributeError: 'TokenClassifierOutput' object has no attribute 'detach'
I'm fine-tuning the BERT model in Named Entity Recognition task using json file dataset, but when I run that code get an error:

```<code>    with torch.no_grad():
         token_classifier_output1 = model(b_input_ids,
                            token_type_ids=None,
                            attention_mask=b_input_mask,
                            labels=b_labels)
         token_classifier_output2 = model(b_input_ids, token_type_ids=None,
                       attention_mask=b_input_mask)
    logits = token_classifier_output2.detach().cpu().numpy()
    label_ids = b_labels.to('cpu').numpy()
    predictions.extend([list(p) for p in np.argmax(logits, axis=2)])
    true_labels.append(label_ids)

    tmp_eval_accuracy = flat_accuracy(logits, label_ids)

    eval_loss += tmp_eval_loss.mean().item()
    eval_accuracy += tmp_eval_accuracy

    nb_eval_examples += b_input_ids.size(0)
    nb_eval_steps += 1
</code>```

when I run that code I get this error:
AttributeError: 'TokenClassifierOutput' object has no attribute 'detach'

Body:
I'm fine-tuning the BERT model in Named Entity Recognition task using json file dataset, but when I run that code get an error:

    with torch.no_grad():
         token_classifier_output1 = model(b_input_ids,
                            token_type_ids=None,
                            attention_mask=b_input_mask,
                            labels=b_labels)
         token_classifier_output2 = model(b_input_ids, token_type_ids=None,
                       attention_mask=b_input_mask)
    logits = token_classifier_output2.detach().cpu().numpy()
    label_ids = b_labels.to('cpu').numpy()
    predictions.extend([list(p) for p in np.argmax(logits, axis=2)])
    true_labels.append(label_ids)

    tmp_eval_accuracy = flat_accuracy(logits, label_ids)

    eval_loss += tmp_eval_loss.mean().item()
    eval_accuracy += tmp_eval_accuracy

    nb_eval_examples += b_input_ids.size(0)
    nb_eval_steps += 1

when I run that code I get this error:
AttributeError: 'TokenClassifierOutput' object has no attribute 'detach'


问:
Blazor InputSelect - Client displays different value to server if List changed
I have an issue with the Blazor InputSelect control displaying an incorrect value at the client if the list changes. I post this article partly as a question but also as a solution

The InputSelect resides in a Blazor Component and is configured to provide a changed event to the parent control since various calculations must be performed which eventually affect other display elements and controls. Therefore, a simple bind of the value doesn't work for me and I use the three-parameter binding model.

The InputSelect displays an initial list. It is bound to a class instance property which is set on first load  - this correctly reflects to the displayed value in the browser.

A user can choose a smaller set of values for the list. Even if this shorter list contains the selected value at the client, after setting the new list at the server, the client now displays the fist (incorrect) item in the list and not the correct value at the server. The bound property at the server still shows the correct value if other server interaction occurs and the value is inspected.

Looking at browser values, I noted that none of the option values within the client select had a selected property set. After changing my code to enforce a selected property the rest of the code worked as expected.

I assume that the internal state of the InputSelect and the html select element at the browser are not in step if the selected option is not set. Does anyone else suffer this issue?

```<code>   <InputSelect Value="@ApertureValue" ValueChanged="@((double value) => SelectChanged(value))" ValueExpression="@(() => ApertureValue)" class="form-control form-control-sm">
        @foreach (Aperture i in Aperture.GetApertures(PreferredWorkingStopsInUse))
       {
                <option value=@i.ApertureValue>@i.ApertureValueDisplay</option>
        }
    </InputSelect>

  <InputSelect Value="@ApertureValue" ValueChanged="@((double value) => SelectChanged(value))" ValueExpression="@(() => ApertureValue)" class="form-control form-control-sm">
        @foreach (Aperture i in Aperture.GetApertures(PreferredWorkingStopsInUse))
        {
            if (i.ApertureValue == ApertureValue)
            {
                <option selected value=@i.ApertureValue>@i.ApertureValueDisplay</option>
            }
            else
            {
                <option value=@i.ApertureValue>@i.ApertureValueDisplay</option>
            }
        }
    </InputSelect>
</code>```

Body:
I have an issue with the Blazor InputSelect control displaying an incorrect value at the client if the list changes. I post this article partly as a question but also as a solution

The InputSelect resides in a Blazor Component and is configured to provide a changed event to the parent control since various calculations must be performed which eventually affect other display elements and controls. Therefore, a simple bind of the value doesn't work for me and I use the three-parameter binding model.

The InputSelect displays an initial list. It is bound to a class instance property which is set on first load  - this correctly reflects to the displayed value in the browser.

A user can choose a smaller set of values for the list. Even if this shorter list contains the selected value at the client, after setting the new list at the server, the client now displays the fist (incorrect) item in the list and not the correct value at the server. The bound property at the server still shows the correct value if other server interaction occurs and the value is inspected.

Looking at browser values, I noted that none of the option values within the client select had a selected property set. After changing my code to enforce a selected property the rest of the code worked as expected.

I assume that the internal state of the InputSelect and the html select element at the browser are not in step if the selected option is not set. Does anyone else suffer this issue?

   <InputSelect Value="@ApertureValue" ValueChanged="@((double value) => SelectChanged(value))" ValueExpression="@(() => ApertureValue)" class="form-control form-control-sm">
        @foreach (Aperture i in Aperture.GetApertures(PreferredWorkingStopsInUse))
       {
                <option value=@i.ApertureValue>@i.ApertureValueDisplay</option>
        }
    </InputSelect>

  <InputSelect Value="@ApertureValue" ValueChanged="@((double value) => SelectChanged(value))" ValueExpression="@(() => ApertureValue)" class="form-control form-control-sm">
        @foreach (Aperture i in Aperture.GetApertures(PreferredWorkingStopsInUse))
        {
            if (i.ApertureValue == ApertureValue)
            {
                <option selected value=@i.ApertureValue>@i.ApertureValueDisplay</option>
            }
            else
            {
                <option value=@i.ApertureValue>@i.ApertureValueDisplay</option>
            }
        }
    </InputSelect>


问:
How to get the value in realtime in nuxt js observable?
I am working on a NuxtJS project. For getting the current screen width in real-time, I created an instance variable based on Accessing screen width in vue components and “window is not defined” in Nuxt.js.

But, the value is not getting updated in real-time. Either there is a delay or I need to refresh. I just need only the current screen width if it is less than 500px it should be true or false.

plugins/breakpoints.js

import Vue from 'vue'

Vue.prototype.$isMobile = Vue.observable(window.innerWidth < 600)

window.addEventListener(
  'resize',
  () => (Vue.prototype.$isMobile = window.innerWidth < 600)
)
```
<p><code>nuxt.config.js</code></p>
<pre class="lang-js prettyprint-override"><code>plugins: [{ src: './plugins/breakpoints', ssr: false }],
</code>```

pages/index.vue

<template>

isMobile {{ $isMobile }}

</template>

```

CodeSandBox(for quick preview): https://codesandbox.io/p/sandbox/reverent-stitch-1sdh6r

Body:
I am working on a NuxtJS project. For getting the current screen width in real-time, I created an instance variable based on Accessing screen width in vue components and “window is not defined” in Nuxt.js.

But, the value is not getting updated in real-time. Either there is a delay or I need to refresh. I just need only the current screen width if it is less than 500px it should be true or false.

plugins/breakpoints.js

import Vue from 'vue'

Vue.prototype.$isMobile = Vue.observable(window.innerWidth < 600)

window.addEventListener(
  'resize',
  () => (Vue.prototype.$isMobile = window.innerWidth < 600)
)

nuxt.config.js

plugins: [{ src: './plugins/breakpoints', ssr: false }],

pages/index.vue

<template>

isMobile {{ $isMobile }}

</template>

CodeSandBox(for quick preview): https://codesandbox.io/p/sandbox/reverent-stitch-1sdh6r


问:
How to update pivot table on many-to-many with Prisma
I want to replace many-to-many pivot table with a new set of values.

schema

```<code>model Role {
  id          Int    @id @default(autoincrement())
  name        String @unique
  description String

  permissions PermissionsOnRoles[]
}

model Permission {
  id          Int    @id @default(autoincrement())
  name        String @unique
  description String

  roles PermissionsOnRoles[]
}

model PermissionsOnRoles {
  permission   Permission @relation(fields: [permissionId], references: [id])
  permissionId Int
  role         Role       @relation(fields: [roleId], references: [id])
  roleId       Int
  description1 String
  description2 String

  @@id([permissionId, roleId])
}
</code>```

function for create

```<code>return await this.prisma.role.create({
      data: {
        description: 'manager',
        name: 'manager',
        permissions: {
          create: [
            {
              description1: 'permission 11',
              description2: 'permission 12',
              permissionId: 1,
            },
            {
              description1: 'permission 31',
              description2: 'permission 32',
              permissionId: 3,
            },
          ],
        },
      },
    });
</code>```

function for update(let say I want to revoke all manager's permissions) using set

```<code>return await this.prisma.role.update({
      where: { id: 2 },
      data: {
        description: 'manager',
        name: 'manager',
        permissions: {
          set: [],
        },
      },
    });
</code>```

when run function for update, I got error

The change you are trying to make would violate the required relation 'PermissionsOnRolesToRole' between the PermissionsOnRoles and Role models.

Body:
I want to replace many-to-many pivot table with a new set of values.

schema

model Role {
  id          Int    @id @default(autoincrement())
  name        String @unique
  description String

  permissions PermissionsOnRoles[]
}

model Permission {
  id          Int    @id @default(autoincrement())
  name        String @unique
  description String

  roles PermissionsOnRoles[]
}

model PermissionsOnRoles {
  permission   Permission @relation(fields: [permissionId], references: [id])
  permissionId Int
  role         Role       @relation(fields: [roleId], references: [id])
  roleId       Int
  description1 String
  description2 String

  @@id([permissionId, roleId])
}

function for create

return await this.prisma.role.create({
      data: {
        description: 'manager',
        name: 'manager',
        permissions: {
          create: [
            {
              description1: 'permission 11',
              description2: 'permission 12',
              permissionId: 1,
            },
            {
              description1: 'permission 31',
              description2: 'permission 32',
              permissionId: 3,
            },
          ],
        },
      },
    });

function for update(let say I want to revoke all manager's permissions) using set

return await this.prisma.role.update({
      where: { id: 2 },
      data: {
        description: 'manager',
        name: 'manager',
        permissions: {
          set: [],
        },
      },
    });

when run function for update, I got error

The change you are trying to make would violate the required relation 'PermissionsOnRolesToRole' between the PermissionsOnRoles and Role models.


问:
How to map properly Oracle Number(1, 0) to boolean using Entity Framework?
I am trying to use an Oracle number(1) in C# code using EF6 in DB-first mode. From what I could see, the only way to use such a type is by using a Boolean while mapping the entities in the edmx file, which is fine.
While the program is able to compile and to run, I always get the following error message when I am in designer mode in the edmx file:

Error 2019: Member Mapping specified is not valid. The type 'Edm.Boolean[Nullable=False,DefaultValue=]' [...] is not compatible with 'OracleEFProvider.number[Nullable=False,DefaultValue=,Precision=1,Scale=0]'

How can I get rid of this message while still mapping a boolean?

I am well aware that the Boolean type isn't supported in Oracle Databases. Each of the posts I saw suggested the mapping trick either manually or automatically by customizing the edmMappings in the app.config. Both of these solutions led to the above error message.
I tried with different entity types, none have worked. As this is a common issue, I suppose I missed something...

In this old SO (Mapping .NET Boolean datatype to oracle number(1,0) in entity framework throws error), someone said there is nothing much to do about this message. Maybe there are news about this since then?


问:
Generating a foil from Self-Avoiding Walk in 5x5 matrix
I need to create an experiment that creates a foil, or a similar stimulus that has a constant change. In my case, I need to take the output from a Self-Avoiding Walk Algorithm 5x5 matrix and move two cells of this path in a way that does not "break" the walking path or create dead ends. In the image below, I would like to keep [0][0] unchanged as entering path, and then [1][0] would remain unchanged as it would break the path, [2][0] would remain unchanged to avoid making [3][0] a dead end, but then [3][0] could be moved to (2)(1) and (3)(2) could be changed to (4)(1)

Any pointers to how I could solve this problem?

Here is the JS Fiddle with generating this matrix: http://jsfiddle.net/eg86hkm7/1/

// Adding this code just because SO makes me do it to post a JSFiddle```


问:
How to restore scroll position on back button click with React Router v6?
How to restore scroll position on back button click with React Router v6? I there a built-in method for that or simple way?

I'm trying to build an infinite scroll with card list. Each card is clickable. On card click card's page rendered with Back button.

I tried to use ScrollRestoration from React Router v6 but it's not working. Is it works only after loaders have completed? And if I don't use loaders then I can't use it?

This component will emulate the browser's scroll restoration on
location changes after loaders have completed to ensure the scroll
position is restored to the right spot, even across domains.

App.tsx

```<code><div>
  <ScrollRestoration
    getKey={(location, matches) => {
      return location.pathname;
    }}
  />
  <Box>
    <InfiniteScroll
      dataLength={currentData().length}
      next={loadMore}
      hasMore={hasMore}
      loader={<Box>Loading more posts</Box>}
      initialScrollY={1000}
    >
      <Box
        display={"grid"}
        gridTemplateColumns={"repeat(auto-fill, minmax(250px, 1fr))"}
        gap={"60px"}
      >
        {currentData().map((item: any) => (
          <Box
            key={item.id}
            onClick={() => navigate("/" + item.id)}
          >
            {item.id}
          </Box>
        ))}
      </Box>{" "}
    </InfiniteScroll>
  </Box>
</div>
</code>```

Codesandbox link: https://codesandbox.io/s/react-router-6-scroll-restoration-vv6fzk?file=/src/App.tsx

Body:
How to restore scroll position on back button click with React Router v6? I there a built-in method for that or simple way?

I'm trying to build an infinite scroll with card list. Each card is clickable. On card click card's page rendered with Back button.

I tried to use ScrollRestoration from React Router v6 but it's not working. Is it works only after loaders have completed? And if I don't use loaders then I can't use it?

This component will emulate the browser's scroll restoration on
location changes after loaders have completed to ensure the scroll
position is restored to the right spot, even across domains.

App.tsx

  <ScrollRestoration
    getKey={(location, matches) => {
      return location.pathname;
    }}
  />
  <Box>
    <InfiniteScroll
      dataLength={currentData().length}
      next={loadMore}
      hasMore={hasMore}
      loader={<Box>Loading more posts</Box>}
      initialScrollY={1000}
    >
      <Box
        display={"grid"}
        gridTemplateColumns={"repeat(auto-fill, minmax(250px, 1fr))"}
        gap={"60px"}
      >
        {currentData().map((item: any) => (
          <Box
            key={item.id}
            onClick={() => navigate("/" + item.id)}
          >
            {item.id}
          </Box>
        ))}
      </Box>{" "}
    </InfiniteScroll>
  </Box>

Codesandbox link: https://codesandbox.io/s/react-router-6-scroll-restoration-vv6fzk?file=/src/App.tsx


问:
Problem while installing create-react-app package
While I was installing the create-react-app package then I got an error which was like this:

```<code>[eslint] Plugin "react" was conflicted between ".eslintrc" and "BaseConfig » C:\Users\12mah\Desktop\react-quiz\node_modules\react-scripts\node_modules\eslint-config-react-app\base.js".
</code>```

I don't know what should I do to fix this.
This line popped up with my output:

```<code>Hello World
</code>```

Compiled with the problem.

```<code>[eslint] Plugin "react" was conflicted between ".eslintrc" and "BaseConfig » C:\Users\12mah\Desktop\react-quiz\node_modules\react-scripts\node_modules\eslint-config-react-app\base.js".
</code>```

like this in the browser

I was expecting a relevant solution. I tried to search on google and youtube but it is not working.

Body:
While I was installing the create-react-app package then I got an error which was like this:

[eslint] Plugin "react" was conflicted between ".eslintrc" and "BaseConfig » C:\Users\12mah\Desktop\react-quiz\node_modules\react-scripts\node_modules\eslint-config-react-app\base.js".

I don't know what should I do to fix this.
This line popped up with my output:

Hello World

Compiled with the problem.

[eslint] Plugin "react" was conflicted between ".eslintrc" and "BaseConfig » C:\Users\12mah\Desktop\react-quiz\node_modules\react-scripts\node_modules\eslint-config-react-app\base.js".

like this in the browser

I was expecting a relevant solution. I tried to search on google and youtube but it is not working.


问:
PostgreSQL to MySQL database, error with \xF1o string value
I'm trying to migrate a PostgreSQL database to MySQL via MySQL Workbench,
on a Windows PC. The PostgreSQL-driver is in 32 bits for Unicode.
The PostgreSQL is setup in C-encoding, I also tried Dutch encoding.

The MysQL-database is in utf8mb4 encoding, also for the table named "aat".

Workbench is giving me this error:

```<code>16:33:05 [INF][      copytable]: Statement execution failed: Incorrect string value: '\xF1o' for column 'rdfs__label' at row 3:
</code>```

How can I migrate the PostgreSQL database succesfully to MySQL?

Edit:
I created a PostgreSQL database with UTF8 encoding based on template[0], but when I run
\l template[1] the Collate and Ctype is still Dutch_Netherlands.1252.

I also put this in my my.ini:

```<code>collation_server = utf8mb4_unicode_ci
character_set_server = utf8mb4
init_connect='SET collation_connection = utf8mb4_unicode_ci'
character_set_client_handshake = FALSE
</code>```

Body:
I'm trying to migrate a PostgreSQL database to MySQL via MySQL Workbench,
on a Windows PC. The PostgreSQL-driver is in 32 bits for Unicode.
The PostgreSQL is setup in C-encoding, I also tried Dutch encoding.

The MysQL-database is in utf8mb4 encoding, also for the table named "aat".

Workbench is giving me this error:

16:33:05 [INF][      copytable]: Statement execution failed: Incorrect string value: '\xF1o' for column 'rdfs__label' at row 3:

How can I migrate the PostgreSQL database succesfully to MySQL?

Edit:
I created a PostgreSQL database with UTF8 encoding based on template[0], but when I run
\l template[1] the Collate and Ctype is still Dutch_Netherlands.1252.

I also put this in my my.ini:

collation_server = utf8mb4_unicode_ci
character_set_server = utf8mb4
init_connect='SET collation_connection = utf8mb4_unicode_ci'
character_set_client_handshake = FALSE


问:
how to solve "Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist." error?
I have a ploblem with making Chrome Extention.I got below error in popup.js file:

"Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist."
also I live in Iran and I have the internet problem and can not access google documents!!!

please help me to solve this problem. Thanks

this is my code:

1.manifest.json

```<code>{
  "name": "Hamid Test",
  "version": "1.0",
  "manifest_version": 3,
  "author": "Hamid Solat",
  "description": "This is a test",
  "icons":{
    "128":"/assets/icons/icon.png"
    },
  "background.service_worker": {
    "scripts": ["assets/js/background.js"],
    "persistent": false
  },

  "action": {
    "default_icon": "/assets/icons/icon.png",
    "default_popup": "popup.html",
    "default_title": "Hamid Test"
  },
  "content_security_policy": {}
  ,
  "permissions": [
    "activeTab",
    "tabs",
    "storage",
    "background",
    "webNavigation"
  ]
}
</code>```

2.popup.html

```<code><!doctype html>
<html>
  <head>
    <title>Hamid Test</title>
    <link rel="stylesheet" href="assets/css/popup.css">
  </head>
  <body>
    <div class="container">
      <h1>Hamid Test</h1>
      <button id="injectMessage">Send</button>
      <div id="validation"></div>
    </div>
    <script type="text/javascript" src="assets/js/popup.js"></script>
  </body>
</html>
</code>```

3.popup.js

```<code>chrome.storage.sync.clear();
let button = document.getElementById("injectMessage");
let validation = document.getElementById("validation");
sleep = async (ms)=>{ return new Promise(resolve => setTimeout(resolve, ms)); }

button.addEventListener("click", async ()=> {
    chrome.runtime.sendMessage({"manageMischief": true});
});
</code>```

4.bacground.js

```<code>chrome.runtime.onMessage.addListener((message, sender)=> {
    if(!message.manageMischief) return;
    else{chrome.tabs.executeScript({
        file: 'assets/js/inject.js'
    }); }
});
</code>```

It's the first time I make the chrome extention...

I also try this in popup.js:
button.addEventListener("click", async ()=> { alert("OK"); });

it worked.... but my problem is in this line:

chrome.runtime.sendMessage({"manageMischief": true});

Body:
I have a ploblem with making Chrome Extention.I got below error in popup.js file:

"Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist."
also I live in Iran and I have the internet problem and can not access google documents!!!

please help me to solve this problem. Thanks

this is my code:

1.manifest.json

{
  "name": "Hamid Test",
  "version": "1.0",
  "manifest_version": 3,
  "author": "Hamid Solat",
  "description": "This is a test",
  "icons":{
    "128":"/assets/icons/icon.png"
    },
  "background.service_worker": {
    "scripts": ["assets/js/background.js"],
    "persistent": false
  },

  "action": {
    "default_icon": "/assets/icons/icon.png",
    "default_popup": "popup.html",
    "default_title": "Hamid Test"
  },
  "content_security_policy": {}
  ,
  "permissions": [
    "activeTab",
    "tabs",
    "storage",
    "background",
    "webNavigation"
  ]
}

2.popup.html

<!doctype html>

    <title>Hamid Test</title>
    <link rel="stylesheet" href="assets/css/popup.css">

Hamid Test

      <button id="injectMessage">Send</button>

3.popup.js

chrome.storage.sync.clear();
let button = document.getElementById("injectMessage");
let validation = document.getElementById("validation");
sleep = async (ms)=>{ return new Promise(resolve => setTimeout(resolve, ms)); }

button.addEventListener("click", async ()=> {
    chrome.runtime.sendMessage({"manageMischief": true});
});

4.bacground.js

chrome.runtime.onMessage.addListener((message, sender)=> {
    if(!message.manageMischief) return;
    else{chrome.tabs.executeScript({
        file: 'assets/js/inject.js'
    }); }
});

It's the first time I make the chrome extention...

I also try this in popup.js:
button.addEventListener("click", async ()=> { alert("OK"); });

it worked.... but my problem is in this line:

chrome.runtime.sendMessage({"manageMischief": true});


问:
display url external product_url in $content woocommerce
```<code>if(!rehub_option('woo_btn_inner_disable')){
    add_action('rhwoo_template_single_add_to_cart', 'woocommerce_template_single_add_to_cart');
}
if ( ! function_exists( 'rh_woo_external_add_to_cart' ) ) {
    function rh_woo_external_add_to_cart() {
        global $product;
        wc_get_template( 'single-product/add-to-cart/external.php', array(
            'product_url' => $product->add_to_cart_url(),
            'button_text' => $product->single_add_to_cart_text(),
        ) );
    }
}

add_filter( 'the_content', 'shorten_product_long_descrition', 20 );
function shorten_product_long_descrition( $content ){
    // Only for single product pages
    if( ! is_product() ) return $content;

    // Set the limit of words
    $limit = 13;

    if (str_word_count($content, 0) > $limit) {
        $arr = str_word_count($content, 2);
        $pos = array_keys($arr);
        $text = '<p>' . substr($content, 0, $pos[$limit]) . "..<a href='" . $product_url . "' class='goto_more_offer_tab button'>...continua la lettura</a></p>";
        $content = force_balance_tags($text); // needded
    }
    return $content;
}
</code>```

I have to insert and display product_url

```<code>'product_url' => $product->add_to_cart_url()
</code>```

in the a href of the above up code:

```<code>"..<a href='" . $product_url . "' ............
</code>```

the code is in the functions.php file
you can help me?
thank you

Body:
if(!rehub_option('woo_btn_inner_disable')){
    add_action('rhwoo_template_single_add_to_cart', 'woocommerce_template_single_add_to_cart');
}
if ( ! function_exists( 'rh_woo_external_add_to_cart' ) ) {
    function rh_woo_external_add_to_cart() {
        global $product;
        wc_get_template( 'single-product/add-to-cart/external.php', array(
            'product_url' => $product->add_to_cart_url(),
            'button_text' => $product->single_add_to_cart_text(),
        ) );
    }
}

add_filter( 'the_content', 'shorten_product_long_descrition', 20 );
function shorten_product_long_descrition( $content ){
    // Only for single product pages
    if( ! is_product() ) return $content;

    // Set the limit of words
    $limit = 13;

    if (str_word_count($content, 0) > $limit) {
        $arr = str_word_count($content, 2);
        $pos = array_keys($arr);
        $text = '
' . substr($content, 0, $pos[$limit]) . ".....continua la lettura
";
        $content = force_balance_tags($text); // needded
    }
    return $content;
}

I have to insert and display product_url

'product_url' => $product->add_to_cart_url()

in the a href of the above up code:

"..<a href='" . $product_url . "' ............

the code is in the functions.php file
you can help me?
thank you


问:
2022 cs50 finince - why does my function return error to confirm password even when i do confirm the password?
When i try to register it always outputs the error/apology "must confirm password".Which should only show if I don't confirm my password which I do.
This is the code for apology function:

```<code>def apology(message, code=400):
    """Render message as an apology to user."""
    def escape(s):
        """
        Escape special characters.

        https://github.com/jacebrowning/memegen#special-characters
        """
        for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
                         ("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]:
            s = s.replace(old, new)
        return s
    return render_template("apology.html", top=code, bottom=escape(message)), code

</code>```

This is my code for register.function:

```<code>@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""

    #user reaches route via POST
    if request.method == "POST":
        # check for possible errors

        # must provide username
        username =request.form.get("username")
        password =request.form.get("password")
        confirmation =request.form.get("confiramtion")

        if not username:
            return apology("must provide username", 400)
        #must provide password
        elif not password :
            return apology("must provide password", 400)
        #must confirm password
        elif not confirmation:
           return apology("must confirm password",400)

        #check if passwords match
        if passwowrd !=  confirmation:
            return apology("password doesen't match",400)

request.form.get("username"))
        #check if username taken
        #insert new user into users table
        hash = generate_password_hash(password)
        try:
            db.execute("INSERT INTO users(username,hash ) VALUES(?,?)",username,hash)
            return redirect("/")
        except:

            return apology("username is already taken", 400)

    else :
            return render_template("register.html")

</code>```

This is my register.html template:

```<code>{% extends "layout.html" %}

{% block title %}
    Register
{% endblock %}

{% block main %}
    <form action="/register" method="post">
        <div class="mb-3">
            <input autocomplete="off" autofocus class="form-control mx-auto w-auto" id="username" name="username" placeholder="Username" type="text">
        </div>
        <div class="mb-3">
            <input class="form-control mx-auto w-auto" id="password" name="password" placeholder="Password" type="password">
        </div>
        <div class="mb-3">
            <input class="form-control mx-auto w-auto" id="password" name="confirmation" placeholder="confirm password" type="password">
        </div>
        <button class="btn btn-primary" type="submit">Register</button>
    </form>
{% endblock %}
</code>```

I don't understand why it doesen't work does anybody have a tip?
I changed my if statements and changing the placement of the code and changed the way I wrote it but I can't find the error.I looked at suggestions of others who hade problems with register function nothing helped.
I am a begginer so I don't have any ideas how to fix it.Please help!

Body:
When i try to register it always outputs the error/apology "must confirm password".Which should only show if I don't confirm my password which I do.
This is the code for apology function:

def apology(message, code=400):
    """Render message as an apology to user."""
    def escape(s):
        """
        Escape special characters.

        https://github.com/jacebrowning/memegen#special-characters
        """
        for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
                         ("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]:
            s = s.replace(old, new)
        return s
    return render_template("apology.html", top=code, bottom=escape(message)), code

This is my code for register.function:

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""

    #user reaches route via POST
    if request.method == "POST":
        # check for possible errors

        # must provide username
        username =request.form.get("username")
        password =request.form.get("password")
        confirmation =request.form.get("confiramtion")

        if not username:
            return apology("must provide username", 400)
        #must provide password
        elif not password :
            return apology("must provide password", 400)
        #must confirm password
        elif not confirmation:
           return apology("must confirm password",400)

        #check if passwords match
        if passwowrd !=  confirmation:
            return apology("password doesen't match",400)

request.form.get("username"))
        #check if username taken
        #insert new user into users table
        hash = generate_password_hash(password)
        try:
            db.execute("INSERT INTO users(username,hash ) VALUES(?,?)",username,hash)
            return redirect("/")
        except:

            return apology("username is already taken", 400)

    else :
            return render_template("register.html")

This is my register.html template:

{% extends "layout.html" %}

{% block title %}
    Register
{% endblock %}

{% block main %}
    <form action="/register" method="post">

            <input autocomplete="off" autofocus class="form-control mx-auto w-auto" id="username" name="username" placeholder="Username" type="text">

            <input class="form-control mx-auto w-auto" id="password" name="password" placeholder="Password" type="password">

            <input class="form-control mx-auto w-auto" id="password" name="confirmation" placeholder="confirm password" type="password">

        <button class="btn btn-primary" type="submit">Register</button>
    </form>
{% endblock %}

I don't understand why it doesen't work does anybody have a tip?
I changed my if statements and changing the placement of the code and changed the way I wrote it but I can't find the error.I looked at suggestions of others who hade problems with register function nothing helped.
I am a begginer so I don't have any ideas how to fix it.Please help!


问:
Trouble with migration command in autodevops
exploring functionality of Gitlab autodevops find feature then you can use  repo/.gitlab/auto-deploy-values.yaml file to customize deploy process with lifecycle.preStop command all works great, but then i try to use application.migrateCommand looks like k8s don't even create job for migration

```<code>#my_value_file
# resources:
#   limits:
#     cpu: 100m
#     memory: 128Mi
#   requests:
#     cpu: 100m
#     memory: 128Mi

## preStop

# lifecycle:
#   preStop:
#     exec:
#       command: ['/bin/sh', '-c', 'curl -X POST XXXXXX'] ## notify

application.migrateCommand: sleep 600 ## sleep for test purpose any command i try wont start.

</code>```

i also take look in template file there value apply in process of deploy
https://gitlab.com/charts/auto-deploy-app/-/blob/master/templates/db-migrate-hook.yaml

inside template it need to be just command and no other imports

https://gitlab.com/gitlab-org/cluster-integration/auto-deploy-image/-/tree/master/assets/auto-deploy-app

try to find any example of usage this feature in live projects, read Helm documentation and initial templates, use other feature from same document

but this one don't work at all

Body:
exploring functionality of Gitlab autodevops find feature then you can use  repo/.gitlab/auto-deploy-values.yaml file to customize deploy process with lifecycle.preStop command all works great, but then i try to use application.migrateCommand looks like k8s don't even create job for migration

#my_value_file
# resources:
#   limits:
#     cpu: 100m
#     memory: 128Mi
#   requests:
#     cpu: 100m
#     memory: 128Mi

## preStop

# lifecycle:
#   preStop:
#     exec:
#       command: ['/bin/sh', '-c', 'curl -X POST XXXXXX'] ## notify

application.migrateCommand: sleep 600 ## sleep for test purpose any command i try wont start.

i also take look in template file there value apply in process of deploy
https://gitlab.com/charts/auto-deploy-app/-/blob/master/templates/db-migrate-hook.yaml

inside template it need to be just command and no other imports

https://gitlab.com/gitlab-org/cluster-integration/auto-deploy-image/-/tree/master/assets/auto-deploy-app

try to find any example of usage this feature in live projects, read Helm documentation and initial templates, use other feature from same document

but this one don't work at all


问:
log in button does not work . i nned to log in in this project for solving other problem
i have a problem :can not login on the front end even if i created user on my sql and associated to role admin. front end is in react . could you please guide me if you know what is the problem derive from. i add here all codes on the spring boot java back-end part .

i created a user with all attributes which are created on spring boot : usaer name, tel, email and is_active. I guess i didnt created user correctly. For attribute is_active i inserted true on my sql.i need to log in for add some entry and solve other problems.

thanks again,

public class User implements java.io.Serializable {

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NonNull
@Size(max = 20)
private String username;

@NotBlank
@NonNull
@Size(max = 50)
@Email
private String email;

@NonNull
@Size(max = 12)
private String telefono;

@JsonIgnore
@NotBlank
@NonNull
@Size(max = 120)
private String password;

private Boolean isActive = false;

@JsonIgnore
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();

public User(@NonNull String username, @NonNull String email, @NonNull String telefono) {
    this.username = username;
    this.email = email;
    this.telefono = telefono;
    this.password="";
}

public Set<Role> getRoles() {
    return roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}
</code>```

}

Body:
i have a problem :can not login on the front end even if i created user on my sql and associated to role admin. front end is in react . could you please guide me if you know what is the problem derive from. i add here all codes on the spring boot java back-end part .

i created a user with all attributes which are created on spring boot : usaer name, tel, email and is_active. I guess i didnt created user correctly. For attribute is_active i inserted true on my sql.i need to log in for add some entry and solve other problems.

thanks again,

public class User implements java.io.Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NonNull
@Size(max = 20)
private String username;

@NotBlank
@NonNull
@Size(max = 50)
@Email
private String email;

@NonNull
@Size(max = 12)
private String telefono;

@JsonIgnore
@NotBlank
@NonNull
@Size(max = 120)
private String password;

private Boolean isActive = false;

@JsonIgnore
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();

public User(@NonNull String username, @NonNull String email, @NonNull String telefono) {
    this.username = username;
    this.email = email;
    this.telefono = telefono;
    this.password="";
}

public Set<Role> getRoles() {
    return roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}

}


问:
Barcode scanner not working on Orange pi zero
I have Barcode scanner such as this and armbian bullseye operating system running in orange pi zero not zero two, when I plugin USB to orange pi zero there is no thing read? I don't know if USB by default enabled from system configuration armbian-config or not?
any suggestion
thanks in advance.

I installed many libs like libusb-0.1-4 and libhidapi-libusb0 but also no thing happens?
and also I followed this guide to read with python but not success with me

very sorry for my bad language


问:
Animations don't work except when devtools is enabled
I have a problem with my site. When I put the chrome devtools, the heart remains purple when selected in 1440px desktop mode. When you remove devtools mode in desktop, you can no longer select the heart so that it remains purple. Similarly, to the right of the price in the restaurant pages, there is an animation that works well on desktop with the chrome devtools but not if you remove the devtools. I thought it was a media queries problem ? Here is some screenshot to explain the problem : with web dev tools of chromewithout webdev tools of chrome

I give you my github link : https://mjandia.github.io/ohmyfood/restaurants/note-enchante.html#
and : https://github.com/mjandia/ohmyfood

If you have a solution to fix the issue, thank you very much

I don't understand why with chrome devtools everything works and not when I remove them

I don't understand why with devtools all runs and not whithout


问:
The method cannot be invoked on a trait object
I would like to create a Command DP with a command which cannot be known at compile time, but i don't know how to make it well.

The minimal code reproduction

use std::path::{Path, PathBuf};
use std::process::exit;

trait Command {
    fn execute<P: AsRef<Path>>(&self, path: P) -> bool
    where
        Self: Sized,
    {
        false
    }
}

struct RenameCommand;

impl RenameCommand {
    pub fn new() -> Self {
        RenameCommand {}
    }
}

impl Command for RenameCommand {
    fn execute<P: AsRef<Path>>(&self, path: P) -> bool {
        false
    }
}

struct CopyCommand;

impl CopyCommand {
    pub fn new() -> Self {
        CopyCommand {}
    }
}

impl Command for CopyCommand {
    fn execute<P: AsRef<Path>>(&self, path: P) -> bool {
        false
    }
}

fn execute_commmand<P: AsRef<Path>>(command: &Box<dyn Command>, path: P) -> bool {
    command.execute(path)
}

fn main() {
    let origin_file_path = PathBuf::from("/bin");

    let command: Box<dyn Command> = match "rename" {
        "rename" => Box::new(RenameCommand),
        "copy" => Box::new(CopyCommand),
        _ => {
            eprintln!("Error");
            exit(1);
        }
    };

    for _ in 0..10{
      // Some code
      // I would like to do something like
      // error: the `execute` method cannot be invoked on a trait object
      command.execute(origin_file_path);
      // Or if needed
      execute_commmand(&command, origin_file_path);
    }

}
```
<p>I used Box to create the struct at runtime but I don't know how to run a method on this boxed struct.</p>
<pre class="lang-rust prettyprint-override"><code>command.execute(data); /// doesn't work
</code>```

so i tried to create a function like

execute_command<P: AsRef<Path>>(command: &Box(dyn Command), path: P) -> bool{
    command.execute(path)
}
```

But i got this error: the execute method cannot be invoked on a trait object.

Body:
I would like to create a Command DP with a command which cannot be known at compile time, but i don't know how to make it well.

The minimal code reproduction

use std::path::{Path, PathBuf};
use std::process::exit;

trait Command {
    fn execute<P: AsRef<Path>>(&self, path: P) -> bool
    where
        Self: Sized,
    {
        false
    }
}

struct RenameCommand;

impl RenameCommand {
    pub fn new() -> Self {
        RenameCommand {}
    }
}

impl Command for RenameCommand {
    fn execute<P: AsRef<Path>>(&self, path: P) -> bool {
        false
    }
}

struct CopyCommand;

impl CopyCommand {
    pub fn new() -> Self {
        CopyCommand {}
    }
}

impl Command for CopyCommand {
    fn execute<P: AsRef<Path>>(&self, path: P) -> bool {
        false
    }
}

fn execute_commmand<P: AsRef<Path>>(command: &Box<dyn Command>, path: P) -> bool {
    command.execute(path)
}

fn main() {
    let origin_file_path = PathBuf::from("/bin");

    let command: Box<dyn Command> = match "rename" {
        "rename" => Box::new(RenameCommand),
        "copy" => Box::new(CopyCommand),
        _ => {
            eprintln!("Error");
            exit(1);
        }
    };

    for _ in 0..10{
      // Some code
      // I would like to do something like
      // error: the `execute` method cannot be invoked on a trait object
      command.execute(origin_file_path);
      // Or if needed
      execute_commmand(&command, origin_file_path);
    }

}

I used Box to create the struct at runtime but I don't know how to run a method on this boxed struct.

command.execute(data); /// doesn't work

so i tried to create a function like

execute_command<P: AsRef<Path>>(command: &Box(dyn Command), path: P) -> bool{
    command.execute(path)
}

But i got this error: the execute method cannot be invoked on a trait object.


问:
mapreduce : what is the expected output from the combiner
I have read that the combiner reduces the network traffic between mappers and reducers. It is kind of like a semi-reducer which summarises the results before they are sent across the network to the reducers.

However, I am not able to understand the following example given here (look at the diagram they have depicted, the combiner combines the keys from various mappers which is something I do not understand. I think combiner has to reduce the data in one mapper only and hence no network traffic. Then the output of the combiner is sent across the network for second level of final aggregation):

Input text:

```<code>What do you mean by Object
What do you know about Java
What is Java Virtual Machine
How Java enabled High Performance
</code>```

Assuming each line goes to a separate mapper

Map phase output:

```<code><What,1> <do,1> <you,1> <mean,1> <by,1> <Object,1>
<What,1> <do,1> <you,1> <know,1> <about,1> <Java,1>
<What,1> <is,1> <Java,1> <Virtual,1> <Machine,1>
<How,1> <Java,1> <enabled,1> <High,1> <Performance,1>
</code>```

Claimed Combiner phase output:

```<code><What,1,1,1> <do,1,1> <you,1,1> <mean,1> <by,1> <Object,1>
<know,1> <about,1> <Java,1,1,1>
<is,1> <Virtual,1> <Machine,1>
<How,1> <enabled,1> <High,1> <Performance,1>
</code>```

I do not understand how the combiner could know <What,1,1,1,1> since what is present in different mappers. I would have expected the output of the combiner to be the semi reduced summary of each line like so:

```<code><What,1> <do,1> <you,1> <mean,1> <by,1> <Object,1>
<What,1> <do,1> <you,1> <know,1> <about,1> <Java,1>
<What,1> <is,1> <Java,1> <Virtual,1> <Machine,1>
<How,1> <Java,1> <enabled,1> <High,1> <Performance,1>

</code>```

Which is the same as the mapper output but would have been different if any of the words were repeated in a line.

Can you help me understand if my understanding of a combiner is right? If not what am I misunderstanding?

Body:
I have read that the combiner reduces the network traffic between mappers and reducers. It is kind of like a semi-reducer which summarises the results before they are sent across the network to the reducers.

However, I am not able to understand the following example given here (look at the diagram they have depicted, the combiner combines the keys from various mappers which is something I do not understand. I think combiner has to reduce the data in one mapper only and hence no network traffic. Then the output of the combiner is sent across the network for second level of final aggregation):

Input text:

What do you mean by Object
What do you know about Java
What is Java Virtual Machine
How Java enabled High Performance

Assuming each line goes to a separate mapper

Map phase output:

<What,1> <do,1> <you,1> <mean,1> <by,1> <Object,1>
<What,1> <do,1> <you,1> <know,1> <about,1> <Java,1>
<What,1> <is,1> <Java,1> <Virtual,1> <Machine,1>
<How,1> <Java,1> <enabled,1> <High,1> <Performance,1>

Claimed Combiner phase output:

<What,1,1,1> <do,1,1> <you,1,1> <mean,1> <by,1> <Object,1>
<know,1> <about,1> <Java,1,1,1>
<is,1> <Virtual,1> <Machine,1>
<How,1> <enabled,1> <High,1> <Performance,1>

I do not understand how the combiner could know <What,1,1,1,1> since what is present in different mappers. I would have expected the output of the combiner to be the semi reduced summary of each line like so:

<What,1> <do,1> <you,1> <mean,1> <by,1> <Object,1>
<What,1> <do,1> <you,1> <know,1> <about,1> <Java,1>
<What,1> <is,1> <Java,1> <Virtual,1> <Machine,1>
<How,1> <Java,1> <enabled,1> <High,1> <Performance,1>

Which is the same as the mapper output but would have been different if any of the words were repeated in a line.

Can you help me understand if my understanding of a combiner is right? If not what am I misunderstanding?


问:
How to cluster by Zip Code - all locations within 100 miles
I have a database without about 700 records, each with their own zip code. I want to show the rows (by unique ID) that fall within a 100 mile cluster. I also have a zip code distance DB from the National Bureau of Economic Research (https://data.nber.org/distance/2022/100miles/). This file is quite large but looks like the table below.

```<code>zip1    miles_to_zip2    zip2
1534    50               1001
1534    44               1002
1534    48               1003
</code>```

This data has 13m rows, but I really only need the distance for the zip codes in my database (about 700 different ones).

I can use Python, R, or Power BI to do this, depending on which is the simplest. How do I group all my unique IDs by a cluster group that identifies locations within 100 miles of each other? For reference, the data I want to analyze looks similar to the table below.

```<code>ID     ZipCode     Sales
1      15110       10,000
2      15115       15,000
3      98000       2,000
4      98001       10,000
5      70570       10,000
</code>```

My goal is essentially to return a column called cluster that would assign ID 1 and 2 to cluster1 and ID 3 and 4 to cluster 2, and 5 to cluster 3 (based on the 100 mile criteria).

Body:
I have a database without about 700 records, each with their own zip code. I want to show the rows (by unique ID) that fall within a 100 mile cluster. I also have a zip code distance DB from the National Bureau of Economic Research (https://data.nber.org/distance/2022/100miles/). This file is quite large but looks like the table below.

zip1    miles_to_zip2    zip2
1534    50               1001
1534    44               1002
1534    48               1003

This data has 13m rows, but I really only need the distance for the zip codes in my database (about 700 different ones).

I can use Python, R, or Power BI to do this, depending on which is the simplest. How do I group all my unique IDs by a cluster group that identifies locations within 100 miles of each other? For reference, the data I want to analyze looks similar to the table below.

ID     ZipCode     Sales
1      15110       10,000
2      15115       15,000
3      98000       2,000
4      98001       10,000
5      70570       10,000

My goal is essentially to return a column called cluster that would assign ID 1 and 2 to cluster1 and ID 3 and 4 to cluster 2, and 5 to cluster 3 (based on the 100 mile criteria).


问:
Reactjs virtualization infinit scroll
I'm trying to implement a virtualisation component with reactjs.

In order to fill the empty top and bottom gap I used an empty div with dynamic height which depends on the scroll position.

```<code>      <div style={{ height: topPlaceholderHeight }} />
         {visibleItems.map(renderItem)}
      <div style={{ height: bottomPlaceholderHeight }} />
</code>```

When the user scrolls > a scroll event is triggered > placeholderHeight is updated > triggers an other scroll event  => infinite loop that leads to an auto scroll to the bottom

```<code>  const [start, setStart] = useState(0);
  const [end, setEnd] = useState(0);
  const [scrollTop, setScrollTop] = useState(0);
  const parentRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const listElement = parentRef.current;
    if (!listElement) return;

    const itemsPerPage = Math.ceil(listElement.offsetHeight / itemHeight) + 2;

    const newStart = Math.max(0, Math.floor(scrollTop / itemHeight) - 1);
    const newEnd = Math.min(items.length, newStart + itemsPerPage);

    setStart(newStart);
    setEnd(newEnd);
  }, [items, itemHeight, scrollTop]);

  useEffect(() => {
    const listElement = parentRef.current;
    if (!listElement) return;

    const scrollHandler = () => {
      setScrollTop(listElement.scrollTop);
    };

    listElement.addEventListener("scroll", scrollHandler);
    return () => listElement.removeEventListener("scroll", scrollHandler);
  }, [parentRef]);
</code>```

Code sandbox

Any suggestions for solving this problem ?

Title: Reactjs virtualization infinit scroll

Body:
I'm trying to implement a virtualisation component with reactjs.

In order to fill the empty top and bottom gap I used an empty div with dynamic height which depends on the scroll position.

         {visibleItems.map(renderItem)}

When the user scrolls > a scroll event is triggered > placeholderHeight is updated > triggers an other scroll event  => infinite loop that leads to an auto scroll to the bottom

  const [start, setStart] = useState(0);
  const [end, setEnd] = useState(0);
  const [scrollTop, setScrollTop] = useState(0);
  const parentRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const listElement = parentRef.current;
    if (!listElement) return;

    const itemsPerPage = Math.ceil(listElement.offsetHeight / itemHeight) + 2;

    const newStart = Math.max(0, Math.floor(scrollTop / itemHeight) - 1);
    const newEnd = Math.min(items.length, newStart + itemsPerPage);

    setStart(newStart);
    setEnd(newEnd);
  }, [items, itemHeight, scrollTop]);

  useEffect(() => {
    const listElement = parentRef.current;
    if (!listElement) return;

    const scrollHandler = () => {
      setScrollTop(listElement.scrollTop);
    };

    listElement.addEventListener("scroll", scrollHandler);
    return () => listElement.removeEventListener("scroll", scrollHandler);
  }, [parentRef]);

Code sandbox

Any suggestions for solving this problem ?


问:
Can Nuxt JS behave like a normal website when changing routes?
I am trying to make Nuxt change routes and appear at the top of the new route, but without seeing it scrolling.

Right now it's either saving the last position, or it's changing the route while scrolling.

I don't want to see the page scrolling.

Setting this code in nuxt.config does nothing:

router: {
  saveScrollPosition: false
}
```
<ol start="2">
<li>Setting this code in app/router.scrollBehavior.js scrolls to top visibly:</li>
</ol>
<pre class="lang-js prettyprint-override"><code>export default function (to, from, savedPosition) {
  return { x: 0, y: 0 }
}
</code>```

Nuxt version 2.15.8

Vue version 2.7.10

Body:
I am trying to make Nuxt change routes and appear at the top of the new route, but without seeing it scrolling.

Right now it's either saving the last position, or it's changing the route while scrolling.

I don't want to see the page scrolling.

Setting this code in nuxt.config does nothing:

router: {
  saveScrollPosition: false
}

Setting this code in app/router.scrollBehavior.js scrolls to top visibly:

export default function (to, from, savedPosition) {
  return { x: 0, y: 0 }
}

Nuxt version 2.15.8

Vue version 2.7.10


问:
Windows build a full encrypted message from outside signing
I can encrypt a message in windows given a certificate with a private key with CryptMsgOpenToEncode and CryptMsgUpdate. This returns an ASN1 signature which contains the signature and the certificate enclosed in a full ASN1 message.

My problem now is that I am forced to use an external signing Web API site. Upon signing, the returned string from this Web site is the signature and the certificates in two separated messages, not within an ASN1.

The question is how to to build the message into a proper detached PKCS#7 signature (which would be  put in a PDF file).

Must I build the ASN1 manually? I'm already using ASNC but I'm not sure how to build the complete message. Can I use openssl to combine certs + signature into a PKCS#7?

Thanks.


问:
How can I install all my project library packages in my system library?
I am using the r package renv. I have somehow managed to delete most of my system library packages. Fortunately, one of my project renv.lock files contains nearly all my packages.

What I want to do is to install all the packages in the renv.lock file in my system library.


问:
Vulkan Memory Allocator c interface issue
I have included vk_mem_alloc.h on my c project and in my cmake file i added it as an interface like this

```<code>add_library(include INTERFACE)
target_include_directories(include INTERFACE include)
</code>```

while include is the folder where i put my vma header file
and i added it without #define VMA_IMPLEMENTATION as mention in documentation like this

```<code>#include "include/vk_mem_alloc.h"
</code>```

and yet it always gives me

```<code>undefined reference to 'vmaCreateAllocator'
</code>```

when i try to initialize it

im using fedora 37 with vulkan 1.3

Body:
I have included vk_mem_alloc.h on my c project and in my cmake file i added it as an interface like this

add_library(include INTERFACE)
target_include_directories(include INTERFACE include)

while include is the folder where i put my vma header file
and i added it without #define VMA_IMPLEMENTATION as mention in documentation like this

#include "include/vk_mem_alloc.h"

and yet it always gives me

undefined reference to 'vmaCreateAllocator'

when i try to initialize it

im using fedora 37 with vulkan 1.3


问:
how to create TABLE like this below efficiently?
enter image description here
enter image description here
IF I want to create tables likes these which every table may includes any type of Component.
For now, I use pure table like below
enter image description here
But it is very hard and not pleasure to write like this way.
If there is any BETTER way to do this thing?</p>


问:
Azure function request Api with cert
When I test the api using console program works fine, but when I tried to do using a azure funtion this fail and I have error "Host lock lease acquired by instance ID 000000"

```<code>X509Certificate2 SenseCert = new X509Certificate2("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\client.pfx");
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Create the HTTP Request and add required headers and content
string xrfkey = "0123456789abcdef";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https:/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" + xrfkey);
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("X-xxxxxxx", xrfkey);
request.Headers.Add("Content-Type", "application/json");
// Add the certificate to the request and provide the user to execute
request.ClientCertificates.Add(SenseCert);
request.Headers.Add("X-xxxxxxxxx", @"UserXXXXXXXXX=internal;UserId=sadasdasdsad");

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
Console.WriteLine(new StreamReader(stream).ReadToEnd());
</code>```

And my function azure program

```<code>[FunctionName("CreateShoppingCartItem")]
    public async Task<IActionResult> CreateShoppingCartItems(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "shoppingcartitem")] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("Creating Shopping Cart Item");
        X509Certificate2 SenseCert = new X509Certificate2("client.pfx");
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        string xrfkey = "0123456789abcdef";
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(@"https:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" + xrfkey);
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json";
        httpWebRequest.Headers.Add("X-xxxxxxx", xrfkey);
        httpWebRequest.Headers.Add("Content-Type", "application/json");
        httpWebRequest.ClientCertificates.Add(SenseCert);
        httpWebRequest.Headers.Add("X-xxxxxxxxx", @"UserXXXXXXXXX=internal;UserId=sadasdasdsad");
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
        HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            log.LogInformation(result);
        }
        return new OkObjectResult("ok");
    }
</code>```

Then I use a cert pfx to authenticate. How do that using azure function.

I have the error when I call post method

Title: Azure function request Api with cert

Body:
When I test the api using console program works fine, but when I tried to do using a azure funtion this fail and I have error "Host lock lease acquired by instance ID 000000"

X509Certificate2 SenseCert = new X509Certificate2("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\client.pfx");
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Create the HTTP Request and add required headers and content
string xrfkey = "0123456789abcdef";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https:/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" + xrfkey);
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("X-xxxxxxx", xrfkey);
request.Headers.Add("Content-Type", "application/json");
// Add the certificate to the request and provide the user to execute
request.ClientCertificates.Add(SenseCert);
request.Headers.Add("X-xxxxxxxxx", @"UserXXXXXXXXX=internal;UserId=sadasdasdsad");

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
Console.WriteLine(new StreamReader(stream).ReadToEnd());

And my function azure program

[FunctionName("CreateShoppingCartItem")]
    public async Task<IActionResult> CreateShoppingCartItems(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "shoppingcartitem")] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("Creating Shopping Cart Item");
        X509Certificate2 SenseCert = new X509Certificate2("client.pfx");
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        string xrfkey = "0123456789abcdef";
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(@"https:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" + xrfkey);
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json";
        httpWebRequest.Headers.Add("X-xxxxxxx", xrfkey);
        httpWebRequest.Headers.Add("Content-Type", "application/json");
        httpWebRequest.ClientCertificates.Add(SenseCert);
        httpWebRequest.Headers.Add("X-xxxxxxxxx", @"UserXXXXXXXXX=internal;UserId=sadasdasdsad");
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
        HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            log.LogInformation(result);
        }
        return new OkObjectResult("ok");
    }

Then I use a cert pfx to authenticate. How do that using azure function.

I have the error when I call post method


问:
GetElementById Cannot Find Properties of null
For some reason when I run this code, the console says cannot find properties of add event listener, but the names are correct.

Popup.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Popup</title>
</head>
<body>
    <h1>Shell Shockers Dark Mode</h1>
    <h2>Settings</h3>

        <script src="popup.js"></script>
        <input type="button" id="hide" value="Hide Name">
        <input type="button" id="show" value="Show Name">
</body>

<style>

    :root {
        --background: #00001D;
    }

    body {
        width: 250px;
        height: 500px;
    }

    h1,h2 {
        color: white;
        text-align: center;
    }

    html {
        background: var(--background);
    }

</style>

</html>
</code>```

Popup.js

```<code>

var hide = document.getElementById('hide');

hide.addEventListener('click', function(){
    localStorage['HideName'] = true;
})

var show = document.getElementById('show');

show.addEventListener('click', function(){
    localStorage['HideName'] = false;
})
</code>```

My console here says that they cannot find the properties of null reading add event listener, but I double checked that the properties are correct? I can't seem to figure out why this is happening.

Body:
For some reason when I run this code, the console says cannot find properties of add event listener, but the names are correct.

Popup.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Popup</title>

Shell Shockers Dark Mode

Settings

        <input type="button" id="hide" value="Hide Name">
        <input type="button" id="show" value="Show Name">

Popup.js

var hide = document.getElementById('hide');

hide.addEventListener('click', function(){
    localStorage['HideName'] = true;
})

var show = document.getElementById('show');

show.addEventListener('click', function(){
    localStorage['HideName'] = false;
})

My console here says that they cannot find the properties of null reading add event listener, but I double checked that the properties are correct? I can't seem to figure out why this is happening.


问:
Access singleton service from Autofac module
I register the following service :

```<code>public static IServiceCollection AddVat(this IServiceCollection services, IConfiguration configuration)
{
    services.AddOptions();
    services.AddOptions<VatOptions>()
        .Bind(configuration.GetRequiredSection("Vat"));

    services.AddSingleton<IVatOptions, VatOptions>(serviceProvider =>
        serviceProvider.GetRequiredService<IOptions<VatOptions>>().Value
    );

    services.AddSingleton<IVatService, VatService>();

    return services;
}
</code>```

Is there a way to access it from an Autofac module ?

```<code>internal sealed class ApplicationModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
      // Get IVatService ?
    }
}
</code>```

Body:
I register the following service :

public static IServiceCollection AddVat(this IServiceCollection services, IConfiguration configuration)
{
    services.AddOptions();
    services.AddOptions<VatOptions>()
        .Bind(configuration.GetRequiredSection("Vat"));

    services.AddSingleton<IVatOptions, VatOptions>(serviceProvider =>
        serviceProvider.GetRequiredService<IOptions<VatOptions>>().Value
    );

    services.AddSingleton<IVatService, VatService>();

    return services;
}

Is there a way to access it from an Autofac module ?

internal sealed class ApplicationModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
      // Get IVatService ?
    }
}


问:
Why does the alert pop up more and more times?
I'm having a confusing problem, but I don't know why it comes up，I have a server level and a client side, they both use socket.io. When a button is clicked, the client side will send a data to the server level, and then the server level will send a feedback to the client side. If the feedback data is 1, the web page will pop up an alert.

The problem is that the alert appears once when I click the button for the first time, twice when I click the button for the second time, and three times when I click the button for the third time...
This is the code for the client：

```<code>function log(names, proto) {
    socket.emit('log',
        JSON.stringify({
            msg: names,
            proto: proto
        })
    )
    socket.on('Existing-user',(e)=>{
        console.log('!')
        if(e===0){
            $(".login").hide()
            $(".content").show()
        }else{
            alert("The username is repeated, please change it.")
        }
    })
}
</code>```

This is the code on the server side：

```<code>    socket.on('log', function (e) {
        let loginfo = JSON.parse(e);
        if(userlist.includes(loginfo.msg)){
            socket.emit('Existing-user',1)
            console.log('!')
        }else{
            userlist.push(loginfo.msg)
            socket.emit('Existing-user',0)
        }
        console.log(userlist)
    })
</code>```

Body:
I'm having a confusing problem, but I don't know why it comes up，I have a server level and a client side, they both use socket.io. When a button is clicked, the client side will send a data to the server level, and then the server level will send a feedback to the client side. If the feedback data is 1, the web page will pop up an alert.

The problem is that the alert appears once when I click the button for the first time, twice when I click the button for the second time, and three times when I click the button for the third time...
This is the code for the client：

function log(names, proto) {
    socket.emit('log',
        JSON.stringify({
            msg: names,
            proto: proto
        })
    )
    socket.on('Existing-user',(e)=>{
        console.log('!')
        if(e===0){
            $(".login").hide()
            $(".content").show()
        }else{
            alert("The username is repeated, please change it.")
        }
    })
}

This is the code on the server side：

    socket.on('log', function (e) {
        let loginfo = JSON.parse(e);
        if(userlist.includes(loginfo.msg)){
            socket.emit('Existing-user',1)
            console.log('!')
        }else{
            userlist.push(loginfo.msg)
            socket.emit('Existing-user',0)
        }
        console.log(userlist)
    })


问:
MongoDB Aggregation - With $match, $or, and $in how to write
I have compared the AMC date with today's date, if it finds a less-than, the machine is said to have expired. After that I create a new amc by date array. So how can I write date in AMC date and, in AMC extend date with last id of AMC in match query of aggregation.

I extended the AMC date but it still shows as expired.

// Below is my code

```<code>let currentDate = moment(new Date()).format("YYYY-MM-DD");

 var AmcDateCheck = await Machine.aggregate([

      {

        $match: {

          $or: [

            { amcToDate: { $lt: currentDate } },

            {

              extendAmcDateArray: {

                amcdateId: { $eq: { $max: "$amcdateId" } },

                $in: [{ extendAmcToDate: { $lt: currentDate } }],

              },

            },

          ],

        },

      },
</code>```

// I want to output like this
The AMC extend date should be matched with today's date and if the machine is expired then it should be shown as expired otherwise not expired.

Body:
I have compared the AMC date with today's date, if it finds a less-than, the machine is said to have expired. After that I create a new amc by date array. So how can I write date in AMC date and, in AMC extend date with last id of AMC in match query of aggregation.

I extended the AMC date but it still shows as expired.

// Below is my code

let currentDate = moment(new Date()).format("YYYY-MM-DD");

 var AmcDateCheck = await Machine.aggregate([

      {

        $match: {

          $or: [

            { amcToDate: { $lt: currentDate } },

            {

              extendAmcDateArray: {

                amcdateId: { $eq: { $max: "$amcdateId" } },

                $in: [{ extendAmcToDate: { $lt: currentDate } }],

              },

            },

          ],

        },

      },

// I want to output like this
The AMC extend date should be matched with today's date and if the machine is expired then it should be shown as expired otherwise not expired.