问:
Should I convert my repetitive string data to integers to help performance?
I have around 900M records with 17 or so string fields. Most of those fields contain one of several possible values. For example, there is a gender field. It contains “M”, “F”, “U”. My question is, if I replace these values with integer values, would that help with performance when querying?

Some of my other fields are longer, up to 20+ characters. Another field contains a range of income, for example “$50,000 - $75,000”. We have 13 different income ranges. Many of our queries are along the lines of, “give me everyone who has an income between $50,000 to $125,000”. What I’m doing now is performing and $in query where I pass in each income range that fits, for example: ‘$50,001 - $ 75,000’, ‘$75,001 - $ 100,000’, ‘$100,001 - $ 125,000’.

Again, if I replace these string values with integers, would that help performance?

EDIT

To add more color to the question:

These fields are various demographic data (age, gender, marital status, income, house value, etc.) The raw data we get is in string format. Even age is a string because we have "99+". I can easily interpret these strings into my own set of numbers so that income of ‘$50,001 - $ 75,000’ would become number 3, for example.

The end user has a web UI that allows them to select values from one or more fields to query. The query is built using the MongoDB C# driver.

A typical query would look like this:

```<code>{
    "MaritalStatus": {
        "$in": [
            "M"
        ]
    },
    "Age": {
        "$in": [
            "70",
            "71",
            "72",
            "73"
        ]
    },
    "Income": {
        "$in": [
            "$ 250,001 - $ 500,000",
            "$ 500,000 OR MORE"
        ]
    },
    "HomeValue": {
        "$in": [
            "$1,500,000 - $1,999,999",
            "$2,000,000 OR MORE"
        ]
    },
    "Zip": {
        "$in": [
            "90210"
        ]
    }
}
</code>```

Body:
I have around 900M records with 17 or so string fields. Most of those fields contain one of several possible values. For example, there is a gender field. It contains “M”, “F”, “U”. My question is, if I replace these values with integer values, would that help with performance when querying?

Some of my other fields are longer, up to 20+ characters. Another field contains a range of income, for example “$50,000 - $75,000”. We have 13 different income ranges. Many of our queries are along the lines of, “give me everyone who has an income between $50,000 to $125,000”. What I’m doing now is performing and $in query where I pass in each income range that fits, for example: ‘$50,001 - $ 75,000’, ‘$75,001 - $ 100,000’, ‘$100,001 - $ 125,000’.

Again, if I replace these string values with integers, would that help performance?

EDIT

To add more color to the question:

These fields are various demographic data (age, gender, marital status, income, house value, etc.) The raw data we get is in string format. Even age is a string because we have "99+". I can easily interpret these strings into my own set of numbers so that income of ‘$50,001 - $ 75,000’ would become number 3, for example.

The end user has a web UI that allows them to select values from one or more fields to query. The query is built using the MongoDB C# driver.

A typical query would look like this:

{
    "MaritalStatus": {
        "$in": [
            "M"
        ]
    },
    "Age": {
        "$in": [
            "70",
            "71",
            "72",
            "73"
        ]
    },
    "Income": {
        "$in": [
            "$ 250,001 - $ 500,000",
            "$ 500,000 OR MORE"
        ]
    },
    "HomeValue": {
        "$in": [
            "$1,500,000 - $1,999,999",
            "$2,000,000 OR MORE"
        ]
    },
    "Zip": {
        "$in": [
            "90210"
        ]
    }
}


来源: stackexchange

问:
Run Node Application on WIndows Server system (with local-network URL)
Basically, we are trying to build an installer for a Windows Server Machine
which would install and run the Node application in the local network so it requires some Local Url for the app (like https://nodeapp...) I would be using IIS to con

https://medium.com/@harshamw/deploying-a-node-js-application-in-iis-using-a-reverse-proxy-process-management-using-pm2-3d59b83d7f76
Using the above link to understand how to run the node app on windows

We are unable to setup the AAR on IIS to configure this

Happy to share more info if needed

Using this flow to have some

2 options for windows service managers
1 ) PM2 -

NFSM

ContentLicense: CC BY-SA 4.0


问:
How to generate links for profile completion with expiry date in NextJS - Supabase
I'm currently working on a NextJS-Supabase project where I have to build a dashboard for some vendors.
Each vendor should be able to login into his dashboard and add his customers to keep track of their informations. The process of adding a customer falls into the following steps :

fill the customer email and submit the request of adding him.

The customer receives an email containing a link available for 5hours.

The link redirects him to a page where he can complete some of his basic information such as address, phone...etc.

Once the form submitted the customer data are updated in Supabase.

I don't know how to implement this in NextJS-Supabase knowing that the customers don't have a user account. Only vendors have a user account and can login/logout.


问:
Flutter: Making a Dropdown Multiselect with Checkboxes
am building a flutter app and am am working with a data from a API i got the list and evreything i did a search bar that works properly by typing either the number of the ticket or the description but am trying to add a new filter , a checkbox  that filters the data i have 2 problems
1: when i press on a checkbox and type confirm it works and it shows but the checkbox dosent stay checked
2: how can i implement it so it filter the data from the api directly
and thank you</p>
```<code>// ignore_for_file: use_key_in_widget_constructors, avoid_print, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, prefer_const_constructors, non_constant_identifier_names, unnecessary_new, avoid_function_literals_in_foreach_calls, unused_import, avoid_types_as_parameter_names, unused_label, unused_element, file_names, library_private_types_in_public_api, unnecessary_string_interpolations
import 'dart:convert';
import 'dart:io';
import 'package:az/Actifs.dart';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';
import 'package:dropdown_search/dropdown_search.dart';

class DataFromAPI extends StatefulWidget {
  @override
  _DataFromAPIState createState() => _DataFromAPIState();
}

List<Sr> _MyAllData=[];
List<Sr> _SrForDsiplay=[];
Map<String, Color>  map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejected":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<String, String>  map1={
"1":"Urgent",
"2":"High",
"3":"Medium",
"4":"Low",
};
/*Map<String, Color>  map3={
"Urgent":Colors.red,
"High":Color.fromARGB(255, 255, 139, 131),
"Medium":Colors.blue,
"Low":Colors.green,
"null":Colors.grey,
};*/

class Multiselect extends StatefulWidget {
  final List<String> items;
  const Multiselect({Key? key, required this.items}) : super(key: key);

  @override
  State<Multiselect> createState() => _MultiselectState();
}

class _MultiselectState extends State<Multiselect> {
  final List<String> _selectedItems=[];

    void _itemChange(String itemValue, bool isSelected) {
    setState(() {
      if (isSelected) {
        _selectedItems.add(itemValue);
      } else {
        _selectedItems.remove(itemValue);
      }
    });
  }

  // this function is called when the Cancel button is pressed
  void _cancel() {
    Navigator.pop(context);
  }

// this function is called when the Submit button is tapped
  void _submit() {
    Navigator.pop(context, _selectedItems);
  }
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
       title: const Text('Select Topics'),
      content: SingleChildScrollView(
        child: ListBody(
          children: widget.items
              .map((item) => CheckboxListTile(
                    value: _selectedItems.contains(item),
                    title: Text(item),
                    controlAffinity: ListTileControlAffinity.leading,
                    onChanged: (isChecked) => _itemChange(item, isChecked!),
                  ))
              .toList(),
        ),
      ),
        actions: [
        TextButton(
          onPressed: _cancel,
          child: const Text('Cancel'),
        ),
        ElevatedButton(
          onPressed: _submit,
          child: const Text('Submit'),
        ),
      ],
    );
  }
}

class _DataFromAPIState extends State<DataFromAPI> {
List<String> _selectedItems=[];
String title_string = "Liste des SR :";
void _ShowMultiSelect() async{
  final List<String> items=[
    'QUEUED',
    'CLOSED',
    'Rejected',
    'INPROG',
    'PENDING',
    'RESOLVED',
    'NEW',
  ];

  final List<String>? results =await showDialog(
    context: context,
     builder: (BuildContext context) {
     return Multiselect(items: items);
    },
  );
  if(results !=null){
    setState(() {
      _selectedItems=results;
    });
  }
}
 @override
void initState() {
  loadData().then((value) {
    _MyAllData.clear();
    setState(() {
      _MyAllData.addAll(value);
      _SrForDsiplay=_MyAllData;
    });
  });
  super.initState();
}

  Future<List<Sr>> loadData() async {
    try {
      var response = await http.get(Uri.parse(
        'http:MXSR/?_lid=&_lpwd=&_format=json'));
      if (response.statusCode == 200) {
        final jsonBody = json.decode(response.body);
        Demandes data = Demandes.fromJson(jsonBody);
        final srAttributes = data.queryMxsrResponse.mxsrSet.sr;
        title_string='Liste des SR : ${srAttributes.length.toString()}';
        return srAttributes;
       }
       } catch (e) {
      throw Exception(e.toString());
    }
    throw Exception("");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner:false,
      home: new Scaffold(resizeToAvoidBottomInset: false ,
        appBar: AppBar(
          title: Text(title_string),
          leading: IconButton(
              icon: Icon(Icons.arrow_back), onPressed: () {  Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Home())); },
             ),
             flexibleSpace: InkWell(onTap: () {
             },),
         ),
        body: FutureBuilder<List<Sr>?>(
          future: loadData(),
          builder: (context, snapshot) {
            if (_MyAllData.isEmpty) {
              return SizedBox(
          height: MediaQuery.of(context).size.height / 1.3,
          child: Center(
           child: CircularProgressIndicator(),
            ),
           );
            } else { return
             ListView(
              children: <Widget>[Padding(
             padding: const EdgeInsets.all(8.0),
             child: Column(children:<Widget>[ElevatedButton(onPressed: _ShowMultiSelect,
              child: const Text('Filter')),
             const Divider(
            height: 30,
            ),
            Wrap(
              children: _selectedItems
                  .map((e) => Chip(
                        label: Text(e),
                      ))
                  .toList(),
            ),
             Row(children:<Widget>[ Expanded(
              child: TextField(
               decoration:
               InputDecoration( hintText: "Enter id or description"),
               onChanged: (text) {
               text=text.toLowerCase();
                setState(() {
               _SrForDsiplay =_MyAllData.where((srAttributes) {
                var srDescription = srAttributes.attributes.description!.content.toString().toLowerCase();
                var srID= srAttributes.attributes.ticketid.content.toString();
                return srDescription.contains(text) || srID.contains(text);
                }).toList();
                title_string='Liste des SR : ${_SrForDsiplay.length.toString()}';
                print(title_string);
                      }
                    );
                  },
                )),])
               ],
               ),),
               new ListView.builder(scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: _SrForDsiplay.length,
                itemBuilder: ((_, index) {
                  return
                     new ListTile(
                          title: new Card(
                               margin: new EdgeInsets.symmetric(
                                vertical: 2.0, horizontal: 8.0),
                                elevation: 10,
                                child: new ListTile(
                                title: new Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Padding(padding: new EdgeInsets.all(2.0)),
                                  Row(children :[
                                    Container(
                                     decoration: BoxDecoration(
                                     border: Border.all(
                                     color: Color.fromARGB(255, 255, 255, 255),
                                     ),
                                     color: map['${_SrForDsiplay[index].attributes.status.content}'],
                                     borderRadius: BorderRadius.all(Radius.circular(20)),
                                     ),
                                     child:Text('  ${_SrForDsiplay[index].attributes.status.content}  '),
                                   ),
                                    Container(child: Text('  '),),
                                   Container(
                                     decoration: BoxDecoration(
                                      border: Border.all(
                                      color: Color.fromARGB(255, 255, 255, 255),
                                     ),
                                     color:Colors.grey,
                                     borderRadius: BorderRadius.all(Radius.circular(20)),
                                     ),
                                     child:Text( map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}'] ?? " null "),
                                       ),
                                      ],
                                     ),
                                    SizedBox(
                                     height: 8,
                                     ),
                                  Row(children: <Widget>[
                                      Expanded( child: Container(child: Text('${_SrForDsiplay[index].attributes.description?.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w600)),),),),
                                       Expanded(child: Container(child:Text( '  ${_SrForDsiplay[index].attributes.ticketid.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w400)),)))
                                     ],),
                                       new Divider(
                                       color: Color.fromARGB(255, 110, 109, 109),
                                     ),
                                  Text(
                                    'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${_SrForDsiplay[index].attributes.statusdate.content}' ))}' ,
                                 style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w400)),
                                    ),
                                  new Text(
                                      'Reported by  : ${_SrForDsiplay[index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w400)),
                                  ),
                                  Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
                                      Text(
                                      '${_SrForDsiplay[index].relatedMbos?.asset[0].attributes.descriptionasset?.content}'),], ),
                                  Row(children: [new Image(image: AssetImage('assets/emp.png'), width: 20),
                                      Text(
                                      '${_SrForDsiplay[index].attributes.assetsiteid?.content}'),], ) ,
                                       Divider(
                                        color: Color.fromARGB(255, 110, 109, 109),
                                     ),
                                     Row(children:[
                                      Expanded(child: Badge(
                                        position: BadgePosition.topEnd(top: -8, end: 20),
                                        badgeColor: Colors.grey,
                                        badgeContent: Text('1'),
                                        child :IconButton(icon :Icon(Icons.file_present_rounded),  padding: const EdgeInsets.all(0),
                                        onPressed: () {
                                        },
                                        ),
                                      )
                                        ),
                                      Expanded(child: IconButton (
                                        icon: Icon(Icons.file_copy),
                                        onPressed: () {  },
                                        ),),
                                      Expanded(child:  IconButton(onPressed:() {
                                      }, icon: Icon(Icons.delete))  )
                                        ],)
                                ],
                              ),
                              trailing: Icon(Icons.arrow_forward_ios_rounded),

                            ),
                          ),
                          onTap: () {
                       Navigator.push(
                      context,MaterialPageRoute(builder: (context) =>SrDetailsScreen(sr: _SrForDsiplay[index])),
                     );
                    }
                  );
                 }
                ),
               )
              ]
             );
            }
          },
        ),
      ),
    );
  }
}
</code>```

Body:
am building a flutter app and am am working with a data from a API i got the list and evreything i did a search bar that works properly by typing either the number of the ticket or the description but am trying to add a new filter , a checkbox  that filters the data i have 2 problems
1: when i press on a checkbox and type confirm it works and it shows but the checkbox dosent stay checked
2: how can i implement it so it filter the data from the api directly
and thank you

// ignore_for_file: use_key_in_widget_constructors, avoid_print, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, prefer_const_constructors, non_constant_identifier_names, unnecessary_new, avoid_function_literals_in_foreach_calls, unused_import, avoid_types_as_parameter_names, unused_label, unused_element, file_names, library_private_types_in_public_api, unnecessary_string_interpolations
import 'dart:convert';
import 'dart:io';
import 'package:az/Actifs.dart';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';
import 'package:dropdown_search/dropdown_search.dart';

class DataFromAPI extends StatefulWidget {
  @override
  _DataFromAPIState createState() => _DataFromAPIState();
}

List<Sr> _MyAllData=[];
List<Sr> _SrForDsiplay=[];
Map<String, Color>  map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejected":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<String, String>  map1={
"1":"Urgent",
"2":"High",
"3":"Medium",
"4":"Low",
};
/*Map<String, Color>  map3={
"Urgent":Colors.red,
"High":Color.fromARGB(255, 255, 139, 131),
"Medium":Colors.blue,
"Low":Colors.green,
"null":Colors.grey,
};*/

class Multiselect extends StatefulWidget {
  final List<String> items;
  const Multiselect({Key? key, required this.items}) : super(key: key);

  @override
  State<Multiselect> createState() => _MultiselectState();
}

class _MultiselectState extends State<Multiselect> {
  final List<String> _selectedItems=[];

    void _itemChange(String itemValue, bool isSelected) {
    setState(() {
      if (isSelected) {
        _selectedItems.add(itemValue);
      } else {
        _selectedItems.remove(itemValue);
      }
    });
  }

  // this function is called when the Cancel button is pressed
  void _cancel() {
    Navigator.pop(context);
  }

// this function is called when the Submit button is tapped
  void _submit() {
    Navigator.pop(context, _selectedItems);
  }
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
       title: const Text('Select Topics'),
      content: SingleChildScrollView(
        child: ListBody(
          children: widget.items
              .map((item) => CheckboxListTile(
                    value: _selectedItems.contains(item),
                    title: Text(item),
                    controlAffinity: ListTileControlAffinity.leading,
                    onChanged: (isChecked) => _itemChange(item, isChecked!),
                  ))
              .toList(),
        ),
      ),
        actions: [
        TextButton(
          onPressed: _cancel,
          child: const Text('Cancel'),
        ),
        ElevatedButton(
          onPressed: _submit,
          child: const Text('Submit'),
        ),
      ],
    );
  }
}

class _DataFromAPIState extends State<DataFromAPI> {
List<String> _selectedItems=[];
String title_string = "Liste des SR :";
void _ShowMultiSelect() async{
  final List<String> items=[
    'QUEUED',
    'CLOSED',
    'Rejected',
    'INPROG',
    'PENDING',
    'RESOLVED',
    'NEW',
  ];

  final List<String>? results =await showDialog(
    context: context,
     builder: (BuildContext context) {
     return Multiselect(items: items);
    },
  );
  if(results !=null){
    setState(() {
      _selectedItems=results;
    });
  }
}
 @override
void initState() {
  loadData().then((value) {
    _MyAllData.clear();
    setState(() {
      _MyAllData.addAll(value);
      _SrForDsiplay=_MyAllData;
    });
  });
  super.initState();
}

  Future<List<Sr>> loadData() async {
    try {
      var response = await http.get(Uri.parse(
        'http:MXSR/?_lid=&_lpwd=&_format=json'));
      if (response.statusCode == 200) {
        final jsonBody = json.decode(response.body);
        Demandes data = Demandes.fromJson(jsonBody);
        final srAttributes = data.queryMxsrResponse.mxsrSet.sr;
        title_string='Liste des SR : ${srAttributes.length.toString()}';
        return srAttributes;
       }
       } catch (e) {
      throw Exception(e.toString());
    }
    throw Exception("");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner:false,
      home: new Scaffold(resizeToAvoidBottomInset: false ,
        appBar: AppBar(
          title: Text(title_string),
          leading: IconButton(
              icon: Icon(Icons.arrow_back), onPressed: () {  Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Home())); },
             ),
             flexibleSpace: InkWell(onTap: () {
             },),
         ),
        body: FutureBuilder<List<Sr>?>(
          future: loadData(),
          builder: (context, snapshot) {
            if (_MyAllData.isEmpty) {
              return SizedBox(
          height: MediaQuery.of(context).size.height / 1.3,
          child: Center(
           child: CircularProgressIndicator(),
            ),
           );
            } else { return
             ListView(
              children: <Widget>[Padding(
             padding: const EdgeInsets.all(8.0),
             child: Column(children:<Widget>[ElevatedButton(onPressed: _ShowMultiSelect,
              child: const Text('Filter')),
             const Divider(
            height: 30,
            ),
            Wrap(
              children: _selectedItems
                  .map((e) => Chip(
                        label: Text(e),
                      ))
                  .toList(),
            ),
             Row(children:<Widget>[ Expanded(
              child: TextField(
               decoration:
               InputDecoration( hintText: "Enter id or description"),
               onChanged: (text) {
               text=text.toLowerCase();
                setState(() {
               _SrForDsiplay =_MyAllData.where((srAttributes) {
                var srDescription = srAttributes.attributes.description!.content.toString().toLowerCase();
                var srID= srAttributes.attributes.ticketid.content.toString();
                return srDescription.contains(text) || srID.contains(text);
                }).toList();
                title_string='Liste des SR : ${_SrForDsiplay.length.toString()}';
                print(title_string);
                      }
                    );
                  },
                )),])
               ],
               ),),
               new ListView.builder(scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: _SrForDsiplay.length,
                itemBuilder: ((_, index) {
                  return
                     new ListTile(
                          title: new Card(
                               margin: new EdgeInsets.symmetric(
                                vertical: 2.0, horizontal: 8.0),
                                elevation: 10,
                                child: new ListTile(
                                title: new Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Padding(padding: new EdgeInsets.all(2.0)),
                                  Row(children :[
                                    Container(
                                     decoration: BoxDecoration(
                                     border: Border.all(
                                     color: Color.fromARGB(255, 255, 255, 255),
                                     ),
                                     color: map['${_SrForDsiplay[index].attributes.status.content}'],
                                     borderRadius: BorderRadius.all(Radius.circular(20)),
                                     ),
                                     child:Text('  ${_SrForDsiplay[index].attributes.status.content}  '),
                                   ),
                                    Container(child: Text('  '),),
                                   Container(
                                     decoration: BoxDecoration(
                                      border: Border.all(
                                      color: Color.fromARGB(255, 255, 255, 255),
                                     ),
                                     color:Colors.grey,
                                     borderRadius: BorderRadius.all(Radius.circular(20)),
                                     ),
                                     child:Text( map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}'] ?? " null "),
                                       ),
                                      ],
                                     ),
                                    SizedBox(
                                     height: 8,
                                     ),
                                  Row(children: <Widget>[
                                      Expanded( child: Container(child: Text('${_SrForDsiplay[index].attributes.description?.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w600)),),),),
                                       Expanded(child: Container(child:Text( '  ${_SrForDsiplay[index].attributes.ticketid.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w400)),)))
                                     ],),
                                       new Divider(
                                       color: Color.fromARGB(255, 110, 109, 109),
                                     ),
                                  Text(
                                    'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${_SrForDsiplay[index].attributes.statusdate.content}' ))}' ,
                                 style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w400)),
                                    ),
                                  new Text(
                                      'Reported by  : ${_SrForDsiplay[index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
                                                  textStyle: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w400)),
                                  ),
                                  Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
                                      Text(
                                      '${_SrForDsiplay[index].relatedMbos?.asset[0].attributes.descriptionasset?.content}'),], ),
                                  Row(children: [new Image(image: AssetImage('assets/emp.png'), width: 20),
                                      Text(
                                      '${_SrForDsiplay[index].attributes.assetsiteid?.content}'),], ) ,
                                       Divider(
                                        color: Color.fromARGB(255, 110, 109, 109),
                                     ),
                                     Row(children:[
                                      Expanded(child: Badge(
                                        position: BadgePosition.topEnd(top: -8, end: 20),
                                        badgeColor: Colors.grey,
                                        badgeContent: Text('1'),
                                        child :IconButton(icon :Icon(Icons.file_present_rounded),  padding: const EdgeInsets.all(0),
                                        onPressed: () {
                                        },
                                        ),
                                      )
                                        ),
                                      Expanded(child: IconButton (
                                        icon: Icon(Icons.file_copy),
                                        onPressed: () {  },
                                        ),),
                                      Expanded(child:  IconButton(onPressed:() {
                                      }, icon: Icon(Icons.delete))  )
                                        ],)
                                ],
                              ),
                              trailing: Icon(Icons.arrow_forward_ios_rounded),

                            ),
                          ),
                          onTap: () {
                       Navigator.push(
                      context,MaterialPageRoute(builder: (context) =>SrDetailsScreen(sr: _SrForDsiplay[index])),
                     );
                    }
                  );
                 }
                ),
               )
              ]
             );
            }
          },
        ),
      ),
    );
  }
}


问:
How do I make use of CSV file and code to train a neural network for python using tensorflow and keras?
I have make use of label studio to annotate my image and export the results as a CSV file.
CSV File header

Currently I have these questions and I hope that someone can point me in correct direction.

How do I use the csv files to train the neural network? I read from online tutorial that stated they use CSV file to train however the codes to how to achieves that is very vague.

Is there a format which I need to follows for the dataset files?

How do I organised the training, validation and test image set for feeding the Convoluted neural network?

Do I need to code for the neural network to read the annotated value from the CSV file and loading the original images files to train the network?

Currently I have tried the following code with reference to online guide with some of my own amendment. https://www.analyticsvidhya.com/blog/2021/07/step-by-step-guide-for-image-classification-on-custom-datasets/

'''
x_test=[]

for folder in os.listdir(test_path):

```<code>sub_path=test_path+"/"+folder

for img in os.listdir(sub_path):

    image_path=sub_path+"/"+img

    img_arr=cv2.imread(image_path)

    img_arr=cv2.resize(img_arr,(224,224))

    x_test.append(img_arr)
</code>```

'''

```<code>x_val=[]

for folder in os.listdir(val_path):

    sub_path=val_path+"/"+folder

    for img in os.listdir(sub_path):

        image_path=sub_path+"/"+img

        img_arr=cv2.imread(image_path)

        img_arr=cv2.resize(img_arr,(224,224))

        x_val.append(img_arr)
</code>```
```<code>train_x=np.array(x_train)
test_x=np.array(x_test)
val_x=np.array(x_val)
</code>```

Convert the image file to numpy array. These images is unlabelled. Original image is DICOM images but I have converted it using another python code from DICOM to JPG image files.

```<code>train_x=train_x/255.0
test_x=test_x/255.0
val_x=val_x/255.0

</code>```

Then normalise by 255.0

```<code>train_datagen = ImageDataGenerator(rescale = 1./255)
test_datagen = ImageDataGenerator(rescale = 1./255)
val_datagen = ImageDataGenerator(rescale = 1./255)
</code>```

Then making use of ImageDataGenerator to generate the tensor image data

```<code>
training_set = train_datagen.flow_from_directory(train_path,
                                                 target_size = (224, 224),
                                                 batch_size = 32,
                                                 class_mode = 'sparse')
test_set = test_datagen.flow_from_directory(test_path,
                                            target_size = (224, 224),
                                            batch_size = 32,
                                            class_mode = 'sparse')
val_set = val_datagen.flow_from_directory(val_path,
                                            target_size = (224, 224),
                                            batch_size = 32,
                                            class_mode = 'sparse')

train_y=training_set.classes
test_y=test_set.classes
val_y=val_set.classes

training_set.class_indices
train_y.shape,test_y.shape,val_y.shape
</code>```

After this steps, the online guide is to sent it to a pre-trained CNN, however for me my objective is to train a new CNN from scratch.

```<code>model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3), padding='Valid')) #default 64

model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

model.summary()

model.add(layers.Flatten())
model.add(layers.Dense(512, activation='softmax')) #64
model.add(layers.Dense(256)) #10
model.add(layers.Dense(128))
model.add(layers.Dense(64))
model.add(layers.Dense(10))
model.summary()

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit_generator(training_set,
                    steps_per_epoch=len(training_set),
                    epochs=100,
                    validation_data=val_set,
                    validation_steps = len(val_set))
</code>```

After 100 epoch

The result from the training is as shown on the image above.

Please guide me on how to make this more accurate and how do I load in my annotated.CSV and my original dataset to make the training of the model better.

Thank you

Body:
I have make use of label studio to annotate my image and export the results as a CSV file.
CSV File header

Currently I have these questions and I hope that someone can point me in correct direction.

How do I use the csv files to train the neural network? I read from online tutorial that stated they use CSV file to train however the codes to how to achieves that is very vague.

Is there a format which I need to follows for the dataset files?

How do I organised the training, validation and test image set for feeding the Convoluted neural network?

Do I need to code for the neural network to read the annotated value from the CSV file and loading the original images files to train the network?

Currently I have tried the following code with reference to online guide with some of my own amendment. https://www.analyticsvidhya.com/blog/2021/07/step-by-step-guide-for-image-classification-on-custom-datasets/

'''
x_test=[]

for folder in os.listdir(test_path):

sub_path=test_path+"/"+folder

for img in os.listdir(sub_path):

    image_path=sub_path+"/"+img

    img_arr=cv2.imread(image_path)

    img_arr=cv2.resize(img_arr,(224,224))

    x_test.append(img_arr)

'''

x_val=[]

for folder in os.listdir(val_path):

    sub_path=val_path+"/"+folder

    for img in os.listdir(sub_path):

        image_path=sub_path+"/"+img

        img_arr=cv2.imread(image_path)

        img_arr=cv2.resize(img_arr,(224,224))

        x_val.append(img_arr)

train_x=np.array(x_train)
test_x=np.array(x_test)
val_x=np.array(x_val)

Convert the image file to numpy array. These images is unlabelled. Original image is DICOM images but I have converted it using another python code from DICOM to JPG image files.

train_x=train_x/255.0
test_x=test_x/255.0
val_x=val_x/255.0

Then normalise by 255.0

train_datagen = ImageDataGenerator(rescale = 1./255)
test_datagen = ImageDataGenerator(rescale = 1./255)
val_datagen = ImageDataGenerator(rescale = 1./255)

Then making use of ImageDataGenerator to generate the tensor image data

training_set = train_datagen.flow_from_directory(train_path,
                                                 target_size = (224, 224),
                                                 batch_size = 32,
                                                 class_mode = 'sparse')
test_set = test_datagen.flow_from_directory(test_path,
                                            target_size = (224, 224),
                                            batch_size = 32,
                                            class_mode = 'sparse')
val_set = val_datagen.flow_from_directory(val_path,
                                            target_size = (224, 224),
                                            batch_size = 32,
                                            class_mode = 'sparse')

train_y=training_set.classes
test_y=test_set.classes
val_y=val_set.classes

training_set.class_indices
train_y.shape,test_y.shape,val_y.shape

After this steps, the online guide is to sent it to a pre-trained CNN, however for me my objective is to train a new CNN from scratch.

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3), padding='Valid')) #default 64

model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

model.summary()

model.add(layers.Flatten())
model.add(layers.Dense(512, activation='softmax')) #64
model.add(layers.Dense(256)) #10
model.add(layers.Dense(128))
model.add(layers.Dense(64))
model.add(layers.Dense(10))
model.summary()

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit_generator(training_set,
                    steps_per_epoch=len(training_set),
                    epochs=100,
                    validation_data=val_set,
                    validation_steps = len(val_set))

After 100 epoch

The result from the training is as shown on the image above.

Please guide me on how to make this more accurate and how do I load in my annotated.CSV and my original dataset to make the training of the model better.

Thank you


问:
Adding older repositories to debian
I have a program that I want to install on Debian 11 (Bullseye)--actually on Armbian or Raspberry Pi OS based on Bullseye. The issue is that it requires libgmime-2.6.x and Bullseye only carries libgmime-3.0.x. Rewriting the code for the program is beyond my expertise, so I would like to add the Debian 10 repositories (Buster Main for sure) into the OS. I know that I can do it manually or use add-repository to do it. But, my question is what will break if I do this? Or is there another way to get all of the libgmime dependencies installed without adding the repository?

Have a great day. :)
Patrick.

Title: Adding older repositories to debian


问:
cx_Oracle.DatabaseError: ORA-01008: not all variables bound
I'm working on an exercise, but I've encountered this situation, the following is my code

```<code>class Account(object):
    @staticmethod
    def add_account_list(user_id, role, email):
        # try:
        time = datetime.now().strftime('%Y-%m-%d')
        for i in range(3 - len(role)):
                role.append("null")
        orcl = OracleAccess()
        str = "DATE " + time
        sql = "INSERT INTO ACCOUNT VALUES(:user_id, :role0, :role1, :role2, :email, :update_time)"
        data = [[user_id], [role[0]], [role[1]], [role[2]], [email], [str]]
        print("data:",data)
        orcl.insert(sql, data)
        orcl.close()
        result = {
            "result": 0,
            "message": ""
        }
        return result
</code>```

I enter the following information

```<code>{
  "user_id": "account",
  "role": [
    "super user",
    "admin",
    "general user"
  ],
  "email": "aaa@gmail.com"
}
</code>```

it kept giving an error

```<code>cx_Oracle.DatabaseError: ORA-01008: not all variables bound
</code>```

I don't know where the problem is

I've searched a lot of articles and still don't know how to fix it, I don't even know why. Neither is clear.

Body:
I'm working on an exercise, but I've encountered this situation, the following is my code

class Account(object):
    @staticmethod
    def add_account_list(user_id, role, email):
        # try:
        time = datetime.now().strftime('%Y-%m-%d')
        for i in range(3 - len(role)):
                role.append("null")
        orcl = OracleAccess()
        str = "DATE " + time
        sql = "INSERT INTO ACCOUNT VALUES(:user_id, :role0, :role1, :role2, :email, :update_time)"
        data = [[user_id], [role[0]], [role[1]], [role[2]], [email], [str]]
        print("data:",data)
        orcl.insert(sql, data)
        orcl.close()
        result = {
            "result": 0,
            "message": ""
        }
        return result

I enter the following information

{
  "user_id": "account",
  "role": [
    "super user",
    "admin",
    "general user"
  ],
  "email": "aaa@gmail.com"
}

it kept giving an error

cx_Oracle.DatabaseError: ORA-01008: not all variables bound

I don't know where the problem is

I've searched a lot of articles and still don't know how to fix it, I don't even know why. Neither is clear.


问:
Android studio not starting
I have installed android studio to my pc but thats not starting. Only show starting window.

My pc os - windows 11 ,  Ram 8gb

I have updated java version.
Checked java paths.
Tried multiple time by unistall and installing.

**Could you please help me for resolve this? **

Title: Android studio not starting


问:
Using claim resolvers in generateJson transformation
I am trying to pass {Culture:LanguageName} and {OAUTH-KV:key} to json body in post request using GenerateJson transfomration method. Unfortunately I am not able to pass it to json, both values are resolved to value "undefined" and skipped during json generation. I managed to make it work but only with

```<code><UserInputType>Readonly</UserInputType>
</code>```

in claim type.

I don't want to display those values in UI form so leaving readonly input type is not an option for me.

added two ClaimType for each param I want to include in my json

Setup another technical profile with <Item Key="IncludeClaimResolvingInClaimsHandling">true</Item> metadata and included AlwaysUseDefaultValue="true" DefaultValue="{Culture:LanguageName}" in InputClaim

used it in my user journey as first step with ClaimsExchange

Used claims setup in first step in my json transformation

Body:
I am trying to pass {Culture:LanguageName} and {OAUTH-KV:key} to json body in post request using GenerateJson transfomration method. Unfortunately I am not able to pass it to json, both values are resolved to value "undefined" and skipped during json generation. I managed to make it work but only with

<UserInputType>Readonly</UserInputType>

in claim type.

I don't want to display those values in UI form so leaving readonly input type is not an option for me.

added two ClaimType for each param I want to include in my json

Setup another technical profile with <Item Key="IncludeClaimResolvingInClaimsHandling">true</Item> metadata and included AlwaysUseDefaultValue="true" DefaultValue="{Culture:LanguageName}" in InputClaim

used it in my user journey as first step with ClaimsExchange

Used claims setup in first step in my json transformation


问:
How to make a chrome extension popup execute code on the current tab with a link?
In my chrome extension (https://chrome.google.com/webstore/detail/dark-mode-shell-shockers/mbbolbckjdjlfpjahlbhcodgagdpcdnf?hl=en&authuser=0) I want to make it so that if they click the popup, they can toggle settings. Although I know how to code this, I cannot figure out how to make it run javascript on the current tab from the popup!

I tried to just run a function, but it only runs on the popup! I think there is a way to do this, but no tutorial is clear on how, they just kind of say that it is possible.


问:
Telegraf not sending timestamp to InfluxDB_v2
I’m struggling with inserting timestamp in influxdb (I've asked this question on influxdb forum and slack channel but no one answered).

This is example of json log

```<code>{"@timestamp":"2022-12-26T04:27:24-05:00","client_ip":"xx.xx.xx.xx","domain":" somedomain.com ","request":"/404","responsetime":"0.001","host":"xx.xx.xx.xx","status":"404"}
</code>```

And this is my input.plugin

```<code>[[inputs.tail]]
 files = ["/var/log/nginx/json.access.log"]
 from_beginning = true
 name_override = "nginxjson"
 json_name_key = "nginxjson"
 data_format = "json"
 json_time_key = "@timestamp"
 json_time_format = "2006-01-02T15:04:05Z07:00"
 tag_keys = ["client_ip", "domain", "request", "host", "status"]
 json_string_fields = ["@timestamp", "responsetime"]
</code>```

I’ve tried also with timestamp as tag, but same, no errors and timestamp doesn’t write to influxdb, nothing happens, every other field or string is inserting normally. If needed, I can provide more info. I'm using latest influxdb version 2.6 and telegraf 1.24

Body:
I’m struggling with inserting timestamp in influxdb (I've asked this question on influxdb forum and slack channel but no one answered).

This is example of json log

{"@timestamp":"2022-12-26T04:27:24-05:00","client_ip":"xx.xx.xx.xx","domain":" somedomain.com ","request":"/404","responsetime":"0.001","host":"xx.xx.xx.xx","status":"404"}

And this is my input.plugin

[[inputs.tail]]
 files = ["/var/log/nginx/json.access.log"]
 from_beginning = true
 name_override = "nginxjson"
 json_name_key = "nginxjson"
 data_format = "json"
 json_time_key = "@timestamp"
 json_time_format = "2006-01-02T15:04:05Z07:00"
 tag_keys = ["client_ip", "domain", "request", "host", "status"]
 json_string_fields = ["@timestamp", "responsetime"]

I’ve tried also with timestamp as tag, but same, no errors and timestamp doesn’t write to influxdb, nothing happens, every other field or string is inserting normally. If needed, I can provide more info. I'm using latest influxdb version 2.6 and telegraf 1.24


问:
Routing Between Multiple Points Using Location Document
Hello I am developing under OS7 using the BB 9930 simulator.

I wanted to know if you can plot routes between multiple points using the Location Document that invokes Blackberry Maps. I have tried specifying multiple locations under the <getRoute> tag but that shows only the route between the last two location points. I tried specifying two <getRoute> tags under the <lbs> tag but that still shows only one route.

Is there any way to show multiple routes using the Location Document format?

If not, then does KML support routing between known latitude/longitude values?

Thanks for the help.

Edit: tags were not showing up properly.

ContentLicense: CC BY-SA 3.0


问:
How to draw a figure with a discrete colormap in rmarkdown
I would like to draw a figure with a discrete colormap using rmarkdown.

I tried using pgfplots. The following code should give my a figure with a discrete colormap instead of a continous one. Using the same code in Latex works as expected.

In the attached log file, I didn't find any clues as to what is going wrong. But I am also not sure what to look for, since there are no errors. Note that I included the undefined control sequence at the end on purpose to cause an error. Otherwise the log file is deleted right after compilation.

figure with continous colorbar

```<code>---
output:
  pdf_document: default
  html_document:
    df_print: paged
header-includes:
- \usepackage{pgfplots}
- \pgfplotsset{compat=1.13}

---

\begin{tikzpicture}
\begin{axis}[
  domain=-2:2,
  view={0}{90},
  colormap={CM}{
  samples of colormap=(13 of hot)},
  colormap access=piecewise constant,
  colorbar right,
  colorbar style={%
     ytick=data,
  }
]
\addplot3[surf,shader=interp]
{exp(-x^2-y^2)*x+0.5};
\end{axis}
\end{tikzpicture}
</code>```

Body:
I would like to draw a figure with a discrete colormap using rmarkdown.

I tried using pgfplots. The following code should give my a figure with a discrete colormap instead of a continous one. Using the same code in Latex works as expected.

In the attached log file, I didn't find any clues as to what is going wrong. But I am also not sure what to look for, since there are no errors. Note that I included the undefined control sequence at the end on purpose to cause an error. Otherwise the log file is deleted right after compilation.

figure with continous colorbar

---
output:
  pdf_document: default
  html_document:
    df_print: paged
header-includes:
- \usepackage{pgfplots}
- \pgfplotsset{compat=1.13}

---

\begin{tikzpicture}
\begin{axis}[
  domain=-2:2,
  view={0}{90},
  colormap={CM}{
  samples of colormap=(13 of hot)},
  colormap access=piecewise constant,
  colorbar right,
  colorbar style={%
     ytick=data,
  }
]
\addplot3[surf,shader=interp]
{exp(-x^2-y^2)*x+0.5};
\end{axis}
\end{tikzpicture}


问:
How can i get the average of RGB values in Python?
I'm trying to individually average the rgb values of each pixel in two images.

```<code>image = cv2.imread(images[z])
image2= cv2.imread(images[z+1])

height, width = image.shape[:2]

 for y in range(height):
    for x in range(width):
      (b, g, r) = image[y, x]
      (b2,g2,r2) = image2[y,x]

      print(b, b2, (b+b2)//2)

      image2[y,x] = ((b+b2)//2,(g+g2)//2,(r+r2)//2)

 cv2_imshow(image2)
</code>```
```<code>print(b, b2, (b+b2)//2)
</code>```

Some output:

```<code>128 137 4
127 136 3
127 137 4
126 135 2
126 134 2
127 132 1
127 132 1
</code>```

When I checked the resulting pixels, I saw that some values greater than 128 were set to 0, and as a result the image quality of the output photo is distorted. how can i solve this problem?

Body:
I'm trying to individually average the rgb values of each pixel in two images.

image = cv2.imread(images[z])
image2= cv2.imread(images[z+1])

height, width = image.shape[:2]

 for y in range(height):
    for x in range(width):
      (b, g, r) = image[y, x]
      (b2,g2,r2) = image2[y,x]

      print(b, b2, (b+b2)//2)

      image2[y,x] = ((b+b2)//2,(g+g2)//2,(r+r2)//2)

 cv2_imshow(image2)

print(b, b2, (b+b2)//2)

Some output:

128 137 4
127 136 3
127 137 4
126 135 2
126 134 2
127 132 1
127 132 1

When I checked the resulting pixels, I saw that some values greater than 128 were set to 0, and as a result the image quality of the output photo is distorted. how can i solve this problem?


问:
How to convert image into base64 and save it I am trying alot to convert my image to base 64 in RNFS system but UNABLE TO DO THAT REACT NATIVE
How to convert image into base64 and save it  I am trying alot to convert my image to base 64 in RNFS system but it gives error and not converting it.

const openCamera =async () => {
let source ;

```<code>let options = {
  storageOptions: {
    skipBackup: true,
    path: 'images',
  },
};
launchCamera(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled image picker');
  } else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  } else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
    alert(response.customButton);
  } else {
    source = JSON.stringify(response.assets[0].uri);
    console.log('Junaid', JSON.stringify(response.assets[0].uri));

  }

  // console.log('Khan',source);
  var data = RNFS.readFile( response.assets[0].uri, 'base64').
  then(res => { console.log('CODE IS NOW  ',data) });

});}
</code>```

Body:
How to convert image into base64 and save it  I am trying alot to convert my image to base 64 in RNFS system but it gives error and not converting it.

const openCamera =async () => {
let source ;

let options = {
  storageOptions: {
    skipBackup: true,
    path: 'images',
  },
};
launchCamera(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled image picker');
  } else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  } else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
    alert(response.customButton);
  } else {
    source = JSON.stringify(response.assets[0].uri);
    console.log('Junaid', JSON.stringify(response.assets[0].uri));

  }

  // console.log('Khan',source);
  var data = RNFS.readFile( response.assets[0].uri, 'base64').
  then(res => { console.log('CODE IS NOW  ',data) });

});}


问:
Imablanced Learning for Unsupervised Learning Data Mining
I'm working for a project and I have a doubt. I'm really new to data mining world, and Supervised and Unsupervised Learning.

I'm currently doing a work in Unsupervised Learning, and I'm trying to understand if the "Imbalaced Learning" methods are used in unsupervised learning problems or if it's only used in supervised ones.

The work is in python, so I've looked for python SMOTE method to deal with imbalanced learning, but it always appear "X_train and y_train", and since unsupervised learning don't have a target, I don't know how would i use SMOTE in this case.


问:
gstreamer cannot capture color images
I am trying to use 4 camera on rPI 4. Therefore, i use a Gstreamer and i don't know how it do  but my camera is always send gray capture. Can Gstreamer change camera's microcontroller? and if yes, how can i fix this issue?

thank you

```<code>gst-launch-1.0 v4l2src device=/dev/video0 ! "video/x-raw, format=YUY2" ! videoconvert ! "video/x-raw, format=NV12" ! videoconvert ! autovideosink

</code>```

i tried this command but it doesnt work, still gray capture

Title: gstreamer cannot capture color images

Body:
I am trying to use 4 camera on rPI 4. Therefore, i use a Gstreamer and i don't know how it do  but my camera is always send gray capture. Can Gstreamer change camera's microcontroller? and if yes, how can i fix this issue?

thank you

gst-launch-1.0 v4l2src device=/dev/video0 ! "video/x-raw, format=YUY2" ! videoconvert ! "video/x-raw, format=NV12" ! videoconvert ! autovideosink

i tried this command but it doesnt work, still gray capture


问:
How can I veto a Drag'n'Drop event from a Primefaces 3 tree?
I noticed that a tree branch disappears if you drag a tree node onto one of its children.

Try it here:
http://www.primefaces.org/showcase-labs/ui/treeDragDrop.jsf

How can I keep this from happening ?


问:
How to perform Multivariate binary logistic regression in R
How can I perform a multivariate binary (logistic, probit..) model in R ?
I've a set of Y (y1, y2,..., yp) response variables which are binaries.

I tried glm function in R but I can't fit multivariate (set of many variables as response in one model)

I tried glmer function in lme4 package. But it allows only two response variables (y1, y2).


问:
TypeError: 'MaxPool2d' object is not iterable
After importing a neural network using OpenCV (import cv2) I received an exception in Git Bash which is the following :

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\adrie\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\adrie\anaconda3\lib\site-packages\customtkinter\windows\widgets\ctk_button.py", line 531, in _clicked
    self._command()
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\interface_reseau.py", line 77, in select_cam
    self.update()
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\interface_reseau.py", line 80, in update
    ret,frame=self.vid.get_frame()
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\interface_reseau.py", line 100, in get_frame
    objs = Object_detector.detect(frame)
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\elements\yolo.py", line 27, in detect
    pred = self.yolo_model(img, augment=False)[0]
  File "C:\Users\adrie\anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1194, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\models\yolo.py", line 121, in forward
    return self.forward_once(x, profile)  # single-scale inference, train
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\models\yolo.py", line 152, in forward_once
    x = m(x)  # run
  File "C:\Users\adrie\anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1194, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\models\common.py", line 160, in forward
    return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
TypeError: 'MaxPool2d' object is not iterable

</code>```

Using OpenCV with a neural network for Object detection and CustomTkinter making an UI interface with a video inside I tried to put in get_frame method the following line :

```<code>objs = Object_detector.detect(frame)
</code>```

and I used it so as to change my frames and getting YOLOv5 on my video.

My code :

```<code>import tkinter as tk
#import ttkbootstrap as ttkb
#from ttkbootstrap.constants import *
import PIL.Image, PIL.ImageTk
import customtkinter
from cv2 import (VideoCapture, namedWindow, imshow, waitKey, destroyWindow, imwrite)
import cv2

import numpy as np
from elements.yolo import OBJ_DETECTION

customtkinter.set_appearance_mode("Dark")
customtkinter.set_default_color_theme("dark-blue")

Object_classes = ['person', 'bicycle', 'car', 'bus' ]

Object_colors = list(np.random.rand(80,3)*255)
Object_detector = OBJ_DETECTION('weights/yolov5s.pt', Object_classes)

def gstreamer_pipeline(capture_width=1280,capture_height=720,display_width=1280,display_height=720,framerate=60,flip_method=0):
    return (
        "nvarguscamerasrc ! "
        "video/x-raw(memory:NVMM), "
        "width=(int)%d, height=(int)%d, "
        "format=(string)NV12, framerate=(fraction)%d/1 ! "
        "nvvidconv flip-method=%d ! "
        "video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
        "videoconvert ! "
        "video/x-raw, format=(string)BGR ! appsink"
        % (
            capture_width,
            capture_height,
            framerate,
            flip_method,
            display_width,
            display_height,
        )
    )

class CapgeminiYOLO:
    def __init__(self,window,size,title,logo,imglight,imgdark):
        self.window = window
        self.window.geometry(size)
        self.width = 2400
        self.height = 760
        self.title = title
        self.image_logo = logo
        self.imagelight = imglight
        self.imagedark = imgdark

        self.window.iconbitmap(self.image_logo)
        self.create_frame_accueil(self.width,self.height/2,self.imagelight,self.imagedark)
        self.frame3=customtkinter.CTkFrame(self.window,width=self.width*2,height=self.height,fg_color="#000000")
        self.frame3.pack(padx=0,pady=0)
        self.button1=customtkinter.CTkButton(self.frame3,text="Testez-moi",command=self.select_cam,text_color="#000000",bg_color="#0048ab",font=customtkinter.CTkFont(family="Torus Notched",size=18, weight="bold"),corner_radius=10)
        self.button1.pack(padx=0,pady=50)
        self.window.mainloop()

    def create_frame_accueil(self,frame_width,frame_height,imglight,imgdark):
        self.frame1=customtkinter.CTkFrame(master=self.window,width=frame_width,height=frame_height*1.2,fg_color="#000000")
        self.frame1.grid(row=0,column=0,padx=20,pady=20)
        self.frame1.pack()
        image = customtkinter.CTkImage(light_image=PIL.Image.open(imglight),dark_image=PIL.Image.open(imgdark),size=(618,179))
        self.create_label(self.frame1,"Bienvenue dans l'interface YOLO de Capgemini",image)

    def create_label(self,frame,text,img):
        label=customtkinter.CTkLabel(master=frame,width=self.width,height=self.height/4,text=text,text_color="#FFFFFF",corner_radius=20,bg_color="#000000",image=img,compound="bottom",font=customtkinter.CTkFont(family="Arial",size=30, weight="bold"))
        label.pack()

    def select_cam(self,video_source=0):
        self.video_source = video_source
        self.vid = MyVideoCapture(self.video_source)
        self.canvas = tk.Canvas(self.frame1,width=self.vid.width,height=self.vid.height,bg="#000000")
        self.delay = 15
        self.button1.configure(state="disabled")
        self.update()

    def update(self):
        ret,frame=self.vid.get_frame()
        if ret:
            self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))
            self.canvas.create_image(0, 0, image = self.photo, anchor = tk.NW)
            self.canvas.pack()
        self.window.after(self.delay,self.update)

class MyVideoCapture:
    def __init__(self,video_source=0):
        self.vid = VideoCapture(video_source)
        if not self.vid.isOpened():
            raise ValueError("unable open video source", video_source)

        self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
        self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)

    def get_frame(self):
        if self.vid.isOpened():
            ret, frame = self.vid.read()
            if ret:
                objs = Object_detector.detect(frame)
                # plotting
                for obj in objs:
                    # print(obj)
                    label = obj['label']
                    score = obj['score']
                    [(xmin,ymin),(xmax,ymax)] = obj['bbox']
                    color = Object_colors[Object_classes.index(label)]
                    frame = rectangle(frame, (xmin,ymin), (xmax,ymax), color, 2)
                    frame = putText(frame, f'{label} ({str(score)})', (xmin,ymin), cv2.FONT_HERSHEY_SIMPLEX , 0.75, color, 1, cv2.LINE_AA)
                return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            else:
                return (ret, None)
        else:
            return (ret,None)
    def __del__(self):
        if self.vid.isOpened():
            self.vid.release()
if __name__ == "__main__":
    app = customtkinter.CTk()
    CapgeminiYOLO(app,"1080x760","Interface YOLO Capgemini","capgeminil.ico","capg_img.png","capg_logo.png")
</code>```

PS : I'm using a repository whose link is https://github.com/amirhosseinh77/JetsonYolo so as to use the method detect. Thanks in advance and have a nice day!

Body:
After importing a neural network using OpenCV (import cv2) I received an exception in Git Bash which is the following :

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\adrie\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\adrie\anaconda3\lib\site-packages\customtkinter\windows\widgets\ctk_button.py", line 531, in _clicked
    self._command()
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\interface_reseau.py", line 77, in select_cam
    self.update()
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\interface_reseau.py", line 80, in update
    ret,frame=self.vid.get_frame()
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\interface_reseau.py", line 100, in get_frame
    objs = Object_detector.detect(frame)
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\elements\yolo.py", line 27, in detect
    pred = self.yolo_model(img, augment=False)[0]
  File "C:\Users\adrie\anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1194, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\models\yolo.py", line 121, in forward
    return self.forward_once(x, profile)  # single-scale inference, train
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\models\yolo.py", line 152, in forward_once
    x = m(x)  # run
  File "C:\Users\adrie\anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1194, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\adrie\OneDrive\Documents\Interface_YOLO\JetsonYolo\models\common.py", line 160, in forward
    return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
TypeError: 'MaxPool2d' object is not iterable

Using OpenCV with a neural network for Object detection and CustomTkinter making an UI interface with a video inside I tried to put in get_frame method the following line :

objs = Object_detector.detect(frame)

and I used it so as to change my frames and getting YOLOv5 on my video.

My code :

import tkinter as tk
#import ttkbootstrap as ttkb
#from ttkbootstrap.constants import *
import PIL.Image, PIL.ImageTk
import customtkinter
from cv2 import (VideoCapture, namedWindow, imshow, waitKey, destroyWindow, imwrite)
import cv2

import numpy as np
from elements.yolo import OBJ_DETECTION

customtkinter.set_appearance_mode("Dark")
customtkinter.set_default_color_theme("dark-blue")

Object_classes = ['person', 'bicycle', 'car', 'bus' ]

Object_colors = list(np.random.rand(80,3)*255)
Object_detector = OBJ_DETECTION('weights/yolov5s.pt', Object_classes)

def gstreamer_pipeline(capture_width=1280,capture_height=720,display_width=1280,display_height=720,framerate=60,flip_method=0):
    return (
        "nvarguscamerasrc ! "
        "video/x-raw(memory:NVMM), "
        "width=(int)%d, height=(int)%d, "
        "format=(string)NV12, framerate=(fraction)%d/1 ! "
        "nvvidconv flip-method=%d ! "
        "video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
        "videoconvert ! "
        "video/x-raw, format=(string)BGR ! appsink"
        % (
            capture_width,
            capture_height,
            framerate,
            flip_method,
            display_width,
            display_height,
        )
    )

class CapgeminiYOLO:
    def __init__(self,window,size,title,logo,imglight,imgdark):
        self.window = window
        self.window.geometry(size)
        self.width = 2400
        self.height = 760
        self.title = title
        self.image_logo = logo
        self.imagelight = imglight
        self.imagedark = imgdark

        self.window.iconbitmap(self.image_logo)
        self.create_frame_accueil(self.width,self.height/2,self.imagelight,self.imagedark)
        self.frame3=customtkinter.CTkFrame(self.window,width=self.width*2,height=self.height,fg_color="#000000")
        self.frame3.pack(padx=0,pady=0)
        self.button1=customtkinter.CTkButton(self.frame3,text="Testez-moi",command=self.select_cam,text_color="#000000",bg_color="#0048ab",font=customtkinter.CTkFont(family="Torus Notched",size=18, weight="bold"),corner_radius=10)
        self.button1.pack(padx=0,pady=50)
        self.window.mainloop()

    def create_frame_accueil(self,frame_width,frame_height,imglight,imgdark):
        self.frame1=customtkinter.CTkFrame(master=self.window,width=frame_width,height=frame_height*1.2,fg_color="#000000")
        self.frame1.grid(row=0,column=0,padx=20,pady=20)
        self.frame1.pack()
        image = customtkinter.CTkImage(light_image=PIL.Image.open(imglight),dark_image=PIL.Image.open(imgdark),size=(618,179))
        self.create_label(self.frame1,"Bienvenue dans l'interface YOLO de Capgemini",image)

    def create_label(self,frame,text,img):
        label=customtkinter.CTkLabel(master=frame,width=self.width,height=self.height/4,text=text,text_color="#FFFFFF",corner_radius=20,bg_color="#000000",image=img,compound="bottom",font=customtkinter.CTkFont(family="Arial",size=30, weight="bold"))
        label.pack()

    def select_cam(self,video_source=0):
        self.video_source = video_source
        self.vid = MyVideoCapture(self.video_source)
        self.canvas = tk.Canvas(self.frame1,width=self.vid.width,height=self.vid.height,bg="#000000")
        self.delay = 15
        self.button1.configure(state="disabled")
        self.update()

    def update(self):
        ret,frame=self.vid.get_frame()
        if ret:
            self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))
            self.canvas.create_image(0, 0, image = self.photo, anchor = tk.NW)
            self.canvas.pack()
        self.window.after(self.delay,self.update)

class MyVideoCapture:
    def __init__(self,video_source=0):
        self.vid = VideoCapture(video_source)
        if not self.vid.isOpened():
            raise ValueError("unable open video source", video_source)

        self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
        self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)

    def get_frame(self):
        if self.vid.isOpened():
            ret, frame = self.vid.read()
            if ret:
                objs = Object_detector.detect(frame)
                # plotting
                for obj in objs:
                    # print(obj)
                    label = obj['label']
                    score = obj['score']
                    [(xmin,ymin),(xmax,ymax)] = obj['bbox']
                    color = Object_colors[Object_classes.index(label)]
                    frame = rectangle(frame, (xmin,ymin), (xmax,ymax), color, 2)
                    frame = putText(frame, f'{label} ({str(score)})', (xmin,ymin), cv2.FONT_HERSHEY_SIMPLEX , 0.75, color, 1, cv2.LINE_AA)
                return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            else:
                return (ret, None)
        else:
            return (ret,None)
    def __del__(self):
        if self.vid.isOpened():
            self.vid.release()
if __name__ == "__main__":
    app = customtkinter.CTk()
    CapgeminiYOLO(app,"1080x760","Interface YOLO Capgemini","capgeminil.ico","capg_img.png","capg_logo.png")

PS : I'm using a repository whose link is https://github.com/amirhosseinh77/JetsonYolo so as to use the method detect. Thanks in advance and have a nice day!


问:
Add pattern to stack driver and console to display (line number/class name/function name) in app engine second gen
I'm currently building a spring boot application using gcp app engine version 2 and I would like to add a pattern to stack driver and console to display function name / line number / class name (like logs displayed in app engine first gen)

I want to change this:

(https://i.stack.imgur.com/6TfSD.png)

to something like this:

(https://i.stack.imgur.com/sxP2g.png)

logback-spring.xml:

(https://i.stack.imgur.com/E5TMn.png)

Also it is not a must you use logback, so if there is any other way to output the desired logs (and works with spring boot and app engine second gen) I can switch to it


问:
FlatMapGroupsWithStateFunction with lazy iterator as return value
When using Apache Spark with stateful processing, it can group rows with same key using flatMapGroupsWithState function

```<code>Dataset<Row> ds = spark.sql("SELECT ... FROM parquetTable")
                             .groupByKey(..., Encoders.STRING()
                             .flatMapGroupsWithState(new FlatMapFunctionEager(),
                                     OutputMode.Append(),
                                     Encoders.kryo(Session.class),
                                     RowEncoder.apply(PARQUET_SCHEMA),
                                     GroupStateTimeout.ProcessingTimeTimeout());
</code>```

Generally, examples or tutorials show a FlatMapGroupsWithStateFunction with a List<Row> created first and iterator to it is returned:

```<code>private class FlatMapFunctionEager implements FlatMapGroupsWithStateFunction<String, Row, Session, Row> {
    @Override
    public Iterator<Row> call(String key, Iterator<Row> values, GroupState<Session> state) throws Exception {
        Session session = null;
        if (state.exists()) {
            session = state.get();
        } else {
            session = createSession();
            state.update(session);
        }

        // here a list is created and populated with results
        List<Row> result = new LinkedList<>();
        while (values.hasNext()) {
            Row row = values.next();
            result.add(process(row, session));
        }

        // here iterator of the list is returned
        return result.iterator();
    }

    private Row process(Row row, Session session) {
        // do processing and return generated row
    }
}
</code>```

However, this sometimes causes memory problems since Spark can group a lot of Rows for processing.
Is it safe to return a lazy iterator that stores Iterator and GroupState provided by the caller?
Or can Iterator and GroupState change after the call and therefore not safe to use them lazily?

Sample code:

```<code>public class FlatMapFunctionLazy implements FlatMapGroupsWithStateFunction<String, Row, Session, Row> {
    @Override
    public Iterator<Row> call(String key, Iterator<Row> values, GroupState<Session> state) throws Exception {
        // here we pass the state and values iterator
        return new LazyIterator(state, values);
    }
}

public class LazyIterator implements Iterator<Row> {
    private final GroupState<Session> state;
    private final Iterator<Row> values;

    public LazyIterator(GroupState<Session> state, Iterator<Row> values) {
        this.state = state;
        this.values = values;
    }

    @Override
    public boolean hasNext() {
        return values.hasNext();
    }

    @Override
    public Row next() {
        // here we use the provided iterator when our iterators next is called
        Row row = values.next();
        return process(row);
    }

    private Row process(Row row) {
        Session session = null;
        // here we query and update the state (GroupState)
        if (state.exists()) {
            session = state.get();
        } else {
            session = createSession();
            state.update(session);
        }

        return process(row, session);
    }

    private Row process(Row row, Session session) {
        // do processing and return generated row
    }
}
</code>```

Is this kind of usage safe or will be the behaviour undefined?

I tried lazy iterator with some sample input and got correct results however I could not be sure for its correctness since sometimes multi-threaded programs may produce correct results even though some race conditions exist and also documentation is not clear about this area.

Body:
When using Apache Spark with stateful processing, it can group rows with same key using flatMapGroupsWithState function

Dataset<Row> ds = spark.sql("SELECT ... FROM parquetTable")
                             .groupByKey(..., Encoders.STRING()
                             .flatMapGroupsWithState(new FlatMapFunctionEager(),
                                     OutputMode.Append(),
                                     Encoders.kryo(Session.class),
                                     RowEncoder.apply(PARQUET_SCHEMA),
                                     GroupStateTimeout.ProcessingTimeTimeout());

Generally, examples or tutorials show a FlatMapGroupsWithStateFunction with a List<Row> created first and iterator to it is returned:

private class FlatMapFunctionEager implements FlatMapGroupsWithStateFunction<String, Row, Session, Row> {
    @Override
    public Iterator<Row> call(String key, Iterator<Row> values, GroupState<Session> state) throws Exception {
        Session session = null;
        if (state.exists()) {
            session = state.get();
        } else {
            session = createSession();
            state.update(session);
        }

        // here a list is created and populated with results
        List<Row> result = new LinkedList<>();
        while (values.hasNext()) {
            Row row = values.next();
            result.add(process(row, session));
        }

        // here iterator of the list is returned
        return result.iterator();
    }

    private Row process(Row row, Session session) {
        // do processing and return generated row
    }
}

However, this sometimes causes memory problems since Spark can group a lot of Rows for processing.
Is it safe to return a lazy iterator that stores Iterator and GroupState provided by the caller?
Or can Iterator and GroupState change after the call and therefore not safe to use them lazily?

Sample code:

public class FlatMapFunctionLazy implements FlatMapGroupsWithStateFunction<String, Row, Session, Row> {
    @Override
    public Iterator<Row> call(String key, Iterator<Row> values, GroupState<Session> state) throws Exception {
        // here we pass the state and values iterator
        return new LazyIterator(state, values);
    }
}

public class LazyIterator implements Iterator<Row> {
    private final GroupState<Session> state;
    private final Iterator<Row> values;

    public LazyIterator(GroupState<Session> state, Iterator<Row> values) {
        this.state = state;
        this.values = values;
    }

    @Override
    public boolean hasNext() {
        return values.hasNext();
    }

    @Override
    public Row next() {
        // here we use the provided iterator when our iterators next is called
        Row row = values.next();
        return process(row);
    }

    private Row process(Row row) {
        Session session = null;
        // here we query and update the state (GroupState)
        if (state.exists()) {
            session = state.get();
        } else {
            session = createSession();
            state.update(session);
        }

        return process(row, session);
    }

    private Row process(Row row, Session session) {
        // do processing and return generated row
    }
}

Is this kind of usage safe or will be the behaviour undefined?

I tried lazy iterator with some sample input and got correct results however I could not be sure for its correctness since sometimes multi-threaded programs may produce correct results even though some race conditions exist and also documentation is not clear about this area.


问:
SQL Server : how to set a column to a random value?
I'm using SQL Server, I'm not experienced in T-SQL, but I want to generate random value including letters and numbers for one column for my project:

```<code>CREATE TABLE [dbo].[Orders]
(
    [Id]               INT NOT NULL,
    [UserId]           INT NOT NULL,
    [MedicineId]       INT NOT NULL,
    [CourierId]        INT NULL,
    [ReadyForDelivery] BIT NOT NULL,
    [OrderNumber]      NVARCHAR(11) NOT NULL,
    CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED ([Id] ASC)
);
</code>```

Id is my primary key also I want to put a random number and letters in the OrderNumber column. How can I do that?

I use migration when I'm creating this table

```<code>protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
                name: "Orders",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    UserId = table.Column<int>(type: "int", nullable: false),
                    MedicineId = table.Column<int>(type: "int", nullable: false),
                    CourierId = table.Column<int>(type: "int", nullable: false),
                    ReadyForDelivery = table.Column<bool>(type: "bit", nullable: false),
                    OrderNumber = table.Column<string>(type: "nvarchar(max)", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Orders", x => x.Id);
                });
}
</code>```

Body:
I'm using SQL Server, I'm not experienced in T-SQL, but I want to generate random value including letters and numbers for one column for my project:

CREATE TABLE [dbo].[Orders]
(
    [Id]               INT NOT NULL,
    [UserId]           INT NOT NULL,
    [MedicineId]       INT NOT NULL,
    [CourierId]        INT NULL,
    [ReadyForDelivery] BIT NOT NULL,
    [OrderNumber]      NVARCHAR(11) NOT NULL,
    CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED ([Id] ASC)
);

Id is my primary key also I want to put a random number and letters in the OrderNumber column. How can I do that?

I use migration when I'm creating this table

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
                name: "Orders",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    UserId = table.Column<int>(type: "int", nullable: false),
                    MedicineId = table.Column<int>(type: "int", nullable: false),
                    CourierId = table.Column<int>(type: "int", nullable: false),
                    ReadyForDelivery = table.Column<bool>(type: "bit", nullable: false),
                    OrderNumber = table.Column<string>(type: "nvarchar(max)", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Orders", x => x.Id);
                });
}


问:
No cache data for this platform
I have installed pccs on my vm with sgx enabled, the I run sudo systemctl start pccs and curl -k -G "https://localhost:8081/sgx/certification/v4/rootcacrl" but I get error No cache data for this platform.
my kernel is :

```<code>cat /proc/version
Linux version 5.15.0-1029-azure (buildd@lcy02-amd64-076) (gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0, GNU ld (GNU Binutils for Ubuntu) 2.34) #36~20.04.1-Ubuntu SMP Tue Dec 6 17:00:26 UTC 2022
</code>```

this is the pccs_server.log:

```<code>2022-12-27 16:25:22.885 [info]: HTTPS Server is running on: https://localhost:8081
2022-12-27 16:26:17.206 [info]: Client Request-ID : 19de7dcf832143418bd560e236a3e745
2022-12-27 16:26:17.210 [error]: Error: No cache data for this platform.
    at ReqCachingMode.getRootCACrlFromPCS (file:///opt/intel/sgx-dcap-pccs/services/caching_modes/cachingMode.js:84:11)
    at CachingModeManager.getRootCACrlFromPCS (file:///opt/intel/sgx-dcap-pccs/services/caching_modes/cachingModeManager.js:73:23)
    at Module.getRootCaCrl (file:///opt/intel/sgx-dcap-pccs/services/rootcacrlService.js:47:36)
    at async getRootCaCrl (file:///opt/intel/sgx-dcap-pccs/controllers/rootcacrlController.js:38:21)
2022-12-27 16:26:17.217 [info]: 127.0.0.1 - - [27/Dec/2022:16:26:17 +0000] "GET /sgx/certification/v4/rootcacrl HTTP/1.1" 404 32 "-" "curl/7.68.0"
</code>```

does any body knows the issue?

Title: No cache data for this platform

Body:
I have installed pccs on my vm with sgx enabled, the I run sudo systemctl start pccs and curl -k -G "https://localhost:8081/sgx/certification/v4/rootcacrl" but I get error No cache data for this platform.
my kernel is :

cat /proc/version
Linux version 5.15.0-1029-azure (buildd@lcy02-amd64-076) (gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0, GNU ld (GNU Binutils for Ubuntu) 2.34) #36~20.04.1-Ubuntu SMP Tue Dec 6 17:00:26 UTC 2022

this is the pccs_server.log:

2022-12-27 16:25:22.885 [info]: HTTPS Server is running on: https://localhost:8081
2022-12-27 16:26:17.206 [info]: Client Request-ID : 19de7dcf832143418bd560e236a3e745
2022-12-27 16:26:17.210 [error]: Error: No cache data for this platform.
    at ReqCachingMode.getRootCACrlFromPCS (file:///opt/intel/sgx-dcap-pccs/services/caching_modes/cachingMode.js:84:11)
    at CachingModeManager.getRootCACrlFromPCS (file:///opt/intel/sgx-dcap-pccs/services/caching_modes/cachingModeManager.js:73:23)
    at Module.getRootCaCrl (file:///opt/intel/sgx-dcap-pccs/services/rootcacrlService.js:47:36)
    at async getRootCaCrl (file:///opt/intel/sgx-dcap-pccs/controllers/rootcacrlController.js:38:21)
2022-12-27 16:26:17.217 [info]: 127.0.0.1 - - [27/Dec/2022:16:26:17 +0000] "GET /sgx/certification/v4/rootcacrl HTTP/1.1" 404 32 "-" "curl/7.68.0"

does any body knows the issue?


问:
How to run long running fucntion in background without using any external job-queue or message-broker in Express.js api?
I want to run time consuming function in background when express api get called. currently I am doing this using RabbitMQ.

var rabbitMQ = require('rabbitmq')

var myApi = async function(req, res) {
    try {
        let { city, country } = req.body

        var channel = await rabbitMQ.connection
        var payload = {city, country}
        var result = channel.publish('rabbitMQxchange', 'myQueue', new Buffer(JSON.stringify(payload)), { persistent: true })

        res.json({success: true})
    } catch(error) {
        res.json({success: false, "Some Error"})
    }
}
```
<p>I dony want to use RabbitMQ or other job queue things. So I want to build some approach like this.</p>
<pre class="lang-js prettyprint-override"><code>function myLongRunningFunction(city, country) {

}

var myApi = async function(req, res) {
    try {
        let { city, country } = req.body

        // This should run in background
        myLongRunningFunction(city, country)

        res.json({success: true})
    } catch(error) {
        res.json({success: false, "Some Error"})
    }
}
</code>```

What can be the approach to run function in background?

Body:
I want to run time consuming function in background when express api get called. currently I am doing this using RabbitMQ.

var rabbitMQ = require('rabbitmq')

var myApi = async function(req, res) {
    try {
        let { city, country } = req.body

        var channel = await rabbitMQ.connection
        var payload = {city, country}
        var result = channel.publish('rabbitMQxchange', 'myQueue', new Buffer(JSON.stringify(payload)), { persistent: true })

        res.json({success: true})
    } catch(error) {
        res.json({success: false, "Some Error"})
    }
}

I dony want to use RabbitMQ or other job queue things. So I want to build some approach like this.

function myLongRunningFunction(city, country) {

}

var myApi = async function(req, res) {
    try {
        let { city, country } = req.body

        // This should run in background
        myLongRunningFunction(city, country)

        res.json({success: true})
    } catch(error) {
        res.json({success: false, "Some Error"})
    }
}

What can be the approach to run function in background?


问:
Terminal Error : Exception occurred while executing 'list'
When I try to connect my android device to my mac to test an app via firebase debugview I got this error.

Exception occurred while executing 'list':
java.lang.SecurityException: Shell does not have permission to access user 150
com.android.server.am.ActivityManagerService.handleIncomingUser:14872 android.app.ActivityManager.handleIncomingUser:4802 com.android.server.pm.PackageManagerShellCommand.translateUserId:3499

When I use another android device it connects successfully. Does anyone know why it happens?

I follow the steps above to connect my phone to my mac:
cmd -> cd desktop -> cd platform-tools-1 ->./adb devices -> (Check if the downloaded app and the package name in firebase are the same)  ./adb shell pm list packages
./adb shell setprop debug.firebase.analytics.app <package_name> -> ./adb devices ->
follow from the Firebase debugView.


问:
Template element fails with some script tags
I create template and insert some html from string.

I know I can use innerHTML, but I am wondering why the following example fails using template?  (even if I remove backslashes the same result)

In the end, only first script tag is added inside ".a" element.

var adContent = '


问:
Why does FileChooser output errors in console? How do I supress them?
Whenever I invoke FileChooser's showOpenDialog() method in JavaFX:

```<code>import javafx.application.Application;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;

public class HelloApplication extends Application {
    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws IOException {
        FileChooser chooser = new FileChooser();
        File file = chooser.showOpenDialog(stage);
    }
}
</code>```

I get these console messages in red:

2022-12-27 20:41:49.955 java[75677:2827731] +[CATransaction synchronize] called within transaction

2022-12-27 20:41:50.093 java[75677:2827731] +[CATransaction synchronize] called within transaction

I tried looking up the problem online but there were only two search hits and they didn't contain a solution. The one on here mentioned something about a bug in JavaFX, but I've faced the same issue even with JavaFX-11 and now with JavaFX-19.

Please note that the method works fine. I just don't want the messages to be output.

Does anybody have an idea what this message means, why it appears, and how to supress it?

Thanks.

Body:
Whenever I invoke FileChooser's showOpenDialog() method in JavaFX:

import javafx.application.Application;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;

public class HelloApplication extends Application {
    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws IOException {
        FileChooser chooser = new FileChooser();
        File file = chooser.showOpenDialog(stage);
    }
}

I get these console messages in red:

2022-12-27 20:41:49.955 java[75677:2827731] +[CATransaction synchronize] called within transaction

2022-12-27 20:41:50.093 java[75677:2827731] +[CATransaction synchronize] called within transaction

I tried looking up the problem online but there were only two search hits and they didn't contain a solution. The one on here mentioned something about a bug in JavaFX, but I've faced the same issue even with JavaFX-11 and now with JavaFX-19.

Please note that the method works fine. I just don't want the messages to be output.

Does anybody have an idea what this message means, why it appears, and how to supress it?

Thanks.


问:
Retrieve data by date and time inside of array element in MongoDB and Nodejs
I want to retrieve data by date and time inside of array from EffectiveDate element.
I saving EffectiveDate by Date.now on Mongodb not with ISO date format.
I want to get result EffectiveDate is not greater than current date and then get the lasted date from list result.

My collection data is at the following sample.

```<code>  {
   “_id”: “63a2b0f87a810608e6ca6d95”,
   “Templates”: [
                {
                “HardwareVer”: “minthein@Joseph”,
                “SoftwareVer”: “11111.0”,
                “RevisionNum”: “mtw”,
                “EffectiveDate”: “2022-12-26T08:29:58.470Z”,
                “WorkTasks”: [
                “63a70c631dbb68ffa7473be1”,
                “63aa9a084c60349138c4d5c3”
                             ],
                “HasTraveller”: true,
                “_id”: “63a70a691dbb68ffa7473ba8”
                },
                {
                 “HardwareVer”: “josephwin”,
                 “SoftwareVer”: “11111.0”,
                 “RevisionNum”: “win”,
                 “EffectiveDate”: “2022-12-26T07:29:58.470Z”,
                 “WorkTasks”: ,
                 “HasTraveller”: false,
                “_id”: “63a70b741dbb68ffa7473bbc”
                },
                {
                 “HardwareVer”: “A333”,
                 “SoftwareVer”: “333.0”,
                 “RevisionNum”: “221227135521”,
                 “EffectiveDate”: “2023-01-27T05:55:09.148Z”,
                 “WorkTasks”: ,
                 “HasTraveller”: false,
                 “_id”: “63aa88c96e0a2601d545e52c”
                }
                ],
                }
</code>```

I wish to get result at the follow

```<code>        {
          “_id”: “63a2b0f87a810608e6ca6d95”,
          “Templates”: [
                       {
                       “HardwareVer”: “minthein@Joseph”,
                       “SoftwareVer”: “11111.0”,
                       “RevisionNum”: “mtw”,
                       “EffectiveDate”: “2022-12-26T08:29:58.470Z”,
                       “WorkTasks”: [
                                    “63a70c631dbb68ffa7473be1”,
                                    “63aa9a084c60349138c4d5c3”
                                    ],
                        “HasTraveller”: true,
                        “_id”: “63a70a691dbb68ffa7473ba8”
                        },
                        ],
                        }
</code>```

Please help me sir.I had start to learning MongoDB and Nodjs.

Body:
I want to retrieve data by date and time inside of array from EffectiveDate element.
I saving EffectiveDate by Date.now on Mongodb not with ISO date format.
I want to get result EffectiveDate is not greater than current date and then get the lasted date from list result.

My collection data is at the following sample.

  {
   “_id”: “63a2b0f87a810608e6ca6d95”,
   “Templates”: [
                {
                “HardwareVer”: “minthein@Joseph”,
                “SoftwareVer”: “11111.0”,
                “RevisionNum”: “mtw”,
                “EffectiveDate”: “2022-12-26T08:29:58.470Z”,
                “WorkTasks”: [
                “63a70c631dbb68ffa7473be1”,
                “63aa9a084c60349138c4d5c3”
                             ],
                “HasTraveller”: true,
                “_id”: “63a70a691dbb68ffa7473ba8”
                },
                {
                 “HardwareVer”: “josephwin”,
                 “SoftwareVer”: “11111.0”,
                 “RevisionNum”: “win”,
                 “EffectiveDate”: “2022-12-26T07:29:58.470Z”,
                 “WorkTasks”: ,
                 “HasTraveller”: false,
                “_id”: “63a70b741dbb68ffa7473bbc”
                },
                {
                 “HardwareVer”: “A333”,
                 “SoftwareVer”: “333.0”,
                 “RevisionNum”: “221227135521”,
                 “EffectiveDate”: “2023-01-27T05:55:09.148Z”,
                 “WorkTasks”: ,
                 “HasTraveller”: false,
                 “_id”: “63aa88c96e0a2601d545e52c”
                }
                ],
                }

I wish to get result at the follow

        {
          “_id”: “63a2b0f87a810608e6ca6d95”,
          “Templates”: [
                       {
                       “HardwareVer”: “minthein@Joseph”,
                       “SoftwareVer”: “11111.0”,
                       “RevisionNum”: “mtw”,
                       “EffectiveDate”: “2022-12-26T08:29:58.470Z”,
                       “WorkTasks”: [
                                    “63a70c631dbb68ffa7473be1”,
                                    “63aa9a084c60349138c4d5c3”
                                    ],
                        “HasTraveller”: true,
                        “_id”: “63a70a691dbb68ffa7473ba8”
                        },
                        ],
                        }

Please help me sir.I had start to learning MongoDB and Nodjs.


问:
Why static variables do not appear in Inspector in Unity
I have Example.cs which has attached to the Main Camera, and in the Main Camera's Inspector I just can see the aPoint appear. Both aPoint and bPoint are public but why static makes bPoint doesn't appear in the Inspector.

using System.Collections;
using UnityEngine;
public class Example : MonoBehavior
{
    public int aPoint;
    public static int bPoint;
}
```