问:
in my total textfield - i couldnt refresh the total when the list of the elements change?
here is my code it is simple just run & try the total not updating!!!
May any one run my code & tell me??
i am getting the total but when the list of _controller3 changed the _controller4 keeping the same value ??

`

```import 'package:flutter/material.dart';
import 'package:simple_time_range_picker/simple_time_range_picker.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Dates Rang',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      /*routes: {
        "dateslist": (context) =>  DatesList(),
        "/": (context) => const HomeScreen(),
      },*/
      home: RangeDatePicker(),
    );
  }
}

class RangeDatePicker extends StatefulWidget {
  @override
  State<RangeDatePicker> createState() => _RangeDatePickerState();
}

class _RangeDatePickerState extends State<RangeDatePicker> {
  String done = "Done";
  int? selectedIndex;
  TimeRangePicker? _selectedTimesRange;
  DateTimeRange? _selectedDateRange;
  final DateTime _startD = DateTime(2020);
  final DateTime _endD = DateTime(2100);
  List<DateTime> itemsDates = [];
  List<DateTime> timesRange = [];
  bool _isEnabled = true;
  final List<TextEditingController> _controller1 = [];
  final List<TextEditingController> _controller2 = [];
  final List<TextEditingController> _controller3 = [];
  final List<TextEditingController> _controller5 = [];
  final TextEditingController _controller4 = TextEditingController();
  final TextEditingController _controller6 = TextEditingController();
  final List dayType = [];
  int totalH = 0;
  int totalM = 0;

  /*@override
  void initState() {
    for (int i = 0; i < itemsDates.length; i++) {
      _controller1.add(TextEditingController());
      _controller2.add(TextEditingController());
      _controller3.add(TextEditingController());
      setState(() {});
    }
    super.initState();
  }*/

  int? differenceDate;

  int getDaysInBetween() {
    if (_selectedDateRange == null) return 0;
    differenceDate =
        _selectedDateRange!.end.difference(_selectedDateRange!.start).inDays;
    print(differenceDate! + 1);
    setState(() {});
    return differenceDate! + 1;
  }

  _showDatePicker() async {
    DateTimeRange? datesRange = await showDateRangePicker(
      context: context,
      firstDate: _startD,
      lastDate: _endD,
      currentDate: DateTime.now(),
      saveText: done,
    );

    if (datesRange != null) {
      // Rebuild the UI
      //print(result.start.toString());
      setState(() {
        _selectedDateRange = datesRange;
        itemsDates = List<DateTime>.generate(getDaysInBetween(), (i) {
          DateTime date = _selectedDateRange?.start ?? DateTime.now();
          return date.add(Duration(days: i));
        });
      });
      _controller1.clear();
      _controller2.clear();
      _controller3.clear();
      _controller5.clear();
      _controller4.clear();
      _controller6.clear();

      for (int i = 0; i < itemsDates.length; i++) {
        _controller1.add(TextEditingController());
        _controller2.add(TextEditingController());
        _controller3.add(TextEditingController());
        _controller5.add(TextEditingController());
        // items.add(items[i]);
        setState(() {});
      }
    }
  }

  /* String? selectedInTime;
  Future<void> displayTimeInDialog() async {
    final TimeOfDay? timeIn =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (timeIn != null) {
      setState(() {
        selectedInTime = timeIn.format(context);
      });
    }
  }

  String? selectedOutTime;
  Future<void> displayTimeOutDialog() async {
    final TimeOfDay? timeOut =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (timeOut != null) {
      setState(() {
        selectedOutTime = timeOut.format(context);
      });
    }
  }*/

  String? formattedTimeIn;
  String? formattedTimeOut;

  DateTime? pickedTimeIn1;
  DateTime? pickedTimeOut1;

  DateTime? parsedTimeIn;
  DateTime? parsedTimeOut;

  int? hours;
  int? minutes;

  Duration? diff;

  int? restDays;
  DateFormat dateFormat = DateFormat("HH:mm");
  Future<void> getDifference(formattedTimeIn, formattedTimeOut) async {
    //var _date = dateFormat.format(DateTime.now());
    pickedTimeIn1 = dateFormat.parse(formattedTimeIn);
    pickedTimeOut1 = dateFormat.parse(formattedTimeOut);
    print(pickedTimeIn1);
    print(pickedTimeOut1);
    if (pickedTimeIn1 == dateFormat.parse(formattedTimeIn) &&
        pickedTimeOut1 == dateFormat.parse(formattedTimeOut)) {
      if (pickedTimeIn1 == dateFormat.parse("7:00")) {
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('between: $hours hours $minutes minutes');
      } else if (pickedTimeIn1 != dateFormat.parse("7:00")) {
        pickedTimeIn1 = dateFormat.parse("7:00");
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('between: $hours hours $minutes minutes');
      }
    } else if (pickedTimeIn1!.isAfter(pickedTimeOut1!)) {
      if (pickedTimeIn1 == dateFormat.parse("7:00")) {
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('After: $hours hours $minutes minutes');
      } else if (pickedTimeIn1 != dateFormat.parse("7:00")) {
        pickedTimeIn1 = dateFormat.parse("7:00");
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('After: $hours hours $minutes minutes');
      }
    } else if (pickedTimeIn1!.isBefore(pickedTimeOut1!)) {
      if (pickedTimeIn1 == dateFormat.parse("7:00")) {
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('befor: $hours hours $minutes minutes');
      } else if (pickedTimeIn1 != dateFormat.parse("7:00")) {
        pickedTimeIn1 = dateFormat.parse("7:00");
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('befor: $hours hours $minutes minutes');
      }
    }
  }

  int io = 0;
  double totalTO = 0.0;
  void _totalTO() {
    for (io; io < itemsDates.length; io++) {
      totalTO += double.parse(_controller3[io].text);
    }
    setState(() {
      totalTO;
      _controller4.text = totalTO.toStringAsFixed(2);
    });
    print(_controller4.text);
    print(totalTO);
  }

  /*void clearText4() {
    _controller4.clear();
    setState(() {});
    print("C4");
  }*/

  int im = 0;
  double totalTM = 0.0;
  _totalTM() {
    for (im; im < itemsDates.length; im++) {
      totalTM += double.parse(_controller5[im].text);
    }

    setState(() {
      totalTM;
      _controller6.text = totalTM.toStringAsFixed(2);
    });
    print(_controller6.text);
    print(totalTM);
  }

  /* void clearText6() {
    if (_controller6.text.isNotEmpty) _controller6.clear();
    setState(() {});
    print("C6");
  }*/

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Pick date range'),
        actions: [
          IconButton(
            icon: const Icon(Icons.date_range_sharp),
            onPressed: () {
              print(itemsDates.length);
              print(differenceDate! + 1);
              print(itemsDates[0]);
            },
          ),
        ],
      ),
      body: _selectedDateRange == null
          ? const Center(
              child: Text('Press the button to show the picker'),
            )
          : SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(30),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Start date
                    Text(
                      "Start date: ${_selectedDateRange!.start.toString().split(' ')[0]}",
                      style: const TextStyle(fontSize: 24, color: Colors.blue),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    // End date
                    Text(
                        "End date: ${_selectedDateRange!.end.toString().split(' ')[0]}",
                        style:
                            const TextStyle(fontSize: 24, color: Colors.red)),

                    ListView.builder(
                      itemCount: itemsDates.length,
                      shrinkWrap: true,
                      itemBuilder: (BuildContext context, int index) {
                        _controller1.add(TextEditingController());
                        _controller2.add(TextEditingController());
                        _controller3.add(TextEditingController());
                        _controller5.add(TextEditingController());
                        return Column(
                          children: [
                            ListTile(
                              tileColor: selectedIndex == index
                                  ? const Color.fromARGB(255, 156, 212, 238)
                                  : null,
                              onTap: () {
                                setState(() {
                                  selectedIndex = index;
                                });
                              },
                              title: SingleChildScrollView(
                                  physics: const BouncingScrollPhysics(),
                                  scrollDirection: Axis.horizontal,
                                  child: Row(children: [
                                    (selectedIndex == index
                                        ? SizedBox(
                                            width: 110,
                                            child: _dropDown(index),
                                          )
                                        : Icon(Icons.date_range)),
                                    const SizedBox(width: 10),
                                    Text(
                                        '${itemsDates[index].day}/${itemsDates[index].month}/${itemsDates[index].year}'),
                                    const SizedBox(width: 10),
                                    SizedBox(
                                      width: 65,
                                      child: TextField(
                                        enabled: _isEnabled,
                                        keyboardType: null,
                                        expands: false,
                                        autofocus: true,
                                        controller: _controller1[index],
                                        readOnly: true,
                                        decoration: InputDecoration(
                                            hintText: _controller1[index].text,
                                            hintStyle:
                                                TextStyle(color: Colors.black)),
                                        onTap: () async {
                                          await _timeIn(context, index);
                                          setState(() {
                                            _controller1[index].text =
                                                formattedTimeIn!;
                                          });
                                        },
                                      ),
                                    ),
                                    const Text("/"),
                                    SizedBox(
                                      width: 65,
                                      child: TextField(
                                        enabled: _isEnabled,
                                        expands: false,
                                        autofocus: true,
                                        controller: _controller2[index],
                                        readOnly: true,
                                        decoration: InputDecoration(
                                            hintText: _controller2[index].text,
                                            hintStyle:
                                                TextStyle(color: Colors.black)),
                                        onTap: () async {
                                          await _timeOut(context, index);
                                          setState(() {
                                            _controller2[index].text =
                                                formattedTimeOut!;
                                            getDifference(formattedTimeIn,
                                                formattedTimeOut);
                                            _controller3[index].text =
                                                '$hours.$minutes';
                                            _totalTPerDay(index);
                                            _totalMPerDay(index);
                                          });
                                        },
                                      ),
                                    ),
                                    const SizedBox(width: 10),
                                    SizedBox(
                                      width: 100,
                                      child: TextField(
                                        enabled: _isEnabled,
                                        decoration: InputDecoration(
                                          hintText: _controller3[index].text,
                                          border: const OutlineInputBorder(
                                            borderSide: BorderSide(
                                                color: Colors.black,
                                                width: 2,
                                                style: BorderStyle.solid),
                                          ),
                                        ),
                                        controller: _controller3[index],
                                        onTap: () {
                                          _totalTPerDay(index);
                                        },
                                      ),
                                    ),
                                    SizedBox(
                                      width: 100,
                                      child: TextField(
                                        enabled: _isEnabled,
                                        decoration: InputDecoration(
                                          hintText: _controller5[index].text,
                                          border: const OutlineInputBorder(
                                            borderSide: BorderSide(
                                                color: Colors.black,
                                                width: 2,
                                                style: BorderStyle.solid),
                                          ),
                                        ),
                                        controller: _controller5[index],
                                        onTap: () {
                                          _totalMPerDay(index);
                                        },
                                      ),
                                    ),
                                  ])
                                  // : Text("$dropdownvalue - ${itemsDates[index].day}/${itemsDates[index].month}/${itemsDates[index].year} - ${_controller1[index].text}/${_controller2[index].text} - ${_controller3[index].text} Hours - ${_controller5[index].text} JOD"),
                                  ),
                            ),
                          ],
                        );
                      },
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 30, vertical: 15),
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          textDirection: null,
                          children: [
                            const Text("Total:        "),
                            SizedBox(
                              width: 80,
                              child: TextField(
                                autofocus: false,
                                decoration: InputDecoration(
                                    hintText: _controller4.text,
                                    border: const OutlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Colors.black,
                                            width: 2,
                                            style: BorderStyle.solid))),
                                controller: _controller4,
                                onTap: () {
                                  // clearText4();
                                  _totalTO();
                                },
                              ),
                            ),
                            SizedBox(
                              width: 80,
                              child: TextField(
                                controller: _controller6,
                                autofocus: false,
                                decoration: InputDecoration(
                                    hintText: _controller6.text,
                                    border: const OutlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Colors.black,
                                            width: 2,
                                            style: BorderStyle.solid))),
                                onTap: () {
                                  // clearText6();
                                  _totalTM();
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await _showDatePicker();
          // _controller1 = [];
          // _controller2 = [];
          // _controller3 = [];
        },
        child: const Icon(Icons.date_range),
      ),
    );
  }

  TimeOfDay? pickedTimeIn;
  Future<void> _timeIn(BuildContext context, int index) async {
    pickedTimeIn = await showTimePicker(
      initialTime: TimeOfDay.now(),
      context: context,
    );
    if (pickedTimeIn == null) {
    } else {
      print(pickedTimeIn!.format(context));
      parsedTimeIn =
          DateFormat.jm().parse(pickedTimeIn!.format(context).toString());
      print(parsedTimeIn);
      formattedTimeIn = DateFormat.jm().format(parsedTimeIn!);
    }
    setState(() {
      _controller1[index].text = formattedTimeIn!;
    });
  }

  TimeOfDay? pickedTimeOut;
  Future<void> _timeOut(BuildContext context, int index) async {
    pickedTimeOut = await showTimePicker(
      initialTime: TimeOfDay.now(),
      context: context,
    );
    if (pickedTimeOut == null) {
    } else {
      print(pickedTimeOut!.format(context));
      parsedTimeOut =
          DateFormat.jm().parse(pickedTimeOut!.format(context).toString());
      print(parsedTimeOut);
      formattedTimeOut = DateFormat.jm().format(parsedTimeOut!);
    }
  }

  String dropdownvalue = "Choice Day";
  List<String> items = [
    "Choice Day",
    "Normal Day",
    "Holly Day",
    "Unuual Day",
    "Sick Day"
  ];

  double T = 0.0;
  double a = 1.25;
  double b = 1.5;

  DropdownButtonFormField<String> _dropDown(int index) {
    return DropdownButtonFormField(
      isExpanded: true,
      value: items[0],
      items: items.map((String dayType) {
        return DropdownMenuItem(
          value: dayType,
          child: Text(dayType),
        );
      }).toList(),
      onChanged: (newValue) {
        if (newValue == "Normal Day" && selectedIndex == index) {
          T = 1.25;
          restDays = 21;
          if (_controller1[index].text.isEmpty) {
            _timeIn(context, index);
            setState(() {
              _isEnabled = true;
            });

            print("empty $newValue");
          } else {
            setState(() {
              _controller1[index].text = formattedTimeIn!;
              _controller2[index].text = formattedTimeOut!;
              getDifference(formattedTimeIn, formattedTimeOut);
              _controller3[index].text = '$hours.$minutes';
              _totalTPerDay(index);
              _totalMPerDay(index);
              _isEnabled = true;
            });
            print("not empty $newValue");
          }
        } else if (newValue == "Holly Day" && selectedIndex == index) {
          T = 1.5;
          restDays = 12 + 1;
          if (_controller1[index].text.isEmpty) {
            _timeIn(context, index);
            setState(() {
              _isEnabled = true;
            });
            print("empty $newValue");
          } else {
            setState(() {
              _controller1[index].text = formattedTimeIn!;
              _controller2[index].text = formattedTimeOut!;
              getDifference(formattedTimeIn, formattedTimeOut);
              _controller3[index].text = '$hours.$minutes';
              _totalTPerDay(index);
              _totalMPerDay(index);
              _isEnabled = true;
            });
            print("not empty $newValue");
          }
        } else if ((newValue == "Unuual Day" || newValue == "Sick Day") &&
            selectedIndex == index) {
          T = 0.0;
          restDays = 24;
          hours = 0;
          minutes = 0;
          setState(() {
            _isEnabled = false;
            _controller1[index].text = "  -------";
            _controller2[index].text = "  -------";
            _controller3[index].text = "0.0";
            _controller5[index].text = "0.0";
          });
        }
        print(T);
        setState(() {
          dropdownvalue = newValue!;
          print(restDays);
        });
      },
    );
  }

  _totalTPerDay(int index) {
    getDifference(_controller1[index].text, _controller2[index].text);
    setState(() {
      _controller3[index].text = '$hours.$minutes';
    });
    return _controller3[index].text;
  }

  _totalMPerDay(int index) {
    (double.tryParse(_controller3[index].text)! * T);

    setState(() {
      _controller5[index].text =
          (double.tryParse(_controller3[index].text)! * T).toStringAsFixed(2);
    });
    return _controller5[index].text;
  }

  String _timeFormated(TimeOfDay time) {
    if (time == null) return "--:--";
    return "${time.hour}:${time.minute}";
  }
}

```

`

May any one run my code & tell me??
i am getting the total but when the list of _controller3 changed the _controller4 keeping the same value ??

Body:
here is my code it is simple just run & try the total not updating!!!
May any one run my code & tell me??
i am getting the total but when the list of _controller3 changed the _controller4 keeping the same value ??

`

import 'package:flutter/material.dart';
import 'package:simple_time_range_picker/simple_time_range_picker.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Dates Rang',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      /*routes: {
        "dateslist": (context) =>  DatesList(),
        "/": (context) => const HomeScreen(),
      },*/
      home: RangeDatePicker(),
    );
  }
}

class RangeDatePicker extends StatefulWidget {
  @override
  State<RangeDatePicker> createState() => _RangeDatePickerState();
}

class _RangeDatePickerState extends State<RangeDatePicker> {
  String done = "Done";
  int? selectedIndex;
  TimeRangePicker? _selectedTimesRange;
  DateTimeRange? _selectedDateRange;
  final DateTime _startD = DateTime(2020);
  final DateTime _endD = DateTime(2100);
  List<DateTime> itemsDates = [];
  List<DateTime> timesRange = [];
  bool _isEnabled = true;
  final List<TextEditingController> _controller1 = [];
  final List<TextEditingController> _controller2 = [];
  final List<TextEditingController> _controller3 = [];
  final List<TextEditingController> _controller5 = [];
  final TextEditingController _controller4 = TextEditingController();
  final TextEditingController _controller6 = TextEditingController();
  final List dayType = [];
  int totalH = 0;
  int totalM = 0;

  /*@override
  void initState() {
    for (int i = 0; i < itemsDates.length; i++) {
      _controller1.add(TextEditingController());
      _controller2.add(TextEditingController());
      _controller3.add(TextEditingController());
      setState(() {});
    }
    super.initState();
  }*/

  int? differenceDate;

  int getDaysInBetween() {
    if (_selectedDateRange == null) return 0;
    differenceDate =
        _selectedDateRange!.end.difference(_selectedDateRange!.start).inDays;
    print(differenceDate! + 1);
    setState(() {});
    return differenceDate! + 1;
  }

  _showDatePicker() async {
    DateTimeRange? datesRange = await showDateRangePicker(
      context: context,
      firstDate: _startD,
      lastDate: _endD,
      currentDate: DateTime.now(),
      saveText: done,
    );

    if (datesRange != null) {
      // Rebuild the UI
      //print(result.start.toString());
      setState(() {
        _selectedDateRange = datesRange;
        itemsDates = List<DateTime>.generate(getDaysInBetween(), (i) {
          DateTime date = _selectedDateRange?.start ?? DateTime.now();
          return date.add(Duration(days: i));
        });
      });
      _controller1.clear();
      _controller2.clear();
      _controller3.clear();
      _controller5.clear();
      _controller4.clear();
      _controller6.clear();

      for (int i = 0; i < itemsDates.length; i++) {
        _controller1.add(TextEditingController());
        _controller2.add(TextEditingController());
        _controller3.add(TextEditingController());
        _controller5.add(TextEditingController());
        // items.add(items[i]);
        setState(() {});
      }
    }
  }

  /* String? selectedInTime;
  Future<void> displayTimeInDialog() async {
    final TimeOfDay? timeIn =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (timeIn != null) {
      setState(() {
        selectedInTime = timeIn.format(context);
      });
    }
  }

  String? selectedOutTime;
  Future<void> displayTimeOutDialog() async {
    final TimeOfDay? timeOut =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (timeOut != null) {
      setState(() {
        selectedOutTime = timeOut.format(context);
      });
    }
  }*/

  String? formattedTimeIn;
  String? formattedTimeOut;

  DateTime? pickedTimeIn1;
  DateTime? pickedTimeOut1;

  DateTime? parsedTimeIn;
  DateTime? parsedTimeOut;

  int? hours;
  int? minutes;

  Duration? diff;

  int? restDays;
  DateFormat dateFormat = DateFormat("HH:mm");
  Future<void> getDifference(formattedTimeIn, formattedTimeOut) async {
    //var _date = dateFormat.format(DateTime.now());
    pickedTimeIn1 = dateFormat.parse(formattedTimeIn);
    pickedTimeOut1 = dateFormat.parse(formattedTimeOut);
    print(pickedTimeIn1);
    print(pickedTimeOut1);
    if (pickedTimeIn1 == dateFormat.parse(formattedTimeIn) &&
        pickedTimeOut1 == dateFormat.parse(formattedTimeOut)) {
      if (pickedTimeIn1 == dateFormat.parse("7:00")) {
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('between: $hours hours $minutes minutes');
      } else if (pickedTimeIn1 != dateFormat.parse("7:00")) {
        pickedTimeIn1 = dateFormat.parse("7:00");
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('between: $hours hours $minutes minutes');
      }
    } else if (pickedTimeIn1!.isAfter(pickedTimeOut1!)) {
      if (pickedTimeIn1 == dateFormat.parse("7:00")) {
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('After: $hours hours $minutes minutes');
      } else if (pickedTimeIn1 != dateFormat.parse("7:00")) {
        pickedTimeIn1 = dateFormat.parse("7:00");
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('After: $hours hours $minutes minutes');
      }
    } else if (pickedTimeIn1!.isBefore(pickedTimeOut1!)) {
      if (pickedTimeIn1 == dateFormat.parse("7:00")) {
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('befor: $hours hours $minutes minutes');
      } else if (pickedTimeIn1 != dateFormat.parse("7:00")) {
        pickedTimeIn1 = dateFormat.parse("7:00");
        pickedTimeOut1 = pickedTimeOut1!.add(const Duration(days: 1));
        diff = pickedTimeOut1!.difference(pickedTimeIn1!);
        hours = diff!.inHours - restDays!;
        minutes = diff!.inMinutes % 60;
        print('befor: $hours hours $minutes minutes');
      }
    }
  }

  int io = 0;
  double totalTO = 0.0;
  void _totalTO() {
    for (io; io < itemsDates.length; io++) {
      totalTO += double.parse(_controller3[io].text);
    }
    setState(() {
      totalTO;
      _controller4.text = totalTO.toStringAsFixed(2);
    });
    print(_controller4.text);
    print(totalTO);
  }

  /*void clearText4() {
    _controller4.clear();
    setState(() {});
    print("C4");
  }*/

  int im = 0;
  double totalTM = 0.0;
  _totalTM() {
    for (im; im < itemsDates.length; im++) {
      totalTM += double.parse(_controller5[im].text);
    }

    setState(() {
      totalTM;
      _controller6.text = totalTM.toStringAsFixed(2);
    });
    print(_controller6.text);
    print(totalTM);
  }

  /* void clearText6() {
    if (_controller6.text.isNotEmpty) _controller6.clear();
    setState(() {});
    print("C6");
  }*/

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Pick date range'),
        actions: [
          IconButton(
            icon: const Icon(Icons.date_range_sharp),
            onPressed: () {
              print(itemsDates.length);
              print(differenceDate! + 1);
              print(itemsDates[0]);
            },
          ),
        ],
      ),
      body: _selectedDateRange == null
          ? const Center(
              child: Text('Press the button to show the picker'),
            )
          : SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(30),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Start date
                    Text(
                      "Start date: ${_selectedDateRange!.start.toString().split(' ')[0]}",
                      style: const TextStyle(fontSize: 24, color: Colors.blue),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    // End date
                    Text(
                        "End date: ${_selectedDateRange!.end.toString().split(' ')[0]}",
                        style:
                            const TextStyle(fontSize: 24, color: Colors.red)),

                    ListView.builder(
                      itemCount: itemsDates.length,
                      shrinkWrap: true,
                      itemBuilder: (BuildContext context, int index) {
                        _controller1.add(TextEditingController());
                        _controller2.add(TextEditingController());
                        _controller3.add(TextEditingController());
                        _controller5.add(TextEditingController());
                        return Column(
                          children: [
                            ListTile(
                              tileColor: selectedIndex == index
                                  ? const Color.fromARGB(255, 156, 212, 238)
                                  : null,
                              onTap: () {
                                setState(() {
                                  selectedIndex = index;
                                });
                              },
                              title: SingleChildScrollView(
                                  physics: const BouncingScrollPhysics(),
                                  scrollDirection: Axis.horizontal,
                                  child: Row(children: [
                                    (selectedIndex == index
                                        ? SizedBox(
                                            width: 110,
                                            child: _dropDown(index),
                                          )
                                        : Icon(Icons.date_range)),
                                    const SizedBox(width: 10),
                                    Text(
                                        '${itemsDates[index].day}/${itemsDates[index].month}/${itemsDates[index].year}'),
                                    const SizedBox(width: 10),
                                    SizedBox(
                                      width: 65,
                                      child: TextField(
                                        enabled: _isEnabled,
                                        keyboardType: null,
                                        expands: false,
                                        autofocus: true,
                                        controller: _controller1[index],
                                        readOnly: true,
                                        decoration: InputDecoration(
                                            hintText: _controller1[index].text,
                                            hintStyle:
                                                TextStyle(color: Colors.black)),
                                        onTap: () async {
                                          await _timeIn(context, index);
                                          setState(() {
                                            _controller1[index].text =
                                                formattedTimeIn!;
                                          });
                                        },
                                      ),
                                    ),
                                    const Text("/"),
                                    SizedBox(
                                      width: 65,
                                      child: TextField(
                                        enabled: _isEnabled,
                                        expands: false,
                                        autofocus: true,
                                        controller: _controller2[index],
                                        readOnly: true,
                                        decoration: InputDecoration(
                                            hintText: _controller2[index].text,
                                            hintStyle:
                                                TextStyle(color: Colors.black)),
                                        onTap: () async {
                                          await _timeOut(context, index);
                                          setState(() {
                                            _controller2[index].text =
                                                formattedTimeOut!;
                                            getDifference(formattedTimeIn,
                                                formattedTimeOut);
                                            _controller3[index].text =
                                                '$hours.$minutes';
                                            _totalTPerDay(index);
                                            _totalMPerDay(index);
                                          });
                                        },
                                      ),
                                    ),
                                    const SizedBox(width: 10),
                                    SizedBox(
                                      width: 100,
                                      child: TextField(
                                        enabled: _isEnabled,
                                        decoration: InputDecoration(
                                          hintText: _controller3[index].text,
                                          border: const OutlineInputBorder(
                                            borderSide: BorderSide(
                                                color: Colors.black,
                                                width: 2,
                                                style: BorderStyle.solid),
                                          ),
                                        ),
                                        controller: _controller3[index],
                                        onTap: () {
                                          _totalTPerDay(index);
                                        },
                                      ),
                                    ),
                                    SizedBox(
                                      width: 100,
                                      child: TextField(
                                        enabled: _isEnabled,
                                        decoration: InputDecoration(
                                          hintText: _controller5[index].text,
                                          border: const OutlineInputBorder(
                                            borderSide: BorderSide(
                                                color: Colors.black,
                                                width: 2,
                                                style: BorderStyle.solid),
                                          ),
                                        ),
                                        controller: _controller5[index],
                                        onTap: () {
                                          _totalMPerDay(index);
                                        },
                                      ),
                                    ),
                                  ])
                                  // : Text("$dropdownvalue - ${itemsDates[index].day}/${itemsDates[index].month}/${itemsDates[index].year} - ${_controller1[index].text}/${_controller2[index].text} - ${_controller3[index].text} Hours - ${_controller5[index].text} JOD"),
                                  ),
                            ),
                          ],
                        );
                      },
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 30, vertical: 15),
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          textDirection: null,
                          children: [
                            const Text("Total:        "),
                            SizedBox(
                              width: 80,
                              child: TextField(
                                autofocus: false,
                                decoration: InputDecoration(
                                    hintText: _controller4.text,
                                    border: const OutlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Colors.black,
                                            width: 2,
                                            style: BorderStyle.solid))),
                                controller: _controller4,
                                onTap: () {
                                  // clearText4();
                                  _totalTO();
                                },
                              ),
                            ),
                            SizedBox(
                              width: 80,
                              child: TextField(
                                controller: _controller6,
                                autofocus: false,
                                decoration: InputDecoration(
                                    hintText: _controller6.text,
                                    border: const OutlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Colors.black,
                                            width: 2,
                                            style: BorderStyle.solid))),
                                onTap: () {
                                  // clearText6();
                                  _totalTM();
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await _showDatePicker();
          // _controller1 = [];
          // _controller2 = [];
          // _controller3 = [];
        },
        child: const Icon(Icons.date_range),
      ),
    );
  }

  TimeOfDay? pickedTimeIn;
  Future<void> _timeIn(BuildContext context, int index) async {
    pickedTimeIn = await showTimePicker(
      initialTime: TimeOfDay.now(),
      context: context,
    );
    if (pickedTimeIn == null) {
    } else {
      print(pickedTimeIn!.format(context));
      parsedTimeIn =
          DateFormat.jm().parse(pickedTimeIn!.format(context).toString());
      print(parsedTimeIn);
      formattedTimeIn = DateFormat.jm().format(parsedTimeIn!);
    }
    setState(() {
      _controller1[index].text = formattedTimeIn!;
    });
  }

  TimeOfDay? pickedTimeOut;
  Future<void> _timeOut(BuildContext context, int index) async {
    pickedTimeOut = await showTimePicker(
      initialTime: TimeOfDay.now(),
      context: context,
    );
    if (pickedTimeOut == null) {
    } else {
      print(pickedTimeOut!.format(context));
      parsedTimeOut =
          DateFormat.jm().parse(pickedTimeOut!.format(context).toString());
      print(parsedTimeOut);
      formattedTimeOut = DateFormat.jm().format(parsedTimeOut!);
    }
  }

  String dropdownvalue = "Choice Day";
  List<String> items = [
    "Choice Day",
    "Normal Day",
    "Holly Day",
    "Unuual Day",
    "Sick Day"
  ];

  double T = 0.0;
  double a = 1.25;
  double b = 1.5;

  DropdownButtonFormField<String> _dropDown(int index) {
    return DropdownButtonFormField(
      isExpanded: true,
      value: items[0],
      items: items.map((String dayType) {
        return DropdownMenuItem(
          value: dayType,
          child: Text(dayType),
        );
      }).toList(),
      onChanged: (newValue) {
        if (newValue == "Normal Day" && selectedIndex == index) {
          T = 1.25;
          restDays = 21;
          if (_controller1[index].text.isEmpty) {
            _timeIn(context, index);
            setState(() {
              _isEnabled = true;
            });

            print("empty $newValue");
          } else {
            setState(() {
              _controller1[index].text = formattedTimeIn!;
              _controller2[index].text = formattedTimeOut!;
              getDifference(formattedTimeIn, formattedTimeOut);
              _controller3[index].text = '$hours.$minutes';
              _totalTPerDay(index);
              _totalMPerDay(index);
              _isEnabled = true;
            });
            print("not empty $newValue");
          }
        } else if (newValue == "Holly Day" && selectedIndex == index) {
          T = 1.5;
          restDays = 12 + 1;
          if (_controller1[index].text.isEmpty) {
            _timeIn(context, index);
            setState(() {
              _isEnabled = true;
            });
            print("empty $newValue");
          } else {
            setState(() {
              _controller1[index].text = formattedTimeIn!;
              _controller2[index].text = formattedTimeOut!;
              getDifference(formattedTimeIn, formattedTimeOut);
              _controller3[index].text = '$hours.$minutes';
              _totalTPerDay(index);
              _totalMPerDay(index);
              _isEnabled = true;
            });
            print("not empty $newValue");
          }
        } else if ((newValue == "Unuual Day" || newValue == "Sick Day") &&
            selectedIndex == index) {
          T = 0.0;
          restDays = 24;
          hours = 0;
          minutes = 0;
          setState(() {
            _isEnabled = false;
            _controller1[index].text = "  -------";
            _controller2[index].text = "  -------";
            _controller3[index].text = "0.0";
            _controller5[index].text = "0.0";
          });
        }
        print(T);
        setState(() {
          dropdownvalue = newValue!;
          print(restDays);
        });
      },
    );
  }

  _totalTPerDay(int index) {
    getDifference(_controller1[index].text, _controller2[index].text);
    setState(() {
      _controller3[index].text = '$hours.$minutes';
    });
    return _controller3[index].text;
  }

  _totalMPerDay(int index) {
    (double.tryParse(_controller3[index].text)! * T);

    setState(() {
      _controller5[index].text =
          (double.tryParse(_controller3[index].text)! * T).toStringAsFixed(2);
    });
    return _controller5[index].text;
  }

  String _timeFormated(TimeOfDay time) {
    if (time == null) return "--:--";
    return "${time.hour}:${time.minute}";
  }
}

`

May any one run my code & tell me??
i am getting the total but when the list of _controller3 changed the _controller4 keeping the same value ??


来源: stackexchange

问:
using vba to do sumif condition to create new table
Thank you for welcoming me into this community. I'm very new to vba!

Essentially my goal is to categorize different services into specific service categories. I have a table with many different service types including "Adopt- Cat", "Adopt-Dog", "Cat Training" in one row and the count for that service in the next row. And I am looking for a way to grab any row that includes "Adopt*" and "Training" into a new table and sum the count for those rows.

Currently this is my code in VBA currently. Looking forward to your support.

Please help!

```<code>Sub Sum_values_if_cells_contain_adopt_and_training()
'declare a variable
Dim ws As Worksheet
Set ws = Worksheets("catsanddogs")
'apply the formula to sum values if cells contain text

ws.Range("D1") = Application.Worksheet.SumIf(ws.Range("A1:A54"), {"adopt-*" OR "*training*"}, ws.Range("B1:B54"))

End Sub
</code>```

When I run this code, I get an error that my code is invalid.

Very new to vba. would love to hear back.

ContentLicense: CC BY-SA 4.0

Body:
Thank you for welcoming me into this community. I'm very new to vba!

Essentially my goal is to categorize different services into specific service categories. I have a table with many different service types including "Adopt- Cat", "Adopt-Dog", "Cat Training" in one row and the count for that service in the next row. And I am looking for a way to grab any row that includes "Adopt*" and "Training" into a new table and sum the count for those rows.

Currently this is my code in VBA currently. Looking forward to your support.

Please help!

Sub Sum_values_if_cells_contain_adopt_and_training()
'declare a variable
Dim ws As Worksheet
Set ws = Worksheets("catsanddogs")
'apply the formula to sum values if cells contain text

ws.Range("D1") = Application.Worksheet.SumIf(ws.Range("A1:A54"), {"adopt-*" OR "*training*"}, ws.Range("B1:B54"))

End Sub

When I run this code, I get an error that my code is invalid.

Very new to vba. would love to hear back.


问:
How can i make the output?
i have an a function which takes item[0] and item[1]

```<code>var output = filteredArr.map(function(item) {
return item[0] + "// the big space                                                                    " + item[1];
}).join("\n ");
</code>```

How can i make the big space to make output like:
a                                                                                1
The output should be on the other hands of a display. I try like this, but it takes up a lot of space and degrades the readability of the code

Title: How can i make the output?

Body:
i have an a function which takes item[0] and item[1]

var output = filteredArr.map(function(item) {
return item[0] + "// the big space                                                                    " + item[1];
}).join("\n ");

How can i make the big space to make output like:
a                                                                                1
The output should be on the other hands of a display. I try like this, but it takes up a lot of space and degrades the readability of the code


问:
Errors after coping-pasting index.html to app.js in react-app

after installing (create-react-app frontend) i copied the code in my previous index.html and pasted it in the app.js and its giving alot of errors . some of the errors say JSX element ('form'),('div'),('input'),('form') has no corresponding closing tag) but i have checked all and made sure they all have closing tags. i have also tried seching the solutions online but no answer .


问:
automatic selection of lag order in robust arima R always returns maximum number of AR lags
I am using library robustarima, which has an option auto.ar=TRUE. According to the description and the book (https://onlinelibrary-wiley-com.eur.idm.oclc.org/doi/pdf/10.1002/9781119214656 chapter 8 page 322) this function should return the appropriate lag, but when I am using it it always returns the maximum value max.p (which is also an option). The book has sample code, which I tried to run as well, but this also gives me the output. Does someone know if I am doing something wrong?

I am using library robustarima, which has an option auto.ar=TRUE. According to the description and the book (https://onlinelibrary-wiley-com.eur.idm.oclc.org/doi/pdf/10.1002/9781119214656 chapter 8 page 322) this function should return the appropriate lag, but when I am using it it always returns the maximum value max.p (which is also an option). The book has sample code, which I tried to run as well, but this also gives me the output. Does someone know if I am doing something wrong? Example:

```<code>library(robustarima)

set.seed(600)
n.innov = 300
n = 200
 theta= 0.8
n.start = n.innov - n
innov = rnorm(n.innov)

x= arima.sim(model = list(ma = theta), n, innov = innov, n.start = n.start)
ao = ifelse(runif(n)>.1, 0, rnorm(n,6,1))
ao = sign(runif(n,-1,1))*ao
y = x + ao

no=sum(ao!=0)
par(mfrow=c(2,1))
plot(x,  ylab=expression(x[t]),ylim=c(-9,9))
plot(y,  ylab=expression(y[t]),ylim=c(-9,9))
ao.times = (1:n)[ao != 0]
points(ao.times, y[ao != 0])
par(mfrow=c(1,1))

out=arima.rob(y~1, auto.ar=TRUE)
summary(out)
</code>```

Which returns

```<code>Call:
arima.rob(formula = y ~ 1, auto.ar = TRUE)

Regression model:
 y ~ 1

ARIMA model:
Ordinary differences: 0 ; AR order: 5 ; MA order: 0

Regression Coefficients:
            Value   Std. Error t value Pr(>|t|)
(Intercept) -0.0277  0.1291    -0.2143  0.8305

AR Coefficients:
      Value   Std. Error t value Pr(>|t|)
AR(1)  0.5822  0.0730     7.9749  0.0000
AR(2) -0.3314  0.0829    -3.9994  0.0001
AR(3)  0.2893  0.0837     3.4559  0.0007
AR(4) -0.2292  0.0829    -2.7659  0.0062
AR(5)  0.0792  0.0730     1.0846  0.2795

Degrees of freedom: 200 total; 194 residual
</code>```

While an AR(2) lag should be returned. Is this me or is there something wrong with the code?
Thanks

Body:
I am using library robustarima, which has an option auto.ar=TRUE. According to the description and the book (https://onlinelibrary-wiley-com.eur.idm.oclc.org/doi/pdf/10.1002/9781119214656 chapter 8 page 322) this function should return the appropriate lag, but when I am using it it always returns the maximum value max.p (which is also an option). The book has sample code, which I tried to run as well, but this also gives me the output. Does someone know if I am doing something wrong?

I am using library robustarima, which has an option auto.ar=TRUE. According to the description and the book (https://onlinelibrary-wiley-com.eur.idm.oclc.org/doi/pdf/10.1002/9781119214656 chapter 8 page 322) this function should return the appropriate lag, but when I am using it it always returns the maximum value max.p (which is also an option). The book has sample code, which I tried to run as well, but this also gives me the output. Does someone know if I am doing something wrong? Example:

library(robustarima)

set.seed(600)
n.innov = 300
n = 200
 theta= 0.8
n.start = n.innov - n
innov = rnorm(n.innov)

x= arima.sim(model = list(ma = theta), n, innov = innov, n.start = n.start)
ao = ifelse(runif(n)>.1, 0, rnorm(n,6,1))
ao = sign(runif(n,-1,1))*ao
y = x + ao

no=sum(ao!=0)
par(mfrow=c(2,1))
plot(x,  ylab=expression(x[t]),ylim=c(-9,9))
plot(y,  ylab=expression(y[t]),ylim=c(-9,9))
ao.times = (1:n)[ao != 0]
points(ao.times, y[ao != 0])
par(mfrow=c(1,1))

out=arima.rob(y~1, auto.ar=TRUE)
summary(out)

Which returns

Call:
arima.rob(formula = y ~ 1, auto.ar = TRUE)

Regression model:
 y ~ 1

ARIMA model:
Ordinary differences: 0 ; AR order: 5 ; MA order: 0

Regression Coefficients:
            Value   Std. Error t value Pr(>|t|)
(Intercept) -0.0277  0.1291    -0.2143  0.8305

AR Coefficients:
      Value   Std. Error t value Pr(>|t|)
AR(1)  0.5822  0.0730     7.9749  0.0000
AR(2) -0.3314  0.0829    -3.9994  0.0001
AR(3)  0.2893  0.0837     3.4559  0.0007
AR(4) -0.2292  0.0829    -2.7659  0.0062
AR(5)  0.0792  0.0730     1.0846  0.2795

Degrees of freedom: 200 total; 194 residual

While an AR(2) lag should be returned. Is this me or is there something wrong with the code?
Thanks


问:
nginx with frontend and backend with HTTPS
I have many doubts about this configuration of nginx in a virtual machine Ubuntu. I want to manage in the same file nginx frontend (e.g. application of React) and backend (e.g. application with Express of node.js). Besides, frontend and backend have to connect with HTTPS. At that moment, this configuration works but I don't know If it is ok.

This is my default file of nginx:

```<code>    server {
        listen 80 default_server;
        listen [::]:80 default_server;

        server_name my-domain.es www.my-domain.es;
        return 301 https://www.my-domain.es;
    }
    server {
        listen [::]:443 ssl ipv6only=on; # managed by Certbot
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/www.my-domain.es/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/www.my-domain.es/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

        root /var/www/www.my-domain.es;
        index index.html;
        server_name www.my-domain.es;

        # Frontend
        location / {
            try_files $uri /index.html =404;
        }

        # Backend
        location /api {
            proxy_pass https://127.0.0.1:3001;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }

    }
</code>```

Thanks a lot by answers!

Body:
I have many doubts about this configuration of nginx in a virtual machine Ubuntu. I want to manage in the same file nginx frontend (e.g. application of React) and backend (e.g. application with Express of node.js). Besides, frontend and backend have to connect with HTTPS. At that moment, this configuration works but I don't know If it is ok.

This is my default file of nginx:

    server {
        listen 80 default_server;
        listen [::]:80 default_server;

        server_name my-domain.es www.my-domain.es;
        return 301 https://www.my-domain.es;
    }
    server {
        listen [::]:443 ssl ipv6only=on; # managed by Certbot
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/www.my-domain.es/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/www.my-domain.es/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

        root /var/www/www.my-domain.es;
        index index.html;
        server_name www.my-domain.es;

        # Frontend
        location / {
            try_files $uri /index.html =404;
        }

        # Backend
        location /api {
            proxy_pass https://127.0.0.1:3001;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }

    }

Thanks a lot by answers!


问:
PGAFIS Extension Installation Guide
I need to install the PGAFIS on my postgress database in order to use it for a project. However, I cannot find any guide on how to compile or install the extension. Neither does the extension has any tangible document on implementation online.

I have located the github repo for pgafis but I could not go further bcos there is no guide on installation. I need every help

Title: PGAFIS Extension Installation Guide


问:
How can I automate the process of releasing the same iOS app with different branding?
Unique one but I'm sure there is a solution.

We run an app that will go onto be used by 100s of different businesses own customers.

A requirement for this is the app will need to appear in the App Store under different name + branding each time and every time.

The functionality within the app will be the same however it will be hitting different end points in places using different organisationIds.

How can we best make changes to this app such as adding features without uploading times to the app store?

Any recommendations?

We've had a look around at length but cannot seem to find a solution using Apples own products. Can't be the first to run into this surely. We specifically need this installed via the app store, can't just put the ipa file somewhere.


问:
Parameters in CATIA VBA
In CATIA, every feature have its own properties corresponding to specific addresses representing it. For example, pad.1 feature has FirstLimit as a property with Length as a parameter of it (as see in the picture). Is it possible to work with this available and default parameters or properties or features through VBA, to, for instance, change the value of some of those parameters, as the way I work with Formulas dialogue as shown in the attached picture.

Title: Parameters in CATIA VBA


问:
change parameter in a flutter package method
I added a package in my flutter web project (flutter_azure_b2c). The package is working fine but I have a problem that I dont want to pass a json file to the package method instead I want to pass the json object directly.
Can I change this by forking the github library or do you have any idea how to do this?</p>


问:
How to demonstate that 2^F(x) is compile-time knowing that F(x) is a compile-time function
Sorry for my english.
I don't know if I use the right terminology.
DEF.: F is a compile-time function if exist the Turing machine which run-time doesn't depend on the input.
I know that for the demostration I need to build a Turing-machine but I don't know how to procede; another metod I though is considering 2^F(x) a composition of compile-time function, because is compotition of 2 applied F(x) times and the text of the exercise garantees that F(x) is compile-time. For the last method I don't know if constant are compile-time.

I tried appling speed-up time but it wasn't useful.
This is a exercise proposed by my professor during the course of "calcolability and complessity" (literal translation); I'm having a lot of difficulty with finding exercise and explanation online (the language doesn't help) so if anyone suggest some exercises, texts or web-sites I would be really grateful.


问:
CyberSource Payment with Flex API V2 Token UnAuthorised issue?
When I am using cyberSource Payment with Flex V2 Token always i am getting 401 Unauthorized error.

Headear and Request API:

Request{method=POST, url=https://apitest.cybersource.com/pts/v2/payments, headers=[v-c-merchant-id:testloginshan, Accept:application/jwt, Date:Wed, 7 Dec 2022 05:44:15 GMT, Host:apitest.cybersource.com, User-Agent:Mozilla/5.0, Signature:keyid="8f5aa7fe-4746-4cf2-beae-62f74cd1e140", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="01Er6UfHx/rOC5dEsEPCFcGcDzGU0ujvEM9Lzp85RJY=", Digest:SHA-256=xLxNBV4ETfGKjD1+b1m+uPdVjA5rc3uieprBWXABvKE=], tags={class retrofit2.Invocation=com.cybersource.flex.sessions.api.FlexSessionService.sendPayment() [okhttp3.RequestBody$Companion$toRequestBody$2@1bbd119, {v-c-merchant-id=testloginshan, Accept=application/jwt, Content-Type=application/json;charset=utf-8, Date=Wed, 7 Dec 2022 05:44:15 GMT, Host=apitest.cybersource.com, User-Agent=Mozilla/5.0, Signature=keyid="8f5aa7fe-4746-4cf2-beae-62f74cd1e140", algorithm="HmacSHA256", headers="host date (request-target) digest v-c-merchant-id", signature="01Er6UfHx/rOC5dEsEPCFcGcDzGU0ujvEM9Lzp85RJY=", Digest=SHA-256=xLxNBV4ETfGKjD1+b1m+uPdVjA5rc3uieprBWXABvKE=}]}}


问:
Playlist of videos loaded in memory with PATH server
I have a table where the path of the videos uploaded to the server is saved (I can change to BYTE saved if necessary), I can't put these videos in a loop autoplay list.

I need to download videos from a server, to have them in MEMORY, and to be able to play them automatically in a LOOP, I did this for WPF with VLC libraries, but I can't find an example to do it on the WEB, currently I use BLAZOR SERVER technologies, with ASP.NET core for the backend, you can combine native html code with BLAZOR

Any help, comment or suggestion would be very helpful, thank you.


问:
This API is not accessible for external HTTP caller
Attempting to call google chat API in Postman on the developer's computer, we get the following response.

{

"error": {

"code": 403,

"message": "This API is not accessible for external HTTP caller.",

"status": "PERMISSION_DENIED"

}

}

We have authenticated using OAuth2 (apiKey/secret) with scope https://www.googleapis.com/auth/chat.messages.

We did like to use Postman to try out this API.

Is it possible to get around this error? If so, how?


问:
Order search bar mixs the information when you search a particular order
We are having a issue regarding the search bar orders  woocommerce.

When we try to search a particular order through the search bar  it mixs the orders and if you try to find any order reference with respect a particular order it still mixs the orders and it doesn't displays the order searched.  Any idea?


问:
Closure field type errors
I'm trying to write a Jest test (using Typescript) for a function that gets and displays error data returned by a Java back-end when an API call fails. The error data is passed through a pair of custom headers. The front-end function works just fine in "real life", but trying to simulate the error return for unit tests is driving me a little batty. The HttpErrorResponse object lazy-parses the headers, which means at first blush looking at the object none of the header data exists. I tried constructing HttpHeader with the mocked data I want and then constructing a HttpErrorResponse from the header and a status, and it doesn't work - my code, which reads header data just fine when running for real, cannot see the http headers created by the mock (but that isn't the subject of this question).

So I decided to try duck-typing a mock error object (even though Typescript puts up a little bit of a fight) and my duck-typed error object isn't quite working and I can't figure out why. Here is the closure I built to stand in for an HttpErrorResponse, with the intent that it responds only to the data and functions that the function I'm unit-testing requires:

```<code>      let duckedResponse = (function (_status, _message) {
        return {
          status: _status,
          headers: function() {
            return {
              get : function (key : string) : string {
                if (key == 'MYERR-CODE')
                {
                  return 'ABC123';
                }
                else if (key == 'MYERR-MESSAGE')
                {
                  return _message;
                }
                return '';
              }
            };
          }
        };
      });

      let error : HttpErrorResponse = duckedResponse(400, 'This is my message') as any as HttpErrorResponse;

      fixture.StandardErrorHandler(error);
</code>```

There is a line of code in the StandardErrorHandler function that does this:

```<code>    message = error.headers.get("MYERR-MESSAGE");
</code>```

and, when running the Jest test, I get this:

```<code>TypeError: error.headers.get is not a function
    message = error.headers.get("MYERR-MESSAGE");
                            ^
</code>```

I can't figure out what I've done wrong so that "get" is not a function. Of course, at the end of the day, I really just need a working solution for passing an error object to my error handling function such that it can successfully pull faked/mocked headers and act on them; that being said, if I can't figure out my bug and get this technique to work then that will be the subject of a different SO question. This question is about my apparently bad closure.

Title: Closure field type errors

Body:
I'm trying to write a Jest test (using Typescript) for a function that gets and displays error data returned by a Java back-end when an API call fails. The error data is passed through a pair of custom headers. The front-end function works just fine in "real life", but trying to simulate the error return for unit tests is driving me a little batty. The HttpErrorResponse object lazy-parses the headers, which means at first blush looking at the object none of the header data exists. I tried constructing HttpHeader with the mocked data I want and then constructing a HttpErrorResponse from the header and a status, and it doesn't work - my code, which reads header data just fine when running for real, cannot see the http headers created by the mock (but that isn't the subject of this question).

So I decided to try duck-typing a mock error object (even though Typescript puts up a little bit of a fight) and my duck-typed error object isn't quite working and I can't figure out why. Here is the closure I built to stand in for an HttpErrorResponse, with the intent that it responds only to the data and functions that the function I'm unit-testing requires:

      let duckedResponse = (function (_status, _message) {
        return {
          status: _status,
          headers: function() {
            return {
              get : function (key : string) : string {
                if (key == 'MYERR-CODE')
                {
                  return 'ABC123';
                }
                else if (key == 'MYERR-MESSAGE')
                {
                  return _message;
                }
                return '';
              }
            };
          }
        };
      });

      let error : HttpErrorResponse = duckedResponse(400, 'This is my message') as any as HttpErrorResponse;

      fixture.StandardErrorHandler(error);

There is a line of code in the StandardErrorHandler function that does this:

    message = error.headers.get("MYERR-MESSAGE");

and, when running the Jest test, I get this:

TypeError: error.headers.get is not a function
    message = error.headers.get("MYERR-MESSAGE");
                            ^

I can't figure out what I've done wrong so that "get" is not a function. Of course, at the end of the day, I really just need a working solution for passing an error object to my error handling function such that it can successfully pull faked/mocked headers and act on them; that being said, if I can't figure out my bug and get this technique to work then that will be the subject of a different SO question. This question is about my apparently bad closure.


问:
Junit Test cases for PubSub Publish message
Facing issue while writing the Junit test cases for below code.</p>
```<code>public String publishJSON(String json) throws InterruptedException, IOException, ExecutionException {
        log.info(" Publishing payload to: "+config.getTopicId());
        TopicName topicName=TopicName.of(config.getPubsubProjectId(),config.getTopicId());
        Publisher publisher=null;
        try {
             publisher =
                    Publisher.newBuilder(topicName)
                        .build();
              ByteString data = ByteString.copyFromUtf8(json);
              PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
              ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
              String messageId = messageIdFuture.get();
              log.info("Published message ID: " + messageId);
           return messageId;
        } catch (ExecutionException e) {
            log.error("Error while publishing messsage" + e.getMessage());
            throw e;
        } catch (IOException e) {
            log.error( "PubSub exception "+ e.getMessage());
            throw e;
        } catch (InterruptedException e) {
            log.error("Connection making exception for PubSub" + e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error( "publishJSON Error : "+ e.getMessage());
            throw e;
        }
        finally {
            if (publisher != null) {
                // When finished with the publisher, shutdown to free up resources.
                publisher.shutdown();
                publisher.awaitTermination(1, TimeUnit.MINUTES);
            }
        }
    }
</code>```

Body:
Facing issue while writing the Junit test cases for below code.

public String publishJSON(String json) throws InterruptedException, IOException, ExecutionException {
        log.info(" Publishing payload to: "+config.getTopicId());
        TopicName topicName=TopicName.of(config.getPubsubProjectId(),config.getTopicId());
        Publisher publisher=null;
        try {
             publisher =
                    Publisher.newBuilder(topicName)
                        .build();
              ByteString data = ByteString.copyFromUtf8(json);
              PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
              ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
              String messageId = messageIdFuture.get();
              log.info("Published message ID: " + messageId);
           return messageId;
        } catch (ExecutionException e) {
            log.error("Error while publishing messsage" + e.getMessage());
            throw e;
        } catch (IOException e) {
            log.error( "PubSub exception "+ e.getMessage());
            throw e;
        } catch (InterruptedException e) {
            log.error("Connection making exception for PubSub" + e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error( "publishJSON Error : "+ e.getMessage());
            throw e;
        }
        finally {
            if (publisher != null) {
                // When finished with the publisher, shutdown to free up resources.
                publisher.shutdown();
                publisher.awaitTermination(1, TimeUnit.MINUTES);
            }
        }
    }


问:
PostgreSQL - Unexpected Behavior: PRIMARY KEY (NEW.id reference in Trigger Function) increments during failed INSERTS, despite row count unchanged
I am experiencing an issue while debugging this postgresql trigger function. While attempting to insert data and observe its result, I am getting errors (expected during the debug process). There have been no successful inserts, and all tables have 0 rows despite my (failed) tests while debugging -- this is also expected. But, for some unknown reason, my reference to NEW.id is incrementing with each failed test. NEW.id is supposed to be the primary key value of the record being inserted. The primary key is supposed to auto-increment after each successful insert (like 0, 1, 2, 3, ...). So how is it possible that NEW.id is incrementing with each failed record INSERT despite row count remaining at 0?

This behavior is preventing me from moving forward in testing. This behavior breaks the logic I am relying on to keep the database clean and structured.

Below I will provide a copy of the trigger function. Below that, I will provide a copy of the error as I see it,

```<code>-- FUNCTION: public.distribute_process_data()

-- DROP FUNCTION IF EXISTS public.distribute_process_data();

CREATE OR REPLACE FUNCTION public.distribute_process_data()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE
    time_stamp timestamp;
    source_id int;
    medium_id int;
    country_id int;
    request_id int;
    error_id int;
    success bool;
BEGIN
    select CURRENT_TIMESTAMP into time_stamp;

    INSERT INTO
        sources(source, category)
        VALUES(NEW.source, NEW.category) ON CONFLICT (source) DO NOTHING
        RETURNING id INTO source_id;

    INSERT INTO
        mediums(sources_id, medium)
        VALUES(source_id, NEW.medium) ON CONFLICT (sources_id, medium) DO NOTHING
        RETURNING id INTO medium_id;

    INSERT INTO
        countries(country)
        VALUES(NEW.country) ON CONFLICT (country) DO NOTHING
        RETURNING id INTO country_id;

    INSERT INTO
        requests(sources_id, request_jsonstring, request_md5hash)
        VALUES(source_id, NEW.request, md5(NEW.request::text)) ON CONFLICT (request_md5hash) DO NOTHING
        RETURNING id INTO request_id;

    CASE
        WHEN NEW.error IS NOT NULL THEN
            INSERT INTO
                errors(timestamp, processes_id, error)
                VALUES(time_stamp, NEW.id, NEW.error)
                RETURNING id INTO error_id;
            select FALSE INTO success;
        ELSE
            select NULL INTO error_id;
            select TRUE INto success;
    END CASE;

    INSERT INTO
        processes(
            id, timestamp, requests_id, errors_id, sources_id, mediums_id, countries_id, successful,
            date, web_visits, conversions, ad_impressions, ad_clicks, ad_cost, companygo_ad_visits,
            companynetwork_ad_visits, companygo_ad_visits_bounce_rate, downloads_desktop, downloads_mobile,
            initiated_registrations, completed_registrations, paid_users, revenue
        )
        VALUES(
            NEW.id, time_stamp, request_id, error_id, medium_id, country_id, success,
            NEW.date, NEW.web_visits, NEW.conversions, NEW.ad_impressions, NEW.ad_clicks, NEW.ad_cost,
            NEW.companygo_ad_visits, NEW.companynetwork_ad_visits, NEW.companygo_ad_visits_bounce_rate,
            NEW.downloads_desktop, NEW.downloads_mobile, NEW.initiated_registrations, NEW.completed_registrations,
            NEW.paid_users, NEW.revenue
        );
    RETURN trigger;
END;
$BODY$;

ALTER FUNCTION public.distribute_process_data()
    OWNER TO postgres;
</code>```

Here is the error:

```<code>---------------------------------------------------------------------------
ForeignKeyViolation                       Traceback (most recent call last)
Cell In [4], line 1
----> 1 cursor.execute(sql)

ForeignKeyViolation: insert or update on table "errors" violates foreign key constraint "processes_fkey"
DETAIL:  Key (processes_id)=(13) is not present in table "processes".
CONTEXT:  SQL statement "INSERT INTO
                errors(timestamp, processes_id, error)
                VALUES(time_stamp, NEW.id, NEW.error)
                RETURNING id"
PL/pgSQL function distribute_process_data() line 34 at SQL statement
</code>```

Notice where it says (processes_id)=(13). That value of 13 began at 1. After each failed INSERT during debug, it incremented by +2. So it progressed like so: 1 -> 3 -> 5 -> 7 -> 9 -> .... Since it is referencing NEW.id though, the expected behavior is that it remains at value 1. Because my tests are failing, therefore row count remains 0, therefore PRIMARY KEY should not be incrementing.

Any help or leads here is very much appreciated.
Thank you.

Body:
I am experiencing an issue while debugging this postgresql trigger function. While attempting to insert data and observe its result, I am getting errors (expected during the debug process). There have been no successful inserts, and all tables have 0 rows despite my (failed) tests while debugging -- this is also expected. But, for some unknown reason, my reference to NEW.id is incrementing with each failed test. NEW.id is supposed to be the primary key value of the record being inserted. The primary key is supposed to auto-increment after each successful insert (like 0, 1, 2, 3, ...). So how is it possible that NEW.id is incrementing with each failed record INSERT despite row count remaining at 0?

This behavior is preventing me from moving forward in testing. This behavior breaks the logic I am relying on to keep the database clean and structured.

Below I will provide a copy of the trigger function. Below that, I will provide a copy of the error as I see it,

-- FUNCTION: public.distribute_process_data()

-- DROP FUNCTION IF EXISTS public.distribute_process_data();

CREATE OR REPLACE FUNCTION public.distribute_process_data()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE
    time_stamp timestamp;
    source_id int;
    medium_id int;
    country_id int;
    request_id int;
    error_id int;
    success bool;
BEGIN
    select CURRENT_TIMESTAMP into time_stamp;

    INSERT INTO
        sources(source, category)
        VALUES(NEW.source, NEW.category) ON CONFLICT (source) DO NOTHING
        RETURNING id INTO source_id;

    INSERT INTO
        mediums(sources_id, medium)
        VALUES(source_id, NEW.medium) ON CONFLICT (sources_id, medium) DO NOTHING
        RETURNING id INTO medium_id;

    INSERT INTO
        countries(country)
        VALUES(NEW.country) ON CONFLICT (country) DO NOTHING
        RETURNING id INTO country_id;

    INSERT INTO
        requests(sources_id, request_jsonstring, request_md5hash)
        VALUES(source_id, NEW.request, md5(NEW.request::text)) ON CONFLICT (request_md5hash) DO NOTHING
        RETURNING id INTO request_id;

    CASE
        WHEN NEW.error IS NOT NULL THEN
            INSERT INTO
                errors(timestamp, processes_id, error)
                VALUES(time_stamp, NEW.id, NEW.error)
                RETURNING id INTO error_id;
            select FALSE INTO success;
        ELSE
            select NULL INTO error_id;
            select TRUE INto success;
    END CASE;

    INSERT INTO
        processes(
            id, timestamp, requests_id, errors_id, sources_id, mediums_id, countries_id, successful,
            date, web_visits, conversions, ad_impressions, ad_clicks, ad_cost, companygo_ad_visits,
            companynetwork_ad_visits, companygo_ad_visits_bounce_rate, downloads_desktop, downloads_mobile,
            initiated_registrations, completed_registrations, paid_users, revenue
        )
        VALUES(
            NEW.id, time_stamp, request_id, error_id, medium_id, country_id, success,
            NEW.date, NEW.web_visits, NEW.conversions, NEW.ad_impressions, NEW.ad_clicks, NEW.ad_cost,
            NEW.companygo_ad_visits, NEW.companynetwork_ad_visits, NEW.companygo_ad_visits_bounce_rate,
            NEW.downloads_desktop, NEW.downloads_mobile, NEW.initiated_registrations, NEW.completed_registrations,
            NEW.paid_users, NEW.revenue
        );
    RETURN trigger;
END;
$BODY$;

ALTER FUNCTION public.distribute_process_data()
    OWNER TO postgres;

Here is the error:

---------------------------------------------------------------------------
ForeignKeyViolation                       Traceback (most recent call last)
Cell In [4], line 1
----> 1 cursor.execute(sql)

ForeignKeyViolation: insert or update on table "errors" violates foreign key constraint "processes_fkey"
DETAIL:  Key (processes_id)=(13) is not present in table "processes".
CONTEXT:  SQL statement "INSERT INTO
                errors(timestamp, processes_id, error)
                VALUES(time_stamp, NEW.id, NEW.error)
                RETURNING id"
PL/pgSQL function distribute_process_data() line 34 at SQL statement

Notice where it says (processes_id)=(13). That value of 13 began at 1. After each failed INSERT during debug, it incremented by +2. So it progressed like so: 1 -> 3 -> 5 -> 7 -> 9 -> .... Since it is referencing NEW.id though, the expected behavior is that it remains at value 1. Because my tests are failing, therefore row count remains 0, therefore PRIMARY KEY should not be incrementing.

Any help or leads here is very much appreciated.
Thank you.


问:
finding and updating an object in a mongo db document in node js
So im trying to find and update a documnet's nested object in a mongo db collection. Im using the exact procedure i used on updating the other fields in that document but its failing to find and update on this specific execution. Weird thing is when i do a findOne its returning the document successfully but as soon as i findOneAndUpdate its not executing.

this is the implementation thats giving me problems
enter image description here

and this is an example of the implementations that are working
enter image description here

i was expecting that same document thats being returned to also be updated


问:
np.percentile along with using for loop and specific end point for the first roll
I have a time series data. I was doing Historical Simulation, and I want to apply np.percentile for my series of data. But the condition is, the np.percentile should start from 0th row and end in 100th row for the first number generation, then for the second number generation np.percentile should take the array as, start in row 1 and end in row 101, so on and so forth the series ends.Basically I want the series to be generated with the percentile values, but with the condition that I stated above

I have trying applying

```<code>def 95_percentile(L):
first_item = L[0]
for i in range (1, len(L)):
L[i-1] = L[i]
L[-1] = first_item
</code>```

along with
Df = np.percentile(arr, 0.05))
but not very sure, how to do that.

Body:
I have a time series data. I was doing Historical Simulation, and I want to apply np.percentile for my series of data. But the condition is, the np.percentile should start from 0th row and end in 100th row for the first number generation, then for the second number generation np.percentile should take the array as, start in row 1 and end in row 101, so on and so forth the series ends.Basically I want the series to be generated with the percentile values, but with the condition that I stated above

I have trying applying

def 95_percentile(L):
first_item = L[0]
for i in range (1, len(L)):
L[i-1] = L[i]
L[-1] = first_item

along with
Df = np.percentile(arr, 0.05))
but not very sure, how to do that.


问:
Back testing trading strategy
am fairly new to programming and been searching how to go about putting take profit and stop loss in my python code. My historical data is in panda dataframe. I already have a trigger for my entry but i cant seems to find in the next preceeding rows:
Which hits first? Tp or Sl? I want to count the number of times to get the percentage of succes in each entry

I have searching in the web what are the best options but got nothing so far

Title: Back testing trading strategy


问:
Adding gprof to C++ Program that takes in arguments
I have been using gprof recently and now I was trying to include this on a big project but the thing is that since my executable needs a argument to work every time I execute the gprof like:

grof <executable> <argv[1]> gmon.out

I get an error saying that gprof: file <argv[1] does not appear to be in gmon.out format. Does anyone know how can I make this work when I have to pass an argument to my executable  ?
Thanks


问:
how to show text suggestion poppoer in content editable
I want to show a popper based on caret position like this

```<code>I have tried with tippy js with popper js configuration but this did not work.i need to show a dynamic popper based on caret position which position will be changed while typing.

 <div contenteditable="true">
        <p></p>
    </div>

</code>```
```<code>    tippy('div', {
        content: 'tooltip!',
        followCursor: true,
        trigger: 'keypress',
        placement: 'left',
    });
</code>```
```<code>this doesn't move the tooltip while typing. Also tried to change offset but did not work and the tooltip position stays at end every time.
</code>```

Body:
I want to show a popper based on caret position like this

I have tried with tippy js with popper js configuration but this did not work.i need to show a dynamic popper based on caret position which position will be changed while typing.

    tippy('div', {
        content: 'tooltip!',
        followCursor: true,
        trigger: 'keypress',
        placement: 'left',
    });

this doesn't move the tooltip while typing. Also tried to change offset but did not work and the tooltip position stays at end every time.


问:
Why the web workers files have to be inside my public folder of the React application?
I've ran into a problem trying to understand how web workers might be used inside React apps:
Uncaught SyntaxError: Unexpected token '<' (at worker.js:1:1)
I did a research on StackOverflow and found out that this problem could be solved just by moving the web worker file to the public folder of my React app. Can someone explain why did it worked?

This works:

This doesn't work and gives error:

(Uncaught SyntaxError: Unexpected token '<' (at worker.js:1:1))

The code (I don't think it matters but anyway):

```<code>//App.js
import React from "react";

const App = () => {
  console.log("hey");
  const worker = new Worker("worker.js");
  return <div>App</div>;
};

export default App;
</code>```
```<code>//worker.js
console.log("work");
</code>```

Body:
I've ran into a problem trying to understand how web workers might be used inside React apps:
Uncaught SyntaxError: Unexpected token '<' (at worker.js:1:1)
I did a research on StackOverflow and found out that this problem could be solved just by moving the web worker file to the public folder of my React app. Can someone explain why did it worked?

This works:

This doesn't work and gives error:

(Uncaught SyntaxError: Unexpected token '<' (at worker.js:1:1))

The code (I don't think it matters but anyway):

//App.js
import React from "react";

const App = () => {
  console.log("hey");
  const worker = new Worker("worker.js");
  return
App
;
};

export default App;

//worker.js
console.log("work");


问:
How can I ensure css hover state is active when an element is revealed below the cursor?
When a div containing links with a hover property is changed from display:none to display:block, if the mouse pointer is over the links, the hover state is not triggered until the pointer is moved.
Is there a way in javascript to either trigger the hover state or force it to be evaluated when the div is revealed.

To explain the context, I am attempting to implement an early Macintosh dropdown list interface style that involves revealing the list options on top of the drop down list when the list box is clicked on.

When I click on the dropdown div, the dropdown-content is displayed but the top item is not highlighted until you move the mouse.

function openMenu(mybutton) {
    var els = document.getElementsByClassName("dropdown-content");
    var els1 = document.getElementsByClassName("dropdown");
    for(var i = 0; i < els1.length; i++) { // Step through all dropdown elements
        if (els1[i] === mybutton) {
            els[i].classList.toggle("show");
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdownContainer {
    border: 1px black solid;
    position:relative;
  width:150px;
}

.dropdown {
    position: relative;
}

.dropdown-content {
    display: none;
    position:absolute;
    top:-1px;
    left:-1px;
  width:150px;
    background-color: white;
    min-width: 120px;
    white-space: nowrap;
    z-index: 1;
    border: 1px #000 solid;
    border-bottom-width: 1px;
}

.dropdown-content a {
  float:none;
  color: black;
  padding: 4px 10px 4px 15px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover, .dropdown-content a:focus {
  background-color: black;
  color: white;
}

.show {
  display: block;
}</code>```

        All Categories

        All Categories
        Boards
        Cables
        Memory

```

I was able to make the first line initially highlight by changing the focus to the first link when the dropdown-content is opened but the problem was then that the the first link stayed highlighted when you moved the mouse over the other links.

Body:
When a div containing links with a hover property is changed from display:none to display:block, if the mouse pointer is over the links, the hover state is not triggered until the pointer is moved.
Is there a way in javascript to either trigger the hover state or force it to be evaluated when the div is revealed.

To explain the context, I am attempting to implement an early Macintosh dropdown list interface style that involves revealing the list options on top of the drop down list when the list box is clicked on.

When I click on the dropdown div, the dropdown-content is displayed but the top item is not highlighted until you move the mouse.

function openMenu(mybutton) {
    var els = document.getElementsByClassName("dropdown-content");
    var els1 = document.getElementsByClassName("dropdown");
    for(var i = 0; i < els1.length; i++) { // Step through all dropdown elements
        if (els1[i] === mybutton) {
            els[i].classList.toggle("show");
        }
    }
}

.dropdownContainer {
    border: 1px black solid;
    position:relative;
  width:150px;
}

.dropdown {
    position: relative;
}

.dropdown-content {
    display: none;
    position:absolute;
    top:-1px;
    left:-1px;
  width:150px;
    background-color: white;
    min-width: 120px;
    white-space: nowrap;
    z-index: 1;
    border: 1px #000 solid;
    border-bottom-width: 1px;
}

.dropdown-content a {
  float:none;
  color: black;
  padding: 4px 10px 4px 15px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover, .dropdown-content a:focus {
  background-color: black;
  color: white;
}

.show {
  display: block;
}

        All Categories

        All Categories
        Boards
        Cables
        Memory

I was able to make the first line initially highlight by changing the focus to the first link when the dropdown-content is opened but the problem was then that the the first link stayed highlighted when you moved the mouse over the other links.


问:
Vite esbuild failing for old Non-ESM package
I'm trying to use glsl-transpiler(https://github.com/stackgl/glsl-transpiler) with my vite project but am running into issues with esbuild, which outputs

[ERROR] [plugin vite:dep-pre-bundle] Failed to resolve entry for package "escaper". The package may have incorrect main/module/exports specified in its package.json.

Adding optimizeDeps: {exclude:['glsl-transpiler']} to defineConfig in vite.config.js allows the app to build, but I get a require is not defined error when I try to use the package due to the https://github.com/stackgl/glsl-transpiler/blob/master/index.js ll:8.

Does anyone know how I can successfully use this old package and its old dependencies in my project?


问:
NodeJS - Import Directly Inside Function While Preserving TypeScript Autocompletion
I'm working on migrating my Firebase Cloud Functions project from JavaScript to TypeScript.

In my existing codebase, to reduce the time taken by cold starts and to be efficient with resources, I would import necessary modules/files within the specific functions that require them, instead of importing at the top-level. I would do it via something like const myPackage = require('helpful-module');.

Now that I'm using TypeScript, I would like my IDE to recognise the available methods and attributes on the code I import. I find that using the require function does not do that, and only when using the import statement do I get the autocompletion I want.

The problem is that when I put the import statement at the top of the individual function that requires it, I get the following error:

An import declaration can only be used at the top level of a namespace
or module.

How can I get TypeScript autocomplete on imported files, while also importing only within the functions that require that file/module?


问:
Django rosetta is saving translation but not showing new translations until the server (docker) restart
I'm using rosetta with default settings and it shows new translations in local server(no docker).
but in production, I'm using docker and it's not showing updates until restart.

docker-compose.yml:

```<code>version: '3'

volumes:
  production_postgres_data: { }
  # django
  production_temp_data: { }
  production_media: { }
  production_static: { }
  production_locale: { }
services:
  django:
    build:
      context: .
      dockerfile: ./compose/production/django/Dockerfile
    volumes:
      - production_temp_data:/tmp/
      - production_media:/app/media/
      - production_static:/app/staticfiles/
      - production_locale:/app/locale/
    depends_on:
      - postgres
    env_file:
      - ./.env
    command: /start
    restart: always
    logging:
      driver: "json-file"
      options:
        max-size: "100m"
        max-file: "10"

  ...
</code>```

django start command:

```<code>#!/bin/bash

set -o errexit
set -o pipefail
set -o nounset

python /app/manage.py collectstatic --noinput
python /app/manage.py makemessages --all --ignore=venv
python /app/manage.py compilemessages --ignore=venv
/usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 -w 1 --threads 1 --access-logfile - --error-logfile - --log-level info --capture-output --enable-stdio-inheritance --chdir=/app --timeout 180
</code>```
```<code>django==4.1.3
gunicorn==20.1.0
django-rosetta==0.9.8
</code>```

There is no logs to debug. tried with ROSETTA_WSGI_AUTO_RELOAD=True but it didn't work.

Body:
I'm using rosetta with default settings and it shows new translations in local server(no docker).
but in production, I'm using docker and it's not showing updates until restart.

docker-compose.yml:

version: '3'

volumes:
  production_postgres_data: { }
  # django
  production_temp_data: { }
  production_media: { }
  production_static: { }
  production_locale: { }
services:
  django:
    build:
      context: .
      dockerfile: ./compose/production/django/Dockerfile
    volumes:
      - production_temp_data:/tmp/
      - production_media:/app/media/
      - production_static:/app/staticfiles/
      - production_locale:/app/locale/
    depends_on:
      - postgres
    env_file:
      - ./.env
    command: /start
    restart: always
    logging:
      driver: "json-file"
      options:
        max-size: "100m"
        max-file: "10"

  ...

django start command:

#!/bin/bash

set -o errexit
set -o pipefail
set -o nounset

python /app/manage.py collectstatic --noinput
python /app/manage.py makemessages --all --ignore=venv
python /app/manage.py compilemessages --ignore=venv
/usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 -w 1 --threads 1 --access-logfile - --error-logfile - --log-level info --capture-output --enable-stdio-inheritance --chdir=/app --timeout 180

django==4.1.3
gunicorn==20.1.0
django-rosetta==0.9.8

There is no logs to debug. tried with ROSETTA_WSGI_AUTO_RELOAD=True but it didn't work.