问:
Why does dynamically adding a QTreeWidget to a QStackedWidget reset the font style?
I have a script (modeled by dialog.py) which contains a stacked widget that embeds a custom widget module (modeled by widget_1.py) into the first page. The user clicks the 'Switch Page' button to add another page to the stacked widget and embed it with a different widget (using widget_1.py here again since it is easy to see the problem later). Everything works out except the style guide for some of the items are ignored in the added page while others are not. Why?

First page of stacked widget with correct font styling.

Second page of stacked widget with default font styling.

dialog.py

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

from widget_1 import widget_1_UI

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.resize(640, 480)
        Dialog.setWindowTitle("I'm a cat. I'm a kitty cat.")
        self.addPage2 = False

        self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)

        self.stackedWidget = QtWidgets.QStackedWidget(Dialog)

        self.page_1 = widget_1_UI()
        self.page_1.setupUi(self.page_1)
        self.stackedWidget.insertWidget(0, self.page_1)
        self.stackedWidget.setCurrentIndex(0)

        self.verticalLayout.addWidget(self.stackedWidget)

        self.btn_nextPage = QtWidgets.QPushButton(Dialog)
        self.btn_nextPage.setText("Switch Page")
        self.verticalLayout.addWidget(self.btn_nextPage)
        self.btn_nextPage.clicked.connect(self.addSecond)
        self.btn_nextPage.clicked.connect(self.nextPage)

    def nextPage(self):
        num = self.stackedWidget.currentIndex()
        if num == 0:
            self.stackedWidget.setCurrentIndex(1)
        else:
            self.stackedWidget.setCurrentIndex(0)

    def addSecond(self):
        if not self.addPage2:
            self.page_2 = widget_1_UI()
            self.page_2.setupUi(self.page_2)
            self.stackedWidget.insertWidget(1, self.page_2)
            self.addPage2 = True

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())
</code>```

widget_1.py

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class widget_1_UI(QtWidgets.QWidget):
    def setupUi(self, Form):
        Form.resize(614, 411)
        Form.setWindowTitle("Main Dialog")

        self.verticalLayout = QtWidgets.QVBoxLayout(Form)

        self.label = QtWidgets.QLabel(Form)
        font = QtGui.QFont()
        font.setFamily("Arial Narrow")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setText("Cat Type")
        self.verticalLayout.addWidget(self.label)

        self.treeWidget = QtWidgets.QTreeWidget(Form)
        font = QtGui.QFont()
        font.setFamily("Arial Narrow")
        font.setPointSize(12)

        self.treeWidget.setFont(font)
        self.treeWidget.header().setVisible(False)
        self.catTypes = ["Happy", "Sleepy", "Hangry", "Needy", "Kneedy"]
        self.catSubtype = ["Orange", "Black", "Brown", "White"]
        for index in range(len(self.catTypes)):
            item_0 = QtWidgets.QTreeWidgetItem(self.treeWidget)
            item_0.setText(0, self.catTypes[index])
            for count in range(len(self.catSubtype)):
                item_1 = QtWidgets.QTreeWidgetItem(item_0)
                item_1.setText(0, self.catSubtype[count])
        self.verticalLayout.addWidget(self.treeWidget)
</code>```

Body:
I have a script (modeled by dialog.py) which contains a stacked widget that embeds a custom widget module (modeled by widget_1.py) into the first page. The user clicks the 'Switch Page' button to add another page to the stacked widget and embed it with a different widget (using widget_1.py here again since it is easy to see the problem later). Everything works out except the style guide for some of the items are ignored in the added page while others are not. Why?

First page of stacked widget with correct font styling.

Second page of stacked widget with default font styling.

dialog.py

from PyQt5 import QtCore, QtGui, QtWidgets

from widget_1 import widget_1_UI

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.resize(640, 480)
        Dialog.setWindowTitle("I'm a cat. I'm a kitty cat.")
        self.addPage2 = False

        self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)

        self.stackedWidget = QtWidgets.QStackedWidget(Dialog)

        self.page_1 = widget_1_UI()
        self.page_1.setupUi(self.page_1)
        self.stackedWidget.insertWidget(0, self.page_1)
        self.stackedWidget.setCurrentIndex(0)

        self.verticalLayout.addWidget(self.stackedWidget)

        self.btn_nextPage = QtWidgets.QPushButton(Dialog)
        self.btn_nextPage.setText("Switch Page")
        self.verticalLayout.addWidget(self.btn_nextPage)
        self.btn_nextPage.clicked.connect(self.addSecond)
        self.btn_nextPage.clicked.connect(self.nextPage)

    def nextPage(self):
        num = self.stackedWidget.currentIndex()
        if num == 0:
            self.stackedWidget.setCurrentIndex(1)
        else:
            self.stackedWidget.setCurrentIndex(0)

    def addSecond(self):
        if not self.addPage2:
            self.page_2 = widget_1_UI()
            self.page_2.setupUi(self.page_2)
            self.stackedWidget.insertWidget(1, self.page_2)
            self.addPage2 = True

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

widget_1.py

from PyQt5 import QtCore, QtGui, QtWidgets

class widget_1_UI(QtWidgets.QWidget):
    def setupUi(self, Form):
        Form.resize(614, 411)
        Form.setWindowTitle("Main Dialog")

        self.verticalLayout = QtWidgets.QVBoxLayout(Form)

        self.label = QtWidgets.QLabel(Form)
        font = QtGui.QFont()
        font.setFamily("Arial Narrow")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setText("Cat Type")
        self.verticalLayout.addWidget(self.label)

        self.treeWidget = QtWidgets.QTreeWidget(Form)
        font = QtGui.QFont()
        font.setFamily("Arial Narrow")
        font.setPointSize(12)

        self.treeWidget.setFont(font)
        self.treeWidget.header().setVisible(False)
        self.catTypes = ["Happy", "Sleepy", "Hangry", "Needy", "Kneedy"]
        self.catSubtype = ["Orange", "Black", "Brown", "White"]
        for index in range(len(self.catTypes)):
            item_0 = QtWidgets.QTreeWidgetItem(self.treeWidget)
            item_0.setText(0, self.catTypes[index])
            for count in range(len(self.catSubtype)):
                item_1 = QtWidgets.QTreeWidgetItem(item_0)
                item_1.setText(0, self.catSubtype[count])
        self.verticalLayout.addWidget(self.treeWidget)


来源: stackexchange

问:
Python 3.11: UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1: character maps to <undefined>
I'm writing local transform for Maltego where I need to first receive data from API in utf-8 and then send it to Maltego in cp1251.

I do something like:

```<code>some_txt_var = txt_from_api.encode("utf-8", "strict").decode("cp1251", "strict")
</code>```

and it works just fine for everything except one cyrillic charachter "И" - Capital Cyrillic I.

Code to illustrate the problem:

```<code>byte1 = "З".encode("utf-8", "strict")
byte2 = "Й".encode("utf-8", "strict")
byte3 = "І".encode("utf-8", "strict")
byte4 = "И".encode("utf-8", "strict")

print(byte1, byte2, byte3, byte4)
</code>```

Result:
b'\xd0\x97' b'\xd0\x99' b'\xd0\x86' b'\xd0\x98'

```<code>text1 = byte1.decode("cp1251", "strict")
text2 = byte2.decode("cp1251", "strict")
text3 = byte3.decode("cp1251", "strict")

print(text1, text2, text3)
</code>```

Result in target application:
З Й І

```<code>text4 = byte4.decode("cp1251", "strict")
</code>```

raises an error:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1: character maps to <undefined>

Can anybody suggest solution or workaround?

I have tried to "force" Maltego, which runs in Java Virtual Machine to accept utf-8 insted of cp1251 by setting JAVA_TOOL_OPTIONS -Dfile.encoding=UTF8 in Windows System Variables, but with no success.

So far I'm temporarily using .decode("cp1251", "replace") and get special \ufffd - Replacement Character instead of "И" сharacter, while all other chars are absolutely OK.

Update: I've managed to "force" Maltego to accept utf-8 encoded strings by changing Windows system language settings.
On Windows 10 computer:
Language settings >> Administrative language settings >> Change system language >> beta:use unicode (utf-8).
This is a workaround rather than a solution since potential users often use Windows machines without the possibility to change language settings due to the necessity to keep cp1251 for the other legacy software depending on this encoding.

Still puzzled by the exceptional treatment of "Cyrillic Capital I" by the Python decoder and will greatly appreciate advice on possible solutions.

ContentLicense: CC BY-SA 4.0

Body:
I'm writing local transform for Maltego where I need to first receive data from API in utf-8 and then send it to Maltego in cp1251.

I do something like:

some_txt_var = txt_from_api.encode("utf-8", "strict").decode("cp1251", "strict")

and it works just fine for everything except one cyrillic charachter "И" - Capital Cyrillic I.

Code to illustrate the problem:

byte1 = "З".encode("utf-8", "strict")
byte2 = "Й".encode("utf-8", "strict")
byte3 = "І".encode("utf-8", "strict")
byte4 = "И".encode("utf-8", "strict")

print(byte1, byte2, byte3, byte4)

Result:
b'\xd0\x97' b'\xd0\x99' b'\xd0\x86' b'\xd0\x98'

text1 = byte1.decode("cp1251", "strict")
text2 = byte2.decode("cp1251", "strict")
text3 = byte3.decode("cp1251", "strict")

print(text1, text2, text3)

Result in target application:
З Й І

text4 = byte4.decode("cp1251", "strict")

raises an error:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1: character maps to <undefined>

Can anybody suggest solution or workaround?

I have tried to "force" Maltego, which runs in Java Virtual Machine to accept utf-8 insted of cp1251 by setting JAVA_TOOL_OPTIONS -Dfile.encoding=UTF8 in Windows System Variables, but with no success.

So far I'm temporarily using .decode("cp1251", "replace") and get special \ufffd - Replacement Character instead of "И" сharacter, while all other chars are absolutely OK.

Update: I've managed to "force" Maltego to accept utf-8 encoded strings by changing Windows system language settings.
On Windows 10 computer:
Language settings >> Administrative language settings >> Change system language >> beta:use unicode (utf-8).
This is a workaround rather than a solution since potential users often use Windows machines without the possibility to change language settings due to the necessity to keep cp1251 for the other legacy software depending on this encoding.

Still puzzled by the exceptional treatment of "Cyrillic Capital I" by the Python decoder and will greatly appreciate advice on possible solutions.


问:
How can I auto sort customers into different Ultimate Member roles based off their age(DOB gathered at registration)?
I'm using Wordpress with Ultimate Member and I'm setting up so that content will be blocked if the user is not registered or below age 21.

I have it so that they are not able to see the content right now by default whether they're registered or not. I'd like to add a bit of code to check their D.O.B. against the current date and if above 21 put them into the customer group that the products are visible for.

Any suggestions or help at all is appreciated :)

I tried adapting this solution but I believe that uses WP-LOGIN, which bypasses Ultimate Member. Also I don't know the language or how to debug.. so my code alterations may have just broken it or such. How to set new user to a group automatically according to their role in Wordpress

added this to a functions.php under /wp-includes/ with the recommended plugin installed and groups created

I'm not sure what the "10" and "1" refer to here or where to find documentation.

add_action( 'user_register', 'myAssignGroup', 10, 1 );

function myAssignGroup($birth_date){

```<code> //Set user age based off now
 user_age = floor((current_time('U') - $birth_date)/(365*24*60*60));

 $user = new WP_User($user_age);

 foreach ($user->age as $age) {
     //for teacher
     if ($age<21) {
         wp_set_object_terms($user_age, 36, 'user-group', FALSE); //by tag_ID
       //wp_set_object_terms($user_age, my-first-group, 'user-group', FALSE);//by term slug
     }
     //for student
     else {
         wp_set_object_terms($user_age, 37, 'user-group', FALSE);
     }
 }
</code>```

}

****** EDIT-WORKING ******

Using the code found here, and the 'Plugin File Editor' option found under the 'Plugins' option on the sidebar, I got it working.

In case anyone else is having troubles with the non-updated instructions/documentation: I added the code to the 'Ultimate Member' plugin itself under "/Inlcudes/core/" in the "um-actions-form.php" file.

****** EDIT-WORKING ******

enter image description here

Body:
I'm using Wordpress with Ultimate Member and I'm setting up so that content will be blocked if the user is not registered or below age 21.

I have it so that they are not able to see the content right now by default whether they're registered or not. I'd like to add a bit of code to check their D.O.B. against the current date and if above 21 put them into the customer group that the products are visible for.

Any suggestions or help at all is appreciated :)

I tried adapting this solution but I believe that uses WP-LOGIN, which bypasses Ultimate Member. Also I don't know the language or how to debug.. so my code alterations may have just broken it or such. How to set new user to a group automatically according to their role in Wordpress

added this to a functions.php under /wp-includes/ with the recommended plugin installed and groups created

I'm not sure what the "10" and "1" refer to here or where to find documentation.

add_action( 'user_register', 'myAssignGroup', 10, 1 );

function myAssignGroup($birth_date){

 //Set user age based off now
 user_age = floor((current_time('U') - $birth_date)/(365*24*60*60));

 $user = new WP_User($user_age);

 foreach ($user->age as $age) {
     //for teacher
     if ($age<21) {
         wp_set_object_terms($user_age, 36, 'user-group', FALSE); //by tag_ID
       //wp_set_object_terms($user_age, my-first-group, 'user-group', FALSE);//by term slug
     }
     //for student
     else {
         wp_set_object_terms($user_age, 37, 'user-group', FALSE);
     }
 }

}

****** EDIT-WORKING ******

Using the code found here, and the 'Plugin File Editor' option found under the 'Plugins' option on the sidebar, I got it working.

In case anyone else is having troubles with the non-updated instructions/documentation: I added the code to the 'Ultimate Member' plugin itself under "/Inlcudes/core/" in the "um-actions-form.php" file.

****** EDIT-WORKING ******

enter image description here


问:
repeated sound while recording in javascript usign mediaRecorder
I have a function in javascript for voice recording, but the sound is repeated when it pay in client.
First I record the voice and I send it to nodejs server then I send it gain using socket to client back
My code
javascript (client)

```<code>function mainFunction(time) {

    navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then((stream) => {
        var madiaRecorder = new MediaRecorder(stream);
        madiaRecorder.start();

        var audioChunks = [];

        madiaRecorder.addEventListener("dataavailable", function (event) {
            console.log("collect");
            if (event.data.size > 0) {
                audioChunks.push(event.data);
            } else {

            }
        });

        madiaRecorder.addEventListener("stop", function () {
            console.log("stop");

            if (!userStatus.microphone || !userStatus.online) return;
            socket.emit("voiceIntenr", { data: audioChunks, room: userData[0].currentRoom });
            audioChunks = [];

            madiaRecorder.start();
            setTimeout(function () {
                madiaRecorder.stop();
            }, time);
        });

        setTimeout(function () {
            madiaRecorder.stop();
        }, time);

    });
}
</code>```

}

Nodejs srevr

```<code>socket.on("voiceIntenr", function ({ data, room }) {
          console.log("datatat");
          socket.broadcast.to(room).emit("send", data);
});
</code>```

Javascript client back

```<code>socket.on("send", function (data) {
    var blob = new Blob(data, { type: "audio/ogg; codecs=opus" });
    var audioURL = window.URL.createObjectURL(blob);
    var audio = new Audio(audioURL);
    audio.play();
});
</code>```

if can anyone help me for get the solution I will Thankful

Body:
I have a function in javascript for voice recording, but the sound is repeated when it pay in client.
First I record the voice and I send it to nodejs server then I send it gain using socket to client back
My code
javascript (client)

function mainFunction(time) {

    navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then((stream) => {
        var madiaRecorder = new MediaRecorder(stream);
        madiaRecorder.start();

        var audioChunks = [];

        madiaRecorder.addEventListener("dataavailable", function (event) {
            console.log("collect");
            if (event.data.size > 0) {
                audioChunks.push(event.data);
            } else {

            }
        });

        madiaRecorder.addEventListener("stop", function () {
            console.log("stop");

            if (!userStatus.microphone || !userStatus.online) return;
            socket.emit("voiceIntenr", { data: audioChunks, room: userData[0].currentRoom });
            audioChunks = [];

            madiaRecorder.start();
            setTimeout(function () {
                madiaRecorder.stop();
            }, time);
        });

        setTimeout(function () {
            madiaRecorder.stop();
        }, time);

    });
}

}

Nodejs srevr

socket.on("voiceIntenr", function ({ data, room }) {
          console.log("datatat");
          socket.broadcast.to(room).emit("send", data);
});

Javascript client back

socket.on("send", function (data) {
    var blob = new Blob(data, { type: "audio/ogg; codecs=opus" });
    var audioURL = window.URL.createObjectURL(blob);
    var audio = new Audio(audioURL);
    audio.play();
});

if can anyone help me for get the solution I will Thankful


问:
Python - using csv.writer in a loop
I have a problem with creating a .csv file that takes data from multiple lists. Those lists are created from another files, where I search for items that are meaningful for me, i.e. file name, function name etc. My code should is executed in a loop for all files in a work folder:

```<code>def save_to_csv_file():
rows = zip(list_name, list_func_name, list_func_return_type_combined, list_func_arg_combined, list_func_object_type)
with open(current_directory + r"\Zadanie\test_csv_2.csv", "w+") as f:
    writer = csv.writer(f, delimiter=";")
    writer.writerow(header_list)
    for row in rows:
        writer.writerow(row)
</code>```

This code creates a .csv file like this:

But after saving data from file Acc.d_prec it overwrites it in second passing of the loop with data from file Adc_Irq.d_prec. And my desired output should look like this:

What changes should I make to achive that?

Title: Python - using csv.writer in a loop

Body:
I have a problem with creating a .csv file that takes data from multiple lists. Those lists are created from another files, where I search for items that are meaningful for me, i.e. file name, function name etc. My code should is executed in a loop for all files in a work folder:

def save_to_csv_file():
rows = zip(list_name, list_func_name, list_func_return_type_combined, list_func_arg_combined, list_func_object_type)
with open(current_directory + r"\Zadanie\test_csv_2.csv", "w+") as f:
    writer = csv.writer(f, delimiter=";")
    writer.writerow(header_list)
    for row in rows:
        writer.writerow(row)

This code creates a .csv file like this:

But after saving data from file Acc.d_prec it overwrites it in second passing of the loop with data from file Adc_Irq.d_prec. And my desired output should look like this:

What changes should I make to achive that?


问:
snapshot.connectionState stuck on 'waiting' and login view only logs in when I hot restart. I've tried everything
When trying to establish connection the circular progress bar just keeps on going because the connection state is stuck on waiting.

NotesView :

import 'package:app_two/lib/constants/routes.dart';
import 'package:app_two/lib/enums/menu_action.dart';
import 'package:app_two/lib/services/auth/auth_service.dart';
import 'package:app_two/lib/services/auth/crud/notes_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

class NotesView extends StatefulWidget {
  const NotesView({super.key});

  @override
  State<NotesView> createState() => _NotesViewState();
}

class _NotesViewState extends State<NotesView> {
  late Future _myFuture;
  late final NotesService _notesService;
  String get userEmail => AuthService.firebase().currentUser!.email!;

  @override
  void initState() {
    super.initState();
    _notesService = NotesService();
    getGet() async {
      return await _notesService.getOrCreateUser(email: userEmail);
    }

    _myFuture = getGet();
  }

  @override
  void dispose() {
    _notesService.close();
    super.dispose();
  }

  // getGet() async {
  //   return await _notesService.getOrCreateUser(email: userEmail);
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Main UI'),
        actions: [
          PopupMenuButton<MenuAction>(
            onSelected: (value) async {
              switch (value) {
                case MenuAction.logout:
                  final shouldLogout = await showLogOutDialog(context);
                  if (shouldLogout) {
                    await AuthService.firebase().logOut();
                    Navigator.of(context).pushNamedAndRemoveUntil(
                      loginRoute,
                      (_) => false,
                    );
                  }
              }
            },
            itemBuilder: (context) {
              return const [
                PopupMenuItem<MenuAction>(
                  value: MenuAction.logout,
                  child: Text('Logout'),
                ),
              ];
            },
          )
        ],
      ),
      body: FutureBuilder(
        future: _myFuture,
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.done:
              print(snapshot.connectionState);
              return const Text('Your notes will appear here');
            case ConnectionState.none:
              print(snapshot.connectionState);
              return const Text('None');
            case ConnectionState.waiting:
              print(snapshot.connectionState);
              return const CircularProgressIndicator();
            case ConnectionState.active:
              print(snapshot.connectionState);
              return const Text('Active');
          }
        },
      ),
    );
  }

  Future<bool> showLogOutDialog(BuildContext context) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('Sign out'),
          content: const Text('Are you sure you want to sign out?'),
          actions: [
            TextButton(
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
                child: const Text('Cancel')),
            TextButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: const Text('Logout'))
          ],
        );
      },
    ).then((value) => value ?? false);
  }
}
```
<p><code>NotesService</code> :</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' show join;
import 'crud_exceptions.dart';

class NotesService {
  Database? _db;

  List<DatabaseNote> _notes = [];

  final _notesStreamController =
      StreamController<List<DatabaseNote>>.broadcast();

  Stream<List<DatabaseNote>> get allNotes => _notesStreamController.stream;

  Future<DatabaseUser> getOrCreateUser({required String email}) async {
    try {
      final user = await getUser(email: email);
      return user;
    } on CouldNotFindUser {
      final createdUser = await createUser(email: email);
      return createdUser;
    } catch (e) {
      rethrow;
    }
  }

  Future<void> _cacheNotes() async {
    final allNotes = await getAllNotes();
    _notes = allNotes.toList();
    _notesStreamController.add(_notes);
  }

  Future<DatabaseNote> updateNote({
    required DatabaseNote note,
    required String text,
  }) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    //make sure note exists
    await getNote(id: note.id);
    //update db
    final updatesCount = await db.update(noteTable, {
      textColumn: text,
      isSyncedwithCloudColumn: 0,
    });
    if (updatesCount == 0) {
      throw CouldNotUpdateNote();
    } else {
      final updatedNote = await getNote(id: note.id);
      _notes.removeWhere((note) => note.id == updatedNote.id);
      _notes.add(updatedNote);
      _notesStreamController.add(_notes);
      return updatedNote;
    }
  }

  Future<Iterable<DatabaseNote>> getAllNotes() async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final notes = await db.query(noteTable);

    return notes.map((noteRow) => DatabaseNote.fromRow(noteRow));
  }

  Future<DatabaseNote> getNote({required int id}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final notes = await db.query(
      noteTable,
      limit: 1,
      where: 'id = ?',
      whereArgs: [id],
    );
    if (notes.isEmpty) {
      throw CouldNotFindNote();
    } else {
      final note = DatabaseNote.fromRow(notes.first);
      _notes.removeWhere((note) => note.id == id);
      _notesStreamController.add(_notes);
      return note;
    }
  }

  Future<int> deleteAllNotes() async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final numberOfdeletions = await db.delete(noteTable);
    _notes = [];
    _notesStreamController.add(_notes);
    return numberOfdeletions;
  }

  Future<void> deleteNote({required int id}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final deletedCount = await db.delete(
      noteTable,
      where: 'id = ?',
      whereArgs: [id],
    );
    if (deletedCount == 0) {
      throw CouldNotDeleteNote();
    } else {
      _notes.removeWhere((note) => note.id == id);
      _notesStreamController.add(_notes);
    }
  }

  Future<DatabaseNote> createNote({required DatabaseUser owner}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    //Make sure owner exists in database withthe correct id
    final dbUser = await getUser(email: owner.email);
    if (dbUser != owner) {
      throw CouldNotFindUser();
    }

    const text = '';
    //create the note
    final noteId = await db.insert(noteTable, {
      userIdColumn: owner.id,
      textColumn: text,
      isSyncedwithCloudColumn: 1,
    });

    final note = DatabaseNote(
      id: noteId,
      userId: owner.id,
      text: text,
      isSyncedWithCloud: true,
    );

    _notes.add(note);
    _notesStreamController.add(_notes);

    return note;
  }

  Future<DatabaseUser> getUser({required String email}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final results = await db.query(
      userTable,
      limit: 1,
      where: 'email = ?',
      whereArgs: [email.toLowerCase()],
    );
    if (results.isEmpty) {
      throw CouldNotFindUser();
    } else {
      return DatabaseUser.fromRow(results.first);
    }
  }

  Future<DatabaseUser> createUser({required String email}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final results = await db.query(
      userTable,
      limit: 1,
      where: 'email = ?',
      whereArgs: [email.toLowerCase()],
    );
    if (results.isNotEmpty) {
      throw UserAlreadyExists();
    }
    final userId = await db.insert(userTable, {
      emailColumn: email.toLowerCase(),
    });

    return DatabaseUser(id: userId, email: email);
  }

  Future<void> deleteUser({required String email}) async {
    final db = _getDatabaseorThrow();
    final deletedCount = await db.delete(
      userTable,
      where: 'email = ?',
      whereArgs: [email.toLowerCase()],
    );
    if (deletedCount != 1) {
      throw CouldNotDeleteUser();
    }
  }

  Database _getDatabaseorThrow() {
    final db = _db;
    if (db == null) {
      throw DatabaseIsNotOpen();
    } else {
      return db;
    }
  }

  Future<void> close() async {
    final db = _db;
    if (db == null) {
      throw DatabaseIsNotOpen();
    } else {
      await db.close();
      _db = null;
    }
  }

  Future<void> _ensureDbIsOpen() async {
    try {
      await open();
    } on DatabaseAlreadyOpenException {
      //empty
    }
  }

  Future<void> open() async {
    if (_db != null) {
      throw DatabaseAlreadyOpenException();
    }
    try {
      await _ensureDbIsOpen();
      final docsPath = await getApplicationDocumentsDirectory();
      final dbPath = join(docsPath.path, dbName);
      final db = await openDatabase(dbPath);
      _db = db;
      //create user table
      await db.execute(createUserTable);
      //create note table
      await db.execute(createNoteTable);
      await _cacheNotes();
    } on MissingPlatformDirectoryException {
      throw UnableToGetDocumentDirectory();
    }
  }
}

@immutable
class DatabaseUser {
  final int id;
  final String email;

  const DatabaseUser({
    required this.id,
    required this.email,
  });
  DatabaseUser.fromRow(Map<String, Object?> map)
      : id = map[idColumn] as int,
        email = map[emailColumn] as String;

  @override
  String toString() => 'Person, ID = $id, email= $email';

  @override
  bool operator ==(covariant DatabaseUser other) => id == other.id;

  @override
  int get hashCode => id.hashCode;
}

class DatabaseNote {
  final int id;
  final int userId;
  final String text;
  final bool isSyncedWithCloud;

  DatabaseNote({
    required this.id,
    required this.userId,
    required this.text,
    required this.isSyncedWithCloud,
  });

  DatabaseNote.fromRow(Map<String, Object?> map)
      : id = map[idColumn] as int,
        userId = map[userIdColumn] as int,
        text = map[textColumn] as String,
        isSyncedWithCloud =
            (map[isSyncedwithCloudColumn] as int) == 1 ? true : false;

  @override
  String toString() =>
      'Note, ID = $id, userId = $userId, isSyncedWithCloud = $isSyncedWithCloud, tesxt = $text';

  @override
  bool operator ==(covariant DatabaseNote other) => id == other.id;

  @override
  int get hashCode => id.hashCode;
}

const dbName = 'notes.db';
const noteTable = 'note';
const userTable = 'user';
const idColumn = 'id';
const emailColumn = 'email';
const userIdColumn = 'user_id';
const textColumn = 'text';
const isSyncedwithCloudColumn = 'is_synced_with_cloud';
const createUserTable = '''CREATE TABLE IF NOT EXISTS "user" (
        "id"    INTEGER NOT NULL,
        "email" TEXT NOT NULL UNIQUE,
        PRIMARY KEY("id" AUTOINCREMENT)
        );''';
const createNoteTable = '''CREATE TABLE IF NOT EXISTS "note" (
          "id"  INTEGER NOT NULL,
          "user_id" INTEGER NOT NULL,
          "text"    TEXT,
          "is_synced_with_cloud"    INTEGER DEFAULT 0,
          FOREIGN KEY("user_id") REFERENCES "user"("id"),
          PRIMARY KEY("id" AUTOINCREMENT)
        );''';
</code>```

main.dart :

import 'package:app_two/lib/constants/routes.dart';
import 'package:app_two/lib/services/auth/auth_service.dart';
import 'package:app_two/views/login_view.dart';
import 'package:app_two/views/notes_view.dart';
import 'package:app_two/views/register_view.dart';
import 'package:app_two/views/verify_email_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_phoenix/flutter_phoenix.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    Phoenix(
      child: MaterialApp(
        title: 'Demo',
        theme: ThemeData(
          primarySwatch: Colors.green,
        ),
        home: const HomePage(),
        routes: {
          loginRoute: (context) => const LoginView(),
          registerRoute: (context) => const RegisterView(),
          notesRoute: (context) => const NotesView(),
          verifyEmailRoute: (context) => const VerifyEmailView(),
        },
      ),
    ),
  );
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: AuthService.firebase().initialize(),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.done:
            final user = AuthService.firebase().currentUser;
            if (user != null) {
              if (user.isEmailVerified) {
                return const NotesView();
              } else {
                return const VerifyEmailView();
              }
            } else {
              return const LoginView();
            }

          default:
            return const CircularProgressIndicator();
        }
      },
    );
  }
}

// class RestartWidget extends StatefulWidget {
//   RestartWidget({required this.child});

//   final Widget child;

//   static void restartApp(BuildContext context) {
//     context.findAncestorStateOfType<_RestartWidgetState>()?.restartApp();
//   }

//   @override
//   _RestartWidgetState createState() => _RestartWidgetState();
// }

// class _RestartWidgetState extends State<RestartWidget> {
//   Key key = UniqueKey();

//   void restartApp() {
//     setState(() {
//       key = UniqueKey();
//     });
//   }

//   @override
//   Widget build(BuildContext context) {
//     return KeyedSubtree(
//       key: key,
//       child: widget.child,
//     );
//   }
// }
```
<p><code>LoginView</code> :</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:app_two/lib/constants/routes.dart';
import 'package:app_two/lib/services/auth/auth_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:app_two/lib/utilities/show_error_dialog.dart';
import 'package:app_two/lib/services/auth/auth_exceptions.dart';
import 'package:flutter_phoenix/flutter_phoenix.dart';

class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  State<LoginView> createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  late final TextEditingController _email;
  late final TextEditingController _password;

  @override
  void initState() {
    _email = TextEditingController();
    _password = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _email.dispose();
    _password.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Login')),
      body: Column(
        children: [
          TextField(
            controller: _email,
            keyboardType: TextInputType.emailAddress,
            decoration: const InputDecoration(hintText: 'Enter your email'),
          ),
          TextField(
            controller: _password,
            obscureText: true,
            enableSuggestions: false,
            autocorrect: false,
            decoration: const InputDecoration(hintText: 'Enter your password'),
          ),
          TextButton(
            onPressed: () async {
              final email = _email.text;
              final password = _password.text;
              try {
                AuthService.firebase().logIn(
                  email: email,
                  password: password,
                );
                var user = AuthService.firebase().currentUser;
                AuthService.firebase().reload();
                user = AuthService.firebase().currentUser;
                if (user?.isEmailVerified == true) {
                  Navigator.of(context).pushNamedAndRemoveUntil(
                    notesRoute,
                    (route) => false,
                  );
                } else {
                  print(user);
                  Navigator.of(context).pushNamedAndRemoveUntil(
                    verifyEmailRoute,
                    (route) => false,
                  );
                }
              } on UserNotFoundAuthException {
                await showErrorDialog(
                  context,
                  'User not found',
                );
              } on WrongPasswordAuthException {
                await showErrorDialog(
                  context,
                  'Wrong credentials',
                );
              } on GenericAuthException {
                await showErrorDialog(
                  context,
                  'Authentication error',
                );
              }
            },
            child: const Text("Login"),
          ),
          TextButton(
              onPressed: () {
                Navigator.of(context).pushNamedAndRemoveUntil(
                  registerRoute,
                  (route) => false,
                );
              },
              child: const Text('Not registered? Register here!'))
        ],
      ),
    );
  }
}
</code>```

After the user logs in I'm supposed to establish a connection and get a message when it is done.

LoginView is supposed to take the user to NotesView after the correct info but it always takes the user to verify email view regardless of what I input. print(user) returns null.

Body:
When trying to establish connection the circular progress bar just keeps on going because the connection state is stuck on waiting.

NotesView :

import 'package:app_two/lib/constants/routes.dart';
import 'package:app_two/lib/enums/menu_action.dart';
import 'package:app_two/lib/services/auth/auth_service.dart';
import 'package:app_two/lib/services/auth/crud/notes_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

class NotesView extends StatefulWidget {
  const NotesView({super.key});

  @override
  State<NotesView> createState() => _NotesViewState();
}

class _NotesViewState extends State<NotesView> {
  late Future _myFuture;
  late final NotesService _notesService;
  String get userEmail => AuthService.firebase().currentUser!.email!;

  @override
  void initState() {
    super.initState();
    _notesService = NotesService();
    getGet() async {
      return await _notesService.getOrCreateUser(email: userEmail);
    }

    _myFuture = getGet();
  }

  @override
  void dispose() {
    _notesService.close();
    super.dispose();
  }

  // getGet() async {
  //   return await _notesService.getOrCreateUser(email: userEmail);
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Main UI'),
        actions: [
          PopupMenuButton<MenuAction>(
            onSelected: (value) async {
              switch (value) {
                case MenuAction.logout:
                  final shouldLogout = await showLogOutDialog(context);
                  if (shouldLogout) {
                    await AuthService.firebase().logOut();
                    Navigator.of(context).pushNamedAndRemoveUntil(
                      loginRoute,
                      (_) => false,
                    );
                  }
              }
            },
            itemBuilder: (context) {
              return const [
                PopupMenuItem<MenuAction>(
                  value: MenuAction.logout,
                  child: Text('Logout'),
                ),
              ];
            },
          )
        ],
      ),
      body: FutureBuilder(
        future: _myFuture,
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.done:
              print(snapshot.connectionState);
              return const Text('Your notes will appear here');
            case ConnectionState.none:
              print(snapshot.connectionState);
              return const Text('None');
            case ConnectionState.waiting:
              print(snapshot.connectionState);
              return const CircularProgressIndicator();
            case ConnectionState.active:
              print(snapshot.connectionState);
              return const Text('Active');
          }
        },
      ),
    );
  }

  Future<bool> showLogOutDialog(BuildContext context) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('Sign out'),
          content: const Text('Are you sure you want to sign out?'),
          actions: [
            TextButton(
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
                child: const Text('Cancel')),
            TextButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: const Text('Logout'))
          ],
        );
      },
    ).then((value) => value ?? false);
  }
}

NotesService :

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' show join;
import 'crud_exceptions.dart';

class NotesService {
  Database? _db;

  List<DatabaseNote> _notes = [];

  final _notesStreamController =
      StreamController<List<DatabaseNote>>.broadcast();

  Stream<List<DatabaseNote>> get allNotes => _notesStreamController.stream;

  Future<DatabaseUser> getOrCreateUser({required String email}) async {
    try {
      final user = await getUser(email: email);
      return user;
    } on CouldNotFindUser {
      final createdUser = await createUser(email: email);
      return createdUser;
    } catch (e) {
      rethrow;
    }
  }

  Future<void> _cacheNotes() async {
    final allNotes = await getAllNotes();
    _notes = allNotes.toList();
    _notesStreamController.add(_notes);
  }

  Future<DatabaseNote> updateNote({
    required DatabaseNote note,
    required String text,
  }) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    //make sure note exists
    await getNote(id: note.id);
    //update db
    final updatesCount = await db.update(noteTable, {
      textColumn: text,
      isSyncedwithCloudColumn: 0,
    });
    if (updatesCount == 0) {
      throw CouldNotUpdateNote();
    } else {
      final updatedNote = await getNote(id: note.id);
      _notes.removeWhere((note) => note.id == updatedNote.id);
      _notes.add(updatedNote);
      _notesStreamController.add(_notes);
      return updatedNote;
    }
  }

  Future<Iterable<DatabaseNote>> getAllNotes() async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final notes = await db.query(noteTable);

    return notes.map((noteRow) => DatabaseNote.fromRow(noteRow));
  }

  Future<DatabaseNote> getNote({required int id}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final notes = await db.query(
      noteTable,
      limit: 1,
      where: 'id = ?',
      whereArgs: [id],
    );
    if (notes.isEmpty) {
      throw CouldNotFindNote();
    } else {
      final note = DatabaseNote.fromRow(notes.first);
      _notes.removeWhere((note) => note.id == id);
      _notesStreamController.add(_notes);
      return note;
    }
  }

  Future<int> deleteAllNotes() async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final numberOfdeletions = await db.delete(noteTable);
    _notes = [];
    _notesStreamController.add(_notes);
    return numberOfdeletions;
  }

  Future<void> deleteNote({required int id}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final deletedCount = await db.delete(
      noteTable,
      where: 'id = ?',
      whereArgs: [id],
    );
    if (deletedCount == 0) {
      throw CouldNotDeleteNote();
    } else {
      _notes.removeWhere((note) => note.id == id);
      _notesStreamController.add(_notes);
    }
  }

  Future<DatabaseNote> createNote({required DatabaseUser owner}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    //Make sure owner exists in database withthe correct id
    final dbUser = await getUser(email: owner.email);
    if (dbUser != owner) {
      throw CouldNotFindUser();
    }

    const text = '';
    //create the note
    final noteId = await db.insert(noteTable, {
      userIdColumn: owner.id,
      textColumn: text,
      isSyncedwithCloudColumn: 1,
    });

    final note = DatabaseNote(
      id: noteId,
      userId: owner.id,
      text: text,
      isSyncedWithCloud: true,
    );

    _notes.add(note);
    _notesStreamController.add(_notes);

    return note;
  }

  Future<DatabaseUser> getUser({required String email}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final results = await db.query(
      userTable,
      limit: 1,
      where: 'email = ?',
      whereArgs: [email.toLowerCase()],
    );
    if (results.isEmpty) {
      throw CouldNotFindUser();
    } else {
      return DatabaseUser.fromRow(results.first);
    }
  }

  Future<DatabaseUser> createUser({required String email}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseorThrow();
    final results = await db.query(
      userTable,
      limit: 1,
      where: 'email = ?',
      whereArgs: [email.toLowerCase()],
    );
    if (results.isNotEmpty) {
      throw UserAlreadyExists();
    }
    final userId = await db.insert(userTable, {
      emailColumn: email.toLowerCase(),
    });

    return DatabaseUser(id: userId, email: email);
  }

  Future<void> deleteUser({required String email}) async {
    final db = _getDatabaseorThrow();
    final deletedCount = await db.delete(
      userTable,
      where: 'email = ?',
      whereArgs: [email.toLowerCase()],
    );
    if (deletedCount != 1) {
      throw CouldNotDeleteUser();
    }
  }

  Database _getDatabaseorThrow() {
    final db = _db;
    if (db == null) {
      throw DatabaseIsNotOpen();
    } else {
      return db;
    }
  }

  Future<void> close() async {
    final db = _db;
    if (db == null) {
      throw DatabaseIsNotOpen();
    } else {
      await db.close();
      _db = null;
    }
  }

  Future<void> _ensureDbIsOpen() async {
    try {
      await open();
    } on DatabaseAlreadyOpenException {
      //empty
    }
  }

  Future<void> open() async {
    if (_db != null) {
      throw DatabaseAlreadyOpenException();
    }
    try {
      await _ensureDbIsOpen();
      final docsPath = await getApplicationDocumentsDirectory();
      final dbPath = join(docsPath.path, dbName);
      final db = await openDatabase(dbPath);
      _db = db;
      //create user table
      await db.execute(createUserTable);
      //create note table
      await db.execute(createNoteTable);
      await _cacheNotes();
    } on MissingPlatformDirectoryException {
      throw UnableToGetDocumentDirectory();
    }
  }
}

@immutable
class DatabaseUser {
  final int id;
  final String email;

  const DatabaseUser({
    required this.id,
    required this.email,
  });
  DatabaseUser.fromRow(Map<String, Object?> map)
      : id = map[idColumn] as int,
        email = map[emailColumn] as String;

  @override
  String toString() => 'Person, ID = $id, email= $email';

  @override
  bool operator ==(covariant DatabaseUser other) => id == other.id;

  @override
  int get hashCode => id.hashCode;
}

class DatabaseNote {
  final int id;
  final int userId;
  final String text;
  final bool isSyncedWithCloud;

  DatabaseNote({
    required this.id,
    required this.userId,
    required this.text,
    required this.isSyncedWithCloud,
  });

  DatabaseNote.fromRow(Map<String, Object?> map)
      : id = map[idColumn] as int,
        userId = map[userIdColumn] as int,
        text = map[textColumn] as String,
        isSyncedWithCloud =
            (map[isSyncedwithCloudColumn] as int) == 1 ? true : false;

  @override
  String toString() =>
      'Note, ID = $id, userId = $userId, isSyncedWithCloud = $isSyncedWithCloud, tesxt = $text';

  @override
  bool operator ==(covariant DatabaseNote other) => id == other.id;

  @override
  int get hashCode => id.hashCode;
}

const dbName = 'notes.db';
const noteTable = 'note';
const userTable = 'user';
const idColumn = 'id';
const emailColumn = 'email';
const userIdColumn = 'user_id';
const textColumn = 'text';
const isSyncedwithCloudColumn = 'is_synced_with_cloud';
const createUserTable = '''CREATE TABLE IF NOT EXISTS "user" (
        "id"    INTEGER NOT NULL,
        "email" TEXT NOT NULL UNIQUE,
        PRIMARY KEY("id" AUTOINCREMENT)
        );''';
const createNoteTable = '''CREATE TABLE IF NOT EXISTS "note" (
          "id"  INTEGER NOT NULL,
          "user_id" INTEGER NOT NULL,
          "text"    TEXT,
          "is_synced_with_cloud"    INTEGER DEFAULT 0,
          FOREIGN KEY("user_id") REFERENCES "user"("id"),
          PRIMARY KEY("id" AUTOINCREMENT)
        );''';

main.dart :

import 'package:app_two/lib/constants/routes.dart';
import 'package:app_two/lib/services/auth/auth_service.dart';
import 'package:app_two/views/login_view.dart';
import 'package:app_two/views/notes_view.dart';
import 'package:app_two/views/register_view.dart';
import 'package:app_two/views/verify_email_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_phoenix/flutter_phoenix.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    Phoenix(
      child: MaterialApp(
        title: 'Demo',
        theme: ThemeData(
          primarySwatch: Colors.green,
        ),
        home: const HomePage(),
        routes: {
          loginRoute: (context) => const LoginView(),
          registerRoute: (context) => const RegisterView(),
          notesRoute: (context) => const NotesView(),
          verifyEmailRoute: (context) => const VerifyEmailView(),
        },
      ),
    ),
  );
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: AuthService.firebase().initialize(),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.done:
            final user = AuthService.firebase().currentUser;
            if (user != null) {
              if (user.isEmailVerified) {
                return const NotesView();
              } else {
                return const VerifyEmailView();
              }
            } else {
              return const LoginView();
            }

          default:
            return const CircularProgressIndicator();
        }
      },
    );
  }
}

// class RestartWidget extends StatefulWidget {
//   RestartWidget({required this.child});

//   final Widget child;

//   static void restartApp(BuildContext context) {
//     context.findAncestorStateOfType<_RestartWidgetState>()?.restartApp();
//   }

//   @override
//   _RestartWidgetState createState() => _RestartWidgetState();
// }

// class _RestartWidgetState extends State<RestartWidget> {
//   Key key = UniqueKey();

//   void restartApp() {
//     setState(() {
//       key = UniqueKey();
//     });
//   }

//   @override
//   Widget build(BuildContext context) {
//     return KeyedSubtree(
//       key: key,
//       child: widget.child,
//     );
//   }
// }

LoginView :

import 'package:app_two/lib/constants/routes.dart';
import 'package:app_two/lib/services/auth/auth_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:app_two/lib/utilities/show_error_dialog.dart';
import 'package:app_two/lib/services/auth/auth_exceptions.dart';
import 'package:flutter_phoenix/flutter_phoenix.dart';

class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  State<LoginView> createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  late final TextEditingController _email;
  late final TextEditingController _password;

  @override
  void initState() {
    _email = TextEditingController();
    _password = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _email.dispose();
    _password.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Login')),
      body: Column(
        children: [
          TextField(
            controller: _email,
            keyboardType: TextInputType.emailAddress,
            decoration: const InputDecoration(hintText: 'Enter your email'),
          ),
          TextField(
            controller: _password,
            obscureText: true,
            enableSuggestions: false,
            autocorrect: false,
            decoration: const InputDecoration(hintText: 'Enter your password'),
          ),
          TextButton(
            onPressed: () async {
              final email = _email.text;
              final password = _password.text;
              try {
                AuthService.firebase().logIn(
                  email: email,
                  password: password,
                );
                var user = AuthService.firebase().currentUser;
                AuthService.firebase().reload();
                user = AuthService.firebase().currentUser;
                if (user?.isEmailVerified == true) {
                  Navigator.of(context).pushNamedAndRemoveUntil(
                    notesRoute,
                    (route) => false,
                  );
                } else {
                  print(user);
                  Navigator.of(context).pushNamedAndRemoveUntil(
                    verifyEmailRoute,
                    (route) => false,
                  );
                }
              } on UserNotFoundAuthException {
                await showErrorDialog(
                  context,
                  'User not found',
                );
              } on WrongPasswordAuthException {
                await showErrorDialog(
                  context,
                  'Wrong credentials',
                );
              } on GenericAuthException {
                await showErrorDialog(
                  context,
                  'Authentication error',
                );
              }
            },
            child: const Text("Login"),
          ),
          TextButton(
              onPressed: () {
                Navigator.of(context).pushNamedAndRemoveUntil(
                  registerRoute,
                  (route) => false,
                );
              },
              child: const Text('Not registered? Register here!'))
        ],
      ),
    );
  }
}

After the user logs in I'm supposed to establish a connection and get a message when it is done.

LoginView is supposed to take the user to NotesView after the correct info but it always takes the user to verify email view regardless of what I input. print(user) returns null.


问:
How to perform asynchronous requests with Yew.rs?
I have an app component inside of a Yew project which is a Rust front-end framework. The syntax for fetching a GET request is still a bit of a mystery to me, for example, the rust-analyzer is complaining about books.clone();:

```<code>struct BookList
use gloo_net::http::Request;
use yew::prelude::*;
use yew::prelude::use_effect;

#[function_component(App)]
pub fn app() -> Html {
  let books: UseStateHandle<Vec<BookList>> = use_state(|| vec![]);

  async fn fetch_books() {
    let response: Vec<> Request::get("http://localhost:3000/books");

    let cloned_books = books.clone();
    cloned_books.set(response.data);
  }

  use_effect(|| {
    fetch_books()
  });
}
</code>```

It is saying:

can't capture dynamic environment in an fn item use the || { ... }
closure form instead

I am essentially trying to write what would be the equivalent to this in React:

```<code>function App() {
  const [books, setBooks] = useState([]);

  const fetchBooks = async () => {
    const response = await axios.get(
      'http://localhost:3000/books'
    );

    setBooks(response.data);
  };

  useEffect(() => {
    fetchBooks();
  }, []);
</code>```

I am told I cannot run futures without use_async

but what I am not clear on and I have tried to do this, is how do I store the fetch(url) in a variable and then pass it to set()?

```<code>#[function_component(App)]
pub fn app() -> Html {
  let books: UseStateHandle<Vec<BookList>> = use_state(|| vec![]);

  let fetch_books = use_async(async {
    let response = fetch("http://localhost:3000/books");
  });

  let fetch_books = fetch_books.clone();
  fetch_books.set(response.data);

  use_effect(|| {
    fetch_books()
  });
}
</code>```

However, I still get complaints from rust-analyzer.

Body:
I have an app component inside of a Yew project which is a Rust front-end framework. The syntax for fetching a GET request is still a bit of a mystery to me, for example, the rust-analyzer is complaining about books.clone();:

struct BookList
use gloo_net::http::Request;
use yew::prelude::*;
use yew::prelude::use_effect;

#[function_component(App)]
pub fn app() -> Html {
  let books: UseStateHandle<Vec<BookList>> = use_state(|| vec![]);

  async fn fetch_books() {
    let response: Vec<> Request::get("http://localhost:3000/books");

    let cloned_books = books.clone();
    cloned_books.set(response.data);
  }

  use_effect(|| {
    fetch_books()
  });
}

It is saying:

can't capture dynamic environment in an fn item use the || { ... }
closure form instead

I am essentially trying to write what would be the equivalent to this in React:

function App() {
  const [books, setBooks] = useState([]);

  const fetchBooks = async () => {
    const response = await axios.get(
      'http://localhost:3000/books'
    );

    setBooks(response.data);
  };

  useEffect(() => {
    fetchBooks();
  }, []);

I am told I cannot run futures without use_async

but what I am not clear on and I have tried to do this, is how do I store the fetch(url) in a variable and then pass it to set()?

#[function_component(App)]
pub fn app() -> Html {
  let books: UseStateHandle<Vec<BookList>> = use_state(|| vec![]);

  let fetch_books = use_async(async {
    let response = fetch("http://localhost:3000/books");
  });

  let fetch_books = fetch_books.clone();
  fetch_books.set(response.data);

  use_effect(|| {
    fetch_books()
  });
}

However, I still get complaints from rust-analyzer.


问:
Linking writable pdf forms to QR code and store safely data
We use writable/fillable pdf forms for quality management. It would be perfect to place QR codes at process critical points in the customer manufacturing. The customer should scan the QR code, open the pdf form, edit the data and store/send the form back to us. The data should be stored by customer (e.g. sending per email), stored in his quality management account (i.e. typical online platform with user account) and at least it should be stored at our internal cloud server (e.g. sharepoint) by out company.

I checked some solutions e.g. generating QR code with Python, but it is unclear how I can link a fillable pdf to it and store the data in suitable way.

It would be great if somebody has an idea how to solve this issue in a most efficient way.


问:
Adding a downloaded library to project
I downloaded the libvorbis library, but I don't understand how to implement it in my project. I tried using Cygwin, but I still get:

```<code>fatal error: vorbis/codec.h: No such file or directory
</code>```

when I try to use the library.

I've also searched for terminal commands to directly install the libvorbis package, and CMake to try and use it, but I still can't figure it out.

Any tips?

Title: Adding a downloaded library to project

Body:
I downloaded the libvorbis library, but I don't understand how to implement it in my project. I tried using Cygwin, but I still get:

fatal error: vorbis/codec.h: No such file or directory

when I try to use the library.

I've also searched for terminal commands to directly install the libvorbis package, and CMake to try and use it, but I still can't figure it out.

Any tips?


问:
Return an average of an array in JavaScript
Looking to receive an array and take and return the average. If it is an empty string return 0.
This is the code I have so far.</p>
```<code>For some reason I am getting NaN when entered an empty array.

function calculateAverage(numbers) {
  if ((numbers = [])) return 0;
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  let result = total / numbers.length;
  return result;
}

</code>```

Body:
Looking to receive an array and take and return the average. If it is an empty string return 0.
This is the code I have so far.

For some reason I am getting NaN when entered an empty array.

function calculateAverage(numbers) {
  if ((numbers = [])) return 0;
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  let result = total / numbers.length;
  return result;
}


问:
Handle Response code that contains no Description in Swagger
In Swagger After Executing a Request.
The Server Response for Errors Doesn't Contain Accurate Description(Bad Request) of the Error
Instead it Shows Only the Status code( Error: response status is 400).

Current Error Image

Upon Inspection of Network Tab the Response Status Code Also Doesn't Contain Status Code Description

Using .NetCore API 3.1
And Swashbuckle Aspnetcore -6.4.0

Statup.cs

```<code>        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "BAIM");
            });
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthentication();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
</code>```

Action Method in Controller

```<code>        [HttpGet]
        public ActionResult<IEnumerable<WeatherForecast>> Get()
        {
            return BadRequest();
        }
</code>```

Required Image

Need the Response With Error Description.
Upon Removing '''app.UseHttpsRedirection();''' From startup.cs Response is in the Required Format But using http is  not Practical.
Reason Why this is Happening is Also Unknown.
If there is way to Customize Error: That is Also Good

I have Tried :

Reinstalling Packages

Removed Exception Handling Middleware Swagger Documentation And
Configuration, Authentication To Check If Its Working For Now .

Tried Sending Only Response Code Only.

Writing Response Instead of Returning Bad Request

Thank a Lot in Advance

Body:
In Swagger After Executing a Request.
The Server Response for Errors Doesn't Contain Accurate Description(Bad Request) of the Error
Instead it Shows Only the Status code( Error: response status is 400).

Current Error Image

Upon Inspection of Network Tab the Response Status Code Also Doesn't Contain Status Code Description

Using .NetCore API 3.1
And Swashbuckle Aspnetcore -6.4.0

Statup.cs

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "BAIM");
            });
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthentication();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

Action Method in Controller

        [HttpGet]
        public ActionResult<IEnumerable<WeatherForecast>> Get()
        {
            return BadRequest();
        }

Required Image

Need the Response With Error Description.
Upon Removing '''app.UseHttpsRedirection();''' From startup.cs Response is in the Required Format But using http is  not Practical.
Reason Why this is Happening is Also Unknown.
If there is way to Customize Error: That is Also Good

I have Tried :

Reinstalling Packages

Removed Exception Handling Middleware Swagger Documentation And
Configuration, Authentication To Check If Its Working For Now .

Tried Sending Only Response Code Only.

Writing Response Instead of Returning Bad Request

Thank a Lot in Advance


问:
Start Activity inside onReceive BroadcastReceiver
I created some custom notifications with 2 pendingintents.
After triggering one of them, I want to start the MainActivity in the onReceive() method.
But none of those 7 versions of the code is working.

I'm using Kotlin, and I'm testing on SDK version 32(emulator) and 33.

```<code>    class switchButtonListener : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {

        val selectedcat = intent?.action
        var idToIdentify = selectedcat!!.split("|")[1]

        if (selectedcat!!.contains("recatIntent")){
            //TestKotlinConstantClass.suggestedCategory = "Ungeplant"
            //overtake value from notification, open fragment0, insert value
            val database2 = SampleSQLiteDBHelperNotCategorized(context).writableDatabase
            val cursorClickedEntry: Cursor = database2.rawQuery(
                "select _id ,amount, date from expenses_notcat where _id ='"+idToIdentify.toString()+"'",
                null
            )

            var manualInputValue = ""
            var entryId = ""
            if (cursorClickedEntry.moveToFirst()) {
                entryId = cursorClickedEntry.getString(0)
                manualInputValue = cursorClickedEntry.getString(1)
                cursorClickedEntry.close()
            }

            TestKotlinConstantClass.acceptedValue = manualInputValue
            that.cancel(SUGGCAT, entryId.toInt())
            if (TestKotlinConstantClass.acceptedValue != "") {

                //version 0
                //val intent = Intent(context, MainActivity::class.java)
                //intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                //context?.startActivity(intent)

                // version 1
                //val i = Intent()
                //i.setClassName("com.example.myapplication", "com.example.myapplication.MainActivity")
                //i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                //context!!.startActivity(i)
                //context!!.applicationContext.startActivity(i)

                // version 2
                val intentone = Intent(context!!.applicationContext, MainActivity::class.java)
                intentone.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
                context!!.startActivity(intentone)

                // version 3
                //val intent1 = Intent()
                //intent1.setClassName(contex!!.packageName, MainActivity::class.java.name)
                //intent1.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                //context!!.startActivity(intent1)

                //version 4
                //val intent = Intent(context, MainActivity::class.java)
                //intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                //context!!.startActivity(intent)

                //version 5
                //val cName = ComponentName("com.example.myapplication", "com.example.myapplication.MainActivity")
                //val intent = Intent("android.intent.action.MAIN")
                //intent.component = cName
                //intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK

                //version 6
                //val intent = context!!.packageManager.getLaunchIntentForPackage("com.example.myapplication")
                //intent!!.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //context!!.startActivity(intent)

                //version 7
                //val intent: Intent = context!!.getPackageManager().getLaunchIntentForPackage(context.getPackageName())!!
                //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                //context!!.startActivity(i)
            }
        }
        else if (selectedcat!!.contains("goneIntent")){
            //remove notification
            // get entryid
            val database2 = SampleSQLiteDBHelperNotCategorized(context).writableDatabase
            val cursorClickedEntry: Cursor = database2.rawQuery(
                "select _id ,amount, date from expenses_notcat where _id ='"+idToIdentify.toString()+"'",
                null
            )
            var entryId = ""
            if (cursorClickedEntry.moveToFirst()){
                entryId = cursorClickedEntry.getString(0)
                cursorClickedEntry.close()
            }

            val databaseNotCat = SampleSQLiteDBHelperNotCategorized(context).writableDatabase
            databaseNotCat.execSQL("DELETE FROM expenses_notcat WHERE _id='"+ entryId.toString()+"'")

            that.cancel(SUGGCAT, entryId.toInt())
        }
    }
}
</code>```

Here is my entry (NotificationListener$switchButtonListener) in the manifest and also the activity I want to launch:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">

        <receiver android:name=".NotificationListener$switchButtonListener"></receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".ExampleWidgetService"
            android:permission="android.permission.BIND_REMOTEVIEWS"/>
    </application>
</manifest>
</code>```

If I execute the code of version 0 in some setOnClickListener, the code works perfectly and launches the main activity.
But its not possible for me to launch the main activity within the onreceive()
of BroadcastReceiver.
Most of the time the app is just doing nothing.

When I fill the intent (TestKotlinConstantClass.intent) and context (TestKotlinConstantClass.context) analog the coding in version 0 in some other widget funtion (where I already start different activities without an error) and store them in some helper variables and use those to start the activity in the onReceive(), it is working fine.
But it shouldn't be like so, that you have to press some widget button before you will be able to start the acitivty from the notification correctly.

```<code>TestKotlinConstantClass.context.startActivity(TestKotlinConstantClass.intent)
</code>```

Body:
I created some custom notifications with 2 pendingintents.
After triggering one of them, I want to start the MainActivity in the onReceive() method.
But none of those 7 versions of the code is working.

I'm using Kotlin, and I'm testing on SDK version 32(emulator) and 33.

    class switchButtonListener : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {

        val selectedcat = intent?.action
        var idToIdentify = selectedcat!!.split("|")[1]

        if (selectedcat!!.contains("recatIntent")){
            //TestKotlinConstantClass.suggestedCategory = "Ungeplant"
            //overtake value from notification, open fragment0, insert value
            val database2 = SampleSQLiteDBHelperNotCategorized(context).writableDatabase
            val cursorClickedEntry: Cursor = database2.rawQuery(
                "select _id ,amount, date from expenses_notcat where _id ='"+idToIdentify.toString()+"'",
                null
            )

            var manualInputValue = ""
            var entryId = ""
            if (cursorClickedEntry.moveToFirst()) {
                entryId = cursorClickedEntry.getString(0)
                manualInputValue = cursorClickedEntry.getString(1)
                cursorClickedEntry.close()
            }

            TestKotlinConstantClass.acceptedValue = manualInputValue
            that.cancel(SUGGCAT, entryId.toInt())
            if (TestKotlinConstantClass.acceptedValue != "") {

                //version 0
                //val intent = Intent(context, MainActivity::class.java)
                //intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                //context?.startActivity(intent)

                // version 1
                //val i = Intent()
                //i.setClassName("com.example.myapplication", "com.example.myapplication.MainActivity")
                //i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                //context!!.startActivity(i)
                //context!!.applicationContext.startActivity(i)

                // version 2
                val intentone = Intent(context!!.applicationContext, MainActivity::class.java)
                intentone.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
                context!!.startActivity(intentone)

                // version 3
                //val intent1 = Intent()
                //intent1.setClassName(contex!!.packageName, MainActivity::class.java.name)
                //intent1.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                //context!!.startActivity(intent1)

                //version 4
                //val intent = Intent(context, MainActivity::class.java)
                //intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                //context!!.startActivity(intent)

                //version 5
                //val cName = ComponentName("com.example.myapplication", "com.example.myapplication.MainActivity")
                //val intent = Intent("android.intent.action.MAIN")
                //intent.component = cName
                //intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK

                //version 6
                //val intent = context!!.packageManager.getLaunchIntentForPackage("com.example.myapplication")
                //intent!!.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //context!!.startActivity(intent)

                //version 7
                //val intent: Intent = context!!.getPackageManager().getLaunchIntentForPackage(context.getPackageName())!!
                //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                //context!!.startActivity(i)
            }
        }
        else if (selectedcat!!.contains("goneIntent")){
            //remove notification
            // get entryid
            val database2 = SampleSQLiteDBHelperNotCategorized(context).writableDatabase
            val cursorClickedEntry: Cursor = database2.rawQuery(
                "select _id ,amount, date from expenses_notcat where _id ='"+idToIdentify.toString()+"'",
                null
            )
            var entryId = ""
            if (cursorClickedEntry.moveToFirst()){
                entryId = cursorClickedEntry.getString(0)
                cursorClickedEntry.close()
            }

            val databaseNotCat = SampleSQLiteDBHelperNotCategorized(context).writableDatabase
            databaseNotCat.execSQL("DELETE FROM expenses_notcat WHERE _id='"+ entryId.toString()+"'")

            that.cancel(SUGGCAT, entryId.toInt())
        }
    }
}

Here is my entry (NotificationListener$switchButtonListener) in the manifest and also the activity I want to launch:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">

        <receiver android:name=".NotificationListener$switchButtonListener"></receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".ExampleWidgetService"
            android:permission="android.permission.BIND_REMOTEVIEWS"/>
    </application>
</manifest>

If I execute the code of version 0 in some setOnClickListener, the code works perfectly and launches the main activity.
But its not possible for me to launch the main activity within the onreceive()
of BroadcastReceiver.
Most of the time the app is just doing nothing.

When I fill the intent (TestKotlinConstantClass.intent) and context (TestKotlinConstantClass.context) analog the coding in version 0 in some other widget funtion (where I already start different activities without an error) and store them in some helper variables and use those to start the activity in the onReceive(), it is working fine.
But it shouldn't be like so, that you have to press some widget button before you will be able to start the acitivty from the notification correctly.

TestKotlinConstantClass.context.startActivity(TestKotlinConstantClass.intent)


问:
How to put condition if we click the "ADD" button to add product to CART in selenium
How to put condition if we click the "ADD" button to add product to CART for some product  customization window will open   and for some product customization window will not open. How to write condition in selenium.

I tried with getWindowHandle but it is not the child window.

```<code>String currentwindow = driver.getWindowHandle();
          // getting all the window handles in Set data structure
          Set<String> allWindows = driver.getWindowHandles();
          // traversing each ids with the help of iterator()
          Iterator<String> i = allWindows.iterator();
          //Iterating through the window handle ids
          while(i.hasNext()){
             String childwindow = i.next();
             if(!childwindow.equalsIgnoreCase(currentwindow)){
                driver.switchTo().window(childwindow);
                System.out.println("The child window is "+childwindow);
             } else {
                System.out.println("There are no children");
             }
          }

</code>```

Body:
How to put condition if we click the "ADD" button to add product to CART for some product  customization window will open   and for some product customization window will not open. How to write condition in selenium.

I tried with getWindowHandle but it is not the child window.

String currentwindow = driver.getWindowHandle();
          // getting all the window handles in Set data structure
          Set<String> allWindows = driver.getWindowHandles();
          // traversing each ids with the help of iterator()
          Iterator<String> i = allWindows.iterator();
          //Iterating through the window handle ids
          while(i.hasNext()){
             String childwindow = i.next();
             if(!childwindow.equalsIgnoreCase(currentwindow)){
                driver.switchTo().window(childwindow);
                System.out.println("The child window is "+childwindow);
             } else {
                System.out.println("There are no children");
             }
          }


问:
How to access a shared folder (A private folder shared with my account by an owner account) with Drive API and Flutter?
I am trying to upload a file to a shared folder but I can not find a solution. I want to upload to a folder that is shared by an owner account, shared with the account I am logged into.

This is how I get the Drive Folder ID of a parent folder, but I am unable to access a shared folder the same way:

```<code>  const mimeType = "application/vnd.google-apps.folder";
  String folderName = "Shared Folder Name";

  final found = await driveApi.files.list(
    spaces: 'drive',
    q: "mimeType = '$mimeType' and name = '$folderName'",
    $fields: "files(id, name)",
  );
  final files = found.files;
  if (files == null) {
    return null;
  }

  if (files.isNotEmpty) {
    return files.first.id;
  }
</code>```

Please help me understand how to access a shared folder, so I will be able to upload my pdf file to that folder.

Thanks

Body:
I am trying to upload a file to a shared folder but I can not find a solution. I want to upload to a folder that is shared by an owner account, shared with the account I am logged into.

This is how I get the Drive Folder ID of a parent folder, but I am unable to access a shared folder the same way:

  const mimeType = "application/vnd.google-apps.folder";
  String folderName = "Shared Folder Name";

  final found = await driveApi.files.list(
    spaces: 'drive',
    q: "mimeType = '$mimeType' and name = '$folderName'",
    $fields: "files(id, name)",
  );
  final files = found.files;
  if (files == null) {
    return null;
  }

  if (files.isNotEmpty) {
    return files.first.id;
  }

Please help me understand how to access a shared folder, so I will be able to upload my pdf file to that folder.

Thanks


问:
Amortized time complexity: DecreaseKey() in Fibonacci Heap
At Wikipedia we can find a description of DecreaseKey(). From my point of view, if we perform the operation of cutting the nodes or remarking them, it may take linear time complexity, depending on the height of the tree from which we are cutting subtrees off. However, in the conclusion we can read that:

The actual time to perform the cutting was O(k), therefore (again with a sufficiently large choice of c) the amortized running time is constant.

Where it is amortized to constant time? How? I don't understand, why it turns out to be constant, if I can see a linear dependency: the number of cut-off trees may be dependent on the height of the tree.


问:
How to change transaction name dynamically using variable/parameter file in Neoload
I want to change the transaction name dynamically. For example, I am running the script for 5 iteration and every iteration I am using different values from the parameter. So for every iteration I want to change the transaction name based on the value I am using.

I tried to pass the variable name but it is throwing error.