问:
Update the screen as the user fill in the textformfield from bottomsheet
I am working to have a ListTile of spare parts that will show on the main screen when the user fill in the TextFormField at the BottomSheet. By this user can decide whether to add or delete the spare part. The state of main screen will update based on that decision. The current problem is that when the user click on the add button at BottomSheet, the data is not passed to the parent widget and that make it hard to change the state of the screen.</p>
```<code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'ACM.dart';
import 'PPMLine.dart';
import 'QrScanner.dart';

class ACMaction extends StatefulWidget {
  const ACMaction({Key key}) : super(key: key);

  @override
  State<ACMaction> createState() => _ACMactionState();
}

class _ACMactionState extends State<ACMaction> {

  static String newPartTitles;
  List<Part> parts = [
    Part(
      pNum3: newPartTitles,
      // pName3: addPart().partName,
      // qty3: addPart().qty
    ),
  ];

  TextEditingController textFieldControllerACM4 = TextEditingController();

  void logout() async {
    await FirebaseAuth.instance.signOut();
    Navigator.pushNamed(context, 'LoginPage');
  }

  @override
  Widget build(BuildContext context) {

    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text('ACM action'),
        backgroundColor: Colors.deepOrange,
        elevation: 0,
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.deepOrange,
              ),
              child: Text(
                'BHSKlia2',
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
            // ListTile(
            //   leading: Icon(Icons.message),
            //   title: Text('Comment'),
            // ),
            // ListTile(
            //   leading: Icon(Icons.check_box),
            //   title: Text('Review'),
            // ),
            ListTile(
              leading: Icon(Icons.history),
              title: Text('Recent'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => submits()),
                );
              },
            ),
            ListTile(
              leading: Icon(Icons.auto_stories),
              title: Text('ACM'),
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => ACMaction()));
              },
            ),
            ListTile(
              leading: Icon(Icons.camera_alt),
              title: Text('QR Scanner'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => qrScan()),
                );
              },
            ),
            ListTile(
              leading: Icon(Icons.close),
              title: Text('Sign Out'),
              onTap: () {
                logout();
              },
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Row(
              children: [
                MyStatefulWidgetACM1(),
                Spacer(),
                Padding(
                  padding: const EdgeInsets.only(right: 10),
                  child: MyHomePage(),
                ),
              ],
            ),
            Container(
              margin: EdgeInsets.all(10),
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Colors.deepOrange,
                border: Border.all(
                    color: Colors.orange, // set border color
                    width: 3.0), // set border width
                borderRadius: BorderRadius.all(
                    Radius.circular(20.0)), // set rounded corner radius
              ),
              child: TextFormField(
                controller: textFieldControllerACM4,
                decoration: InputDecoration(
                  border: const OutlineInputBorder(),
                  filled: true,
                  hintText: 'Corrective Action Detail',
                  labelText: 'Corrective Action Detail',
                ),
                maxLines: 5,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Row(
                children: [
                  TextButton(
                      onPressed: () {
                        showModalBottomSheet(
                            context: context,
                            builder: (context) => addPart(
                                newPartTitle: newPartTitles, callback: (newValue){
                                  newPartTitles = newValue;
                            },));
                        print(newPartTitles);
                      },
                      child: Text('Add Spare Part')),
                  Spacer(),
                  TextButton(onPressed: () {}, child: Text('Delete Spare Part'))
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Column(
                children: [
                  ListView.builder(
                    itemBuilder: (context, index) {
                      return PartTile(
                        pNum: parts[index].pNum3,
                        // pName: parts[index].pName3,
                        // qty: parts[index].qty3,
                      );
                    },
                    itemCount: parts.length,
                    shrinkWrap: true,
                    scrollDirection: Axis.vertical,
                  ),
                  // PartList(pNum2: parts[0].pNum3 , pName2: parts[0].pName3,qty2: parts[0].qty3),
                  // SizedBox(height: 20),
                  // PartList(),
                  // SizedBox(height: 20),
                  // PartList(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

//shift
class MyStatefulWidgetACM1 extends StatefulWidget {
  const MyStatefulWidgetACM1({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetStateACM1 createState() => _MyStatefulWidgetStateACM1();
}

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetStateACM1 extends State<MyStatefulWidgetACM1> {
  static String dropdownValue = 'Alpha';

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 20),
      alignment: Alignment.bottomLeft,
      child: DropdownButton<String>(
        value: dropdownValue,
        icon: const Icon(Icons.arrow_downward),
        iconSize: 24,
        elevation: 16,
        style: const TextStyle(
            color: Colors.deepOrange,
            fontWeight: FontWeight.bold,
            fontSize: 25),
        underline: Container(
          height: 2,
          color: Colors.deepOrangeAccent,
        ),
        onChanged: (String newValue) {
          setState(() {
            dropdownValue = newValue;
          });
        },
        items: <String>['Alpha', 'Bravo', 'Charlie', 'Delta']
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      ),
    );
  }
}

//calendar
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static DateTime currentDate = DateTime.now();

  Future<void> _selectDate(BuildContext context) async {
    final DateTime pickedDate = await showDatePicker(
        context: context,
        builder: (BuildContext context, Widget child) {
          return Theme(
            data: ThemeData.dark().copyWith(
              colorScheme: ColorScheme.dark(
                primary: Colors.deepOrange,
                onPrimary: Colors.white,
                surface: Colors.deepOrange,
                onSurface: Colors.black,
              ),
              dialogBackgroundColor: Colors.orange,
            ),
            child: child,
          );
        },
        initialDate: currentDate,
        firstDate: DateTime(2015),
        lastDate: DateTime(2050));
    if (pickedDate != null && pickedDate != currentDate)
      setState(() {
        currentDate = pickedDate;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text(
            'Date: ${currentDate.year}.${currentDate.month}.${currentDate.day}',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          Container(
            height: 30,
            width: 150,
            child: FlatButton(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
              color: Colors.deepOrange,
              onPressed: () => _selectDate(context),
              child: Text('Select date'),
            ),
          ),
        ],
      ),
    );
  }
}

class addPart extends StatelessWidget {

  addPart({Key key, this.newPartTitle, this.callback}) : super(key: key);

  Function callback;

  String newPartTitle;

  // TextEditingController partNum = TextEditingController();
  // TextEditingController partName = TextEditingController();
  // TextEditingController qty = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Column(
          children: [
            TextFormField(
              onChanged: (partNum) {
                newPartTitle = partNum;
              },
              autofocus: true,
              // controller: partNum,
              decoration: InputDecoration(hintText: 'Part Number'),
            ),
            // TextFormField(
            //   controller: partName,
            //   decoration: InputDecoration(hintText: 'Part Name'),
            // ),
            // TextFormField(
            //   controller: qty,
            //   decoration: InputDecoration(hintText: 'Qty'),
            // ),
            Row(
              children: [
                usedOrNew(),
                Spacer(),
                IconButton(
                    onPressed: () {
                      callback();
                      print(newPartTitle);
                    },
                    icon: Icon(Icons.add)),
              ],
            )
          ],
        ),
      ),
    );
  }
}

class usedOrNew extends StatefulWidget {
  const usedOrNew({Key key}) : super(key: key);

  @override
  State<usedOrNew> createState() => _usedOrNewState();
}

class _usedOrNewState extends State<usedOrNew> {
  bool groupValue = true;
  final Map<bool, Widget> action = const <bool, Widget>{
    true: Text("Used"),
    false: Text("New")
  };

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        margin: EdgeInsets.all(10),
        padding: EdgeInsets.all(10),
        child: CupertinoSlidingSegmentedControl(
          groupValue: groupValue,
          children: action,
          onValueChanged: (i) {
            setState(() {
              groupValue = i;
            });
          },
        ),
      ),
    );
  }
}

class PartList extends StatefulWidget {
  PartList({
    Key key,
    this.pNum2,
  }) : super(key: key);

  String pNum2;
  // TextEditingController pName2;
  // TextEditingController qty2;

  @override
  State<PartList> createState() => _PartListState();
}

class _PartListState extends State<PartList> {
  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.deepOrange,
      child: ListView(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        children: [
          PartTile(
            pNum: widget.pNum2,
          ),
        ],
      ),
    );
  }
}

class PartTile extends StatefulWidget {
  PartTile({
    Key key,
    this.pNum,
  }) : super(key: key);

  String pNum;
  // TextEditingController pName;
  // TextEditingController qty;

  @override
  State<PartTile> createState() => _PartTileState();
}

class _PartTileState extends State<PartTile> {
  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          DataTable(
            dividerThickness: 3,
            columns: [
              DataColumn(
                  label: Text(
                'Spare Part Detail',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
              ))
            ],
            rows: [
              DataRow(
                cells: [
                  DataCell(
                    Text('Spare Part Number : ${widget.pNum}'),
                  ),
                ],
              ),
              // DataRow(
              //   cells: [
              //     DataCell(
              //       Text('Spare Part Name : ${widget.pName}'),
              //     ),
              //   ],
              // ),
              // DataRow(
              //   cells: [
              //     DataCell(
              //       Text('Spare Part Quatity : ${widget.qty}'),
              //     ),
              //   ],
              // ),
              DataRow(
                cells: [
                  DataCell(
                    Text(_usedOrNewState().groupValue ? 'Used' : 'New'),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class Part {
  String pNum3 = addPart().newPartTitle;
  // TextEditingController pName3;
  // TextEditingController qty3;

  Part({
    this.pNum3
  });
}
</code>```

Body:
I am working to have a ListTile of spare parts that will show on the main screen when the user fill in the TextFormField at the BottomSheet. By this user can decide whether to add or delete the spare part. The state of main screen will update based on that decision. The current problem is that when the user click on the add button at BottomSheet, the data is not passed to the parent widget and that make it hard to change the state of the screen.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'ACM.dart';
import 'PPMLine.dart';
import 'QrScanner.dart';

class ACMaction extends StatefulWidget {
  const ACMaction({Key key}) : super(key: key);

  @override
  State<ACMaction> createState() => _ACMactionState();
}

class _ACMactionState extends State<ACMaction> {

  static String newPartTitles;
  List<Part> parts = [
    Part(
      pNum3: newPartTitles,
      // pName3: addPart().partName,
      // qty3: addPart().qty
    ),
  ];

  TextEditingController textFieldControllerACM4 = TextEditingController();

  void logout() async {
    await FirebaseAuth.instance.signOut();
    Navigator.pushNamed(context, 'LoginPage');
  }

  @override
  Widget build(BuildContext context) {

    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text('ACM action'),
        backgroundColor: Colors.deepOrange,
        elevation: 0,
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.deepOrange,
              ),
              child: Text(
                'BHSKlia2',
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
            // ListTile(
            //   leading: Icon(Icons.message),
            //   title: Text('Comment'),
            // ),
            // ListTile(
            //   leading: Icon(Icons.check_box),
            //   title: Text('Review'),
            // ),
            ListTile(
              leading: Icon(Icons.history),
              title: Text('Recent'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => submits()),
                );
              },
            ),
            ListTile(
              leading: Icon(Icons.auto_stories),
              title: Text('ACM'),
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => ACMaction()));
              },
            ),
            ListTile(
              leading: Icon(Icons.camera_alt),
              title: Text('QR Scanner'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => qrScan()),
                );
              },
            ),
            ListTile(
              leading: Icon(Icons.close),
              title: Text('Sign Out'),
              onTap: () {
                logout();
              },
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Row(
              children: [
                MyStatefulWidgetACM1(),
                Spacer(),
                Padding(
                  padding: const EdgeInsets.only(right: 10),
                  child: MyHomePage(),
                ),
              ],
            ),
            Container(
              margin: EdgeInsets.all(10),
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Colors.deepOrange,
                border: Border.all(
                    color: Colors.orange, // set border color
                    width: 3.0), // set border width
                borderRadius: BorderRadius.all(
                    Radius.circular(20.0)), // set rounded corner radius
              ),
              child: TextFormField(
                controller: textFieldControllerACM4,
                decoration: InputDecoration(
                  border: const OutlineInputBorder(),
                  filled: true,
                  hintText: 'Corrective Action Detail',
                  labelText: 'Corrective Action Detail',
                ),
                maxLines: 5,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Row(
                children: [
                  TextButton(
                      onPressed: () {
                        showModalBottomSheet(
                            context: context,
                            builder: (context) => addPart(
                                newPartTitle: newPartTitles, callback: (newValue){
                                  newPartTitles = newValue;
                            },));
                        print(newPartTitles);
                      },
                      child: Text('Add Spare Part')),
                  Spacer(),
                  TextButton(onPressed: () {}, child: Text('Delete Spare Part'))
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Column(
                children: [
                  ListView.builder(
                    itemBuilder: (context, index) {
                      return PartTile(
                        pNum: parts[index].pNum3,
                        // pName: parts[index].pName3,
                        // qty: parts[index].qty3,
                      );
                    },
                    itemCount: parts.length,
                    shrinkWrap: true,
                    scrollDirection: Axis.vertical,
                  ),
                  // PartList(pNum2: parts[0].pNum3 , pName2: parts[0].pName3,qty2: parts[0].qty3),
                  // SizedBox(height: 20),
                  // PartList(),
                  // SizedBox(height: 20),
                  // PartList(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

//shift
class MyStatefulWidgetACM1 extends StatefulWidget {
  const MyStatefulWidgetACM1({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetStateACM1 createState() => _MyStatefulWidgetStateACM1();
}

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetStateACM1 extends State<MyStatefulWidgetACM1> {
  static String dropdownValue = 'Alpha';

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 20),
      alignment: Alignment.bottomLeft,
      child: DropdownButton<String>(
        value: dropdownValue,
        icon: const Icon(Icons.arrow_downward),
        iconSize: 24,
        elevation: 16,
        style: const TextStyle(
            color: Colors.deepOrange,
            fontWeight: FontWeight.bold,
            fontSize: 25),
        underline: Container(
          height: 2,
          color: Colors.deepOrangeAccent,
        ),
        onChanged: (String newValue) {
          setState(() {
            dropdownValue = newValue;
          });
        },
        items: <String>['Alpha', 'Bravo', 'Charlie', 'Delta']
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      ),
    );
  }
}

//calendar
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static DateTime currentDate = DateTime.now();

  Future<void> _selectDate(BuildContext context) async {
    final DateTime pickedDate = await showDatePicker(
        context: context,
        builder: (BuildContext context, Widget child) {
          return Theme(
            data: ThemeData.dark().copyWith(
              colorScheme: ColorScheme.dark(
                primary: Colors.deepOrange,
                onPrimary: Colors.white,
                surface: Colors.deepOrange,
                onSurface: Colors.black,
              ),
              dialogBackgroundColor: Colors.orange,
            ),
            child: child,
          );
        },
        initialDate: currentDate,
        firstDate: DateTime(2015),
        lastDate: DateTime(2050));
    if (pickedDate != null && pickedDate != currentDate)
      setState(() {
        currentDate = pickedDate;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text(
            'Date: ${currentDate.year}.${currentDate.month}.${currentDate.day}',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          Container(
            height: 30,
            width: 150,
            child: FlatButton(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
              color: Colors.deepOrange,
              onPressed: () => _selectDate(context),
              child: Text('Select date'),
            ),
          ),
        ],
      ),
    );
  }
}

class addPart extends StatelessWidget {

  addPart({Key key, this.newPartTitle, this.callback}) : super(key: key);

  Function callback;

  String newPartTitle;

  // TextEditingController partNum = TextEditingController();
  // TextEditingController partName = TextEditingController();
  // TextEditingController qty = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Column(
          children: [
            TextFormField(
              onChanged: (partNum) {
                newPartTitle = partNum;
              },
              autofocus: true,
              // controller: partNum,
              decoration: InputDecoration(hintText: 'Part Number'),
            ),
            // TextFormField(
            //   controller: partName,
            //   decoration: InputDecoration(hintText: 'Part Name'),
            // ),
            // TextFormField(
            //   controller: qty,
            //   decoration: InputDecoration(hintText: 'Qty'),
            // ),
            Row(
              children: [
                usedOrNew(),
                Spacer(),
                IconButton(
                    onPressed: () {
                      callback();
                      print(newPartTitle);
                    },
                    icon: Icon(Icons.add)),
              ],
            )
          ],
        ),
      ),
    );
  }
}

class usedOrNew extends StatefulWidget {
  const usedOrNew({Key key}) : super(key: key);

  @override
  State<usedOrNew> createState() => _usedOrNewState();
}

class _usedOrNewState extends State<usedOrNew> {
  bool groupValue = true;
  final Map<bool, Widget> action = const <bool, Widget>{
    true: Text("Used"),
    false: Text("New")
  };

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        margin: EdgeInsets.all(10),
        padding: EdgeInsets.all(10),
        child: CupertinoSlidingSegmentedControl(
          groupValue: groupValue,
          children: action,
          onValueChanged: (i) {
            setState(() {
              groupValue = i;
            });
          },
        ),
      ),
    );
  }
}

class PartList extends StatefulWidget {
  PartList({
    Key key,
    this.pNum2,
  }) : super(key: key);

  String pNum2;
  // TextEditingController pName2;
  // TextEditingController qty2;

  @override
  State<PartList> createState() => _PartListState();
}

class _PartListState extends State<PartList> {
  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.deepOrange,
      child: ListView(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        children: [
          PartTile(
            pNum: widget.pNum2,
          ),
        ],
      ),
    );
  }
}

class PartTile extends StatefulWidget {
  PartTile({
    Key key,
    this.pNum,
  }) : super(key: key);

  String pNum;
  // TextEditingController pName;
  // TextEditingController qty;

  @override
  State<PartTile> createState() => _PartTileState();
}

class _PartTileState extends State<PartTile> {
  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          DataTable(
            dividerThickness: 3,
            columns: [
              DataColumn(
                  label: Text(
                'Spare Part Detail',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
              ))
            ],
            rows: [
              DataRow(
                cells: [
                  DataCell(
                    Text('Spare Part Number : ${widget.pNum}'),
                  ),
                ],
              ),
              // DataRow(
              //   cells: [
              //     DataCell(
              //       Text('Spare Part Name : ${widget.pName}'),
              //     ),
              //   ],
              // ),
              // DataRow(
              //   cells: [
              //     DataCell(
              //       Text('Spare Part Quatity : ${widget.qty}'),
              //     ),
              //   ],
              // ),
              DataRow(
                cells: [
                  DataCell(
                    Text(_usedOrNewState().groupValue ? 'Used' : 'New'),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class Part {
  String pNum3 = addPart().newPartTitle;
  // TextEditingController pName3;
  // TextEditingController qty3;

  Part({
    this.pNum3
  });
}


来源: stackexchange

问:
How to handle lag in KAFKA join
I have a KAFKA application that joins two streams. The two streams:

A stream of data of type A, in intervals of 2-5 minutes. Approximately 60-80 thousand keys. A filter is applied. About 40k remain.

A stream of data of type B, every hour. A transformer is applied on it to modify the output. This involves mysql queries. There are approximately a thousand keys, but the output after the transformer could be between 20-40k. The initial key is different, but match the keys in A after the transform function.

I have a join window of an hour:

```<code>val joinWindow: JoinWindows = JoinWindows.ofTimeDifferenceAndGrace(Duration.ofHours(1), Duration.ofMinutes(10))
</code>```

The application is running, and the OFFSET was set to EARLIEST with the hopes that we could back-calculate a bit. This should be about 4 days. In my previous experience with kafka streams, the stream was able to catch up (with a Materialized window of 1 hour), presumably by seeing that newer records have been cached.

However, this KAFKA application is lagging 4 days behind still and I don't know the cause. Is it:

A: The two streams in combination with the join have too much data to process and thus the application is slow?

B: The JOIN function waits the full hour before joining, even though it is back-calculating? With that in mind, it will never catch up.

I could set the offset to LATEST, but should the application crash, it has to be able to catch up.

There are 3 AWS ECS tasks running. Each has two threads.

Is there a point when there is simply too much data for the JOIN to handle?

Thank you

Trying to speed up the transformers. Considering writing a custom joiner if the application cannot be sped up.

ContentLicense: CC BY-SA 4.0

Title: How to handle lag in KAFKA join

Body:
I have a KAFKA application that joins two streams. The two streams:

A stream of data of type A, in intervals of 2-5 minutes. Approximately 60-80 thousand keys. A filter is applied. About 40k remain.

A stream of data of type B, every hour. A transformer is applied on it to modify the output. This involves mysql queries. There are approximately a thousand keys, but the output after the transformer could be between 20-40k. The initial key is different, but match the keys in A after the transform function.

I have a join window of an hour:

val joinWindow: JoinWindows = JoinWindows.ofTimeDifferenceAndGrace(Duration.ofHours(1), Duration.ofMinutes(10))

The application is running, and the OFFSET was set to EARLIEST with the hopes that we could back-calculate a bit. This should be about 4 days. In my previous experience with kafka streams, the stream was able to catch up (with a Materialized window of 1 hour), presumably by seeing that newer records have been cached.

However, this KAFKA application is lagging 4 days behind still and I don't know the cause. Is it:

A: The two streams in combination with the join have too much data to process and thus the application is slow?

B: The JOIN function waits the full hour before joining, even though it is back-calculating? With that in mind, it will never catch up.

I could set the offset to LATEST, but should the application crash, it has to be able to catch up.

There are 3 AWS ECS tasks running. Each has two threads.

Is there a point when there is simply too much data for the JOIN to handle?

Thank you

Trying to speed up the transformers. Considering writing a custom joiner if the application cannot be sped up.


问:
VScode Is there a way to fold code by a special comment prefix?
I am using snakefile that got out of control. I kinda like that it is one file, but even with all the rules folded I have to deal with a long scrollbar.
Is there a way/extension to allow code to collapse by special comment prefix?

#% normalize data
rule count:
    ...
# some comment that should
rule divide:
    ...
rule drop_duplicates:
    ...
#% statistical tests
rule ttest:
   ...
#% output
rule all:
    ...
rule zip:
    ...
```
<p>this way I could fold it into:</p>
<pre class="lang-py prettyprint-override"><code>#% normalize data
#% statistical tests
#% output
</code>```

I think that would be easier to handle than dealing with multiple files.

thank you,

tried searching online, and found an extension that should do that but could not make it work (https://marketplace.visualstudio.com/items?itemName=zokugun.explicit-folding).
if someone wants to check my zokugun explicit-folding rules i tried:

{
    "workbench.colorTheme": "Default Dark+",
    "remote.SSH.remotePlatform": {
        "rocket": "linux",
        "Jovian": "linux",
        "JovianLocal": "linux"
    },
    "git.ignoreLegacyWarning": true,
    "cmake.configureOnOpen": true,
    "terminal.integrated.enableMultiLinePasteWarning": false,
    "audioCues.taskCompleted": "on",
    "audioCues.taskFailed": "on",
    "notebook.lineNumbers": "on",
    "window.zoomLevel": -1,
    "jupyter.askForKernelRestart": false,
    "[python]": {
        "explicitFolding.rules": [
            {
                "beginRegex": "#%%",
                "endRegex": "##%",
                "autofold": true
            },
            {
                "indentation": true,
                "offSide": true
            }
        ],
    "explicitFolding.autoFold": "1",
    },
    "explicitFolding.rules": [

    ],
}
```

Body:
I am using snakefile that got out of control. I kinda like that it is one file, but even with all the rules folded I have to deal with a long scrollbar.
Is there a way/extension to allow code to collapse by special comment prefix?

#% normalize data
rule count:
    ...
# some comment that should
rule divide:
    ...
rule drop_duplicates:
    ...
#% statistical tests
rule ttest:
   ...
#% output
rule all:
    ...
rule zip:
    ...

this way I could fold it into:

#% normalize data
#% statistical tests
#% output

I think that would be easier to handle than dealing with multiple files.

thank you,

tried searching online, and found an extension that should do that but could not make it work (https://marketplace.visualstudio.com/items?itemName=zokugun.explicit-folding).
if someone wants to check my zokugun explicit-folding rules i tried:

{
    "workbench.colorTheme": "Default Dark+",
    "remote.SSH.remotePlatform": {
        "rocket": "linux",
        "Jovian": "linux",
        "JovianLocal": "linux"
    },
    "git.ignoreLegacyWarning": true,
    "cmake.configureOnOpen": true,
    "terminal.integrated.enableMultiLinePasteWarning": false,
    "audioCues.taskCompleted": "on",
    "audioCues.taskFailed": "on",
    "notebook.lineNumbers": "on",
    "window.zoomLevel": -1,
    "jupyter.askForKernelRestart": false,
    "[python]": {
        "explicitFolding.rules": [
            {
                "beginRegex": "#%%",
                "endRegex": "##%",
                "autofold": true
            },
            {
                "indentation": true,
                "offSide": true
            }
        ],
    "explicitFolding.autoFold": "1",
    },
    "explicitFolding.rules": [

    ],
}


问:
How to modify js function with swift
I want to change the following code, but I don't know js, I use swift, is there any way to make this code can change the X and Y axes to what I want (swift),
I want to change to local time and data, can someone help me?</p>
```<code> chart.events.load = HIFunction(
jsFunction: "function () { var series = this.series[0]; setInterval(function ()
 { var x = (new Date()).getTime(), y = Math.random() * 2 - 1; series.addPoint([x, y], true, false); }, 10000); }")
</code>```

Title: How to modify js function with swift

Body:
I want to change the following code, but I don't know js, I use swift, is there any way to make this code can change the X and Y axes to what I want (swift),
I want to change to local time and data, can someone help me?

 chart.events.load = HIFunction(
jsFunction: "function () { var series = this.series[0]; setInterval(function ()
 { var x = (new Date()).getTime(), y = Math.random() * 2 - 1; series.addPoint([x, y], true, false); }, 10000); }")


问:
Compiling JS with import/export
I am trying to reduce the size of compiled vanilla js files. While testing various scenarios I noticed that when compiling with laravel-mix, it appears to bundle all imported modules from a directory when using import/export in an index file.

componants/index.js

    export { default as Autosave } from './autosave';
    export { default as Checkbox } from './checkbox';
    export { default as DropDownButton } from './dropdown-button';
    export { default as Dialog } from './dialog';
    export { default as Loader } from './loader-message';
    export { default as Slideup } from './slideup-message';
    export { default as Texteditor } from './texteditor';
    export { default as Datepicker } from './datepicker';
    export { default as SelectCustom } from './select-custom';
    export { default as SelectFromList } from './select-from-list';
    export { default as SelectFromListLogin } from './select-from-list-login';
    export { default as Sidebar } from './sidebar';
    export { default as SupportList } from './supportlist';
    export { default as Tooltip } from './tooltip';
    export { default as Uploader } from './uploader';```
</div>
</div>
</p>
<p>When importing the Slideup module through import/export as follows</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { Slideup } from "../../componants"</code>```

The resulting compiled output is 354 KiB

When importing the individual Slideup module as follows

import  Slideup  from "../../componants/slideup"```

The resulting compiled output is 11 KiB

I would like to continue using index.js files with import/export without the increased overhead. Is this expected behaviour and if so is there a setup to avoid this ?

Title: Compiling JS with import/export

Body:
I am trying to reduce the size of compiled vanilla js files. While testing various scenarios I noticed that when compiling with laravel-mix, it appears to bundle all imported modules from a directory when using import/export in an index file.

componants/index.js

    export { default as Autosave } from './autosave';
    export { default as Checkbox } from './checkbox';
    export { default as DropDownButton } from './dropdown-button';
    export { default as Dialog } from './dialog';
    export { default as Loader } from './loader-message';
    export { default as Slideup } from './slideup-message';
    export { default as Texteditor } from './texteditor';
    export { default as Datepicker } from './datepicker';
    export { default as SelectCustom } from './select-custom';
    export { default as SelectFromList } from './select-from-list';
    export { default as SelectFromListLogin } from './select-from-list-login';
    export { default as Sidebar } from './sidebar';
    export { default as SupportList } from './supportlist';
    export { default as Tooltip } from './tooltip';
    export { default as Uploader } from './uploader';

When importing the Slideup module through import/export as follows

import { Slideup } from "../../componants"

The resulting compiled output is 354 KiB

When importing the individual Slideup module as follows

import  Slideup  from "../../componants/slideup"

The resulting compiled output is 11 KiB

I would like to continue using index.js files with import/export without the increased overhead. Is this expected behaviour and if so is there a setup to avoid this ?


问:
How do I correctly build an API POST request with sound and get a string in Flutter?
I have an example of sending a sound file by POST method using Go language as an example
It should return a string of text.

how to correctly build this request on Flutter as well ?

```<code>package main

import (
  "bytes"
  "io/ioutil"
  "log"
  "net/http"
)

func main() {
  data, _ := ioutil.ReadFile("input.wav")

  req, _ := http.NewRequest(
    "POST",
    "https://api.data.com/v2/transcribe",
    bytes.NewBuffer(data))

  req.Header.Set("Content-Type", "application/octet-stream")
  req.Header.Set("Punctuate", "true")
  req.Header.Set("token", "{API_TOKEN}")

  client := &http.Client{}

  resp, _ := client.Do(req)
  if err != nil {
    log.Fatal(err)
  }
  defer resp.Body.Close()

  body, _ := ioutil.ReadAll(resp.Body)

  transcription := string(body)
  log.Println(transcription)
}

</code>```

Body:
I have an example of sending a sound file by POST method using Go language as an example
It should return a string of text.

how to correctly build this request on Flutter as well ?

package main

import (
  "bytes"
  "io/ioutil"
  "log"
  "net/http"
)

func main() {
  data, _ := ioutil.ReadFile("input.wav")

  req, _ := http.NewRequest(
    "POST",
    "https://api.data.com/v2/transcribe",
    bytes.NewBuffer(data))

  req.Header.Set("Content-Type", "application/octet-stream")
  req.Header.Set("Punctuate", "true")
  req.Header.Set("token", "{API_TOKEN}")

  client := &http.Client{}

  resp, _ := client.Do(req)
  if err != nil {
    log.Fatal(err)
  }
  defer resp.Body.Close()

  body, _ := ioutil.ReadAll(resp.Body)

  transcription := string(body)
  log.Println(transcription)
}


问:
How to remove seconds and milliseconds from TimeSpan when saving to the database?
I want to store the time in a SQL Server database without seconds or milliseconds, eg 15:42:00instead of 15:42:05.009. However, it is stored in seconds and milliseconds. How can I remove seconds and milliseconds with getter and setter?

This is my code:

```<code>[Column(TypeName = "time")]
[DisplayFormat(DataFormatString = @"{0:hh\:mm}")]
public TimeSpan Time { get; set; }
</code>```

CLARIFICATION:
Through the frontend, I enter a value in the 12-hour time unit into the input, for example "12:30 ". I want to save the value coming from the frontend to the database in the same form. However, it is stored in the database with seconds and milliseconds, for example "12:30:24.0170000". I want to save the incoming value to the database without seconds and milliseconds.

P.S. That's right, I can change the display format of the same value in the database in the frontend. But I want to do everything in the backend.

Body:
I want to store the time in a SQL Server database without seconds or milliseconds, eg 15:42:00instead of 15:42:05.009. However, it is stored in seconds and milliseconds. How can I remove seconds and milliseconds with getter and setter?

This is my code:

[Column(TypeName = "time")]
[DisplayFormat(DataFormatString = @"{0:hh\:mm}")]
public TimeSpan Time { get; set; }

CLARIFICATION:
Through the frontend, I enter a value in the 12-hour time unit into the input, for example "12:30 ". I want to save the value coming from the frontend to the database in the same form. However, it is stored in the database with seconds and milliseconds, for example "12:30:24.0170000". I want to save the incoming value to the database without seconds and milliseconds.

P.S. That's right, I can change the display format of the same value in the database in the frontend. But I want to do everything in the backend.


问:
How to fix this error when launching Pycharm from anaconda : Cannot start pycharm
When I am trying to launch pycharm from anaconda or from terminal, I am facing this error.

Required tools are missing: realpath  (SHELL=/bin/bash PATH=/home/payal/anaconda3/envs/learn_python/bin:/home/payal/anaconda3/condabin:/home/payal/anaconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin)

with the below messages on terminal
qt.svg: link path0_fill hasn't been detected!

This is the path content of bashrc file

```<code>
export PATH=/home/payal/anaconda3/bin:$PATH

__conda_setup="$('/home/payal/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/home/payal/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/home/payal/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/home/payal/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
</code>```

I tried installing coreutils as per solution discussed in the comments of the link : Cannot open pycharm in Ubuntu , but didnot work.

please help

Body:
When I am trying to launch pycharm from anaconda or from terminal, I am facing this error.

Required tools are missing: realpath  (SHELL=/bin/bash PATH=/home/payal/anaconda3/envs/learn_python/bin:/home/payal/anaconda3/condabin:/home/payal/anaconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin)

with the below messages on terminal
qt.svg: link path0_fill hasn't been detected!

This is the path content of bashrc file

export PATH=/home/payal/anaconda3/bin:$PATH

__conda_setup="$('/home/payal/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/home/payal/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/home/payal/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/home/payal/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup

I tried installing coreutils as per solution discussed in the comments of the link : Cannot open pycharm in Ubuntu , but didnot work.

please help


问:
Delete table name in html css php
My problem is the following:
I made display the characteristics of my table [enc_cmd_num] in php, the problem is that I want to display only the data and not the column name.

Here is my code :

```<code> <?php
            //CONNEXION ODBC SERVER//
            $dsn="";
            $user="";
            $password="";
            $conn=odbc_connect($dsn,$user, $password);

            //REQUETES
            $sql = <<<EOF
                    SELECT top 10 [enc_cmd_num]
                    FROM [encaissement]
                    WHERE enc_date= '20221130'
                    EOF;

            $results = odbc_exec($conn,$sql);
            odbc_result_all($results);

</code>```

Title: Delete table name in html css php

Body:
My problem is the following:
I made display the characteristics of my table [enc_cmd_num] in php, the problem is that I want to display only the data and not the column name.

Here is my code :

 <?php
            //CONNEXION ODBC SERVER//
            $dsn="";
            $user="";
            $password="";
            $conn=odbc_connect($dsn,$user, $password);

            //REQUETES
            $sql = <<<EOF
                    SELECT top 10 [enc_cmd_num]
                    FROM [encaissement]
                    WHERE enc_date= '20221130'
                    EOF;

            $results = odbc_exec($conn,$sql);
            odbc_result_all($results);


问:
Set z-index with content overflowing to brother components
We have two components that are brothers and each one declares its own stacking context. The components can be collapsed, so only the header with some dropdowns are visible.

When being collapsed, the dropdown menus overflow its content and should be visible on top of its brothers. Since the z-index of the dropdowns is inside the stacking context of its parent, it works for displaying on top of elements in the same component, but fails to be on top of the brother component, because it is added later in the DOM.

How can I set the z-index so the dropdown menus are displayed on top of the brother components?

Note I can not set a decreasing z-index sequentially to each component, so components that are first are displayed above. In the picture the dropdown menu is opened pointing down but it could also be open pointing up.


问:
PowerBuilder Script to set ARITHABORT ON/OFF
How to set ARITHABORT (SessionProperty in SQL server) in PowerBuilder script?
While opening an application (which is created in PB) I want to set ARITHABORT ON/OFF.

Please help...With your answers


问:
Using echarts to draw a circle with center as given coordinate points and a given radius
I want to plot a circle with a center as (150,350) and a radius of 50 units.

Below is the code I am using:

```<code>option = {
xAxis: {
type: 'value',
min: 50,
max: 500,
interval: 100
},
yAxis: {
type: 'value',
min: 50,
max: 500,
interval: 100
},
graphic: [
{
elements: [
     {
     id: 'small_circle',
     type: 'circle',
     z: 100,
shape: {
    // x coordinate for center
    cx: 150 ,
    // y coordinate for center
    cy: 350 ,[enter image description here](https://i.stack.imgur.com/11jL9.png)
    // radius
    r: 50,
     },
style: {
    fill: 'rgba(0, 140, 250, 0.5)',
    stroke: 'rgba(0, 50, 150, 0.5)',
lineWidth: 2
}
}
]
}
],
};
</code>```

Issue : The circle rendered does not have the center (cx,cy).

Any help on how to draw the circle with given center ?

Body:
I want to plot a circle with a center as (150,350) and a radius of 50 units.

Below is the code I am using:

option = {
xAxis: {
type: 'value',
min: 50,
max: 500,
interval: 100
},
yAxis: {
type: 'value',
min: 50,
max: 500,
interval: 100
},
graphic: [
{
elements: [
     {
     id: 'small_circle',
     type: 'circle',
     z: 100,
shape: {
    // x coordinate for center
    cx: 150 ,
    // y coordinate for center
    cy: 350 ,[enter image description here](https://i.stack.imgur.com/11jL9.png)
    // radius
    r: 50,
     },
style: {
    fill: 'rgba(0, 140, 250, 0.5)',
    stroke: 'rgba(0, 50, 150, 0.5)',
lineWidth: 2
}
}
]
}
],
};

Issue : The circle rendered does not have the center (cx,cy).

Any help on how to draw the circle with given center ?


问:
How to send image with other data into server using laravel api on flutter
How i can send image with other registration data into MySQL server... i am using this method to send data:

```<code>Map data = {
  'name': firstName,
  'last_name': lastName,
  'number': phoneNumber,
  'status': "pending",
  'email': email,
  'roll_as': roll,
  'password': "random",
  'profilepicture': image,
  'birth_month': month,
  'birth_day': date,
  'birth_year': year,
  "description": bio,
};
print(data);

String body = json.encode(data);
// var response = await request.send();
var response = await http.post(
  uri,
  body: body,
  headers: {
    "Content-Type": "application/json",
    "accept": "application/json",
    "Access-Control-Allow-Origin": "*"
  },
);
print(response.body);
print(response.statusCode);
</code>```

i am getting error on image . i have searched and try to use MultiPart Method but i don't know how to send other data with image using multipart.

Body:
How i can send image with other registration data into MySQL server... i am using this method to send data:

Map data = {
  'name': firstName,
  'last_name': lastName,
  'number': phoneNumber,
  'status': "pending",
  'email': email,
  'roll_as': roll,
  'password': "random",
  'profilepicture': image,
  'birth_month': month,
  'birth_day': date,
  'birth_year': year,
  "description": bio,
};
print(data);

String body = json.encode(data);
// var response = await request.send();
var response = await http.post(
  uri,
  body: body,
  headers: {
    "Content-Type": "application/json",
    "accept": "application/json",
    "Access-Control-Allow-Origin": "*"
  },
);
print(response.body);
print(response.statusCode);

i am getting error on image . i have searched and try to use MultiPart Method but i don't know how to send other data with image using multipart.


问:
GLMM alike solution - adding an interaction step as an element of scikit-learn Pipeline for columns transformed in previous steps
I'm trying to create a solution that will be somehow similar to the Mixed Effects Model (GLMM) that is not present in scikit-learn at the moment. Imagine a simple heart-disease dataset from https://www.kaggle.com/datasets/johnsmith88/heart-disease-dataset that looks like this:

I conduct some standard procedures:

```<code># numerical variables
num_cols = ['age',
            'trestbps',
            'chol',
            'thalach',
            'oldpeak'
            ]

# categorical variables
cat_cols = ['sex',
            'cp',
            'fbs',
            'restecg',
            'exang',
            'slope',
            'ca',
            'thal'
            ]

# changing format of the categorical variables
df[cat_cols] = df[cat_cols].apply(lambda x: x.astype('object'))

# target variable
y = df['target']

# features
X = df.drop(['target'], axis=1)

# data split:

# random seed
np.random.seed(42)

# splitting the data
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.2,
                                                    stratify=y)
</code>```

...and use the standard transformers to pre-process the variables.

```<code># pipeline for numerical data
num_preprocessing = Pipeline([('num_imputer', SimpleImputer(strategy='mean')), # imputing with mean
                              ('minmaxscaler', MinMaxScaler())]) # scaling

# pipeline for categorical data
cat_preprocessing = Pipeline([('cat_imputer', SimpleImputer(strategy='constant', fill_value='missing')), # filling missing values
                              ('onehot', OneHotEncoder(drop='first', handle_unknown='ignore'))]) # One Hot Encoding

# preprocessor - combining pipelines
preprocessor = ColumnTransformer([
    ('categorical', cat_preprocessing, cat_cols),
    ('numerical', num_preprocessing, num_cols)
])
</code>```

so I can run a logistic regression:

```<code># any model parameters
log_ini_params = {'penalty': 'l2',
                  'tol': 0.0073559740277086005,
                  'C': 1.1592424247511928,
                  'fit_intercept': True,
                  'solver': 'liblinear'
                  }

# model - Pipeline
log_clf = Pipeline([('preprocessor', preprocessor),
                    ('clf', LogisticRegression(**log_ini_params))]
                  )

# fitting the model
log_clf.fit(X_train, y_train)

</code>```

And have a look at the named steps:

```<code>{'preprocessor': ColumnTransformer(transformers=[('categorical',
                                  Pipeline(steps=[('cat_imputer',
                                                   SimpleImputer(fill_value='missing',
                                                                 strategy='constant')),
                                                  ('onehot',
                                                   OneHotEncoder(drop='first',
                                                                 handle_unknown='ignore'))]),
                                  ['sex', 'cp', 'fbs', 'restecg', 'exang',
                                   'slope', 'ca', 'thal']),
                                 ('numerical',
                                  Pipeline(steps=[('num_imputer',
                                                   SimpleImputer()),
                                                  ('minmaxscaler',
                                                   MinMaxScaler())]),
                                  ['age', 'trestbps', 'chol', 'thalach',
                                   'oldpeak'])]),
 'clf': LogisticRegression(C=1.1592424247511928, solver='liblinear',
                    tol=0.0073559740277086005)}
</code>```

...in order to extract feature importances:

```<code># numeric labels
nums = log_clf.named_steps['preprocessor'].transformers_[1][2]

# categorical labels
cats = log_clf.named_steps['preprocessor'].transformers_[0][1]['onehot'].get_feature_names_out(cat_cols).tolist()

# features
feats = nums + cats

# adjusting features to columns
features_dict = dict(zip(feats, log_clf.named_steps['clf'].coef_.tolist()[0]))

#  chart
features_df = pd.DataFrame(features_dict, index=[0])
features_df.T.plot.bar(title='Feature Importance', legend=False, figsize=(20,10));
</code>```

So far so good. However, imagine we deal with a multi-level problem, for example the data contains information about the hospital of each patient:

```<code># seed
np.random.seed(42)

# adding 3 hospitals
df['hospital'] = np.random.randint(1, 3, len(df)).astype('object')
</code>```

So our data looks like below:

The research problem is to investigate if the coefficients of the regression for some variables are different for observations within each hospital.

The most proper way to deal with this problem is GLMM, using R library I would simply type something like:

```<code>model = lmer(target ~ 1 + variable + (1 + variable|hospital), data = df)
</code>```

However, in Python we're either limited to statsmodels or can conduct some tests like interactions between our variables and the grouping variable (hospital in our case)

The questions are:

How is it possible to include the multiplication step between one-hot-encoded Hospital variable (it would probably be added to the cat_columns or have it's own Pipeline) and other PREPROCESSED variables (selected scaled nums for example age and chol) so new variables like hospital_2_age appear in the Pipeline/ColumnTransformer?

Obviously - there are some methodoligical issues on the way, for example if the scaling should be conducted globally or per grouping variable etc. (but it's not a programming question)

It is not a purely programming question, but if 1. is an overkill - is there a smooth way to implement a GLMM in scikit-learn Pipeline in such workflow?

Body:
I'm trying to create a solution that will be somehow similar to the Mixed Effects Model (GLMM) that is not present in scikit-learn at the moment. Imagine a simple heart-disease dataset from https://www.kaggle.com/datasets/johnsmith88/heart-disease-dataset that looks like this:

I conduct some standard procedures:

# numerical variables
num_cols = ['age',
            'trestbps',
            'chol',
            'thalach',
            'oldpeak'
            ]

# categorical variables
cat_cols = ['sex',
            'cp',
            'fbs',
            'restecg',
            'exang',
            'slope',
            'ca',
            'thal'
            ]

# changing format of the categorical variables
df[cat_cols] = df[cat_cols].apply(lambda x: x.astype('object'))

# target variable
y = df['target']

# features
X = df.drop(['target'], axis=1)

# data split:

# random seed
np.random.seed(42)

# splitting the data
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.2,
                                                    stratify=y)

...and use the standard transformers to pre-process the variables.

# pipeline for numerical data
num_preprocessing = Pipeline([('num_imputer', SimpleImputer(strategy='mean')), # imputing with mean
                              ('minmaxscaler', MinMaxScaler())]) # scaling

# pipeline for categorical data
cat_preprocessing = Pipeline([('cat_imputer', SimpleImputer(strategy='constant', fill_value='missing')), # filling missing values
                              ('onehot', OneHotEncoder(drop='first', handle_unknown='ignore'))]) # One Hot Encoding

# preprocessor - combining pipelines
preprocessor = ColumnTransformer([
    ('categorical', cat_preprocessing, cat_cols),
    ('numerical', num_preprocessing, num_cols)
])

so I can run a logistic regression:

# any model parameters
log_ini_params = {'penalty': 'l2',
                  'tol': 0.0073559740277086005,
                  'C': 1.1592424247511928,
                  'fit_intercept': True,
                  'solver': 'liblinear'
                  }

# model - Pipeline
log_clf = Pipeline([('preprocessor', preprocessor),
                    ('clf', LogisticRegression(**log_ini_params))]
                  )

# fitting the model
log_clf.fit(X_train, y_train)

And have a look at the named steps:

{'preprocessor': ColumnTransformer(transformers=[('categorical',
                                  Pipeline(steps=[('cat_imputer',
                                                   SimpleImputer(fill_value='missing',
                                                                 strategy='constant')),
                                                  ('onehot',
                                                   OneHotEncoder(drop='first',
                                                                 handle_unknown='ignore'))]),
                                  ['sex', 'cp', 'fbs', 'restecg', 'exang',
                                   'slope', 'ca', 'thal']),
                                 ('numerical',
                                  Pipeline(steps=[('num_imputer',
                                                   SimpleImputer()),
                                                  ('minmaxscaler',
                                                   MinMaxScaler())]),
                                  ['age', 'trestbps', 'chol', 'thalach',
                                   'oldpeak'])]),
 'clf': LogisticRegression(C=1.1592424247511928, solver='liblinear',
                    tol=0.0073559740277086005)}

...in order to extract feature importances:

# numeric labels
nums = log_clf.named_steps['preprocessor'].transformers_[1][2]

# categorical labels
cats = log_clf.named_steps['preprocessor'].transformers_[0][1]['onehot'].get_feature_names_out(cat_cols).tolist()

# features
feats = nums + cats

# adjusting features to columns
features_dict = dict(zip(feats, log_clf.named_steps['clf'].coef_.tolist()[0]))

#  chart
features_df = pd.DataFrame(features_dict, index=[0])
features_df.T.plot.bar(title='Feature Importance', legend=False, figsize=(20,10));

So far so good. However, imagine we deal with a multi-level problem, for example the data contains information about the hospital of each patient:

# seed
np.random.seed(42)

# adding 3 hospitals
df['hospital'] = np.random.randint(1, 3, len(df)).astype('object')

So our data looks like below:

The research problem is to investigate if the coefficients of the regression for some variables are different for observations within each hospital.

The most proper way to deal with this problem is GLMM, using R library I would simply type something like:

model = lmer(target ~ 1 + variable + (1 + variable|hospital), data = df)

However, in Python we're either limited to statsmodels or can conduct some tests like interactions between our variables and the grouping variable (hospital in our case)

The questions are:

How is it possible to include the multiplication step between one-hot-encoded Hospital variable (it would probably be added to the cat_columns or have it's own Pipeline) and other PREPROCESSED variables (selected scaled nums for example age and chol) so new variables like hospital_2_age appear in the Pipeline/ColumnTransformer?

Obviously - there are some methodoligical issues on the way, for example if the scaling should be conducted globally or per grouping variable etc. (but it's not a programming question)

It is not a purely programming question, but if 1. is an overkill - is there a smooth way to implement a GLMM in scikit-learn Pipeline in such workflow?


问:
FlatMap doesnt send completion
I have two methods that chained by flatMap

```<code>        return requests
            .combineLatest()
            .flatMap({ response in
                Log.warning("\(response)")
                do {
                    return try self.uploadFS(connections: response.map({ $0.connection }))
                } catch {
                    return Just([Common_Empty]()).eraseToAnyPublisher()
                }
            })
            .eraseToAnyPublisher()
</code>```

upload fs method returns own publisher

```<code>func uploadFS() -> AnyPublisher<[Common_Empty], Never> {
        let requests = makeRequests()
        return requests// return requests
            .combineLatest()
//            .sink(
//                receiveCompletion: { completion in
//                    Log.info("\(completion)")
//                },
//                receiveValue: { value in
//                    Log.info("Recieved value: \(value)")
//                }
//            )
//            .store(in: &Self.retainedCancellables)
            .eraseToAnyPublisher()
}
</code>```

if I change return type value and will return Void uncommented block will be executed, but I dont understand why completion not sent to downstream

I tried catch completion in upstream and it works

Title: FlatMap doesnt send completion

Body:
I have two methods that chained by flatMap

        return requests
            .combineLatest()
            .flatMap({ response in
                Log.warning("\(response)")
                do {
                    return try self.uploadFS(connections: response.map({ $0.connection }))
                } catch {
                    return Just([Common_Empty]()).eraseToAnyPublisher()
                }
            })
            .eraseToAnyPublisher()

upload fs method returns own publisher

func uploadFS() -> AnyPublisher<[Common_Empty], Never> {
        let requests = makeRequests()
        return requests// return requests
            .combineLatest()
//            .sink(
//                receiveCompletion: { completion in
//                    Log.info("\(completion)")
//                },
//                receiveValue: { value in
//                    Log.info("Recieved value: \(value)")
//                }
//            )
//            .store(in: &Self.retainedCancellables)
            .eraseToAnyPublisher()
}

if I change return type value and will return Void uncommented block will be executed, but I dont understand why completion not sent to downstream

I tried catch completion in upstream and it works


问:
Certificate Chain (String) Splitter with Java
I issue SSL certificates via API request and then end of the request I am getting certificate chain in string format(Not Pem file). So I need to get attribute values from the chain and for that reason I need to split that chain. I already have methods for the getting values, only thing that I need to get that chains separately.

I am getting four different certificate chain in String like below;

```<code>-----BEGIN CERTIFICATE------
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
-----END CERTIFICATE--------
-----BEGIN CERTIFICATE------
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
-----END CERTIFICATE--------
-----BEGIN CERTIFICATE------
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
-----END CERTIFICATE--------
-----BEGIN CERTIFICATE------
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
-----END CERTIFICATE--------
</code>```

So I need to get each chain between the -----BEGIN CERTIFICATE------ and -----END CERTIFICATE-----
then I already have method for the reading of the chain. (getIssuer, getSerialNumber etc.)

Do you have any short cut solution for that ?

Body:
I issue SSL certificates via API request and then end of the request I am getting certificate chain in string format(Not Pem file). So I need to get attribute values from the chain and for that reason I need to split that chain. I already have methods for the getting values, only thing that I need to get that chains separately.

I am getting four different certificate chain in String like below;

-----BEGIN CERTIFICATE------
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
-----END CERTIFICATE--------
-----BEGIN CERTIFICATE------
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
-----END CERTIFICATE--------
-----BEGIN CERTIFICATE------
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
-----END CERTIFICATE--------
-----BEGIN CERTIFICATE------
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
asdm1239asdkqkweqwejamdasdma
-----END CERTIFICATE--------

So I need to get each chain between the -----BEGIN CERTIFICATE------ and -----END CERTIFICATE-----
then I already have method for the reading of the chain. (getIssuer, getSerialNumber etc.)

Do you have any short cut solution for that ?


问:
mysql converting all records to json format
I want to get all records with corresponding names as a JSON output.
This solve partly my problem
How to convert result table to JSON array in MySQL

```<code>SELECT JSON_ARRAYAGG(JSON_OBJECT('name', name, 'phone', phone)) from Person;
</code>```

But instead of specifying names and records, I would like to get all of them, something like

```<code>SELECT JSON_ARRAYAGG(JSON_OBJECT(*, *)) from Person;
</code>```

How can I achieve it?

Body:
I want to get all records with corresponding names as a JSON output.
This solve partly my problem
How to convert result table to JSON array in MySQL

SELECT JSON_ARRAYAGG(JSON_OBJECT('name', name, 'phone', phone)) from Person;

But instead of specifying names and records, I would like to get all of them, something like

SELECT JSON_ARRAYAGG(JSON_OBJECT(*, *)) from Person;

How can I achieve it?


问:
FFmpeg h264_qsv decode with C++ - More data is required to decode header
I have a small sample project to decode one h264 frame with ffmpeg QSV hw:
ffmpegQSV.
The ffmpeg version is: release/5.1 and the build flags are (example contains ffmpeg built library):

```<code>./configure --prefix=../FFmpegHelper --pkg-config-flags=--static --pkg-config=pkg-config --disable-pthreads --disable-os2threads --disable-alsa --disable-appkit --disable-avfoundation --disable-bzlib --disable-coreimage --disable-iconv --disable-libxcb --disable-libxcb-shm --disable-libxcb-xfixes --disable-libxcb-shape --disable-lzma --disable-sndio --disable-sdl2 --disable-xlib --disable-zlib --disable-amf --disable-audiotoolbox --disable-cuda --disable-cuvid --disable-v4l2-m2m --disable-vaapi --disable-vdpau --disable-videotoolbox --enable-d3d11va --enable-dxva2 --disable-nvdec --disable-nvenc --enable-decoder=h264,aac,mp3 --enable-encoder=aac,libmp3lame --enable-parser=h264,aac,mp3 --enable-demuxer=flv,mov,mpegts,h264,aac,mp3,live_flv --enable-muxer=flv,mov,mpegts --enable-protocol=file,rtmp,pipe,hls --enable-filters --disable-doc --disable-ffprobe --enable-w32threads --enable-gpl --disable-static --enable-shared --enable-libx264 --enable-libx265 --enable-libmfx
</code>```

In the example I have a valid h264 IFrame with SPS and PPS data.
When I run the decode with NO_ACCEL the ffmpeg decodes a valid 1920x1080 frame in the CPU with no error.

```<code>int resultCode = FFmpegVideoPInvoke.CreateVideoDecoder(FFmpegVideoCodecId.H264, EHwAccel.NO_ACCEL, out decoderPtr);
</code>```

But when I try to use QSV hardware accerelation with change the line to:

```<code>int resultCode = FFmpegVideoPInvoke.CreateVideoDecoder(FFmpegVideoCodecId.H264, EHwAccel.QSV, out decoderPtr);
</code>```

the following errors occured and the avcodec_receive_frame always returns AVERROR(EAGAIN) because more data required to decode header:

When I use the command line ffmpeg with h264_qsv decoding it works perfect and the decode process is in the GPU.

I use the following examples for QSV decoding, but can't figure out what is my problem:
Link1 Link2 and the ffmpeg.exe source: Link3

I don't know if the initial warning message cause the problem or not... The documentation is really poor, I can't find any other example for QSV decoding.

Body:
I have a small sample project to decode one h264 frame with ffmpeg QSV hw:
ffmpegQSV.
The ffmpeg version is: release/5.1 and the build flags are (example contains ffmpeg built library):

./configure --prefix=../FFmpegHelper --pkg-config-flags=--static --pkg-config=pkg-config --disable-pthreads --disable-os2threads --disable-alsa --disable-appkit --disable-avfoundation --disable-bzlib --disable-coreimage --disable-iconv --disable-libxcb --disable-libxcb-shm --disable-libxcb-xfixes --disable-libxcb-shape --disable-lzma --disable-sndio --disable-sdl2 --disable-xlib --disable-zlib --disable-amf --disable-audiotoolbox --disable-cuda --disable-cuvid --disable-v4l2-m2m --disable-vaapi --disable-vdpau --disable-videotoolbox --enable-d3d11va --enable-dxva2 --disable-nvdec --disable-nvenc --enable-decoder=h264,aac,mp3 --enable-encoder=aac,libmp3lame --enable-parser=h264,aac,mp3 --enable-demuxer=flv,mov,mpegts,h264,aac,mp3,live_flv --enable-muxer=flv,mov,mpegts --enable-protocol=file,rtmp,pipe,hls --enable-filters --disable-doc --disable-ffprobe --enable-w32threads --enable-gpl --disable-static --enable-shared --enable-libx264 --enable-libx265 --enable-libmfx

In the example I have a valid h264 IFrame with SPS and PPS data.
When I run the decode with NO_ACCEL the ffmpeg decodes a valid 1920x1080 frame in the CPU with no error.

int resultCode = FFmpegVideoPInvoke.CreateVideoDecoder(FFmpegVideoCodecId.H264, EHwAccel.NO_ACCEL, out decoderPtr);

But when I try to use QSV hardware accerelation with change the line to:

int resultCode = FFmpegVideoPInvoke.CreateVideoDecoder(FFmpegVideoCodecId.H264, EHwAccel.QSV, out decoderPtr);

the following errors occured and the avcodec_receive_frame always returns AVERROR(EAGAIN) because more data required to decode header:

When I use the command line ffmpeg with h264_qsv decoding it works perfect and the decode process is in the GPU.

I use the following examples for QSV decoding, but can't figure out what is my problem:
Link1 Link2 and the ffmpeg.exe source: Link3

I don't know if the initial warning message cause the problem or not... The documentation is really poor, I can't find any other example for QSV decoding.


问:
Docker cp maven package into running container by maven
For local development I'd like to copy a maven war package into a docker container right after mvn package has created the package. How can I accomplish this?

My workflow as of right now is with a specific dockerid:

$ mvn clean package
$ docker cp the.war dockerid:/usr/local/tomcat/webapps/the.war
```
<p>A Tomcat server in the docker container recognizes the new war and starts again.</p>
<p>I tried adding the maven-antrun-plugin. However, the war is not deployed, whether I use it in the install or package phase. I get no error or warning with e.g. <code>mvn clean package</code>. However, <code>the.war</code> file is not copied into the docker container.</p>
<p>Below the dockerid is hardcoded momentarily.</p>
```   <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.jdk>1.8</version.jdk>
        <version.maven.compiler>3.6.1</version.maven.compiler>
   ...
   </properties>
...
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>3.1.0</version>
        </dependency>
...
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <configuration>
                            <target>
                                <exec executable="docker">
                                    <arg value="cp"/>
                                    <arg value="${basedir}/target/the.war"/>
                                    <arg value="dockerid:/usr/local/tomcat/webapps/the.war"/>
                                </exec>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
```

Body:
For local development I'd like to copy a maven war package into a docker container right after mvn package has created the package. How can I accomplish this?

My workflow as of right now is with a specific dockerid:

$ mvn clean package
$ docker cp the.war dockerid:/usr/local/tomcat/webapps/the.war

A Tomcat server in the docker container recognizes the new war and starts again.

I tried adding the maven-antrun-plugin. However, the war is not deployed, whether I use it in the install or package phase. I get no error or warning with e.g. mvn clean package. However, the.war file is not copied into the docker container.

Below the dockerid is hardcoded momentarily.

   <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.jdk>1.8</version.jdk>
        <version.maven.compiler>3.6.1</version.maven.compiler>
   ...
   </properties>
...
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>3.1.0</version>
        </dependency>
...
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <configuration>
                            <target>
                                <exec executable="docker">
                                    <arg value="cp"/>
                                    <arg value="${basedir}/target/the.war"/>
                                    <arg value="dockerid:/usr/local/tomcat/webapps/the.war"/>
                                </exec>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>


问:
Create a preloading sweet alert 2
I need to create a preload popup made with sweet alert2 that preloads the elaboration of some codes in the same page.

```<code><?php
    ob_start();
    session_start();

    if( isset($_POST['btn-success'])  ) {
        // do something.
        // i.e load a big image and after go to url destination: https://www.google.com
        header("location:  https://www.google.com");
  }
  ?>

  <html>
    <head>
<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    </head>
    <body>
        <form method="post">
               <button class="btn btn-success" type="button" name="btn-success" id="btfw">click to confirm</button>
        </form>

</body>
<script>

$("body").on("click", ".btn-success", function() {
    Swal.fire(
  'loading...',
  'You clicked the button!',
  'success'
)

});

</script>

    </html>
</code>```

I know how it works when the form points to another page, so when i use ajax for example. In this case I don't know how to preload codes that is in the same page

Title: Create a preloading sweet alert 2

Body:
I need to create a preload popup made with sweet alert2 that preloads the elaboration of some codes in the same page.

<?php
    ob_start();
    session_start();

    if( isset($_POST['btn-success'])  ) {
        // do something.
        // i.e load a big image and after go to url destination: https://www.google.com
        header("location:  https://www.google.com");
  }
  ?>

        <form method="post">
               <button class="btn btn-success" type="button" name="btn-success" id="btfw">click to confirm</button>
        </form>

I know how it works when the form points to another page, so when i use ajax for example. In this case I don't know how to preload codes that is in the same page


问:
Socket programming in c
I want to ask how the server file in c is contact with client file in socket programming in c?

when I run the server file it stops at listen() function and wait..

when I run the client file it makes the server file to continue running and move to accept function in server file.

but I don't know how the two files communicatee with each other?
This is the two files Server.c and Client.c

Server.c

```<code>`
    #define _WINSOCK_DEPRECATED_NO_WARNINGS
    #define _CRT_SECURE_NO_DEPRECATE
    #pragma comment(lib,"Ws2_32.lib")
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include<sys/types.h>
    #include<sys/stat.h>

    #include <sys/types.h>
    #include <winsock2.h>
    #include <fcntl.h>
    #include <io.h>
    #include <Ws2tcpip.h>
    #include <InetReg.h>
    #define PORT    9909

    struct sockaddr_in sockAddress;
    struct sockaddr_in clientAddress;

    int main() {
        int socketfd ;
        struct addrinfo hints;

        WSADATA wsaData;

        if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
            printf("Failed intialize wsa\n");
        else
            printf("Success intialize wsa\n");
        //Create socket

        socketfd = socket(AF_INET,SOCK_STREAM,0);
        if (socketfd == -1)
            printf("fails socket creation");
        else
            printf("Succness socket creation");

        //intailize address of sockaddress
        memset(&sockAddress, 0, sizeof(sockAddress));
        sockAddress.sin_family = AF_INET;
        sockAddress.sin_port = htons(PORT);
        sockAddress.sin_addr.s_addr = htonl(INADDR_ANY);

        //Bind the socket to local port

        int bindfd = bind(socketfd, (struct sockaddr*)&sockAddress,sizeof(sockAddress));
        if (bindfd == -1)
            printf("Fail Binding socket to local port\n");
        else
            printf("Success Binding socket to local port\n");

        //listen the request from client
        int listenfd = listen(socketfd, 1); //return 0 means success
        if (listenfd != 0)
            printf("Fail listening\n");
        else
            printf("start listening to local port\n");

        //accepting

        memset(&clientAddress, 0, sizeof(clientAddress));
        int clientAddressLength=sizeof(clientAddress);
        int clientSocketfd = accept(socketfd,(struct sockaddr*)&clientAddress,&clientAddressLength);
        if (clientSocketfd == -1)
            printf("failed to accept");
        else
            printf("Accepted...");
        //Writing

        char msg[100] = "Hello my name is ahmed server";
        unsigned int i = sizeof(msg);
        //_write(socketfd,msg,i);
        send(clientSocketfd, msg, sizeof(msg), true);
        //printf("sent: %s\n", msg);
        printf("\n\n\nServer address: %d\n\n\n", sockAddress.sin_addr.s_addr);
        printf("ServerAddress: %d\n", clientSocketfd);

        //close

        closesocket(clientSocketfd);
        closesocket(socketfd);

        system("pause");

        return 0;
    }
</code>```

`

Client.c

```<code>#define _CRT_SECURE_NO_DEPRECATE
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib,"Ws2_32.lib")

#include <stdio.h>
#include <winsock2.h>

#define PORT 9909

struct sockaddr_in SocketAddress;

int main() {

    WSADATA wsaData;

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
        printf("Failed intialize wsa\n");
    else
        printf("Success intialize wsa\n");

    //intialize socket

    int SocketFd = socket(AF_INET,SOCK_STREAM,0);
    if (SocketFd == -1)
        printf("Failed intialize socket\n");
    else
        printf("Success intialize socket\n");

    //intialize socket address
    memset(&SocketAddress,0,sizeof(SocketAddress));
    SocketAddress.sin_family = AF_INET;
    SocketAddress.sin_port = htons(PORT);
    SocketAddress.sin_addr.s_addr = inet_addr("127.0.0.1");

    //connectivity
    int c = connect(SocketFd,(struct sockaddr*)&SocketAddress,sizeof(SocketAddress));
    printf("client: %d", SocketFd);

    printf("\n\n\nClient address: %d\n\n\n", SocketAddress.sin_addr.s_addr);
    return 0;

}
</code>```

Title: Socket programming in c

Body:
I want to ask how the server file in c is contact with client file in socket programming in c?

when I run the server file it stops at listen() function and wait..

when I run the client file it makes the server file to continue running and move to accept function in server file.

but I don't know how the two files communicatee with each other?
This is the two files Server.c and Client.c

Server.c

`
    #define _WINSOCK_DEPRECATED_NO_WARNINGS
    #define _CRT_SECURE_NO_DEPRECATE
    #pragma comment(lib,"Ws2_32.lib")
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include<sys/types.h>
    #include<sys/stat.h>

    #include <sys/types.h>
    #include <winsock2.h>
    #include <fcntl.h>
    #include <io.h>
    #include <Ws2tcpip.h>
    #include <InetReg.h>
    #define PORT    9909

    struct sockaddr_in sockAddress;
    struct sockaddr_in clientAddress;

    int main() {
        int socketfd ;
        struct addrinfo hints;

        WSADATA wsaData;

        if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
            printf("Failed intialize wsa\n");
        else
            printf("Success intialize wsa\n");
        //Create socket

        socketfd = socket(AF_INET,SOCK_STREAM,0);
        if (socketfd == -1)
            printf("fails socket creation");
        else
            printf("Succness socket creation");

        //intailize address of sockaddress
        memset(&sockAddress, 0, sizeof(sockAddress));
        sockAddress.sin_family = AF_INET;
        sockAddress.sin_port = htons(PORT);
        sockAddress.sin_addr.s_addr = htonl(INADDR_ANY);

        //Bind the socket to local port

        int bindfd = bind(socketfd, (struct sockaddr*)&sockAddress,sizeof(sockAddress));
        if (bindfd == -1)
            printf("Fail Binding socket to local port\n");
        else
            printf("Success Binding socket to local port\n");

        //listen the request from client
        int listenfd = listen(socketfd, 1); //return 0 means success
        if (listenfd != 0)
            printf("Fail listening\n");
        else
            printf("start listening to local port\n");

        //accepting

        memset(&clientAddress, 0, sizeof(clientAddress));
        int clientAddressLength=sizeof(clientAddress);
        int clientSocketfd = accept(socketfd,(struct sockaddr*)&clientAddress,&clientAddressLength);
        if (clientSocketfd == -1)
            printf("failed to accept");
        else
            printf("Accepted...");
        //Writing

        char msg[100] = "Hello my name is ahmed server";
        unsigned int i = sizeof(msg);
        //_write(socketfd,msg,i);
        send(clientSocketfd, msg, sizeof(msg), true);
        //printf("sent: %s\n", msg);
        printf("\n\n\nServer address: %d\n\n\n", sockAddress.sin_addr.s_addr);
        printf("ServerAddress: %d\n", clientSocketfd);

        //close

        closesocket(clientSocketfd);
        closesocket(socketfd);

        system("pause");

        return 0;
    }

`

Client.c

#define _CRT_SECURE_NO_DEPRECATE
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib,"Ws2_32.lib")

#include <stdio.h>
#include <winsock2.h>

#define PORT 9909

struct sockaddr_in SocketAddress;

int main() {

    WSADATA wsaData;

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
        printf("Failed intialize wsa\n");
    else
        printf("Success intialize wsa\n");

    //intialize socket

    int SocketFd = socket(AF_INET,SOCK_STREAM,0);
    if (SocketFd == -1)
        printf("Failed intialize socket\n");
    else
        printf("Success intialize socket\n");

    //intialize socket address
    memset(&SocketAddress,0,sizeof(SocketAddress));
    SocketAddress.sin_family = AF_INET;
    SocketAddress.sin_port = htons(PORT);
    SocketAddress.sin_addr.s_addr = inet_addr("127.0.0.1");

    //connectivity
    int c = connect(SocketFd,(struct sockaddr*)&SocketAddress,sizeof(SocketAddress));
    printf("client: %d", SocketFd);

    printf("\n\n\nClient address: %d\n\n\n", SocketAddress.sin_addr.s_addr);
    return 0;

}


问:
Error: Specified qdisc not found with tc inside docker
I am trying to use tc to emulate network conditions inside docker containers. My linux is an ubuntu 20.04 LTS inside WSL2.

For this, I am running the container with

```<code>docker run -it --cap-add=NET_ADMIN ubuntu:latest
</code>```

Then inside the docker running

```<code>apt-get update
apt-get install linux-generics # for kernel-modules-extra
apt-get install iproute2
tc qdisc add dev eth0 root handle 1: prio
</code>```

But the last command prints Error: Specified qdisc not found even though tc qdisc show prints

```<code>qdisc noqueue 0: dev lo root refcnt 2
qdisc noqueue 0: dev eth0 root refcnt 2
</code>```

There have been many issues opened regarding this question, most of them either refer to compiling a custom kernel (not a viable option for me), installing kernel-modules-extra (which I have done) or just not solving the issue/it solving itself.

Body:
I am trying to use tc to emulate network conditions inside docker containers. My linux is an ubuntu 20.04 LTS inside WSL2.

For this, I am running the container with

docker run -it --cap-add=NET_ADMIN ubuntu:latest

Then inside the docker running

apt-get update
apt-get install linux-generics # for kernel-modules-extra
apt-get install iproute2
tc qdisc add dev eth0 root handle 1: prio

But the last command prints Error: Specified qdisc not found even though tc qdisc show prints

qdisc noqueue 0: dev lo root refcnt 2
qdisc noqueue 0: dev eth0 root refcnt 2

There have been many issues opened regarding this question, most of them either refer to compiling a custom kernel (not a viable option for me), installing kernel-modules-extra (which I have done) or just not solving the issue/it solving itself.


问:
Get new array from existing input document
i'm learning mongodb aggregation pipeline, now in this stage I have an array object with property "diagnosisGroup" & "paidAmount".
mongodb stage
I need to create two arrays:

diagnosisArray: [diagnosis1, diagnosis2, ...] (elements come from current stage document)

paidAmountArray: [paidAmount1, paidAmount2, ...]

How can I get it now


问:
How do i trigger an element using hyper link in "React Router Dom" with "Link and to"?
// the trigger button for modal;

```<code>        <div className="container">
            <div className="interior">
                <Link className="btn" to={"#open-modal"}> Basic CSS-Only Modal</Link>
            </div>
        </div>
</code>```

// The modal;

```<code>            <div id="open-modal" className="modal-window">
                <div>
                    <Link to={"#"} title="Close" className="modal-close">Close</Link>
                    <h1>Modal Title</h1>
                    <div>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum temporibus aperiam                           doloribus nisi blanditiis? Esse quae ipsam aliquid consequatur explicabo debitis tempora voluptas                repellendus rerum unde enim, sequi ullam recusandae?
                    </div>
                </div>
            </div>
</code>```

I just want to trigger the modal but it's not working with React Router but when i tried this with simple HTMl tags like "" and "href" attribute, it worked perfectly. But it's not working with Link and to even my all imports are good. I also tried giving id to "to" attribute without hash "#" but it didn't worked

Body:
// the trigger button for modal;

                <Link className="btn" to={"#open-modal"}> Basic CSS-Only Modal</Link>

// The modal;

                    <Link to={"#"} title="Close" className="modal-close">Close</Link>

Modal Title

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum temporibus aperiam                           doloribus nisi blanditiis? Esse quae ipsam aliquid consequatur explicabo debitis tempora voluptas                repellendus rerum unde enim, sequi ullam recusandae?

I just want to trigger the modal but it's not working with React Router but when i tried this with simple HTMl tags like "" and "href" attribute, it worked perfectly. But it's not working with Link and to even my all imports are good. I also tried giving id to "to" attribute without hash "#" but it didn't worked


问:
Download a ReadableStream from a Service Worker ? (chrome extension MV3)
I am updating a chrome extension from MV2 to MV3, and there is a step where I want to save a video. The documentation normally says to use :

```<code>video.pipe(fs.createWriteStream(outputPath))
</code>```

where 'video' is a ReadableStream, but for obvious reasons a browser extension can't access to the file system.
So in MV2 I converted it to a blob, applied URL.createObjectURL, and passed it to chrome.downloads.download(URL) and it worked fine.
But with MV3, you apparently can't use URL.createObjectURL in service workers... see this

So how can I download the stream?

I failed to try :

use StreamSaver.js (it uses the 'window' object, a SW can't access it)

opening a new tab and pass the data to it (instructions unclear :
answer)

convert the blob to base64 (I don't even know what it means)

Body:
I am updating a chrome extension from MV2 to MV3, and there is a step where I want to save a video. The documentation normally says to use :

video.pipe(fs.createWriteStream(outputPath))

where 'video' is a ReadableStream, but for obvious reasons a browser extension can't access to the file system.
So in MV2 I converted it to a blob, applied URL.createObjectURL, and passed it to chrome.downloads.download(URL) and it worked fine.
But with MV3, you apparently can't use URL.createObjectURL in service workers... see this

So how can I download the stream?

I failed to try :

use StreamSaver.js (it uses the 'window' object, a SW can't access it)

opening a new tab and pass the data to it (instructions unclear :
answer)

convert the blob to base64 (I don't even know what it means)


问:
Numpy is already installed，but “ImportError：the module named ‘numpy’ is not found” is still provoked
I try to create a "pypy3.7" environment by Anaconda,but get a problems as follows:

“numpy is already in the list”

“importError” still happens

I have tried reinstalled several times but nothing different happens.


问:
How to add servlet filter logic as jar to other maven project
I have created a logging project where it has servlet filter and added this as jar to other department service and when I call end point of department service logging filter is not getting called.</p>


问:
http https - 404 not found - reverse proxy problem
I deploy a Mean app with nodejs and express.

I made a reverse proxy with nginx.

`

```<code> location /soc/ {
                root /capza_app/back/;
                index index.js;
#               proxy_set_header X-Real-IP;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;
                proxy_set_header X-NginX-Proxy true;
                proxy_set_header AccesControl-Allow-Origin *;
                proxy_pass http://ip:3000/;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_http_version 1.1;
</code>```

`

I call my api in front here:
apiUrl = 'https://mydomain/soc/transaction/'

After all go in back in my index.js:
app.use('/soc/transaction', TransactionController);

My index send in my controller.

I have 404 error.
Without the reverse proxy, i have Mixed Content: The page at https as loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint http.

maybe routes problems but I don't know what i am do wrong.

Thanks

I try to change my route, chang my reverse proxy

Body:
I deploy a Mean app with nodejs and express.

I made a reverse proxy with nginx.

`

 location /soc/ {
                root /capza_app/back/;
                index index.js;
#               proxy_set_header X-Real-IP;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;
                proxy_set_header X-NginX-Proxy true;
                proxy_set_header AccesControl-Allow-Origin *;
                proxy_pass http://ip:3000/;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_http_version 1.1;

`

I call my api in front here:
apiUrl = 'https://mydomain/soc/transaction/'

After all go in back in my index.js:
app.use('/soc/transaction', TransactionController);

My index send in my controller.

I have 404 error.
Without the reverse proxy, i have Mixed Content: The page at https as loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint http.

maybe routes problems but I don't know what i am do wrong.

Thanks

I try to change my route, chang my reverse proxy


问:
How to resolve 'object null is not iterable' error while making prediction using tensorflow js?
I was trying to make a sequence classifier using tf.js as a project. I trained a tensorflow.keras model on the data and converted the model to tfjs as below:

```<code>tfjs.converters.save_keras_model(model, './')
</code>```

Then, I uploaded it into my javascript using the following code:

```<code>import * as tf from '@tensorflow/tfjs';

var model = null;
async function loadModel() {
    model = await tf.loadLayersModel('assets/model/model.json');
    console.log('Loaded')
}
loadModel();
</code>```

I developed a function to make predictions. Code for the same is:

```<code>async function pred() {
    tens = tf.zeros([batchSize, sentenceLength]);
    const preds = await model.predict(tens);
    return preds;
}
</code>```

When I call pred() function it raises the following error:

```<code>TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
</code>```

I can tell that the error happened in model.predict() line, but I am not able to debug this. Any help is appreciated.

Edit:
It seems that the cause of the error was the following tag in index.html file:

```<code><script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
</code>```

When I removed this line, the error got resolved.

Body:
I was trying to make a sequence classifier using tf.js as a project. I trained a tensorflow.keras model on the data and converted the model to tfjs as below:

tfjs.converters.save_keras_model(model, './')

Then, I uploaded it into my javascript using the following code:

import * as tf from '@tensorflow/tfjs';

var model = null;
async function loadModel() {
    model = await tf.loadLayersModel('assets/model/model.json');
    console.log('Loaded')
}
loadModel();

I developed a function to make predictions. Code for the same is:

async function pred() {
    tens = tf.zeros([batchSize, sentenceLength]);
    const preds = await model.predict(tens);
    return preds;
}

When I call pred() function it raises the following error:

TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

I can tell that the error happened in model.predict() line, but I am not able to debug this. Any help is appreciated.

Edit:
It seems that the cause of the error was the following tag in index.html file:

When I removed this line, the error got resolved.