问:
Display firestore information randomly
```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:tasteefood/appColors/app_colors.dart';
import 'package:tasteefood/model/user_model.dart';
import 'package:tasteefood/pages/detailPage/details_page.dart';
import 'package:tasteefood/pages/favorite/favorite_page.dart';
import 'package:tasteefood/pages/settings/settings.dart';
import 'package:tasteefood/route/routing_page.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:tasteefood/search/search.dart';
import 'package:tasteefood/widgets/grid_view_widget.dart';
import 'package:tasteefood/widgets/single_product.dart';

late UserModel userModel;

Size? size;

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String query = "";
  var result;
  searchFunction(query, searchList) {
    result = searchList.where((element) {
      return element["productName"].toUpperCase().contains(query) ||
          element["productName"].toLowerCase().contains(query) ||
          element["productName"].toUpperCase().contains(query) &&
              element["productName"].toLowerCase().contains(query);
    }).toList();
    return result;
  }

  Future getCurrentUserDataFunction() async {
    await FirebaseFirestore.instance
        .collection("users")
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .get()
        .then(
      (DocumentSnapshot documentSnapshot) {
        if (documentSnapshot.exists) {
          userModel = UserModel.fromDocument(documentSnapshot);
        } else {
          print("Document does not exist the database");
        }
      },
    );
  }

  Widget buildCategory() {
    return Column(
      children: [
        ListTile(
          leading: Text(
            "Catégories",
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.normal,
            ),
          ),
          title: Align(
            alignment: Alignment.topRight,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => SearchPage()),
                );
              },
              child: new Text("+"),
            ),
          ),
        ),
        Container(
          height: size!.height * 0.1 + 20,
          child: StreamBuilder(
            stream:
                FirebaseFirestore.instance.collection("categories").snapshots(),
            builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshort) {
              if (!streamSnapshort.hasData) {
                return Center(child: const CircularProgressIndicator());
              }
              return ListView.builder(
                scrollDirection: Axis.horizontal,
                physics: BouncingScrollPhysics(),
                itemCount: streamSnapshort.data!.docs.length,
                itemBuilder: (ctx, index) {
                  return Categories(
                    onTap: () {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (context) => GridViewWidget(
                            subCollection: streamSnapshort.data!.docs[index]
                                ["categoryName"],
                            collection: "categories",
                            id: streamSnapshort.data!.docs[index].id,
                          ),
                        ),
                      );
                    },
                    categoryName: streamSnapshort.data!.docs[index]
                        ["categoryName"],
                    image: streamSnapshort.data!.docs[index]["categoryImge"],
                  );
                },
              );
            },
          ),
        ),
      ],
    );
  }

  Widget buildProduct(
      {required Stream<QuerySnapshot<Map<String, dynamic>>>? stream}) {
    return Container(
      height: size!.height / 3 + 40,
      child: StreamBuilder(
        stream: stream,
        builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshort) {
          if (!streamSnapshort.hasData) {
            return Center(child: const CircularProgressIndicator());
          }
          return ListView.builder(
            scrollDirection: Axis.horizontal,
            physics: BouncingScrollPhysics(),
            itemCount: streamSnapshort.data!.docs.length,
            itemBuilder: (ctx, index) {
              var varData = searchFunction(query, streamSnapshort.data!.docs);
              var data = varData[index];
              // var data = streamSnapshort.data!.docs[index];
              return SingleProduct(
                onTap: () {
                  RoutingPage.goTonext(
                    context: context,
                    navigateTo: DetailsPage(
                      productCategory: data["productCategory"],
                      productId: data["productId"],
                      productImage: data["productImage"],
                      productName: data["productName"],
                      productRate: data["productRate"],
                      productDescription: data["productDescription"],
                      productLink: data["productLink"],
                      companyphone: data["companyphone"],
                    ),
                  );
                },
                productId: data["productId"],
                productCategory: data["productCategory"],
                productRate: data["productRate"],
                productImage: data["productImage"],
                productName: data["productName"],
              );
            },
          );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    size = MediaQuery.of(context).size;
    getCurrentUserDataFunction();
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'CityAnnecy',
          style: GoogleFonts.roboto(
            fontSize: 26,
            fontWeight: FontWeight.bold,
            color: Color.fromARGB(255, 227, 38, 38),
          ),
        ),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.favorite),
            tooltip: 'Favorite',
            onPressed: () {
              RoutingPage.goTonext(
                context: context,
                navigateTo: FavoritePage(),
              );
            },
          ), //IconButton
          IconButton(
            icon: const Icon(Icons.settings),
            tooltip: 'Settings Icon',
            onPressed: () {
              RoutingPage.goTonext(
                context: context,
                navigateTo: SettingsPage(),
              );
            },
          ), //IconButton
        ], //<Widget
        automaticallyImplyLeading: false,
        elevation: 0,
        backgroundColor: Colors.transparent,
      ),
      body: ListView(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Material(
              elevation: 7,
              shadowColor: Colors.grey[300],
              child: TextFormField(
                onChanged: (value) {
                  setState(() {
                    query = value;
                  });
                },
                decoration: InputDecoration(
                  prefixIcon: Icon(Icons.search),
                  fillColor: AppColors.KwhiteColor,
                  hintText: "Rechercher",
                  filled: true,
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                  ),
                ),
              ),
            ),
          ),
          query == ""
              ? Column(
                  children: [
                    buildCategory(),
                    ListTile(
                      leading: Text(
                        "Activités",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      title: Align(
                        alignment: Alignment.topRight,
                        child: GestureDetector(
                          onTap: () {
                            RoutingPage.goTonext(
                              context: context,
                              navigateTo: SearchPage(),
                            );
                          },
                          child: new Text("+"),
                        ),
                      ),
                    ),
                    buildProduct(
                      stream: FirebaseFirestore.instance
                          .collection("products")
                          .orderBy("randomField")
                          .snapshots(),
                    ),
                    ListTile(
                      leading: Text(
                        "Sélection de la semaine",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      title: Align(
                        alignment: Alignment.topRight,
                        child: GestureDetector(
                          onTap: () {
                            RoutingPage.goTonext(
                              context: context,
                              navigateTo: SearchPage(),
                            );
                          },
                          child: new Text("+"),
                        ),
                      ),
                    ),
                    buildProduct(
                      stream: FirebaseFirestore.instance
                          .collection("products")
                          .snapshots(),
                    ),
                  ],
                )
              : Container(
                  child: StreamBuilder(
                    stream: FirebaseFirestore.instance
                        .collection("products")
                        .snapshots(),
                    builder: (context,
                        AsyncSnapshot<QuerySnapshot> streamSnapshort) {
                      if (!streamSnapshort.hasData) {
                        return Center(child: const CircularProgressIndicator());
                      }
                      var varData =
                          searchFunction(query, streamSnapshort.data!.docs);
                      return result.isEmpty
                          ? Center(child: Text("Not Found"))
                          : GridView.builder(
                              shrinkWrap: true,
                              itemCount: result.length,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2,
                                crossAxisSpacing: 5.0,
                                mainAxisSpacing: 5.0,
                                childAspectRatio: 0.6,
                              ),
                              itemBuilder: (ctx, index) {
                                var data = varData[index];
                                return SingleProduct(
                                  onTap: () {
                                    RoutingPage.goTonext(
                                      context: context,
                                      navigateTo: DetailsPage(
                                        productCategory:
                                            data["productCategory"],
                                        productId: data["productId"],
                                        productImage: data["productImage"],
                                        productName: data["productName"],
                                        productRate: data["productRate"],
                                        productDescription:
                                            data["productDescription"],
                                        productLink: data["productLink"],
                                        companyphone: data["companyphone"],
                                      ),
                                    );
                                  },
                                  productId: data["productId"],
                                  productCategory: data["productCategory"],
                                  productRate: data["productRate"],
                                  productImage: data["productImage"],
                                  productName: data["productName"],
                                );
                              },
                            );
                    },
                  ),
                ),
        ],
      ),
    );
  }
}

class Categories extends StatelessWidget {
  final String image;
  final String categoryName;
  final Function()? onTap;
  const Categories({
    Key? key,
    required this.onTap,
    required this.categoryName,
    required this.image,
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.all(12.0),
        width: size!.width / 2 - 35,
        decoration: BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.cover,
            image: NetworkImage(
              image,
            ),
          ),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colors.black.withOpacity(0.6),
          ),
          child: Center(
            child: Text(
              categoryName,
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
</code>```

enter image description here

Hello,

I want to randomly display my information of my products retrieved via firestore

How to adapt my code to my request

First my code displays retrieves categories, products but still displays the same order

The concerned function is: buildproduct()

In firestore I searched but I did not find on the instance

I want my products to be displayed randomly

I followed tutorials but I can't adapt my code to

Title: Display firestore information randomly

Body:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:tasteefood/appColors/app_colors.dart';
import 'package:tasteefood/model/user_model.dart';
import 'package:tasteefood/pages/detailPage/details_page.dart';
import 'package:tasteefood/pages/favorite/favorite_page.dart';
import 'package:tasteefood/pages/settings/settings.dart';
import 'package:tasteefood/route/routing_page.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:tasteefood/search/search.dart';
import 'package:tasteefood/widgets/grid_view_widget.dart';
import 'package:tasteefood/widgets/single_product.dart';

late UserModel userModel;

Size? size;

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String query = "";
  var result;
  searchFunction(query, searchList) {
    result = searchList.where((element) {
      return element["productName"].toUpperCase().contains(query) ||
          element["productName"].toLowerCase().contains(query) ||
          element["productName"].toUpperCase().contains(query) &&
              element["productName"].toLowerCase().contains(query);
    }).toList();
    return result;
  }

  Future getCurrentUserDataFunction() async {
    await FirebaseFirestore.instance
        .collection("users")
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .get()
        .then(
      (DocumentSnapshot documentSnapshot) {
        if (documentSnapshot.exists) {
          userModel = UserModel.fromDocument(documentSnapshot);
        } else {
          print("Document does not exist the database");
        }
      },
    );
  }

  Widget buildCategory() {
    return Column(
      children: [
        ListTile(
          leading: Text(
            "Catégories",
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.normal,
            ),
          ),
          title: Align(
            alignment: Alignment.topRight,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => SearchPage()),
                );
              },
              child: new Text("+"),
            ),
          ),
        ),
        Container(
          height: size!.height * 0.1 + 20,
          child: StreamBuilder(
            stream:
                FirebaseFirestore.instance.collection("categories").snapshots(),
            builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshort) {
              if (!streamSnapshort.hasData) {
                return Center(child: const CircularProgressIndicator());
              }
              return ListView.builder(
                scrollDirection: Axis.horizontal,
                physics: BouncingScrollPhysics(),
                itemCount: streamSnapshort.data!.docs.length,
                itemBuilder: (ctx, index) {
                  return Categories(
                    onTap: () {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (context) => GridViewWidget(
                            subCollection: streamSnapshort.data!.docs[index]
                                ["categoryName"],
                            collection: "categories",
                            id: streamSnapshort.data!.docs[index].id,
                          ),
                        ),
                      );
                    },
                    categoryName: streamSnapshort.data!.docs[index]
                        ["categoryName"],
                    image: streamSnapshort.data!.docs[index]["categoryImge"],
                  );
                },
              );
            },
          ),
        ),
      ],
    );
  }

  Widget buildProduct(
      {required Stream<QuerySnapshot<Map<String, dynamic>>>? stream}) {
    return Container(
      height: size!.height / 3 + 40,
      child: StreamBuilder(
        stream: stream,
        builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshort) {
          if (!streamSnapshort.hasData) {
            return Center(child: const CircularProgressIndicator());
          }
          return ListView.builder(
            scrollDirection: Axis.horizontal,
            physics: BouncingScrollPhysics(),
            itemCount: streamSnapshort.data!.docs.length,
            itemBuilder: (ctx, index) {
              var varData = searchFunction(query, streamSnapshort.data!.docs);
              var data = varData[index];
              // var data = streamSnapshort.data!.docs[index];
              return SingleProduct(
                onTap: () {
                  RoutingPage.goTonext(
                    context: context,
                    navigateTo: DetailsPage(
                      productCategory: data["productCategory"],
                      productId: data["productId"],
                      productImage: data["productImage"],
                      productName: data["productName"],
                      productRate: data["productRate"],
                      productDescription: data["productDescription"],
                      productLink: data["productLink"],
                      companyphone: data["companyphone"],
                    ),
                  );
                },
                productId: data["productId"],
                productCategory: data["productCategory"],
                productRate: data["productRate"],
                productImage: data["productImage"],
                productName: data["productName"],
              );
            },
          );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    size = MediaQuery.of(context).size;
    getCurrentUserDataFunction();
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'CityAnnecy',
          style: GoogleFonts.roboto(
            fontSize: 26,
            fontWeight: FontWeight.bold,
            color: Color.fromARGB(255, 227, 38, 38),
          ),
        ),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.favorite),
            tooltip: 'Favorite',
            onPressed: () {
              RoutingPage.goTonext(
                context: context,
                navigateTo: FavoritePage(),
              );
            },
          ), //IconButton
          IconButton(
            icon: const Icon(Icons.settings),
            tooltip: 'Settings Icon',
            onPressed: () {
              RoutingPage.goTonext(
                context: context,
                navigateTo: SettingsPage(),
              );
            },
          ), //IconButton
        ], //<Widget
        automaticallyImplyLeading: false,
        elevation: 0,
        backgroundColor: Colors.transparent,
      ),
      body: ListView(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Material(
              elevation: 7,
              shadowColor: Colors.grey[300],
              child: TextFormField(
                onChanged: (value) {
                  setState(() {
                    query = value;
                  });
                },
                decoration: InputDecoration(
                  prefixIcon: Icon(Icons.search),
                  fillColor: AppColors.KwhiteColor,
                  hintText: "Rechercher",
                  filled: true,
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                  ),
                ),
              ),
            ),
          ),
          query == ""
              ? Column(
                  children: [
                    buildCategory(),
                    ListTile(
                      leading: Text(
                        "Activités",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      title: Align(
                        alignment: Alignment.topRight,
                        child: GestureDetector(
                          onTap: () {
                            RoutingPage.goTonext(
                              context: context,
                              navigateTo: SearchPage(),
                            );
                          },
                          child: new Text("+"),
                        ),
                      ),
                    ),
                    buildProduct(
                      stream: FirebaseFirestore.instance
                          .collection("products")
                          .orderBy("randomField")
                          .snapshots(),
                    ),
                    ListTile(
                      leading: Text(
                        "Sélection de la semaine",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      title: Align(
                        alignment: Alignment.topRight,
                        child: GestureDetector(
                          onTap: () {
                            RoutingPage.goTonext(
                              context: context,
                              navigateTo: SearchPage(),
                            );
                          },
                          child: new Text("+"),
                        ),
                      ),
                    ),
                    buildProduct(
                      stream: FirebaseFirestore.instance
                          .collection("products")
                          .snapshots(),
                    ),
                  ],
                )
              : Container(
                  child: StreamBuilder(
                    stream: FirebaseFirestore.instance
                        .collection("products")
                        .snapshots(),
                    builder: (context,
                        AsyncSnapshot<QuerySnapshot> streamSnapshort) {
                      if (!streamSnapshort.hasData) {
                        return Center(child: const CircularProgressIndicator());
                      }
                      var varData =
                          searchFunction(query, streamSnapshort.data!.docs);
                      return result.isEmpty
                          ? Center(child: Text("Not Found"))
                          : GridView.builder(
                              shrinkWrap: true,
                              itemCount: result.length,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2,
                                crossAxisSpacing: 5.0,
                                mainAxisSpacing: 5.0,
                                childAspectRatio: 0.6,
                              ),
                              itemBuilder: (ctx, index) {
                                var data = varData[index];
                                return SingleProduct(
                                  onTap: () {
                                    RoutingPage.goTonext(
                                      context: context,
                                      navigateTo: DetailsPage(
                                        productCategory:
                                            data["productCategory"],
                                        productId: data["productId"],
                                        productImage: data["productImage"],
                                        productName: data["productName"],
                                        productRate: data["productRate"],
                                        productDescription:
                                            data["productDescription"],
                                        productLink: data["productLink"],
                                        companyphone: data["companyphone"],
                                      ),
                                    );
                                  },
                                  productId: data["productId"],
                                  productCategory: data["productCategory"],
                                  productRate: data["productRate"],
                                  productImage: data["productImage"],
                                  productName: data["productName"],
                                );
                              },
                            );
                    },
                  ),
                ),
        ],
      ),
    );
  }
}

class Categories extends StatelessWidget {
  final String image;
  final String categoryName;
  final Function()? onTap;
  const Categories({
    Key? key,
    required this.onTap,
    required this.categoryName,
    required this.image,
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.all(12.0),
        width: size!.width / 2 - 35,
        decoration: BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.cover,
            image: NetworkImage(
              image,
            ),
          ),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colors.black.withOpacity(0.6),
          ),
          child: Center(
            child: Text(
              categoryName,
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

enter image description here

Hello,

I want to randomly display my information of my products retrieved via firestore

How to adapt my code to my request

First my code displays retrieves categories, products but still displays the same order

The concerned function is: buildproduct()

In firestore I searched but I did not find on the instance

I want my products to be displayed randomly

I followed tutorials but I can't adapt my code to


来源: stackexchange

问:
Encrypt in python then decrypt in dart
I generate pair keys in dart, send the pem encoded public key via socket to python, recieve & retrieve the key from pem, then i encrypt a plaint text with the retrieved public key and send the cipher text back to dart via socket. when i try to decrypt the ciphertext with the matching private key im getting the following error:  [VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Invalid argument(s): decoding error #0      OAEPEncoding._decodeBlock (package:pointycastle/asymmetric/oaep.dart:452:7) . Im kind of sure that the problem is with the encoding in python's encrypt function but i couldn't catch it.

1- Generating RSA keys in dart (pointycastle) and then send the pem encoded public key to python.

```<code>String produceKey(RSAPublicKey my_pub) {
String public_pem = rsa_helper.CryptoUtils.encodeRSAPublicKeyToPem(my_pub);
return "//encryptedKEY" + public_pem; // communication via socket
</code>```

}

2- Recieve key and encrypt with it in python (using Cryptography library)

```<code>  public_key =serialization.load_pem_public_key(bytes(mykey,'utf8'), backend=default_backend())
                    message = "send 10 BTC to halit"

                    message = base64.b64encode(bytes(message,'utf8'))

                    encrypted_message = public_key.encrypt(
                        message,
                        padding.OAEP(
                            mgf=padding.MGF1(algorithm=hashes.SHA1()),
                            algorithm=hashes.SHA1(),
                            label=None
                        )
                    )
                    b = base64.b64encode(encrypted_message)
                    base64_str = b.decode('utf8')
//then send  cipher text to client
</code>```

3- Decrypt the recivied cipher text

```<code>        String cipher_text = serverResponse.substring(9);//take the cipher text from the socket.(first 9 character identifier so we pass them)
        Uint8List plain_text = rsaDecrypt(my_private,cipher_text);//decrypts cipher text given private key and the cipher text
        print(plain_text);
</code>```

Notes: socket communication is tested and looks to be well,
Pem public key that is sent is matching with the one is generated.

```<code>Uint8List rsaDecrypt(RSAPrivateKey myPrivate, Uint8List cipherText) {
final decryptor = OAEPEncoding(RSAEngine())
..init(false, PrivateKeyParameter<RSAPrivateKey>(myPrivate)); // false=decrypt

return _processInBlocks(decryptor, cipherText);
}
  //decrypt method from pointycastle package.
</code>```

Test Case

having pair keys:

```<code>  -----BEGIN PRIVATE KEY-----
   MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCPGT5j+2qdxrKp
   trWW4hZcIwdacuduH16J7FO/0URzKoXdA5M5xVXwU/6HxREkKp+A+XUQN8HZCILP
   mQzXkmWCLWNQP92o6WUeZQW6bcXYt11mS9JmDhDPXwuiq33vEMJFlXi1L1Wrq2nR
   WVHKsJAuwswCfEjBfVdrJjut88JGXD/w5Et3t3A/zVX2eGAM1sn97kt57/PESObP
   RVLB+avTVAEAu4Qb3/uMvRlmDVgE6eE6pm5La+ObyVrfDdP41ly7zNf3VqgtM0dM
   OuurDmIGigXLvbrbIsx/TVxmwXvtreWhSyBISKMUMPB2NgcnvEXjXkt+PO00dGcN
   8NI3erI9AgMBAAECggEAeHXWqJHfqVu30NgmuxItong2W3S4z2IG0nIn+iRuy8fz
   Eh9NU2eENaBvdtl02Y4r4YWdfv6A53ObsqhzQBFT9CbDIK3yqZt37QM7tDluQEXz
   kQao4hJbIkYvZEua4qGn+K2gBF4Jb08H8ByRlt/VMBf5Zuo60O7zpRZ1TLUTSOhi
   7V0Teuu8djneHRtLzPgnfvGa1Ok6f4ObZGFgoZqTXK9HXxEc4+nICQoYc8BsMUlL
   iPFnBzU4MlvF5xUT4bYWqQjsQBoHM7zVrpAtZ3xKeSSdbkEWivYkt36h+RQLm3SM
   /1M5Ji92MjoFnLawh2XbZ+QD3W4owSvtd91n48lH/QKBgQDEbBI/7kfew6WO921D
   jaEEIRwDxOn0kYZhoGozU8zUWUQBfCfDR5MNJWELvioCfTWcyAJ/+ysalSezYIHU
   nuSGe8YrFTWI/xkGdUk1rfdSehbcnoPBwAM7wgW+twIdJpCAk6VbVMdh2hQNKDEN
   0hAawk2PGr+2zm0qHuJhL0benwKBgQC6gKrbyv9XV6Th7blU0cnvY1fF3pdBKBFx
   U8oABAXi+8db2nUUxZ/zbOUUKFYd0yX5SukXArek8xrzPjf52CReL845k6M76fDy
   uSK4xQz900rueRaOANU4XxW+n+afti6CuoB5IINKRIne1S9ZEpmbtVWi0Y59+ANf
   1GmXgictowKBgFcD7V3HCK3GDIz2TcBUeNVkeY2t6VsAMQEE2KdeY2pbFUZ3IwJe
   reVv/rr+BoxNvbdz36+krGa9VvYfNcTkkyaEpLinT60eHY7/3GvcYql2DrSzwHjP
   wF7zyCnB1zzkvbVIM0PvndhajPF7MagGvD2ugD96QR4R+shjIDSfhgzPAoGBAI5b
   8o+NNzULYH9YP1RgQnzpXrFaBCinFhFkPNegOoIVYApcCWzOoRZls8KcO4fOibjt
   lliLKXTOYG71ujKK6s++O/M1H693FgWgjcFuIEmLxDGd2jqQpjC+W9HDKn4UyRHe
   nHxY9f51rKucHOUnznrNgs2imdrLun+mmuccYR1zAoGAHDkVep3Hy7cXVGwJzVeS
   lvAHadFlQ4TcvJqVv+uNB8hRsH7BZqsyWfnepWuy7MychkuWGHpiIpzBFxeMFvi1
   aKa1yjNARIHQLpXvZntVVM7pb2hWFKTNyOwKMJrp8o2h0DJKOar7jlLyNs3ZIDFM
   n7w9iHpANOewTaT8svyFnxI=
   -----END PRIVATE KEY-----

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjxk+Y/tqncayqba1luIW
XCMHWnLnbh9eiexTv9FEcyqF3QOTOcVV8FP+h8URJCqfgPl1EDfB2QiCz5kM15Jl
gi1jUD/dqOllHmUFum3F2LddZkvSZg4Qz18Loqt97xDCRZV4tS9Vq6tp0VlRyrCQ
LsLMAnxIwX1XayY7rfPCRlw/8ORLd7dwP81V9nhgDNbJ/e5Lee/zxEjmz0VSwfmr
01QBALuEG9/7jL0ZZg1YBOnhOqZuS2vjm8la3w3T+NZcu8zX91aoLTNHTDrrqw5i
BooFy7262yLMf01cZsF77a3loUsgSEijFDDwdjYHJ7xF415LfjztNHRnDfDSN3qy
PQIDAQAB
-----END PUBLIC KEY-----

plain_text = "Send To Halit 10BTC";
</code>```

the cipher text im getting in python is:

```<code>jQO/VTb2lJut94GB5ABgV5gXsd2ee3x++EUz9FaMMEn8zxSisfUY7qiaAtwfV8bIOw+rcvfmyfIdxngSDS1B6qj5gp/OWDRhcExY7rfPTbY0Y1unuS4N8+C4dO1sFDANKSwl5tDfrs1ZN99J8H24jO9TjB0EPAAezxO8/DyjPRhe0wiBunObz0iiyVK73APoHJ1atCQ8cjKXUipCELpvog5k+XAdVwBeLb6N+Yw9LNUCMlIMXalj2koZ6IwbMY687qx2XlSgIH11pZC8ArRg82CCW/zi5gYckbeWVkC75ne/O3q3wd7h8/t8rdD/62hIyucV68udIFW7amCSN8/XFQ==
</code>```

Getting Error mentioned above (Decoding error).

EDIT

Here is my server code in python which takes public key pem and encrypt some plain text and send the cipher text back to client

```<code>from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
import base64
import socket
import threading
import time
import traceback

IP = "127.0.0.1"
PORT = 5005
clients = []
client_names = []

def messageHandler(client,message:str): # send the message to the client
    if (not client == "osmanClient"):
        client.send(message.encode("utf-8"));
        time.sleep(0.3)

def handle(client,address):
    while True:
        try:
            msg = client.recv(1024).decode("utf-8")
            if (msg):
                print(msg)
                if len(msg) > 6 and msg[:6] == "//name":
                        client_names.append(msg[6:])
                        clients.append(client)
                        messageHandler(client,"//sendKEY") # request public key from client

                elif(len(msg)>14 and msg[:14]== "//encryptedKEY"):   # if the client send the pub key
                        mykey = msg[14:] # the pem string of public key
                        public_key =serialization.load_pem_public_key(bytes(mykey,'utf8'), backend=default_backend()) # retrieve public key from the pem
                        message = "send 10 BTC to halit"
                        message = base64.b64encode(bytes(message,'utf8'))
                        encrypted_message = public_key.encrypt(
                            message,
                            padding.OAEP(
                                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                                algorithm=hashes.SHA1(),
                                label=None
                            )
                        )
                        b = base64.b64encode(encrypted_message)
                        base64_str = b.decode('utf8')
                        print(base64_str)
                        messageHandler(client,"//hmacKey"+base64_str)# send the message to the client
                else:
                    print("KEY EKLEMEDE HATA OLUŞTU")

            else:
                print("ELSE KOLUNA DUSTU   :::   " + msg)

        except:
            # print(msg[6:]+"  :  NA BURAYA GİRDİ")
            print(traceback.format_exc())
            client.close()
            clients.remove(client)
            break
if __name__ == "__main__":
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((IP, PORT))
    server.listen()

    # Sunucu, bağlantı isteği gelene kadar dinlemeye devam ediyor
    print("Sunucu dinlemeye başladı...")
    while True:
        # Bağlantı isteği geldiğinde, kullanıcıyı kabul edip ve handle fonksiyonunu çalıştırarak mesajları dinlemeye başlayoruz
        client, address = server.accept()
        threading.Thread(target=handle, args=(client,address)).start()
</code>```

and on Client side

```<code>import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
import 'dart:convert';
import 'dart:math';
import 'package:encrypt/rsa.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'dart:ui';
import 'crypto.dart' as rsa_helper;

void main() async {

  Random random = new Random();
  int randomPort = random.nextInt(15000)+50000;
  final pair = rsa_helper.CryptoUtils.generateRSAKeyPair();
  final my_private = pair.privateKey as RSAPrivateKey;
  final my_public = pair.publicKey as RSAPublicKey;
  String mysocketIP = "localhost";
  print("Your IP:   $mysocketIP");
  print("Your PORT:  $randomPort");
  var sleepDuration = Duration(milliseconds: 400);
  var clientList = [];
  String serverIP = "localhost";
  int serverPort = 5005;
  Socket serverSocket = await Socket.connect(serverIP, serverPort);

  serverSocket.listen(
        (Uint8List data) async {
      String serverResponse = String.fromCharCodes(data);
       if(serverResponse.substring(0,9) == "//hmacKey"){
        print('cipher text recieved from server!'); // we recieved the cipher text
        String cipher_text = serverResponse.substring(9);
        String plain_text = decrypt_message(cipher_text, my_private);
      }

      else if(serverResponse =="//sendKEY") {
        sleep(sleepDuration);
        stdout.write(".");
        sleep(sleepDuration);
        print(".");
        // send the encoded pem public key to server
         serverSocket.add(utf8.encode("//encryptedKEY"+ rsa_helper.CryptoUtils.encodeRSAPublicKeyToPem(my_public)));
      }
      else{
        print("server:   $serverResponse");
      }

    },
    onError: (error) {
      print("Client: $error \n");
      serverSocket.destroy();
    },
    onDone: () async {
      print('Client: Server left. \n');

    },
  );
  serverSocket.add(utf8.encode("//nameTopaco"));
  await Future.delayed(Duration(seconds: 50));
  serverSocket.close();
}
</code>```

where as crypto.util class is class with the following utility code:
https://raw.githubusercontent.com/Ephenodrom/Dart-Basic-Utils/master/lib/src/CryptoUtils.dart

Solution
Thanks to Topaco, In client when decrypting we should decrypt like

```<code>String server_response = serverResponse.substring(9);
          print(server_response);
          final Uint8List cipherText = base64Decode(server_response);
          final decrypted = rsaDecrypt(my_private, cipherText);
          final decoded = utf8.decode(decrypted);
          final b64Decoded = base64Decode(decoded);
          print(decoded);
          print(utf8.decode(b64Decoded));
</code>```

ContentLicense: CC BY-SA 4.0

Title: Encrypt in python then decrypt in dart

Body:
I generate pair keys in dart, send the pem encoded public key via socket to python, recieve & retrieve the key from pem, then i encrypt a plaint text with the retrieved public key and send the cipher text back to dart via socket. when i try to decrypt the ciphertext with the matching private key im getting the following error:  [VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Invalid argument(s): decoding error #0      OAEPEncoding._decodeBlock (package:pointycastle/asymmetric/oaep.dart:452:7) . Im kind of sure that the problem is with the encoding in python's encrypt function but i couldn't catch it.

1- Generating RSA keys in dart (pointycastle) and then send the pem encoded public key to python.

String produceKey(RSAPublicKey my_pub) {
String public_pem = rsa_helper.CryptoUtils.encodeRSAPublicKeyToPem(my_pub);
return "//encryptedKEY" + public_pem; // communication via socket

}

2- Recieve key and encrypt with it in python (using Cryptography library)

  public_key =serialization.load_pem_public_key(bytes(mykey,'utf8'), backend=default_backend())
                    message = "send 10 BTC to halit"

                    message = base64.b64encode(bytes(message,'utf8'))

                    encrypted_message = public_key.encrypt(
                        message,
                        padding.OAEP(
                            mgf=padding.MGF1(algorithm=hashes.SHA1()),
                            algorithm=hashes.SHA1(),
                            label=None
                        )
                    )
                    b = base64.b64encode(encrypted_message)
                    base64_str = b.decode('utf8')
//then send  cipher text to client

3- Decrypt the recivied cipher text

        String cipher_text = serverResponse.substring(9);//take the cipher text from the socket.(first 9 character identifier so we pass them)
        Uint8List plain_text = rsaDecrypt(my_private,cipher_text);//decrypts cipher text given private key and the cipher text
        print(plain_text);

Notes: socket communication is tested and looks to be well,
Pem public key that is sent is matching with the one is generated.

Uint8List rsaDecrypt(RSAPrivateKey myPrivate, Uint8List cipherText) {
final decryptor = OAEPEncoding(RSAEngine())
..init(false, PrivateKeyParameter<RSAPrivateKey>(myPrivate)); // false=decrypt

return _processInBlocks(decryptor, cipherText);
}
  //decrypt method from pointycastle package.

Test Case

having pair keys:

  -----BEGIN PRIVATE KEY-----
   MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCPGT5j+2qdxrKp
   trWW4hZcIwdacuduH16J7FO/0URzKoXdA5M5xVXwU/6HxREkKp+A+XUQN8HZCILP
   mQzXkmWCLWNQP92o6WUeZQW6bcXYt11mS9JmDhDPXwuiq33vEMJFlXi1L1Wrq2nR
   WVHKsJAuwswCfEjBfVdrJjut88JGXD/w5Et3t3A/zVX2eGAM1sn97kt57/PESObP
   RVLB+avTVAEAu4Qb3/uMvRlmDVgE6eE6pm5La+ObyVrfDdP41ly7zNf3VqgtM0dM
   OuurDmIGigXLvbrbIsx/TVxmwXvtreWhSyBISKMUMPB2NgcnvEXjXkt+PO00dGcN
   8NI3erI9AgMBAAECggEAeHXWqJHfqVu30NgmuxItong2W3S4z2IG0nIn+iRuy8fz
   Eh9NU2eENaBvdtl02Y4r4YWdfv6A53ObsqhzQBFT9CbDIK3yqZt37QM7tDluQEXz
   kQao4hJbIkYvZEua4qGn+K2gBF4Jb08H8ByRlt/VMBf5Zuo60O7zpRZ1TLUTSOhi
   7V0Teuu8djneHRtLzPgnfvGa1Ok6f4ObZGFgoZqTXK9HXxEc4+nICQoYc8BsMUlL
   iPFnBzU4MlvF5xUT4bYWqQjsQBoHM7zVrpAtZ3xKeSSdbkEWivYkt36h+RQLm3SM
   /1M5Ji92MjoFnLawh2XbZ+QD3W4owSvtd91n48lH/QKBgQDEbBI/7kfew6WO921D
   jaEEIRwDxOn0kYZhoGozU8zUWUQBfCfDR5MNJWELvioCfTWcyAJ/+ysalSezYIHU
   nuSGe8YrFTWI/xkGdUk1rfdSehbcnoPBwAM7wgW+twIdJpCAk6VbVMdh2hQNKDEN
   0hAawk2PGr+2zm0qHuJhL0benwKBgQC6gKrbyv9XV6Th7blU0cnvY1fF3pdBKBFx
   U8oABAXi+8db2nUUxZ/zbOUUKFYd0yX5SukXArek8xrzPjf52CReL845k6M76fDy
   uSK4xQz900rueRaOANU4XxW+n+afti6CuoB5IINKRIne1S9ZEpmbtVWi0Y59+ANf
   1GmXgictowKBgFcD7V3HCK3GDIz2TcBUeNVkeY2t6VsAMQEE2KdeY2pbFUZ3IwJe
   reVv/rr+BoxNvbdz36+krGa9VvYfNcTkkyaEpLinT60eHY7/3GvcYql2DrSzwHjP
   wF7zyCnB1zzkvbVIM0PvndhajPF7MagGvD2ugD96QR4R+shjIDSfhgzPAoGBAI5b
   8o+NNzULYH9YP1RgQnzpXrFaBCinFhFkPNegOoIVYApcCWzOoRZls8KcO4fOibjt
   lliLKXTOYG71ujKK6s++O/M1H693FgWgjcFuIEmLxDGd2jqQpjC+W9HDKn4UyRHe
   nHxY9f51rKucHOUnznrNgs2imdrLun+mmuccYR1zAoGAHDkVep3Hy7cXVGwJzVeS
   lvAHadFlQ4TcvJqVv+uNB8hRsH7BZqsyWfnepWuy7MychkuWGHpiIpzBFxeMFvi1
   aKa1yjNARIHQLpXvZntVVM7pb2hWFKTNyOwKMJrp8o2h0DJKOar7jlLyNs3ZIDFM
   n7w9iHpANOewTaT8svyFnxI=
   -----END PRIVATE KEY-----

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjxk+Y/tqncayqba1luIW
XCMHWnLnbh9eiexTv9FEcyqF3QOTOcVV8FP+h8URJCqfgPl1EDfB2QiCz5kM15Jl
gi1jUD/dqOllHmUFum3F2LddZkvSZg4Qz18Loqt97xDCRZV4tS9Vq6tp0VlRyrCQ
LsLMAnxIwX1XayY7rfPCRlw/8ORLd7dwP81V9nhgDNbJ/e5Lee/zxEjmz0VSwfmr
01QBALuEG9/7jL0ZZg1YBOnhOqZuS2vjm8la3w3T+NZcu8zX91aoLTNHTDrrqw5i
BooFy7262yLMf01cZsF77a3loUsgSEijFDDwdjYHJ7xF415LfjztNHRnDfDSN3qy
PQIDAQAB
-----END PUBLIC KEY-----

plain_text = "Send To Halit 10BTC";

the cipher text im getting in python is:

jQO/VTb2lJut94GB5ABgV5gXsd2ee3x++EUz9FaMMEn8zxSisfUY7qiaAtwfV8bIOw+rcvfmyfIdxngSDS1B6qj5gp/OWDRhcExY7rfPTbY0Y1unuS4N8+C4dO1sFDANKSwl5tDfrs1ZN99J8H24jO9TjB0EPAAezxO8/DyjPRhe0wiBunObz0iiyVK73APoHJ1atCQ8cjKXUipCELpvog5k+XAdVwBeLb6N+Yw9LNUCMlIMXalj2koZ6IwbMY687qx2XlSgIH11pZC8ArRg82CCW/zi5gYckbeWVkC75ne/O3q3wd7h8/t8rdD/62hIyucV68udIFW7amCSN8/XFQ==

Getting Error mentioned above (Decoding error).

EDIT

Here is my server code in python which takes public key pem and encrypt some plain text and send the cipher text back to client

from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
import base64
import socket
import threading
import time
import traceback

IP = "127.0.0.1"
PORT = 5005
clients = []
client_names = []

def messageHandler(client,message:str): # send the message to the client
    if (not client == "osmanClient"):
        client.send(message.encode("utf-8"));
        time.sleep(0.3)

def handle(client,address):
    while True:
        try:
            msg = client.recv(1024).decode("utf-8")
            if (msg):
                print(msg)
                if len(msg) > 6 and msg[:6] == "//name":
                        client_names.append(msg[6:])
                        clients.append(client)
                        messageHandler(client,"//sendKEY") # request public key from client

                elif(len(msg)>14 and msg[:14]== "//encryptedKEY"):   # if the client send the pub key
                        mykey = msg[14:] # the pem string of public key
                        public_key =serialization.load_pem_public_key(bytes(mykey,'utf8'), backend=default_backend()) # retrieve public key from the pem
                        message = "send 10 BTC to halit"
                        message = base64.b64encode(bytes(message,'utf8'))
                        encrypted_message = public_key.encrypt(
                            message,
                            padding.OAEP(
                                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                                algorithm=hashes.SHA1(),
                                label=None
                            )
                        )
                        b = base64.b64encode(encrypted_message)
                        base64_str = b.decode('utf8')
                        print(base64_str)
                        messageHandler(client,"//hmacKey"+base64_str)# send the message to the client
                else:
                    print("KEY EKLEMEDE HATA OLUŞTU")

            else:
                print("ELSE KOLUNA DUSTU   :::   " + msg)

        except:
            # print(msg[6:]+"  :  NA BURAYA GİRDİ")
            print(traceback.format_exc())
            client.close()
            clients.remove(client)
            break
if __name__ == "__main__":
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((IP, PORT))
    server.listen()

    # Sunucu, bağlantı isteği gelene kadar dinlemeye devam ediyor
    print("Sunucu dinlemeye başladı...")
    while True:
        # Bağlantı isteği geldiğinde, kullanıcıyı kabul edip ve handle fonksiyonunu çalıştırarak mesajları dinlemeye başlayoruz
        client, address = server.accept()
        threading.Thread(target=handle, args=(client,address)).start()

and on Client side

import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
import 'dart:convert';
import 'dart:math';
import 'package:encrypt/rsa.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'dart:ui';
import 'crypto.dart' as rsa_helper;

void main() async {

  Random random = new Random();
  int randomPort = random.nextInt(15000)+50000;
  final pair = rsa_helper.CryptoUtils.generateRSAKeyPair();
  final my_private = pair.privateKey as RSAPrivateKey;
  final my_public = pair.publicKey as RSAPublicKey;
  String mysocketIP = "localhost";
  print("Your IP:   $mysocketIP");
  print("Your PORT:  $randomPort");
  var sleepDuration = Duration(milliseconds: 400);
  var clientList = [];
  String serverIP = "localhost";
  int serverPort = 5005;
  Socket serverSocket = await Socket.connect(serverIP, serverPort);

  serverSocket.listen(
        (Uint8List data) async {
      String serverResponse = String.fromCharCodes(data);
       if(serverResponse.substring(0,9) == "//hmacKey"){
        print('cipher text recieved from server!'); // we recieved the cipher text
        String cipher_text = serverResponse.substring(9);
        String plain_text = decrypt_message(cipher_text, my_private);
      }

      else if(serverResponse =="//sendKEY") {
        sleep(sleepDuration);
        stdout.write(".");
        sleep(sleepDuration);
        print(".");
        // send the encoded pem public key to server
         serverSocket.add(utf8.encode("//encryptedKEY"+ rsa_helper.CryptoUtils.encodeRSAPublicKeyToPem(my_public)));
      }
      else{
        print("server:   $serverResponse");
      }

    },
    onError: (error) {
      print("Client: $error \n");
      serverSocket.destroy();
    },
    onDone: () async {
      print('Client: Server left. \n');

    },
  );
  serverSocket.add(utf8.encode("//nameTopaco"));
  await Future.delayed(Duration(seconds: 50));
  serverSocket.close();
}

where as crypto.util class is class with the following utility code:
https://raw.githubusercontent.com/Ephenodrom/Dart-Basic-Utils/master/lib/src/CryptoUtils.dart

Solution
Thanks to Topaco, In client when decrypting we should decrypt like

String server_response = serverResponse.substring(9);
          print(server_response);
          final Uint8List cipherText = base64Decode(server_response);
          final decrypted = rsaDecrypt(my_private, cipherText);
          final decoded = utf8.decode(decrypted);
          final b64Decoded = base64Decode(decoded);
          print(decoded);
          print(utf8.decode(b64Decoded));


问:
Where can I store my scheduled tasks for continuity?
I am using Nestjs. I wrote a function to execute given function after n minutes.

It is here :

```<code>@Injectable()
export class TasksService {
  constructor(private schedulerRegistry: SchedulerRegistry) {}

  execAfterGivenMinutes(cb: Function, minutes: number) {
    const TIMEOUT_NAME = 'after_minutes_' + nanoid();

    const timeout = setTimeout(() => {
      cb();

      this.deleteTimeout(TIMEOUT_NAME);
    }, minutes * 60000);

    this.schedulerRegistry.addTimeout(TIMEOUT_NAME, timeout);
  }

  private deleteTimeout(name: string) {
    this.schedulerRegistry.deleteTimeout(name);
  }
}
</code>```

However, there may be uncompleted tasks when the server crashes for any reason. For example there is a callback that is given the task function to execute after 2 minutes, but after 1 minute the server crashed and task did not complete. I do not want this. What is the possible things that I can do.

I thought storing tasks another server but if there is any solution I won't implement this.

Body:
I am using Nestjs. I wrote a function to execute given function after n minutes.

It is here :

@Injectable()
export class TasksService {
  constructor(private schedulerRegistry: SchedulerRegistry) {}

  execAfterGivenMinutes(cb: Function, minutes: number) {
    const TIMEOUT_NAME = 'after_minutes_' + nanoid();

    const timeout = setTimeout(() => {
      cb();

      this.deleteTimeout(TIMEOUT_NAME);
    }, minutes * 60000);

    this.schedulerRegistry.addTimeout(TIMEOUT_NAME, timeout);
  }

  private deleteTimeout(name: string) {
    this.schedulerRegistry.deleteTimeout(name);
  }
}

However, there may be uncompleted tasks when the server crashes for any reason. For example there is a callback that is given the task function to execute after 2 minutes, but after 1 minute the server crashed and task did not complete. I do not want this. What is the possible things that I can do.

I thought storing tasks another server but if there is any solution I won't implement this.


问:
Is there any way to count the production of specific rules in order in a context free grammar?
Is there any way to use a counter in context-free grammars?

I need to add a module number (for example starting from M1:0, M1:1, ... , M1:K representing the module number) and I want to count every block productions in order. The following production rule just adds an arbitrary digit number from <digit_list>:

```<code>S ⇒ <block> <fblock> <fcblock>
<block> ⇒ <cblocks><pblock>
<cblock> ⇒ <Module_ID>:<digit_list><cblock>|<Module_ID>:<digit_list><cblock><cblock>|<Module_ID>:<digit_list><cblock><cblock><cblock>
<cblock> ⇒ [C<block>]
<bblock> ⇒ BN|λ
<pblock> ⇒ <Module_ID>:<digit_list>[P<dblock>] |λ
<dblock> ⇒ D|λ
<fblock> ⇒ <Module_ID>:<digit_list>[F]
<fcblock>⇒ <Module_ID>:<digit_list>[FC<UNIT><dblock>]|λ
<UNIT> ⇒ 64|128
<Module_ID> ⇒ M1
<digit_list>⇒ <digit>|<digit><digit_list>
<digit>⇒ 0|1|2|...|9
</code>```

Is there any way to generate and count the modules number produced on the right-hand side of the production rules (the modules that have <Module_ID>:<digit_list> before) that I need to count them?

Is there any example or resources that I can use and refer to them?

Edited:

For example, the following shows the generated string I need to add M1:0 and etc before the modules in bracket [] to count them:

```<code>M1:0[CBN][CBN][C]M1:1[PD]M1:2[F]M1:3[FC64D]
</code>```

Body:
Is there any way to use a counter in context-free grammars?

I need to add a module number (for example starting from M1:0, M1:1, ... , M1:K representing the module number) and I want to count every block productions in order. The following production rule just adds an arbitrary digit number from <digit_list>:

S ⇒ <block> <fblock> <fcblock>
<block> ⇒ <cblocks><pblock>
<cblock> ⇒ <Module_ID>:<digit_list><cblock>|<Module_ID>:<digit_list><cblock><cblock>|<Module_ID>:<digit_list><cblock><cblock><cblock>
<cblock> ⇒ [C<block>]
<bblock> ⇒ BN|λ
<pblock> ⇒ <Module_ID>:<digit_list>[P<dblock>] |λ
<dblock> ⇒ D|λ
<fblock> ⇒ <Module_ID>:<digit_list>[F]
<fcblock>⇒ <Module_ID>:<digit_list>[FC<UNIT><dblock>]|λ
<UNIT> ⇒ 64|128
<Module_ID> ⇒ M1
<digit_list>⇒ <digit>|<digit><digit_list>
<digit>⇒ 0|1|2|...|9

Is there any way to generate and count the modules number produced on the right-hand side of the production rules (the modules that have <Module_ID>:<digit_list> before) that I need to count them?

Is there any example or resources that I can use and refer to them?

Edited:

For example, the following shows the generated string I need to add M1:0 and etc before the modules in bracket [] to count them:

M1:0[CBN][CBN][C]M1:1[PD]M1:2[F]M1:3[FC64D]


问:
Is there any way to get the conceptnet dump file that only contains English nodes
I tried to download the whole dump file (assertions) from the https://github.com/commonsense/conceptnet5/wiki/Downloads This file is extremely large (~10GB) and then I write a python script to filter out non-English nodes:

```<code>FILE = 'conceptnet-assertions-5.7.0.csv'
data = pd.read_csv(FILE, delimiter='\t')
data.columns = ['uri', 'relation', 'start', 'end', 'json']
# delete non-english nodes
data = data[data['start'].apply(lambda row: row.find('en') > 0) & data['end'].apply(lambda row: row.find('en') > 0)]
data.index = range(data.shape[0])
print(data)
</code>```

However, employing pandas to read this large csv file is very time-consuming and even after a long time I still cannot get the result. In this case, I wonder if there is any effecient way to filter out non-english nodes?

Body:
I tried to download the whole dump file (assertions) from the https://github.com/commonsense/conceptnet5/wiki/Downloads This file is extremely large (~10GB) and then I write a python script to filter out non-English nodes:

FILE = 'conceptnet-assertions-5.7.0.csv'
data = pd.read_csv(FILE, delimiter='\t')
data.columns = ['uri', 'relation', 'start', 'end', 'json']
# delete non-english nodes
data = data[data['start'].apply(lambda row: row.find('en') > 0) & data['end'].apply(lambda row: row.find('en') > 0)]
data.index = range(data.shape[0])
print(data)

However, employing pandas to read this large csv file is very time-consuming and even after a long time I still cannot get the result. In this case, I wonder if there is any effecient way to filter out non-english nodes?


问:
Is there a way to import a js file globally as soon as the html is loaded?
I have an animation.js file in my vue app and I want to import this file globally.

When I import the JavaScript file into main.js, I have the problem that the HTML is not fully loaded yet and therefore the classes I am looking for in the JavaScript file are not found.

If I simply include the JS file in index.html with the script tag, I have the problem that after building the classes are only found by the navbar and footer component, because these are used directly in App.vue. All other components of the website are in <routerview/> and are not found.

This is the animation.js file:

```<code>    const observerOpacity = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animated-opacity');
            }
        });
    });

    const animatedOpacity = document.querySelectorAll('.animate-opacity');
    animatedOpacity.forEach((el) => observerOpacity.observe(el));
</code>```

This is my main.js (with my failed import):

```<code>import { createApp } from 'vue'
import './resources/css/app.pcss'
import App from './App.vue'
import router from "./router/index.js"

createApp(App).use(router).mount('#app')

import './resources/js/animate.js'
</code>```

I would like to find a way to import that animate.js globally and as soon as the dom is loaded complete.

Body:
I have an animation.js file in my vue app and I want to import this file globally.

When I import the JavaScript file into main.js, I have the problem that the HTML is not fully loaded yet and therefore the classes I am looking for in the JavaScript file are not found.

If I simply include the JS file in index.html with the script tag, I have the problem that after building the classes are only found by the navbar and footer component, because these are used directly in App.vue. All other components of the website are in <routerview/> and are not found.

This is the animation.js file:

    const observerOpacity = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animated-opacity');
            }
        });
    });

    const animatedOpacity = document.querySelectorAll('.animate-opacity');
    animatedOpacity.forEach((el) => observerOpacity.observe(el));

This is my main.js (with my failed import):

import { createApp } from 'vue'
import './resources/css/app.pcss'
import App from './App.vue'
import router from "./router/index.js"

createApp(App).use(router).mount('#app')

import './resources/js/animate.js'

I would like to find a way to import that animate.js globally and as soon as the dom is loaded complete.


问:
Can't get PyTesseract to recognize [, {, and :
I was messing with the settings (-psm), trying different test scenarios. Somehow, pytesseract just does not process the following screenshot into text for me. Completely. It returns an empty array/string/whatever it returns. I tried using unidecode utf-8 to no avail. Is the problem in the brackets?


问:
Django UpdateView - how to return an HttpResponse instead of a URL from "get_success_url"
In the get_success_url you are supposed to provide a reverse url, however I want to pass a simple HTTPResponse (without a template), how can I accomplish that with an UpdateView like so?</p>
```<code>class SomeView(UpdateView):
    model = MyModel
    form_class = MyModelForm
    template_name = 'form.html'

    def get_success_url(self):
        response = HttpResponse('', status=204)
        return response
</code>```

Body:
In the get_success_url you are supposed to provide a reverse url, however I want to pass a simple HTTPResponse (without a template), how can I accomplish that with an UpdateView like so?

class SomeView(UpdateView):
    model = MyModel
    form_class = MyModelForm
    template_name = 'form.html'

    def get_success_url(self):
        response = HttpResponse('', status=204)
        return response


问:
Opencv c++ lsb steganography not generating complete image
I am using this code to do lsb steganography, everything seems to work fine but the generated image [[enter image description here](https://i.stack.imgur.com/DNvJQ.png)](https://i.stack.imgur.com/kr1vy.png), is cut like not all the column are done by the for loop.

thank you for your help

```<code>#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <list>
#include <string>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stdlib.h>

using namespace cv;
using namespace std;

void reverseStr(string& str);
static string decimalToBinary(int dec);
static int binaryToDecimal(string binary);

int main()
{

    string pixelImg;
    string pixelMessage;
    string pixelDecoded;
    Mat secretMessage = imread("C:\\Users\\jad\\Desktop\\IPA\\message.png");
    Mat carrierImg = imread("C:\\Users\\jad\\Desktop\\IPA\\grayscale_carrier.png");
    Mat encodedImg = carrierImg.clone();
    Mat decodedImg = Mat(secretMessage.rows, secretMessage.cols, secretMessage.type());

    if (carrierImg.empty())
    {
        std::cout << "Could not read the image: " << std::endl;
        return 1;
    }

    cout << "rows " << carrierImg.rows << " cols " << carrierImg.cols << endl;

    namedWindow("Carrier image");
    imshow("Carrier image", carrierImg);
    namedWindow("Binary message");
    imshow("Binary message", secretMessage);
    int k = waitKey(0);

    for (int i = 0; i < carrierImg.rows; i++) {
        for (int j = 0; j < carrierImg.cols; j++) {
            pixelImg = decimalToBinary(encodedImg.at<uchar>(i, j));
            pixelMessage = decimalToBinary(secretMessage.at<uchar>(i,j));
            //pixelImg.replace(pixelImg.size() -1, 1, pixelMessage.substr(0,1));
            pixelImg.at(pixelImg.size() - 1) = pixelMessage.at(pixelMessage.size() - 1);
            //cout << i << ") " << j << ") " << binaryToDecimal(pixelImg) << endl;
            encodedImg.at<uchar>(i, j) = binaryToDecimal(pixelImg);
        }
    }

    for (int i = 0; i < carrierImg.rows; i++) {
        for (int j = 0; j < carrierImg.cols; j++) {
            pixelDecoded = decimalToBinary(encodedImg.at<uchar>(i, j));
            if (pixelDecoded.at(pixelDecoded.size() - 1) == '1') {
                decodedImg.at<uchar>(i, j) = 255;
            } else {
                decodedImg.at<uchar>(i, j) = 0;
            }
            int pixelValue = decodedImg.at<uchar>(i, j);
        //    cout << " j: " << j << " " << pixelValue << " pixel value " << decodedImg.at<uchar>(i, j) << " pixelbinary " << pixelDecoded << endl;
        }
    }

    //cout << "rows " << encodedImg.rows << " cols " << encodedImg.cols << endl;

    namedWindow("Encoded image");
    imshow("Encoded image", encodedImg);
    namedWindow("Decoded image");
    imshow("Decoded image", decodedImg);

    int l = waitKey(0);

    return 0;
}

static int binaryToDecimal(string binary) {
    int number = 0;

    for (int i = 0; i <= binary.size(); i++) {
        if (binary.substr(i, 1) == "1") {
            number += pow(2, binary.size() - i - 1);
        }
    }

    return number;
}

static string decimalToBinary(int dec) {
    if (dec < 1) {
        return "0";
    }

    string binStr = "";

    while (dec > 0)
    {
        binStr = binStr.insert(0, string(1, (char)((dec % 2) + 48)));

        dec /= 2;
    }

    reverseStr(binStr);
    while (binStr.size() != 8) {
        binStr.push_back('0');
    }
    reverseStr(binStr);
    return binStr;
}

void reverseStr(string& str)
{
    int n = str.length();

    // Swap character starting from two
    // corners
    for (int i = 0; i < n / 2; i++)
        swap(str[i], str[n - i - 1]);
}
</code>```

I am using this code to do lsb steganography, everything seems to work fine but the generated image [[enter image description here](https://i.stack.imgur.com/DNvJQ.png)](https://i.stack.imgur.com/kr1vy.png), is cut like not all the column are done by the for loop.

thank you for your help

Body:
I am using this code to do lsb steganography, everything seems to work fine but the generated image [[enter image description here](https://i.stack.imgur.com/DNvJQ.png)](https://i.stack.imgur.com/kr1vy.png), is cut like not all the column are done by the for loop.

thank you for your help

#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <list>
#include <string>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stdlib.h>

using namespace cv;
using namespace std;

void reverseStr(string& str);
static string decimalToBinary(int dec);
static int binaryToDecimal(string binary);

int main()
{

    string pixelImg;
    string pixelMessage;
    string pixelDecoded;
    Mat secretMessage = imread("C:\\Users\\jad\\Desktop\\IPA\\message.png");
    Mat carrierImg = imread("C:\\Users\\jad\\Desktop\\IPA\\grayscale_carrier.png");
    Mat encodedImg = carrierImg.clone();
    Mat decodedImg = Mat(secretMessage.rows, secretMessage.cols, secretMessage.type());

    if (carrierImg.empty())
    {
        std::cout << "Could not read the image: " << std::endl;
        return 1;
    }

    cout << "rows " << carrierImg.rows << " cols " << carrierImg.cols << endl;

    namedWindow("Carrier image");
    imshow("Carrier image", carrierImg);
    namedWindow("Binary message");
    imshow("Binary message", secretMessage);
    int k = waitKey(0);

    for (int i = 0; i < carrierImg.rows; i++) {
        for (int j = 0; j < carrierImg.cols; j++) {
            pixelImg = decimalToBinary(encodedImg.at<uchar>(i, j));
            pixelMessage = decimalToBinary(secretMessage.at<uchar>(i,j));
            //pixelImg.replace(pixelImg.size() -1, 1, pixelMessage.substr(0,1));
            pixelImg.at(pixelImg.size() - 1) = pixelMessage.at(pixelMessage.size() - 1);
            //cout << i << ") " << j << ") " << binaryToDecimal(pixelImg) << endl;
            encodedImg.at<uchar>(i, j) = binaryToDecimal(pixelImg);
        }
    }

    for (int i = 0; i < carrierImg.rows; i++) {
        for (int j = 0; j < carrierImg.cols; j++) {
            pixelDecoded = decimalToBinary(encodedImg.at<uchar>(i, j));
            if (pixelDecoded.at(pixelDecoded.size() - 1) == '1') {
                decodedImg.at<uchar>(i, j) = 255;
            } else {
                decodedImg.at<uchar>(i, j) = 0;
            }
            int pixelValue = decodedImg.at<uchar>(i, j);
        //    cout << " j: " << j << " " << pixelValue << " pixel value " << decodedImg.at<uchar>(i, j) << " pixelbinary " << pixelDecoded << endl;
        }
    }

    //cout << "rows " << encodedImg.rows << " cols " << encodedImg.cols << endl;

    namedWindow("Encoded image");
    imshow("Encoded image", encodedImg);
    namedWindow("Decoded image");
    imshow("Decoded image", decodedImg);

    int l = waitKey(0);

    return 0;
}

static int binaryToDecimal(string binary) {
    int number = 0;

    for (int i = 0; i <= binary.size(); i++) {
        if (binary.substr(i, 1) == "1") {
            number += pow(2, binary.size() - i - 1);
        }
    }

    return number;
}

static string decimalToBinary(int dec) {
    if (dec < 1) {
        return "0";
    }

    string binStr = "";

    while (dec > 0)
    {
        binStr = binStr.insert(0, string(1, (char)((dec % 2) + 48)));

        dec /= 2;
    }

    reverseStr(binStr);
    while (binStr.size() != 8) {
        binStr.push_back('0');
    }
    reverseStr(binStr);
    return binStr;
}

void reverseStr(string& str)
{
    int n = str.length();

    // Swap character starting from two
    // corners
    for (int i = 0; i < n / 2; i++)
        swap(str[i], str[n - i - 1]);
}

I am using this code to do lsb steganography, everything seems to work fine but the generated image [[enter image description here](https://i.stack.imgur.com/DNvJQ.png)](https://i.stack.imgur.com/kr1vy.png), is cut like not all the column are done by the for loop.

thank you for your help


问:
Javasctipt object to array
I have an object which is like [ 'Country 1', 'Country 2' ] When I console log the type of that it gives me 'object'. I want to convert that to an array.

I used this :

```<code>const arr = Object.values(countries);
console.log(typeof arr); //Still give me object
</code>```

How can I get an array from that?

Title: Javasctipt object to array

Body:
I have an object which is like [ 'Country 1', 'Country 2' ] When I console log the type of that it gives me 'object'. I want to convert that to an array.

I used this :

const arr = Object.values(countries);
console.log(typeof arr); //Still give me object

How can I get an array from that?


问:
Computed property in Vue does not change when updating its data through an event listener
I have a select input that has multiple options and I have already written a function that finds the selected option and dispatches a custom event with the selected value contained in it.

My custom event is called "newOptionSelected".

Now I have a different component written in VueJS and this is its script section:

```<code>export default {
data()
{
    return {
        option: null,
    }
},
computed: {
    selectedOption()
    {
        return this.option
    },
},
mounted()
{
    document.addEventListener("newOptionSelected", function(event){
        this.option = event.detail.option;
        console.log(this.option);
    });
}
}
</code>```

However, this doesn't work and selectedOption does not get updated when I select a new option. I am using VueJS by adding it as a JS script to my files and I'm not using Vue CLI. Any idea how I can fix this? Thanks.

Body:
I have a select input that has multiple options and I have already written a function that finds the selected option and dispatches a custom event with the selected value contained in it.

My custom event is called "newOptionSelected".

Now I have a different component written in VueJS and this is its script section:

export default {
data()
{
    return {
        option: null,
    }
},
computed: {
    selectedOption()
    {
        return this.option
    },
},
mounted()
{
    document.addEventListener("newOptionSelected", function(event){
        this.option = event.detail.option;
        console.log(this.option);
    });
}
}

However, this doesn't work and selectedOption does not get updated when I select a new option. I am using VueJS by adding it as a JS script to my files and I'm not using Vue CLI. Any idea how I can fix this? Thanks.


问:
How can I make a URL redirect to a local file while keeping the URL in the address bar of my browser?
I have an HTTPS URL and a local file to redirect to. How can I set up the URL to redirect to my local file and have the browser still show the URL rather than the C:\Users… filepath?

I don’t mean that the website will do this; just that my computer will read the URL in this way.

What I’m looking for:

https://… typed into address bar

(computer reads URL as instruction to serve local file)

address bar still shows https://…, page shows the local file

I tried using the Redirector web extension, but it doesn’t seem to support something this specific.


问:
Django admin panel: How to show models with ManyToMany and OneToMany relationship within another model?
I tried so hard to write a question title that could somewhat point to the problem, but couldn't. So here is the question in details:

I have a Product model, a Usage model and a SubUsage model. Usage model has a OneToMAny relationship with SubUsage model, where for every usage there may be various sub_usages, and the Product model has ManyToMany relationship with these two models, in which a product may have different usages and sub_usages.

These models are as below:

```<code>class Usage(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    usage_name = models.CharField(
        max_length=255,
        null=False,
        blank=False,
        unique=True,
    )

class SubUsage(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    sub_usage_name = models.CharField(
        max_length=255,
        null=False,
        blank=False,
    )
    usage = models.ForeignKey(
        Usage,
        on_delete=models.CASCADE,
    )

class Product(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    product_name = models.CharField(
        max_length=255,
        null=False,
        blank=False,
        unique=True,
    )
    usage = models.ManyToManyField(Usage)
    sub_usage = models.ManyToManyField(SubUsage)
</code>```

Now in the admin panel, I have product form, in which I can choose usages and sub_usages; as the image below:

The problem is that, each usage has different sub_usages, which may has the same name as another sub_usage of another usage; I want to be able to know that each item in sub_usages list is related to which usage, so that if a product has only usage1 and usage2, then the admin won't mistakenly select a sub_usage from usage3 which has the same name as a sub_usage from usage2.

Body:
I tried so hard to write a question title that could somewhat point to the problem, but couldn't. So here is the question in details:

I have a Product model, a Usage model and a SubUsage model. Usage model has a OneToMAny relationship with SubUsage model, where for every usage there may be various sub_usages, and the Product model has ManyToMany relationship with these two models, in which a product may have different usages and sub_usages.

These models are as below:

class Usage(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    usage_name = models.CharField(
        max_length=255,
        null=False,
        blank=False,
        unique=True,
    )

class SubUsage(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    sub_usage_name = models.CharField(
        max_length=255,
        null=False,
        blank=False,
    )
    usage = models.ForeignKey(
        Usage,
        on_delete=models.CASCADE,
    )

class Product(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    product_name = models.CharField(
        max_length=255,
        null=False,
        blank=False,
        unique=True,
    )
    usage = models.ManyToManyField(Usage)
    sub_usage = models.ManyToManyField(SubUsage)

Now in the admin panel, I have product form, in which I can choose usages and sub_usages; as the image below:

The problem is that, each usage has different sub_usages, which may has the same name as another sub_usage of another usage; I want to be able to know that each item in sub_usages list is related to which usage, so that if a product has only usage1 and usage2, then the admin won't mistakenly select a sub_usage from usage3 which has the same name as a sub_usage from usage2.


问:
React Hooks - Is this a pattern? (exposition of available methods and protection against mistakes)
I have the following hook (in my RN app), which exposes 4 methods, each of them communicates with an external page. I intend to ensure the simplicity with which this action is carried out, in addition to saving possible errors by introducing typos.

This is the code:

export default function useOpenPolicyPage(
  {
    onSuccess,
    onError,
  } = {}
) {
  const {
    result,
    error,
    openWebsite,
  } = useOpenWebsite({ onSuccess, onError });

  /**
   * Opens our community guidelines.
   *
   * @returns {Promise<void>} An empty promise.
   */
  const openCommunityGuidelines = () =>
    openWebsite(POLICY_PAGES.communityGuidelines, false);

  /**
   * Opens our legal notice.
   *
   * @returns {Promise<void>} An empty promise.
   */
  const openLegalNotice = () =>
    openWebsite(POLICY_PAGES.legalNotice, false);

  /**
   * Opens our privacy policy.
   *
   * @returns {Promise<void>} An empty promise.
   */
  const openPrivacyPolicy = () =>
    openWebsite(POLICY_PAGES.privacyPolicy, false);

  /**
   * Opens our cookies policy.
   *
   * @returns {Promise<void>} An empty promise.
   */
  const openCookiesPolicy = () =>
    openWebsite(POLICY_PAGES.cookiesPolicy, false);

  return {
    result,
    error,
    openCommunityGuidelines,
    openLegalNotice,
    openPrivacyPolicy,
    openCookiesPolicy,
  };
};
```
<p>On the one hand, this technique caught my attention, since it would be enough to do the following to open a page:</p>
```const { displayError } = useErrorHandler();

const { openPrivacyPolicy } = useOpenPolicyPage({
  onError: displayError,
});

return (
  <Text onPress={openPrivacyPolicy}>
    Open our Privacy Policy!
  </Text>
);
```
<p>But, on the other hand, I see that it is unnecessary and we could improve the performance by avoiding the creation of 4 extra functions... just doing:</p>
<pre class="lang-js prettyprint-override"><code>const { displayError } = useErrorHandler();

const {
  openWebsite,
} = useOpenWebsite({ onError: displayError });

const handleOnPress = () => {
  openWebsite(POLICY_PAGES.privacyPolicy, false);
};

return (
  <Text onPress={handleOnPress}>
    Open our Privacy Policy!
  </Text>
);
</code>```

Still, I think the first solution is better, since in a large code base, it is possible that some teammate might miss using the constant or passing the argument false, which is a technical requirement and indicates that the website visited is not sensitive, but a trusted source.

Is the first example a pattern?

Body:
I have the following hook (in my RN app), which exposes 4 methods, each of them communicates with an external page. I intend to ensure the simplicity with which this action is carried out, in addition to saving possible errors by introducing typos.

This is the code:

export default function useOpenPolicyPage(
  {
    onSuccess,
    onError,
  } = {}
) {
  const {
    result,
    error,
    openWebsite,
  } = useOpenWebsite({ onSuccess, onError });

  /**
   * Opens our community guidelines.
   *
   * @returns {Promise<void>} An empty promise.
   */
  const openCommunityGuidelines = () =>
    openWebsite(POLICY_PAGES.communityGuidelines, false);

  /**
   * Opens our legal notice.
   *
   * @returns {Promise<void>} An empty promise.
   */
  const openLegalNotice = () =>
    openWebsite(POLICY_PAGES.legalNotice, false);

  /**
   * Opens our privacy policy.
   *
   * @returns {Promise<void>} An empty promise.
   */
  const openPrivacyPolicy = () =>
    openWebsite(POLICY_PAGES.privacyPolicy, false);

  /**
   * Opens our cookies policy.
   *
   * @returns {Promise<void>} An empty promise.
   */
  const openCookiesPolicy = () =>
    openWebsite(POLICY_PAGES.cookiesPolicy, false);

  return {
    result,
    error,
    openCommunityGuidelines,
    openLegalNotice,
    openPrivacyPolicy,
    openCookiesPolicy,
  };
};

On the one hand, this technique caught my attention, since it would be enough to do the following to open a page:

const { displayError } = useErrorHandler();

const { openPrivacyPolicy } = useOpenPolicyPage({
  onError: displayError,
});

return (
  <Text onPress={openPrivacyPolicy}>
    Open our Privacy Policy!
  </Text>
);

But, on the other hand, I see that it is unnecessary and we could improve the performance by avoiding the creation of 4 extra functions... just doing:

const { displayError } = useErrorHandler();

const {
  openWebsite,
} = useOpenWebsite({ onError: displayError });

const handleOnPress = () => {
  openWebsite(POLICY_PAGES.privacyPolicy, false);
};

return (
  <Text onPress={handleOnPress}>
    Open our Privacy Policy!
  </Text>
);

Still, I think the first solution is better, since in a large code base, it is possible that some teammate might miss using the constant or passing the argument false, which is a technical requirement and indicates that the website visited is not sensitive, but a trusted source.

Is the first example a pattern?


问:
Unity3D - Albedo-only reflections?
Is it possible to let reflections only influence the colors of an object's screen pixels, but not their brightness'?

Meaning, let reflections be treated exactly like a Material's Albedo (texture)?

Rationale:

If a Material's Metallic value is cranked up to 1, all surfaces of objects using this Material become uniformly fully lit, even surfaces which receive little or no light.

There might be a real-world-physics reason for this which makes sense in some scenarios, but in others - especially dark environments - this just looks plain wrong.

I've tried to customize the Standard shader (using the one from 'builtin_shaders.zip') accordingly, but due to close to zilch knowledge about shader programming not to much avail.

If anyone can offer any help about this, it would be highly appreciated.

Title: Unity3D - Albedo-only reflections?


问:
How do I place a qtchart in a specific place in my GUI?
I create a GUI for my python program using pyqt and QtDesigner. And I need to use Qtcharts to have a line chart in my GUI. However, I haven't found any way to display the chart in my GUI, instead, the chart always is shown in a separate dialogue box.

Let's consider this piece of simple code for my line chart:

```<code>import sys
from PySide6.QtCore import QPointF
from PySide6.QtGui import QPainter
from PySide6.QtWidgets import QMainWindow, QApplication
from PySide6.QtCharts import QChart, QChartView, QLineSeries
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt, QPointF
from PyQt6.QtCharts import QChart, QChartView, QLineSeries

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setGeometry(200, 200, 700, 400)
        self.setWindowTitle("PyQt6 LineChart")
        self.line_chart()

    def line_chart(self):
        series = QLineSeries()
        series.append([
            QPointF(1.0, 1.0), QPointF(2.0, 73.0), QPointF(3.0, 268.0),
            QPointF(4.0, 17.0), QPointF(5.0, 120.0), QPointF(6.0, 210.0)])

        chart = QChart()
        chart.addSeries(series)
        chart.createDefaultAxes()
        chart.setTitle("Line Chart Example")

        chart.setAnimationOptions(QChart.AnimationOption.AllAnimations)
        chart.setTheme(QChart.ChartTheme.ChartThemeDark)

        chartview = QChartView(chart)
        self.setCentralWidget(chartview)

app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())
</code>```

And here is my simple GUI created in QtDesigner:

The pink box is a Qlabel which I wish to see the chart there.
Here is the Python code of this simple GUI ( Converted .ui to .py)

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

class Ui_Simpleform(object):
    def setupUi(self, Simpleform):
        Simpleform.setObjectName("Simpleform")
        Simpleform.resize(459, 348)
        self.tableView = QtWidgets.QTableView(Simpleform)
        self.tableView.setGeometry(QtCore.QRect(-200, 440, 256, 192))
        self.tableView.setObjectName("tableView")
        self.label = QtWidgets.QLabel(Simpleform)
        self.label.setGeometry(QtCore.QRect(40, 120, 101, 61))
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(Simpleform)
        self.label_2.setGeometry(QtCore.QRect(150, 80, 291, 151))
        self.label_2.setStyleSheet("background-color: rgb(255, 170, 255);\n"
"border-radius: 10px;\n"
"background-color: rgb(251, 205, 255);")
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")

        self.retranslateUi(Simpleform)
        QtCore.QMetaObject.connectSlotsByName(Simpleform)

    def retranslateUi(self, Simpleform):
        _translate = QtCore.QCoreApplication.translate
        Simpleform.setWindowTitle(_translate("Simpleform", "Form"))
        self.label.setText(_translate("Simpleform", "View the Chart:"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Simpleform = QtWidgets.QWidget()
    ui = Ui_Simpleform()
    ui.setupUi(Simpleform)
    Simpleform.show()
    sys.exit(app.exec())
</code>```

In fact, label_2 is the place I wish to put my chart there.
Is there any way?

Thank you All!

Body:
I create a GUI for my python program using pyqt and QtDesigner. And I need to use Qtcharts to have a line chart in my GUI. However, I haven't found any way to display the chart in my GUI, instead, the chart always is shown in a separate dialogue box.

Let's consider this piece of simple code for my line chart:

import sys
from PySide6.QtCore import QPointF
from PySide6.QtGui import QPainter
from PySide6.QtWidgets import QMainWindow, QApplication
from PySide6.QtCharts import QChart, QChartView, QLineSeries
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt, QPointF
from PyQt6.QtCharts import QChart, QChartView, QLineSeries

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setGeometry(200, 200, 700, 400)
        self.setWindowTitle("PyQt6 LineChart")
        self.line_chart()

    def line_chart(self):
        series = QLineSeries()
        series.append([
            QPointF(1.0, 1.0), QPointF(2.0, 73.0), QPointF(3.0, 268.0),
            QPointF(4.0, 17.0), QPointF(5.0, 120.0), QPointF(6.0, 210.0)])

        chart = QChart()
        chart.addSeries(series)
        chart.createDefaultAxes()
        chart.setTitle("Line Chart Example")

        chart.setAnimationOptions(QChart.AnimationOption.AllAnimations)
        chart.setTheme(QChart.ChartTheme.ChartThemeDark)

        chartview = QChartView(chart)
        self.setCentralWidget(chartview)

app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())

And here is my simple GUI created in QtDesigner:

The pink box is a Qlabel which I wish to see the chart there.
Here is the Python code of this simple GUI ( Converted .ui to .py)

from PyQt6 import QtCore, QtGui, QtWidgets

class Ui_Simpleform(object):
    def setupUi(self, Simpleform):
        Simpleform.setObjectName("Simpleform")
        Simpleform.resize(459, 348)
        self.tableView = QtWidgets.QTableView(Simpleform)
        self.tableView.setGeometry(QtCore.QRect(-200, 440, 256, 192))
        self.tableView.setObjectName("tableView")
        self.label = QtWidgets.QLabel(Simpleform)
        self.label.setGeometry(QtCore.QRect(40, 120, 101, 61))
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(Simpleform)
        self.label_2.setGeometry(QtCore.QRect(150, 80, 291, 151))
        self.label_2.setStyleSheet("background-color: rgb(255, 170, 255);\n"
"border-radius: 10px;\n"
"background-color: rgb(251, 205, 255);")
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")

        self.retranslateUi(Simpleform)
        QtCore.QMetaObject.connectSlotsByName(Simpleform)

    def retranslateUi(self, Simpleform):
        _translate = QtCore.QCoreApplication.translate
        Simpleform.setWindowTitle(_translate("Simpleform", "Form"))
        self.label.setText(_translate("Simpleform", "View the Chart:"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Simpleform = QtWidgets.QWidget()
    ui = Ui_Simpleform()
    ui.setupUi(Simpleform)
    Simpleform.show()
    sys.exit(app.exec())

In fact, label_2 is the place I wish to put my chart there.
Is there any way?

Thank you All!


问:
Chrome extension violates the following Content Security Policy directive: "default-src 'self' blob: filesystem: chrome-extension-resource
I'm doing currency converter chrome extension and so far I've done almost everything but the math. It ain't mathing. I have popup.js javascript file inside folder with popup.html in which I call popup.js for the math. When I try to use my program on chrome, it gives me error that sounds like this:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "default-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

I would get this message when I click the button "Calculate". Even stranger now, I changed something and deleted changes afterwards and now I don't get that error message, but it still wouldn't display the converter value. Here's my code:

So this is the body part of popup.html

```<code><div class="modal-content">
            <p>Pretvorite eure u kune i obrnuto bez problema!</p>
        </p>
        <form>
            <p>
                <label for="amount">Količina:</label>
                <input type="text" id="amount" value="">
                <select id="select">
                    <option value="HRK">HRK </option>
                    <option value="EUR">EUR </option>
                </select>
                <select id="select1">
                    <option value="HRK">HRK </option>
                    <option value="EUR">EUR </option>
                </select>
                <input type="text" id="result" value="">
            </p>
            <p>
                <input type="button" value="Calculate" onclick="calculate();">
                <input type="reset" value="Resetiraj">
            </p>
        </form>
</code>```

This is whole popup.js

```<code>function calculate() {
    var amount = parseFloat(document.getElementById("amount").value);
    var select = document.getElementById("select");
    var select1 = document.getElementById("select1");
    var result = document.getElementById("result");

    if (select.value === "HRK" && select1.value === "HRK")  {
      result.value = (amount * 1);
    }
    if (select.value === "HRK" && select1.value === "EUR")  {
      result.value = (amount * 0.13272);
    }
    if (select.value === "EUR" && select1.value === "HRK")  {
      result.value = (amount * 7.53450);
    }
  }
</code>```

I call .js in body of html with

```<code><script type = "text/javascript" src = "popup. js"></script>
</code>```

Also, this is not relevant to this problem, I'd like to display the tiktok icon at the very bottom of extension window. The font I'm using should support icons (fontawesome), but they don't display. It only shows rectangular window and that's all. Here's the code part in the body of html for that

```<code><div class="modal-icons">
            <div class="flex-container">
                <div class="flex">
                    <a href="here's my TT link" target="_blank"> #This works
                        <i class="fab fa-tiktok"></i> #This for sure won't work
                    </a>
                </div>
            </div>
        </div>
</code>```

I saw some article here on stackoverflow about the same issue I mentioned (that error message) and tried fixing it by following the resolution on that article, but it didn't help. The error message was gone when I removed that resolution from my original code, but the conversion still wouldn't work.

Body:
I'm doing currency converter chrome extension and so far I've done almost everything but the math. It ain't mathing. I have popup.js javascript file inside folder with popup.html in which I call popup.js for the math. When I try to use my program on chrome, it gives me error that sounds like this:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "default-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

I would get this message when I click the button "Calculate". Even stranger now, I changed something and deleted changes afterwards and now I don't get that error message, but it still wouldn't display the converter value. Here's my code:

So this is the body part of popup.html

Pretvorite eure u kune i obrnuto bez problema!

        <form>

                Količina:
                <input type="text" id="amount" value="">
                <select id="select">
                    <option value="HRK">HRK </option>
                    <option value="EUR">EUR </option>
                </select>
                <select id="select1">
                    <option value="HRK">HRK </option>
                    <option value="EUR">EUR </option>
                </select>
                <input type="text" id="result" value="">

                <input type="button" value="Calculate" onclick="calculate();">
                <input type="reset" value="Resetiraj">

        </form>

This is whole popup.js

function calculate() {
    var amount = parseFloat(document.getElementById("amount").value);
    var select = document.getElementById("select");
    var select1 = document.getElementById("select1");
    var result = document.getElementById("result");

    if (select.value === "HRK" && select1.value === "HRK")  {
      result.value = (amount * 1);
    }
    if (select.value === "HRK" && select1.value === "EUR")  {
      result.value = (amount * 0.13272);
    }
    if (select.value === "EUR" && select1.value === "HRK")  {
      result.value = (amount * 7.53450);
    }
  }

I call .js in body of html with

Also, this is not relevant to this problem, I'd like to display the tiktok icon at the very bottom of extension window. The font I'm using should support icons (fontawesome), but they don't display. It only shows rectangular window and that's all. Here's the code part in the body of html for that

                     #This works
                         #This for sure won't work

I saw some article here on stackoverflow about the same issue I mentioned (that error message) and tried fixing it by following the resolution on that article, but it didn't help. The error message was gone when I removed that resolution from my original code, but the conversion still wouldn't work.