问:
How to grow or shrink the MainWinodw based on content Widgets in PyQt5?
My problem: How to grow or shrink the main window size  based on its dependent widget?  Here is my code. In My code, I use StackLayout, group box, Labels, Pushbutton, and QLineedit.  If I change the Item in the first combo box from "Excel" to "CSV", the item will change and display the contents. But In that Place, My necessity is to change the main window size. That is the main window will become shrink to its content. If I select "CSV" to "Excel", then Mainwindow will grow and show all contents.</p>
```<code>import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QFileDialog,QPushButton, QLabel, QVBoxLayout,
                      QHBoxLayout,QLineEdit,QSizePolicy,QComboBox,QStyle,QStyleFactory,QGroupBox,QStackedWidget,
                      QFrame)
from PyQt5.QtGui import QFont,QIcon
from PyQt5.QtCore import QDir,Qt,QRect,QPoint

combo_box_data_source_type_item = ["Excel/","CSV/","JSON/","XML/"]
combo_box_excel_available_sheets_item = ["All"]
combo_box_excel_available_Columns_item = ["All"]

class MyStackedlayout(QStackedWidget):
    def minimumSize(self):
        if self.currentWidget():
            s = self.currentWidget().minimumSize()
            if s.isEmpty():
                s = self.currentWidget().minimumSizeHint()
                return s
            return super().minimumSize()

class DialogApp(QWidget):
   def __init__(self):
      super().__init__()

      self.style_window = QStyleFactory.create("Windows")
      self.current_data_source_type_index = 0
      self.current_data_source_type_text = ""

      self.overall_frame = QFrame()
      self.overall_frame_layout = QVBoxLayout(self.overall_frame)

      self.left_layout = QVBoxLayout()
      self.main_layout = QHBoxLayout()
      self.main_frame = QFrame()
      self.main_frame_layout = QVBoxLayout()
      self.overall_frame_layout.addLayout(self.left_layout)
      self.main_layout.addWidget(self.overall_frame)
      self.setLayout(self.main_layout)
      self.setLayout(self.main_frame_layout)

      self.lbl_data_source_type = QLabel("Data Source Type")
      self.lbl_data_source_type.adjustSize()
      self.lbl_input_file = QLabel("Input File")
      self.lbl_input_file.adjustSize()

      self.combobox_data_source_type = QComboBox()
      self.combobox_data_source_type.setFixedSize(420,40)
      self.combobox_data_source_type.setFont(QFont("Lucida Sans Unicode",11 ))
      self.combobox_data_source_type.addItems(combo_box_data_source_type_item)
      self.combobox_data_source_type.setCurrentIndex(0)
      self.current_data_source_type_index = 0
      self.current_data_source_type_text = self.combobox_data_source_type.currentText()
      self.combobox_data_source_type.currentIndexChanged.connect(self.selectionchange_data_source_type)

      self.textbox_file_path = QLineEdit()
      self.textbox_file_path.setFixedSize(376,40)
      self.textbox_file_path.setReadOnly(True)

      self.button_open_path = QPushButton()
      self.button_open_path.setObjectName("ob_btn_openpath")
      self.button_open_path.setFocusPolicy(Qt.NoFocus)
      self.button_open_path.setFixedSize(40,40)
      self.button_open_path.setIcon((QIcon(self.style_window.standardIcon(QStyle.SP_DialogOpenButton))))
      self.button_open_path.clicked.connect(self.get_text_file)

      self.input_file_path_hbox= QHBoxLayout()
      self.input_file_path_hbox.addWidget(self.textbox_file_path)
      self.input_file_path_hbox.addWidget(self.button_open_path)
      self.input_file_path_hbox.setSpacing(4)
      self.input_file_path_hbox.setContentsMargins(0,0,0,0)
      self.input_file_path_hbox.setAlignment(Qt.AlignLeft)

      self.groupbox_data_souce_options = QGroupBox("Data Source Options")
      self.groupbox_data_souce_options.setFixedWidth(420)

      self.lbl_available_sheets = QLabel("Available Sheets")
      self.lbl_available_sheets.adjustSize()
      self.lbl_available_columns = QLabel("Available Columns")
      self.lbl_available_columns.adjustSize()
      self.combobox_available_sheets = QComboBox()
      self.combobox_available_sheets.setFixedSize(400,40)
      self.combobox_available_sheets.setFont(QFont("Lucida Sans Unicode", 11))
      self.combobox_available_sheets.setCurrentIndex(0)

      self.groupbox_excel_layout = QVBoxLayout()
      self.groupbox_data_souce_options.setLayout(self.groupbox_excel_layout)
      self.groupbox_excel_layout.addWidget(self.lbl_available_sheets)
      self.groupbox_excel_layout.addWidget(self.combobox_available_sheets)
      self.groupbox_excel_layout.addWidget(self.lbl_available_columns)
      self.groupbox_excel_layout.addStretch()

      self.dialog = QFileDialog()
      self.dialog.setWindowTitle("Pick File to Import")
      self.dialog.setViewMode(QFileDialog.ViewMode.Detail)

      self.stackwidget = MyStackedlayout()

      self.left_layout.addStretch()
      self.left_layout.addWidget(self.lbl_data_source_type)
      self.left_layout.addWidget(self.combobox_data_source_type)
      self.left_layout.addWidget(self.lbl_input_file)
      self.left_layout.addLayout(self.input_file_path_hbox)
      self.left_layout.setAlignment(Qt.AlignLeft)
      self.left_layout.addWidget(self.stackwidget)
      self.stackwidget.addWidget(self.groupbox_data_souce_options)
      self.left_layout.addStretch()

   def selectionchange_data_source_type(self,index):
      self.current_data_source_type_index = index
      self.current_data_source_type_text = self.combobox_data_source_type.currentText()
      if self.current_data_source_type_text.split('/')[0] == "Excel":
         self.stackwidget.setCurrentWidget(self.groupbox_data_souce_options)
      elif self.current_data_source_type_text.split('/')[0] == "CSV":
         lbl1 = QLabel("Csv Group Box")
         self.stackwidget.addWidget(lbl1)
         self.stackwidget.setCurrentWidget(lbl1)

      stackwidget_resize = MyStackedlayout.minimumSize(self.stackwidget)
      # print(stackwidget_resize)
      self.stackwidget.resize(stackwidget_resize)

   def get_text_file(self):

      if self.current_data_source_type_text.split('/')[0] == "Excel":
         self.dialog.setNameFilters(["Excel File (*.xlsx *.xls)"])
      elif self.current_data_source_type_text.split('/')[0] == "CSV":
         self.dialog.setNameFilters(["CSV File (*.csv)"])

      self.dialog.setFileMode(QFileDialog.ExistingFiles)
      self.dialog.fileSelected.connect(self.file_selected)

if __name__ == '__main__':
   app = QApplication(sys.argv)
   demo = DialogApp()
   demo.show()
   sys.exit(app.exec_())
</code>```

Body:
My problem: How to grow or shrink the main window size  based on its dependent widget?  Here is my code. In My code, I use StackLayout, group box, Labels, Pushbutton, and QLineedit.  If I change the Item in the first combo box from "Excel" to "CSV", the item will change and display the contents. But In that Place, My necessity is to change the main window size. That is the main window will become shrink to its content. If I select "CSV" to "Excel", then Mainwindow will grow and show all contents.

import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QFileDialog,QPushButton, QLabel, QVBoxLayout,
                      QHBoxLayout,QLineEdit,QSizePolicy,QComboBox,QStyle,QStyleFactory,QGroupBox,QStackedWidget,
                      QFrame)
from PyQt5.QtGui import QFont,QIcon
from PyQt5.QtCore import QDir,Qt,QRect,QPoint

combo_box_data_source_type_item = ["Excel/","CSV/","JSON/","XML/"]
combo_box_excel_available_sheets_item = ["All"]
combo_box_excel_available_Columns_item = ["All"]

class MyStackedlayout(QStackedWidget):
    def minimumSize(self):
        if self.currentWidget():
            s = self.currentWidget().minimumSize()
            if s.isEmpty():
                s = self.currentWidget().minimumSizeHint()
                return s
            return super().minimumSize()

class DialogApp(QWidget):
   def __init__(self):
      super().__init__()

      self.style_window = QStyleFactory.create("Windows")
      self.current_data_source_type_index = 0
      self.current_data_source_type_text = ""

      self.overall_frame = QFrame()
      self.overall_frame_layout = QVBoxLayout(self.overall_frame)

      self.left_layout = QVBoxLayout()
      self.main_layout = QHBoxLayout()
      self.main_frame = QFrame()
      self.main_frame_layout = QVBoxLayout()
      self.overall_frame_layout.addLayout(self.left_layout)
      self.main_layout.addWidget(self.overall_frame)
      self.setLayout(self.main_layout)
      self.setLayout(self.main_frame_layout)

      self.lbl_data_source_type = QLabel("Data Source Type")
      self.lbl_data_source_type.adjustSize()
      self.lbl_input_file = QLabel("Input File")
      self.lbl_input_file.adjustSize()

      self.combobox_data_source_type = QComboBox()
      self.combobox_data_source_type.setFixedSize(420,40)
      self.combobox_data_source_type.setFont(QFont("Lucida Sans Unicode",11 ))
      self.combobox_data_source_type.addItems(combo_box_data_source_type_item)
      self.combobox_data_source_type.setCurrentIndex(0)
      self.current_data_source_type_index = 0
      self.current_data_source_type_text = self.combobox_data_source_type.currentText()
      self.combobox_data_source_type.currentIndexChanged.connect(self.selectionchange_data_source_type)

      self.textbox_file_path = QLineEdit()
      self.textbox_file_path.setFixedSize(376,40)
      self.textbox_file_path.setReadOnly(True)

      self.button_open_path = QPushButton()
      self.button_open_path.setObjectName("ob_btn_openpath")
      self.button_open_path.setFocusPolicy(Qt.NoFocus)
      self.button_open_path.setFixedSize(40,40)
      self.button_open_path.setIcon((QIcon(self.style_window.standardIcon(QStyle.SP_DialogOpenButton))))
      self.button_open_path.clicked.connect(self.get_text_file)

      self.input_file_path_hbox= QHBoxLayout()
      self.input_file_path_hbox.addWidget(self.textbox_file_path)
      self.input_file_path_hbox.addWidget(self.button_open_path)
      self.input_file_path_hbox.setSpacing(4)
      self.input_file_path_hbox.setContentsMargins(0,0,0,0)
      self.input_file_path_hbox.setAlignment(Qt.AlignLeft)

      self.groupbox_data_souce_options = QGroupBox("Data Source Options")
      self.groupbox_data_souce_options.setFixedWidth(420)

      self.lbl_available_sheets = QLabel("Available Sheets")
      self.lbl_available_sheets.adjustSize()
      self.lbl_available_columns = QLabel("Available Columns")
      self.lbl_available_columns.adjustSize()
      self.combobox_available_sheets = QComboBox()
      self.combobox_available_sheets.setFixedSize(400,40)
      self.combobox_available_sheets.setFont(QFont("Lucida Sans Unicode", 11))
      self.combobox_available_sheets.setCurrentIndex(0)

      self.groupbox_excel_layout = QVBoxLayout()
      self.groupbox_data_souce_options.setLayout(self.groupbox_excel_layout)
      self.groupbox_excel_layout.addWidget(self.lbl_available_sheets)
      self.groupbox_excel_layout.addWidget(self.combobox_available_sheets)
      self.groupbox_excel_layout.addWidget(self.lbl_available_columns)
      self.groupbox_excel_layout.addStretch()

      self.dialog = QFileDialog()
      self.dialog.setWindowTitle("Pick File to Import")
      self.dialog.setViewMode(QFileDialog.ViewMode.Detail)

      self.stackwidget = MyStackedlayout()

      self.left_layout.addStretch()
      self.left_layout.addWidget(self.lbl_data_source_type)
      self.left_layout.addWidget(self.combobox_data_source_type)
      self.left_layout.addWidget(self.lbl_input_file)
      self.left_layout.addLayout(self.input_file_path_hbox)
      self.left_layout.setAlignment(Qt.AlignLeft)
      self.left_layout.addWidget(self.stackwidget)
      self.stackwidget.addWidget(self.groupbox_data_souce_options)
      self.left_layout.addStretch()

   def selectionchange_data_source_type(self,index):
      self.current_data_source_type_index = index
      self.current_data_source_type_text = self.combobox_data_source_type.currentText()
      if self.current_data_source_type_text.split('/')[0] == "Excel":
         self.stackwidget.setCurrentWidget(self.groupbox_data_souce_options)
      elif self.current_data_source_type_text.split('/')[0] == "CSV":
         lbl1 = QLabel("Csv Group Box")
         self.stackwidget.addWidget(lbl1)
         self.stackwidget.setCurrentWidget(lbl1)

      stackwidget_resize = MyStackedlayout.minimumSize(self.stackwidget)
      # print(stackwidget_resize)
      self.stackwidget.resize(stackwidget_resize)

   def get_text_file(self):

      if self.current_data_source_type_text.split('/')[0] == "Excel":
         self.dialog.setNameFilters(["Excel File (*.xlsx *.xls)"])
      elif self.current_data_source_type_text.split('/')[0] == "CSV":
         self.dialog.setNameFilters(["CSV File (*.csv)"])

      self.dialog.setFileMode(QFileDialog.ExistingFiles)
      self.dialog.fileSelected.connect(self.file_selected)

if __name__ == '__main__':
   app = QApplication(sys.argv)
   demo = DialogApp()
   demo.show()
   sys.exit(app.exec_())


来源: stackexchange

问:
How can I stop Mui's Date-Picker from jumping the screen when it closes off screen?
When I open a mui date picker then scroll so it's at all off screen/hidden and then close it by clicking outside of it the screen jumps so the initial input is in view. I would like the screen not to jump/scroll at all when the picker closes.

For an example, open the first datepicker (titled "date desktop") in mui's example page, scroll down the page so the datepicker disappears, then click away from the datepicker.

Mui's page: https://mui.com/x/react-date-pickers/getting-started/

I think this has something to do with the popper trying to focus the datepicker and bring it back on screen when it closes but I'm not sure what to target to disable this behavior'.

I tried the above and expected the datepicker to close and the screen to stay in place, but instead it jumped.

You could also see the behaviour in this code sandbox: https://codesandbox.io/s/focused-architecture-fg5yvl

Open the datepicker, scroll down so it's off screen, then click. You'll be jumped up to the datepicker; Is there a way to avoid this behaviour?

ContentLicense: CC BY-SA 4.0


问:
No prop for export button in DataGrid

I wanted to disable or remove the export button but there were no props in the documentation to disable this button.

```<code>  <DataGrid
        rows={suppliers}
        columns={columns}
        getRowId={(row) => row.supplier_id}
        pageSize={5}
        rowsPerPageOptions={[5]}
        // disableColumnFilter
        // disableColumnSelector
        // disableDensitySelector
        components={{ Toolbar: GridToolbar }}
        componentsProps={{
            toolbar: {
                showQuickFilter: true,
                quickFilterProps: { debounceMs: 500 }
            }
        }}
    />
</code>```

Example:

```<code>disableColumnFilter
disableColumnSelector
disableDensitySelector
</code>```

Title: No prop for export button in DataGrid

Body:
I wanted to disable or remove the export button but there were no props in the documentation to disable this button.

  <DataGrid
        rows={suppliers}
        columns={columns}
        getRowId={(row) => row.supplier_id}
        pageSize={5}
        rowsPerPageOptions={[5]}
        // disableColumnFilter
        // disableColumnSelector
        // disableDensitySelector
        components={{ Toolbar: GridToolbar }}
        componentsProps={{
            toolbar: {
                showQuickFilter: true,
                quickFilterProps: { debounceMs: 500 }
            }
        }}
    />

Example:

disableColumnFilter
disableColumnSelector
disableDensitySelector


问:
reading and uploading to mongodb through schemas
I'm very new to node and mongoose schemas, so this might be a noob question.

I'm trying to fetch the data to display on my home page. Right now, the home page uses a function in a separate file to call the Api and fetch from the backend, which seems to be working. On the backend of my route, I make two calls to separate DB functions. One that adds the payment to the payment collection and the other that updates the values in the user details collection.

When I make my db calls, it seems to get hung up and cannot complete the query. I tested this by just logging to the console and the log before the function prints, but the one after does not.

This is my router code:

```<code>const express = require('express');
const db = require('../db/DbCalls');
const historyRoutes = express.Router();

// will collect/sort by date all purchases, refunds, and payments for user
historyRoutes.route("/home").get( async function (req, res) {
    let transactions = [];
    const params = {
        limit: 0
    }
    //retrieve lists
    const purchases =  await db.getPurchases(params);
    const payments =  await db.getPayments();
    const refunds =  await db.getRefunds();
    //merge lists
    transactions = purchases.concat(payments);
    transactions = transactions.concat(refunds);
    //sort lists by most recent transaction
    transactions.sort(function(a,b){
        return a.date - b.date;
    });
    res.json(transactions);
});
module.exports = historyRoutes;
</code>```

These are my database call functions

```<code>const Purchase = require('../Schemas/purchase');
const Payment = require('../Schemas/payment');
const Refund = require('../Schemas/refund');
const User = require('../Schemas/user');
// All database functions used in router files
    // retrieves all purchases
    async function getPurchases(params) {
        try {
            console.log(params.limit);
            console.log('entered');
            Purchase.find().limit(params.limit).exec(
                function (err, results ){
                    if (err) console.log('error');
                    console.log(results);
                    return results;
                }
            );
        } catch (err) {
            console.log('error');
            throw (err);
        }
    }
    // retrieves all payments
    async function getPayments() {
        try {
            const results = await Payment.find().exec();
            console.log(results);
            return results;
        } catch (err) {
            console.log(err);
            throw err;
        }
    }
    // retrieves all refunds
    async function getRefunds() {
        try {
            const results = await Refund.find().exec();
            console.log(results);
            return results;
        } catch (err) {
            console.log(err);
            throw err;
        }

    }
    // retrieves max limit, current limit, and current balance
    async function getUserDetails() {
        try{
            const results = await User.findOne({name: 'user'}).exec();
            console.log(results);
            return results;
        }catch (err) {
            console.log(err);
            throw err;
        }
    }
    // updates user details
    async function updateUserDetails(body) {
        try {
            const result = await User.updateOne({name:'user'},body).exec();
            console.log(result);
            return result;
        } catch (err) {
            console.log(err);
            throw err;
        }
    }
    // adds a single transaction

    async function addPayment(body){
        const payment = new Payment({
            transType: 'payment',
            amount:body.amount,
            title: 'Paid to Fizz',
            count: body.count,
            date: Date.now()
        });
        thing.save().then(
            ()=> {
                console.log('Added Payment Successfully');
                return
            }
        ).catch(
            (err)=> {
                console.log(`Error adding payment ${err}.`);
                return
            }
        )
    }
    async function addTransaction(body) {
        try {
            let result;
            if (body.type === 'purchase') {
                result = await Purchase.insertOne(body);
            }
            if (body.type === 'payment') {
                result = await Payment.insertOne(body);
            }
            if (body.type === 'refund') {
                result = await Refund.insertOne(body);
            }
            console.log(result);
            return result;
        } catch (err) {
            throw err;
        }
    }
module.exports = {addTransaction, updateUserDetails, getPayments, getPurchases, getRefunds, getUserDetails};
</code>```

These are my schemas

```<code>const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const paymentSchema = new Schema({
    transType: {type: String, required:true},
    amount: {type: Number, required:true},
    title: {type: String, required:true},
    rfndStatus : {type: Boolean, required:true},
    count : {type: Number, required:true},
    date: {type: Date, required:true}
});

module.exports = mongoose.model("payment", paymentSchema);
</code>```
```<code>const mongoose = require('mongoose');
var Schema = mongoose.Schema;
const purchaseSchema = new Schema({
    transType: {type: String,required:true},
    amount: {type: Number,required:true},
    title: {type: String,required:true},
    rfndStatus : {type: Boolean,required:true},
    date: {type: Date,required:true}
});

module.exports = mongoose.model('purchase', purchaseSchema);
</code>```
```<code>const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const refundSchema = new Schema({
    transType: {type: String, required:true},
    title: {type: String, required:true},
    amount: {type: Number, required:true},
    date: {type: Date, required:true}
});

module.exports = mongoose.model("refund", refundSchema);
</code>```
```<code>const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {type:String},
    balance: {type: Number, required: true},
    currentLimit: {type:Number, required: true},
    MaximumLimit: {type: Number, required: true}
});

module.exports = mongoose.model("user", userSchema);
</code>```

I don't really know where I'm going wrong in structure.

Body:
I'm very new to node and mongoose schemas, so this might be a noob question.

I'm trying to fetch the data to display on my home page. Right now, the home page uses a function in a separate file to call the Api and fetch from the backend, which seems to be working. On the backend of my route, I make two calls to separate DB functions. One that adds the payment to the payment collection and the other that updates the values in the user details collection.

When I make my db calls, it seems to get hung up and cannot complete the query. I tested this by just logging to the console and the log before the function prints, but the one after does not.

This is my router code:

const express = require('express');
const db = require('../db/DbCalls');
const historyRoutes = express.Router();

// will collect/sort by date all purchases, refunds, and payments for user
historyRoutes.route("/home").get( async function (req, res) {
    let transactions = [];
    const params = {
        limit: 0
    }
    //retrieve lists
    const purchases =  await db.getPurchases(params);
    const payments =  await db.getPayments();
    const refunds =  await db.getRefunds();
    //merge lists
    transactions = purchases.concat(payments);
    transactions = transactions.concat(refunds);
    //sort lists by most recent transaction
    transactions.sort(function(a,b){
        return a.date - b.date;
    });
    res.json(transactions);
});
module.exports = historyRoutes;

These are my database call functions

const Purchase = require('../Schemas/purchase');
const Payment = require('../Schemas/payment');
const Refund = require('../Schemas/refund');
const User = require('../Schemas/user');
// All database functions used in router files
    // retrieves all purchases
    async function getPurchases(params) {
        try {
            console.log(params.limit);
            console.log('entered');
            Purchase.find().limit(params.limit).exec(
                function (err, results ){
                    if (err) console.log('error');
                    console.log(results);
                    return results;
                }
            );
        } catch (err) {
            console.log('error');
            throw (err);
        }
    }
    // retrieves all payments
    async function getPayments() {
        try {
            const results = await Payment.find().exec();
            console.log(results);
            return results;
        } catch (err) {
            console.log(err);
            throw err;
        }
    }
    // retrieves all refunds
    async function getRefunds() {
        try {
            const results = await Refund.find().exec();
            console.log(results);
            return results;
        } catch (err) {
            console.log(err);
            throw err;
        }

    }
    // retrieves max limit, current limit, and current balance
    async function getUserDetails() {
        try{
            const results = await User.findOne({name: 'user'}).exec();
            console.log(results);
            return results;
        }catch (err) {
            console.log(err);
            throw err;
        }
    }
    // updates user details
    async function updateUserDetails(body) {
        try {
            const result = await User.updateOne({name:'user'},body).exec();
            console.log(result);
            return result;
        } catch (err) {
            console.log(err);
            throw err;
        }
    }
    // adds a single transaction

    async function addPayment(body){
        const payment = new Payment({
            transType: 'payment',
            amount:body.amount,
            title: 'Paid to Fizz',
            count: body.count,
            date: Date.now()
        });
        thing.save().then(
            ()=> {
                console.log('Added Payment Successfully');
                return
            }
        ).catch(
            (err)=> {
                console.log(`Error adding payment ${err}.`);
                return
            }
        )
    }
    async function addTransaction(body) {
        try {
            let result;
            if (body.type === 'purchase') {
                result = await Purchase.insertOne(body);
            }
            if (body.type === 'payment') {
                result = await Payment.insertOne(body);
            }
            if (body.type === 'refund') {
                result = await Refund.insertOne(body);
            }
            console.log(result);
            return result;
        } catch (err) {
            throw err;
        }
    }
module.exports = {addTransaction, updateUserDetails, getPayments, getPurchases, getRefunds, getUserDetails};

These are my schemas

const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const paymentSchema = new Schema({
    transType: {type: String, required:true},
    amount: {type: Number, required:true},
    title: {type: String, required:true},
    rfndStatus : {type: Boolean, required:true},
    count : {type: Number, required:true},
    date: {type: Date, required:true}
});

module.exports = mongoose.model("payment", paymentSchema);

const mongoose = require('mongoose');
var Schema = mongoose.Schema;
const purchaseSchema = new Schema({
    transType: {type: String,required:true},
    amount: {type: Number,required:true},
    title: {type: String,required:true},
    rfndStatus : {type: Boolean,required:true},
    date: {type: Date,required:true}
});

module.exports = mongoose.model('purchase', purchaseSchema);

const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const refundSchema = new Schema({
    transType: {type: String, required:true},
    title: {type: String, required:true},
    amount: {type: Number, required:true},
    date: {type: Date, required:true}
});

module.exports = mongoose.model("refund", refundSchema);

const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {type:String},
    balance: {type: Number, required: true},
    currentLimit: {type:Number, required: true},
    MaximumLimit: {type: Number, required: true}
});

module.exports = mongoose.model("user", userSchema);

I don't really know where I'm going wrong in structure.


问:
GoogleMapReact not rendering markers when defined as component
I am initializng the map and updating the markers based on the search of googleAutoComplete. This works when I render the component inline to the map.

If I declare the same component in a separate jsx , then the markers stops working.

This works

```<code> <GoogleMapReact
                                bootstrapURLKeys={{key: process.env.REACT_APP_GOOGLE_API_KEY}}
                                defaultCenter={coordinates}
                                center={coordinates}
                                defaultZoom={10}
                                margin={[50, 50, 50, 50]}
                                options={{disableDefaultUI: true, zoomControl: true, styles: mapStyles}}
                                onChange={e => {
                                    setChildClicked(-1);
                                    setCoordinates({lat: e.center.lat, lng: e.center.lng})
                                    setBounds({ne: e.marginBounds.ne, sw: e.marginBounds.sw})
                                }}
                                onChildClick={(child) => {
                                    setChildClicked(child)
                                }}
                            >
                                {placesofintrests?.results?.map((placesofintrest, i) => (
                                    <div className="wrapper"
                                         lat={Number(placesofintrest?.geometry?.location?.lat)}
                                         lng={Number(placesofintrest?.geometry?.location?.lng)}
                                         key={i}
                                    >
                                        <img alt={placesofintrest?.name} src="assets/img/placesofintrest.png"/>
                                    </div>
                                ))}
</GoogleMapReact>
</code>```

Now , if I rewrite the code with a extracted component (jsx) , it does not place the markers properly.

```<code><GoogleMapReact
                                bootstrapURLKeys={{key: process.env.REACT_APP_GOOGLE_API_KEY}}
                                defaultCenter={coordinates}
                                center={coordinates}
                                defaultZoom={10}
                                margin={[50, 50, 50, 50]}
                                options={{disableDefaultUI: true, zoomControl: true, styles: mapStyles}}
                                onChange={e => {
                                    setChildClicked(-1);
                                    setCoordinates({lat: e.center.lat, lng: e.center.lng})
                                    setBounds({ne: e.marginBounds.ne, sw: e.marginBounds.sw})
                                }}
                                onChildClick={(child) => {
                                    setChildClicked(child)
                                }}
                            >
                                {placesofintrests?.results?.map((placesofintrest, i) => (
                                    <MapMarker placesofintrest={placesofintrest} key={i}/>
                                ))}
</GoogleMapReact>
</code>```
```<code>import React from "react";

const MapMarker = ({placesofintrest}) => {
    return (<div className="wrapper"
                 lat={Number(placesofintrest?.geometry?.location?.lat)}
                 lng={Number(placesofintrest?.geometry?.location?.lng)}
    >
        <img alt={placesofintrest?.name} src="assets/img/placesofintrest.png"/>
    </div>)
};
export default MapMarker;
</code>```

Body:
I am initializng the map and updating the markers based on the search of googleAutoComplete. This works when I render the component inline to the map.

If I declare the same component in a separate jsx , then the markers stops working.

This works

 <GoogleMapReact
                                bootstrapURLKeys={{key: process.env.REACT_APP_GOOGLE_API_KEY}}
                                defaultCenter={coordinates}
                                center={coordinates}
                                defaultZoom={10}
                                margin={[50, 50, 50, 50]}
                                options={{disableDefaultUI: true, zoomControl: true, styles: mapStyles}}
                                onChange={e => {
                                    setChildClicked(-1);
                                    setCoordinates({lat: e.center.lat, lng: e.center.lng})
                                    setBounds({ne: e.marginBounds.ne, sw: e.marginBounds.sw})
                                }}
                                onChildClick={(child) => {
                                    setChildClicked(child)
                                }}
                            >
                                {placesofintrests?.results?.map((placesofintrest, i) => (

                                ))}
</GoogleMapReact>

Now , if I rewrite the code with a extracted component (jsx) , it does not place the markers properly.

<GoogleMapReact
                                bootstrapURLKeys={{key: process.env.REACT_APP_GOOGLE_API_KEY}}
                                defaultCenter={coordinates}
                                center={coordinates}
                                defaultZoom={10}
                                margin={[50, 50, 50, 50]}
                                options={{disableDefaultUI: true, zoomControl: true, styles: mapStyles}}
                                onChange={e => {
                                    setChildClicked(-1);
                                    setCoordinates({lat: e.center.lat, lng: e.center.lng})
                                    setBounds({ne: e.marginBounds.ne, sw: e.marginBounds.sw})
                                }}
                                onChildClick={(child) => {
                                    setChildClicked(child)
                                }}
                            >
                                {placesofintrests?.results?.map((placesofintrest, i) => (
                                    <MapMarker placesofintrest={placesofintrest} key={i}/>
                                ))}
</GoogleMapReact>

import React from "react";

const MapMarker = ({placesofintrest}) => {
    return (

)
};
export default MapMarker;


问:
Supplying params to getSelector during selectors creation
I just started with Rtk query. I got a problem. It looks like I don't understand completely how to create selectors for queries that comes with parameters.
I have an endpoint

```<code>getRoutePlanByHubAndDate: builder.query<EntityState<RoutePlans[]>, { hub: number; date: string }>({
      query: ({ hub, date }) => ({
        url: `${process.env.NEXT_PUBLIC_LMD_DISPATCH_URI}routePlans/${hub}/${date}?page=0&size=20`
      }),
      transformResponse: (response: RoutePlans[], args): EntityState<RoutePlans[]> => {
        return dispatchAdapter.setAll(initialState, response) as any // {ids: [], entities: {}}
      },
      providesTags: ['Dispatch']
    }),
</code>```

When I create selectors I am not sure how to pass my params into getSelector

```<code>export const selectRoutesResult = (state: AppState, params: { hub: number; date: string; page: number }) =>
  dispatchApi.endpoints.getRoutePlanByHubAndDate.select(params)(state) ?? []

const selectRoutesData = createSelector([selectRoutesResult], (routesResult) => routesResult.data)

export const {
  selectAll: selectAllRoutes,
  selectById: selectRoutesById,
  selectIds: selectRouteIds
} = dispatchAdapter.getSelectors((state: AppState): EntityState<RoutePlans[]> => {
  return selectRoutesData(state, params) ?? initialState as EntityState<RoutePlans[]>
})
</code>```

I am not sure how to supply params argument in selectRoutesData since getSelector only takes state

Thank you in advance

Body:
I just started with Rtk query. I got a problem. It looks like I don't understand completely how to create selectors for queries that comes with parameters.
I have an endpoint

getRoutePlanByHubAndDate: builder.query<EntityState<RoutePlans[]>, { hub: number; date: string }>({
      query: ({ hub, date }) => ({
        url: `${process.env.NEXT_PUBLIC_LMD_DISPATCH_URI}routePlans/${hub}/${date}?page=0&size=20`
      }),
      transformResponse: (response: RoutePlans[], args): EntityState<RoutePlans[]> => {
        return dispatchAdapter.setAll(initialState, response) as any // {ids: [], entities: {}}
      },
      providesTags: ['Dispatch']
    }),

When I create selectors I am not sure how to pass my params into getSelector

export const selectRoutesResult = (state: AppState, params: { hub: number; date: string; page: number }) =>
  dispatchApi.endpoints.getRoutePlanByHubAndDate.select(params)(state) ?? []

const selectRoutesData = createSelector([selectRoutesResult], (routesResult) => routesResult.data)

export const {
  selectAll: selectAllRoutes,
  selectById: selectRoutesById,
  selectIds: selectRouteIds
} = dispatchAdapter.getSelectors((state: AppState): EntityState<RoutePlans[]> => {
  return selectRoutesData(state, params) ?? initialState as EntityState<RoutePlans[]>
})

I am not sure how to supply params argument in selectRoutesData since getSelector only takes state

Thank you in advance


问:
How to correctly profile memory for a data structure with nested objects
I'm aware that sys.getsizeof returns the number of bytes the argument uses, but I want to make sure I'm not missing anything like references in the following data structures (it's the strings I'm most unsure about...). I'm also not sure how using __slots__ impacts the memory used by a class and if I need to do something extra to account for it

class Node:
  __slots__ = ('attributes', 'children')

  def __init__(self, attributes = None, children = None):
    self.attributes = attributes # a string
    self.children = children # a dict of string key to Node value

dict1 = {'a': '123|234'} # dict of string key to string value
dict2 = {'a': [123,234] # dict of string key to array of integers
dict3 = {'a': ['123','234'] # dict of string key to array of strings
```


问:
Migrating Hibernate Search 5.11.11.Final to any Hibernate Search 6
Is there any way to avoid usage of BooleanJunction while migrating to Hibernate 6?
My (poor) understanding is that Hibernate 6 abandoned Quer DSL and is using JPA criteria instead. Code sample is just about 10 % of code that I have to cover all search cases and it uses more that shown here, meaning BooleanJunction is needed for this to work.

```<code>import javax.persistence.EntityManager;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.SearchFactory;
import org.hibernate.search.query.dsl.QueryContextBuilder;
import org.hibernate.search.query.dsl.EntityContext;
import org.hibernate.search.query.dsl.QueryBuilder;

// ...

@Autowired
private final EntityManager entityManager;

private static final Pattern SPACES =
    Pattern.compile("\\s+", Pattern.UNICODE_CHARACTER_CLASS);

private static final int MIN_TOKEN_LENGTH = 2;

@AllArgsConstructor @Getter
public enum SearchField {
    // there are 20 entries; here is one just to show
    NAME(SearchField.NAME_STR, 20.0f);
    private String fieldName;
    private float  boostFactor;
}

// ...

final FullTextEntityManager fullTextEntityManager =
    Search.getFullTextEntityManager(this.entityManager);

final SearchFactory searchFactory =
    fullTextEntityManager.getSearchFactory();

final QueryContextBuilder queryContextBuilder =
    searchFactory.buildQueryBuilder();

final EntityContext entityContext =
    queryContextBuilder.forEntity(clazz);

final QueryBuilder queryBuilder =
    entityContext.get();

// ...

final String searchTerm = "some search term";
final String[] searchTerms =
    Arrays.stream(SPACES.split(searchTerm))
        .map(StringUtils::trimToNull)
        .filter(Objects::nonNull)
        .filter(s -> s.length() >= IndexingUtil.MIN_TOKEN_LENGTH)
        .toArray(String[]::new);

final List<Query> queries = new LinkedList<>();

for (int i = 0; i < searchTerms.length; ++i) {
    final String word = searchTerms[i];
    queries.add(
        queryBuilder
            .bool()
            .should(
                QueryForField.q(
                    SearchField.NAME,
                    word,
                    queryBuilder
                )
            )
            .boostedTo(SearchField.NAME.getBoostFactor()
        );
    );
}

// more queries are added, not only query by `name`

final BooleanJunction<?> master = queryBuilder.bool();
queries.stream().filter(Objects::nonNull).forEach(master::must);
final Query q = master.createQuery();
</code>```

Body:
Is there any way to avoid usage of BooleanJunction while migrating to Hibernate 6?
My (poor) understanding is that Hibernate 6 abandoned Quer DSL and is using JPA criteria instead. Code sample is just about 10 % of code that I have to cover all search cases and it uses more that shown here, meaning BooleanJunction is needed for this to work.

import javax.persistence.EntityManager;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.SearchFactory;
import org.hibernate.search.query.dsl.QueryContextBuilder;
import org.hibernate.search.query.dsl.EntityContext;
import org.hibernate.search.query.dsl.QueryBuilder;

// ...

@Autowired
private final EntityManager entityManager;

private static final Pattern SPACES =
    Pattern.compile("\\s+", Pattern.UNICODE_CHARACTER_CLASS);

private static final int MIN_TOKEN_LENGTH = 2;

@AllArgsConstructor @Getter
public enum SearchField {
    // there are 20 entries; here is one just to show
    NAME(SearchField.NAME_STR, 20.0f);
    private String fieldName;
    private float  boostFactor;
}

// ...

final FullTextEntityManager fullTextEntityManager =
    Search.getFullTextEntityManager(this.entityManager);

final SearchFactory searchFactory =
    fullTextEntityManager.getSearchFactory();

final QueryContextBuilder queryContextBuilder =
    searchFactory.buildQueryBuilder();

final EntityContext entityContext =
    queryContextBuilder.forEntity(clazz);

final QueryBuilder queryBuilder =
    entityContext.get();

// ...

final String searchTerm = "some search term";
final String[] searchTerms =
    Arrays.stream(SPACES.split(searchTerm))
        .map(StringUtils::trimToNull)
        .filter(Objects::nonNull)
        .filter(s -> s.length() >= IndexingUtil.MIN_TOKEN_LENGTH)
        .toArray(String[]::new);

final List<Query> queries = new LinkedList<>();

for (int i = 0; i < searchTerms.length; ++i) {
    final String word = searchTerms[i];
    queries.add(
        queryBuilder
            .bool()
            .should(
                QueryForField.q(
                    SearchField.NAME,
                    word,
                    queryBuilder
                )
            )
            .boostedTo(SearchField.NAME.getBoostFactor()
        );
    );
}

// more queries are added, not only query by `name`

final BooleanJunction<?> master = queryBuilder.bool();
queries.stream().filter(Objects::nonNull).forEach(master::must);
final Query q = master.createQuery();


问:
How to get can channel id using char name
How to get can channel id using char name?

For example. my CANoe first can channel is 1, and it's name is "BCAN", is there a capl function that can get 1 from "BCAN"?


问:
Read/Write Packets for PTP/USB on Windows
I'm trying to create a PTP/USB driver for Windows. Here's what I've done so far:

I was able to successfully use WIA, but win32 scans the entire SD card and builds a tree of files before I can do anything (takes 5 minutes, so unusable)

Tried SetupAPI with CreatePipe(), got unsupported error code

Tried SetupAPI with WinUSB, got unsupported error code (later decided against using WinUSB for misc reasons)

Tried SetupAPI with ReadFile/WriteFile and DeviceIoControl, got more unsupported errors
My SetupAPI code to discover the camera is working perfectly. The GUID for what I'm connecting to is {6BDD1FC6-810F-11D0-BEC7-08002BE2092F}. My PTP driver is working perfectly on Linux with LibUSB bindings.

Not asking for code fixes, just want to know which path I should try again. Thanks for any advice.


问:
How can i get my progress bar to show the current time of a song?
in my audio player for my portfolio i am having an issue getting the progress bar to fill up with the current part of the song. in the console when i inspect, it does show progress is being made.

```<code>// Update Progress Bar & Time
function updateProgressBar(e) {
    if (isPlaying) {
        const { duration, currentTime} = e.srcElement;
        console.log(duration, currentTime);
        // Update progress bar width
        const progressPercent = (currentTime / duration) * 100;
        progress.style.width = `${progressPercent}%`;
    }
}

</code>```

i have tried changing the format

Body:
in my audio player for my portfolio i am having an issue getting the progress bar to fill up with the current part of the song. in the console when i inspect, it does show progress is being made.

// Update Progress Bar & Time
function updateProgressBar(e) {
    if (isPlaying) {
        const { duration, currentTime} = e.srcElement;
        console.log(duration, currentTime);
        // Update progress bar width
        const progressPercent = (currentTime / duration) * 100;
        progress.style.width = `${progressPercent}%`;
    }
}

i have tried changing the format


问:
Angular Firebase check if token has been revoked
In my Angular app, I have a guard that checks if the user exists and if the email is verified. Then it does the redirections accordingly.

Here's the code:

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.apiService.getCurrentUser().pipe(map(user => {
  if (user !== null) {
    if (user.isEmailVerified) {
      return true
    } else {
      this.router.navigate([VERIFICATION_PATH], { queryParams: { 'redirectURL': state.url } })
      return false
    }
  } else {
    this.routerService.params = { queryParams: { 'redirectURL': state.url } }
    this.router.navigate([CONNECTION_PATH], { queryParams: { 'redirectURL': state.url } })
    return false
  }
}))
</code>```

}

Now I would like to check if the token has been revoked. I've seen that I can use the admin sdk but I would like to do it with the client sdk if possible. I wasn't able to find a way.

Body:
In my Angular app, I have a guard that checks if the user exists and if the email is verified. Then it does the redirections accordingly.

Here's the code:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.apiService.getCurrentUser().pipe(map(user => {
  if (user !== null) {
    if (user.isEmailVerified) {
      return true
    } else {
      this.router.navigate([VERIFICATION_PATH], { queryParams: { 'redirectURL': state.url } })
      return false
    }
  } else {
    this.routerService.params = { queryParams: { 'redirectURL': state.url } }
    this.router.navigate([CONNECTION_PATH], { queryParams: { 'redirectURL': state.url } })
    return false
  }
}))

}

Now I would like to check if the token has been revoked. I've seen that I can use the admin sdk but I would like to do it with the client sdk if possible. I wasn't able to find a way.


问:
How to handle event for `select` control being populated
The stackblitz code is at: https://stackblitz.com/edit/angular-ivy-dnmsa3?file=src/app/raport-for-date/raport-for-date.component.html.

I have the following HTML select control defined like below :

```<code> <select
  formControlName="dates"
  class="form-select"
  (change)="onSelected(dates.value)"
>
  <option *ngFor="let date of latesetList">{{ date }}</option>
</select>
</code>```

I would like to detect the change in select control in two cases:

Whenever select box is populated with new values

Whenever selection is changed - even if the same value is re-selected

Is it possible to do that - because the code above is not working? onSelected is called only if I change selection to smothing different then the current selection.

The files containing the above code are:
report-for-date.component.html
report-for-date.component.ts

Body:
The stackblitz code is at: https://stackblitz.com/edit/angular-ivy-dnmsa3?file=src/app/raport-for-date/raport-for-date.component.html.

I have the following HTML select control defined like below :

 <select
  formControlName="dates"
  class="form-select"
  (change)="onSelected(dates.value)"
>
  <option *ngFor="let date of latesetList">{{ date }}</option>
</select>

I would like to detect the change in select control in two cases:

Whenever select box is populated with new values

Whenever selection is changed - even if the same value is re-selected

Is it possible to do that - because the code above is not working? onSelected is called only if I change selection to smothing different then the current selection.

The files containing the above code are:
report-for-date.component.html
report-for-date.component.ts


问:
I have NAs in my data set so my cor() is coming up as NA
how do i re-write this to get it to run ignoring the NAs?

I am expecting a correlation value between the variables and I am getting NA.

cor(vehicle_year,speed)

cor(subject_age,speed)

cor(posted_speed,speed)


问:
I am trying to do an interpolation with IDW and I get TypeError: cannot convert the series to <class 'float'>
```<code>idw.idw_interpolation(
    input_point_shapefile="C:/INFORMATICA APLICADA 22-23/Estaciones.shp",
    extent_shapefile="C:/INFORMATICA APLICADA 22-23/zonas_urbana_dmq.shp",
    column_name="SO2",
    power=2,
    search_radious=4,
    output_resolution=250)

</code>```

I am trying to do an interpolation with IDW and I get TypeError: cannot convert the series to <class 'float'>.

Body:
idw.idw_interpolation(
    input_point_shapefile="C:/INFORMATICA APLICADA 22-23/Estaciones.shp",
    extent_shapefile="C:/INFORMATICA APLICADA 22-23/zonas_urbana_dmq.shp",
    column_name="SO2",
    power=2,
    search_radious=4,
    output_resolution=250)

I am trying to do an interpolation with IDW and I get TypeError: cannot convert the series to <class 'float'>.


问:
SecItemAdd returns errSecParam error after including SecAccessControlRef
I wish to implement kSecAttrAccessControl into my SecItemAdd function but the SecItemAdd keeps returning the errSecParam error.

Is anyone able to spot the error or is there anything missing in the code below?

```<code>static NSDictionary * AFKeyChainQueryDictionaryWithIdentifier(NSString *identifier){
    NSCParameterAssert(identifier);
    SecAccessControlRef sacObject = SecAccessControlCreateWithFlags(kCFAllocatorDefault,
                                            kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
                                            kSecAccessControlUserPresence,
                                            nil);

    return @{
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: @"AFOAuthCredentialService",
            kSecAttrAccount: identifier,
            kSecAttrAccessControl: (__bridge_transfer id)sacObject,
            kSecUseAuthenticationUI: (__bridge_transfer id)kSecUseAuthenticationUIAllow,

    };
}
</code>```
```<code>+ (BOOL)storeCredential:(AFOAuthCredential *)credential
        withIdentifier:(NSString *)identifier
        withAccessbility:(id)accessbility
{
    //credential contains credential.ValueA and credential.ValueB

    NSMutableDictionary *queryDictionary = [AFKeychainQueryDictionaryWithIdentifier(identifier) mutableCopy];

    NSMutableDictionary *update = [NSMutableDictionary dictionary];
    update[(__bridge id)kSecValueData] = [NSKeyedArchiver archiveDataWithRootObject:credential];
    update[(__bridge id)kSecAttrAccessible] = (__bridge id)kSecAttrAccessibleAlways;

    [queryDictionary addEntriesFromDictionary:update];

    status = SecItemAdd((__bridge CFDictionaryRef)queryDictionary, NULL);

    return status;
}
</code>```

After researching on most of the forums I had tried to implement the suggestions such as removing kSecAttrAccessible or directly converting credential.ValueA from NSString to NSData. None of them are worked.

I have tried to remove the kSecAttrAccessControl and it is able to create in SecItemAdd so the logic seems correct. But kSecAttrAccessControl must be included as one of the requirements.

Body:
I wish to implement kSecAttrAccessControl into my SecItemAdd function but the SecItemAdd keeps returning the errSecParam error.

Is anyone able to spot the error or is there anything missing in the code below?

static NSDictionary * AFKeyChainQueryDictionaryWithIdentifier(NSString *identifier){
    NSCParameterAssert(identifier);
    SecAccessControlRef sacObject = SecAccessControlCreateWithFlags(kCFAllocatorDefault,
                                            kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
                                            kSecAccessControlUserPresence,
                                            nil);

    return @{
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: @"AFOAuthCredentialService",
            kSecAttrAccount: identifier,
            kSecAttrAccessControl: (__bridge_transfer id)sacObject,
            kSecUseAuthenticationUI: (__bridge_transfer id)kSecUseAuthenticationUIAllow,

    };
}

+ (BOOL)storeCredential:(AFOAuthCredential *)credential
        withIdentifier:(NSString *)identifier
        withAccessbility:(id)accessbility
{
    //credential contains credential.ValueA and credential.ValueB

    NSMutableDictionary *queryDictionary = [AFKeychainQueryDictionaryWithIdentifier(identifier) mutableCopy];

    NSMutableDictionary *update = [NSMutableDictionary dictionary];
    update[(__bridge id)kSecValueData] = [NSKeyedArchiver archiveDataWithRootObject:credential];
    update[(__bridge id)kSecAttrAccessible] = (__bridge id)kSecAttrAccessibleAlways;

    [queryDictionary addEntriesFromDictionary:update];

    status = SecItemAdd((__bridge CFDictionaryRef)queryDictionary, NULL);

    return status;
}

After researching on most of the forums I had tried to implement the suggestions such as removing kSecAttrAccessible or directly converting credential.ValueA from NSString to NSData. None of them are worked.

I have tried to remove the kSecAttrAccessControl and it is able to create in SecItemAdd so the logic seems correct. But kSecAttrAccessControl must be included as one of the requirements.


问:
Why Does string_agg Not Make Changes In This Context
I was starting down the road of testing within group(), and I came across this unexpected behavior of string_agg (or maybe substring).  In the following code, mType is a field containing things like 'HMA - etc.etc.etc.' or 'ACP - etc.etc.etc.'  In the following context, the 2nd selected field fails to change the delimiter from a ',' to a '-'

```<code>select string_agg( substring( mType,1,3 ), ',' )  mType
      ,string_agg( substring( mType,1,3), '-' )  mType2
from ourDB..mTypeTable
where ref = '3944900'
</code>```

Returns:

If I change the substring from 1,3 to 1,4, then things work.

```<code>select string_agg( substring( mType,1,3 ), ',' )  mType
      ,string_agg( substring( mType,1,4), '-' )  mType2
from ourDB..mTypeTable
where ref = '3944900'
</code>```

Returns:

Why does TSQL fail to change the delimiter in the first context? Is this some kind of optimization moment or something where TSQL is reusing the last substring because it's pulling from the same field in the same table in the same select?

Body:
I was starting down the road of testing within group(), and I came across this unexpected behavior of string_agg (or maybe substring).  In the following code, mType is a field containing things like 'HMA - etc.etc.etc.' or 'ACP - etc.etc.etc.'  In the following context, the 2nd selected field fails to change the delimiter from a ',' to a '-'

select string_agg( substring( mType,1,3 ), ',' )  mType
      ,string_agg( substring( mType,1,3), '-' )  mType2
from ourDB..mTypeTable
where ref = '3944900'

Returns:

If I change the substring from 1,3 to 1,4, then things work.

select string_agg( substring( mType,1,3 ), ',' )  mType
      ,string_agg( substring( mType,1,4), '-' )  mType2
from ourDB..mTypeTable
where ref = '3944900'

Returns:

Why does TSQL fail to change the delimiter in the first context? Is this some kind of optimization moment or something where TSQL is reusing the last substring because it's pulling from the same field in the same table in the same select?


问:
Flask POST Request to start an asynchronous process/task (or use websockets)
I have a Flask endpoint that starts an automated email campaign to a list of contacts I have. The body of the POST request has a "emailAmount" key which tells the process how many emails to send out.

Essentially what I want it to do is start the process of sending these emails out, and after each email sent out, show live feedback on the frontend like a loading bar, or just a live count of how many emails have been sent since the process started, and then some sort of live feedback on the front end telling the user when the process has completed. The email process is abstracted to a class I built called "AutomateEmailClient".

```<code>from flask import Blueprint
from flask_login import login_required, current_user
from forms.startProcess import ProcessForm
from ..emails.client import AutomateEmailClient

email_router = Blueprint("email",__name__)

@email_router.route('/start', methods=['POST'])
@login__required()
def start_process():
     form = ProcessForm() #Validate body of req with WTForms
     if form.validate_on_submit():
         #Interact with AutomateEmailClient object from different package a few levels up

         return #? Return synchronously after email process has finished? or asynchronously and use websockets for live feedback to frontend?

</code>```

However, after I return from the start_process() function, obviously the request/response cycle is dead, and if I just run the email process and have the return synchronously after, I would basically just have a hanging response for several minutes.

I'm assuming I need to use websockets, and possibly some sort of asynchronous functionality or multi processing, but I'm not sure what is the best approach or how to implement it.

Body:
I have a Flask endpoint that starts an automated email campaign to a list of contacts I have. The body of the POST request has a "emailAmount" key which tells the process how many emails to send out.

Essentially what I want it to do is start the process of sending these emails out, and after each email sent out, show live feedback on the frontend like a loading bar, or just a live count of how many emails have been sent since the process started, and then some sort of live feedback on the front end telling the user when the process has completed. The email process is abstracted to a class I built called "AutomateEmailClient".

from flask import Blueprint
from flask_login import login_required, current_user
from forms.startProcess import ProcessForm
from ..emails.client import AutomateEmailClient

email_router = Blueprint("email",__name__)

@email_router.route('/start', methods=['POST'])
@login__required()
def start_process():
     form = ProcessForm() #Validate body of req with WTForms
     if form.validate_on_submit():
         #Interact with AutomateEmailClient object from different package a few levels up

         return #? Return synchronously after email process has finished? or asynchronously and use websockets for live feedback to frontend?

However, after I return from the start_process() function, obviously the request/response cycle is dead, and if I just run the email process and have the return synchronously after, I would basically just have a hanging response for several minutes.

I'm assuming I need to use websockets, and possibly some sort of asynchronous functionality or multi processing, but I'm not sure what is the best approach or how to implement it.


问:
expo app crashes in production despite working fine in local te
My expo app worked perfectly on local android and ios simulators. Therefore, I published my app to the google play store, but it instantly crashed when i open it there. The crash bug report in google play console said this:

```<code>
Exception java.lang.AssertionError: APK bundle must contain the expected embedded asset index.android.bundle
at expo.modules.updates.loader.EmbeddedLoader.loadAsset (EmbeddedLoader.kt:85)
at expo.modules.updates.loader.Loader.downloadAllAssets (Loader.kt:226)
at expo.modules.updates.loader.Loader.processUpdateManifest (Loader.kt:189)
at expo.modules.updates.loader.Loader.access$processUpdateManifest (Loader.kt:18)
at expo.modules.updates.loader.Loader$start$1.onSuccess (Loader.kt:101)
at expo.modules.updates.loader.EmbeddedLoader.loadManifest (EmbeddedLoader.kt:58)
at expo.modules.updates.loader.Loader.start (Loader.kt:91)
at expo.modules.updates.loader.LoaderTask.launchFallbackUpdateFromDisk (LoaderTask.kt:242)
at expo.modules.updates.loader.LoaderTask.start (LoaderTask.kt:99)
at expo.modules.updates.UpdatesController.start (UpdatesController.kt:290)
at expo.modules.updates.UpdatesController$Companion.initialize (UpdatesController.kt:464)
at expo.modules.updates.UpdatesPackage$createReactNativeHostHandlers$handler$1.onWillCreateReactInstanceManager (UpdatesPackage.kt:41)
at expo.modules.ReactNativeHostWrapperBase.createReactInstanceManager (ReactNativeHostWrapperBase.kt:27)
at com.facebook.react.ReactNativeHost.getReactInstanceManager (ReactNativeHost.java:42)
at com.arnav_123.lbnapp_new.MainApplication.onCreate (MainApplication.java:66)
at android.app.Instrumentation.callApplicationOnCreate (Instrumentation.java:1211)
at android.app.ActivityThread.handleBindApplication (ActivityThread.java:7506)
at android.app.ActivityThread.access$1600 (ActivityThread.java:310)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2281)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loopOnce (Looper.java:226)
at android.os.Looper.loop (Looper.java:313)
at android.app.ActivityThread.main (ActivityThread.java:8669)
at java.lang.reflect.Method.invoke
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1135)

</code>```
```<code>Environment info:
expo-env-info 1.0.5 environment info:
System:
OS: macOS 12.0.1
Shell: 5.8 - /bin/zsh
Binaries:
Node: 16.17.0 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/bin/yarn
npm: 9.1.2 - ~/lbnapp_new/node_modules/.bin/npm
Managers:
CocoaPods: 1.11.3 - /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5
IDEs:
Android Studio: 2021.3 AI-213.7172.25.2113.9123335
Xcode: 13.4.1/13F100 - /usr/bin/xcodebuild
npmPackages:
@expo/webpack-config: ^0.17.0 => 0.17.3
expo: ^46.0.16 => 46.0.17
react: 18.0.0 => 18.0.0
react-dom: 18.0.0 => 18.0.0
react-native: 0.69.6 => 0.69.6
react-native-web: ~0.18.7 => 0.18.10
npmGlobalPackages:
eas-cli: 2.8.0
expo-cli: 6.0.8
Expo Workflow: bare

</code>```

Im truly at a loss, any help would be appreciated

Ran it on all local devices, but randomly crashes in production

Body:
My expo app worked perfectly on local android and ios simulators. Therefore, I published my app to the google play store, but it instantly crashed when i open it there. The crash bug report in google play console said this:

Exception java.lang.AssertionError: APK bundle must contain the expected embedded asset index.android.bundle
at expo.modules.updates.loader.EmbeddedLoader.loadAsset (EmbeddedLoader.kt:85)
at expo.modules.updates.loader.Loader.downloadAllAssets (Loader.kt:226)
at expo.modules.updates.loader.Loader.processUpdateManifest (Loader.kt:189)
at expo.modules.updates.loader.Loader.access$processUpdateManifest (Loader.kt:18)
at expo.modules.updates.loader.Loader$start$1.onSuccess (Loader.kt:101)
at expo.modules.updates.loader.EmbeddedLoader.loadManifest (EmbeddedLoader.kt:58)
at expo.modules.updates.loader.Loader.start (Loader.kt:91)
at expo.modules.updates.loader.LoaderTask.launchFallbackUpdateFromDisk (LoaderTask.kt:242)
at expo.modules.updates.loader.LoaderTask.start (LoaderTask.kt:99)
at expo.modules.updates.UpdatesController.start (UpdatesController.kt:290)
at expo.modules.updates.UpdatesController$Companion.initialize (UpdatesController.kt:464)
at expo.modules.updates.UpdatesPackage$createReactNativeHostHandlers$handler$1.onWillCreateReactInstanceManager (UpdatesPackage.kt:41)
at expo.modules.ReactNativeHostWrapperBase.createReactInstanceManager (ReactNativeHostWrapperBase.kt:27)
at com.facebook.react.ReactNativeHost.getReactInstanceManager (ReactNativeHost.java:42)
at com.arnav_123.lbnapp_new.MainApplication.onCreate (MainApplication.java:66)
at android.app.Instrumentation.callApplicationOnCreate (Instrumentation.java:1211)
at android.app.ActivityThread.handleBindApplication (ActivityThread.java:7506)
at android.app.ActivityThread.access$1600 (ActivityThread.java:310)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2281)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loopOnce (Looper.java:226)
at android.os.Looper.loop (Looper.java:313)
at android.app.ActivityThread.main (ActivityThread.java:8669)
at java.lang.reflect.Method.invoke
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1135)

Environment info:
expo-env-info 1.0.5 environment info:
System:
OS: macOS 12.0.1
Shell: 5.8 - /bin/zsh
Binaries:
Node: 16.17.0 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/bin/yarn
npm: 9.1.2 - ~/lbnapp_new/node_modules/.bin/npm
Managers:
CocoaPods: 1.11.3 - /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5
IDEs:
Android Studio: 2021.3 AI-213.7172.25.2113.9123335
Xcode: 13.4.1/13F100 - /usr/bin/xcodebuild
npmPackages:
@expo/webpack-config: ^0.17.0 => 0.17.3
expo: ^46.0.16 => 46.0.17
react: 18.0.0 => 18.0.0
react-dom: 18.0.0 => 18.0.0
react-native: 0.69.6 => 0.69.6
react-native-web: ~0.18.7 => 0.18.10
npmGlobalPackages:
eas-cli: 2.8.0
expo-cli: 6.0.8
Expo Workflow: bare

Im truly at a loss, any help would be appreciated

Ran it on all local devices, but randomly crashes in production


问:
How do these counters start at the same thing but count for different things and end up having different results?
```<code>import random
while True:
    fwd= random.randint(2,20)
    bkwd= random.randint(2,fwd-1)
    total=random.randint(10,85)
    f= 0
    b = 0
    t= 0
    steps_taken= 0

    if bkwd > fwd:
        break

#I don't understand how below this part works
    while total > 0:
        f = 0

        while fwd > f:
            if total > 0:
                print("F", end="")
                f=f+1
                t=t+1
                total=total-1
                steps_taken= steps_taken+1
            else:
               f = fwd
               t = t
               total = total
               steps_taken= steps_taken
#Up until f=fwd

        b = 0

        while bkwd > b:
            if total > 0:
                print("B", end="")
                t=t-1
                b=b+1
                total=total-1
                steps_taken= steps_taken+1
            else:
               b = bkwd
               t = t
               total = total
               steps_taken = steps_taken

    if f > total or b > total:
        break

print(" ",t, "steps from the start")
print("Forward:", f, "Backward:", b, "Total:", steps_taken )
</code>```

These are the instructions:

A person walks a random amount of steps forward, and then a different
random number of steps backwards.

The random steps are anywhere between 2 and 20 The number of steps
forward is always greater than the number of steps backwards That
motion of forward / backward random steps repeats itself again and
again The motion is consistent (the number of forward steps stays the
same throughout the motion, and the number of backwards steps stays
the same throughout the motion) After making a specific amount of
total steps the person is told to stop and will be a certain amount of
steps forward from where they started.

The total number of steps is generated randomly and will be between 10
and 85 You are writing a program to simulate the motion taken by the
person.

Display that motion and the number of steps he ends away from where he
started.

For Example:

If the program generated the forward steps to be 4, and the backward
steps to be 2, and the total number of steps to be 13, your program
would display:

```<code>FFFFBBFFFFBBF = 5 Steps from the start
</code>```

If the program generated the forward steps to be 5, and the backward steps to be 3, and the total steps to be 16, your program would display

```<code>FFFFFBBBFFFFFBBB = 4 Steps from the start
</code>```

Body:
import random
while True:
    fwd= random.randint(2,20)
    bkwd= random.randint(2,fwd-1)
    total=random.randint(10,85)
    f= 0
    b = 0
    t= 0
    steps_taken= 0

    if bkwd > fwd:
        break

#I don't understand how below this part works
    while total > 0:
        f = 0

        while fwd > f:
            if total > 0:
                print("F", end="")
                f=f+1
                t=t+1
                total=total-1
                steps_taken= steps_taken+1
            else:
               f = fwd
               t = t
               total = total
               steps_taken= steps_taken
#Up until f=fwd

        b = 0

        while bkwd > b:
            if total > 0:
                print("B", end="")
                t=t-1
                b=b+1
                total=total-1
                steps_taken= steps_taken+1
            else:
               b = bkwd
               t = t
               total = total
               steps_taken = steps_taken

    if f > total or b > total:
        break

print(" ",t, "steps from the start")
print("Forward:", f, "Backward:", b, "Total:", steps_taken )

These are the instructions:

A person walks a random amount of steps forward, and then a different
random number of steps backwards.

The random steps are anywhere between 2 and 20 The number of steps
forward is always greater than the number of steps backwards That
motion of forward / backward random steps repeats itself again and
again The motion is consistent (the number of forward steps stays the
same throughout the motion, and the number of backwards steps stays
the same throughout the motion) After making a specific amount of
total steps the person is told to stop and will be a certain amount of
steps forward from where they started.

The total number of steps is generated randomly and will be between 10
and 85 You are writing a program to simulate the motion taken by the
person.

Display that motion and the number of steps he ends away from where he
started.

For Example:

If the program generated the forward steps to be 4, and the backward
steps to be 2, and the total number of steps to be 13, your program
would display:

FFFFBBFFFFBBF = 5 Steps from the start

If the program generated the forward steps to be 5, and the backward steps to be 3, and the total steps to be 16, your program would display

FFFFFBBBFFFFFBBB = 4 Steps from the start


问:
golang command line flag syntax form
I want my go program to only accept command line flags with = form.

Those are forms from the flag documentation that are accepted currently:

```<code>-flag
--flag   // double dashes are also permitted
-flag=x
-flag x  // non-boolean flags only
</code>```

This is what I want my program to accept:

```<code>--flag=x
-flag=x
</code>```

Basically what I want to accomplish: go run . --color=blue "String I wanna color" here len(os.Args[1:]) should be 2.

Running with space: go run . --color blue "String I wanna color" here len(os.Args[1:] should be equal to 3.

I've only been learning programming for few weeks, I hope this question makes sense and has solution.

I read go flag documentation and looked into functions inside flag package to figure out solution, but I couldn't find anything related to my problem expect only boolean flag accepts form with = sign.

Title: golang command line flag syntax form

Body:
I want my go program to only accept command line flags with = form.

Those are forms from the flag documentation that are accepted currently:

-flag
--flag   // double dashes are also permitted
-flag=x
-flag x  // non-boolean flags only

This is what I want my program to accept:

--flag=x
-flag=x

Basically what I want to accomplish: go run . --color=blue "String I wanna color" here len(os.Args[1:]) should be 2.

Running with space: go run . --color blue "String I wanna color" here len(os.Args[1:] should be equal to 3.

I've only been learning programming for few weeks, I hope this question makes sense and has solution.

I read go flag documentation and looked into functions inside flag package to figure out solution, but I couldn't find anything related to my problem expect only boolean flag accepts form with = sign.


问:
Has 'exchange-information' from Binance-API an equivalent in CoinGecko-API?
With Binance-API (https://binance-docs.github.io/apidocs/futures/en/#exchange-information )
one can get this information

symbols > filters >
{
"filterType": "LOT_SIZE",
"maxQty": "10000000",
"minQty": "1",
"stepSize": "1"
},
{
"filterType": "MARKET_LOT_SIZE",
"maxQty": "590119",
"minQty": "1",
"stepSize": "1"
}`

this way (Python)

```<code>client = Client(api_key, api_secret, tld="com", testnet=TESTNET)
futures_info_dict = client.futures_exchange_info()
result = {}
for symbol_info in futures_info_dict\['symbols'\]:
    symbol = symbol_info\['symbol'\]
    filter_dict = symbol_info\['filters'\]\[2\]
    result\[symbol\] = {
        'minQty': float(filter_dict\['minQty'\]),
        'maxQty': float(filter_dict\['maxQty'\]),
        'precision': symbol_info\['quantityPrecision'\]
    }\`
</code>```

Can 'minQty', 'maxQty' be  extracted in a straightforward way with CoinGecko-API? If true, how?
If not, do the above items have equivalents in CoinGecko-API ? Thank you.

```<code>All I could do with CoinGecko-API was

    cg = CoinGeckoAPI()
    bitcoin_price = cg.get_price(ids='bitcoin', vs_currencies='usd')
    futures_info_dict = cg.get_exchanges_by_id('binance')

, getting a totally different output from 'exchange-information' ...
</code>```

Body:
With Binance-API (https://binance-docs.github.io/apidocs/futures/en/#exchange-information )
one can get this information

symbols > filters >
{
"filterType": "LOT_SIZE",
"maxQty": "10000000",
"minQty": "1",
"stepSize": "1"
},
{
"filterType": "MARKET_LOT_SIZE",
"maxQty": "590119",
"minQty": "1",
"stepSize": "1"
}`

this way (Python)

client = Client(api_key, api_secret, tld="com", testnet=TESTNET)
futures_info_dict = client.futures_exchange_info()
result = {}
for symbol_info in futures_info_dict\['symbols'\]:
    symbol = symbol_info\['symbol'\]
    filter_dict = symbol_info\['filters'\]\[2\]
    result\[symbol\] = {
        'minQty': float(filter_dict\['minQty'\]),
        'maxQty': float(filter_dict\['maxQty'\]),
        'precision': symbol_info\['quantityPrecision'\]
    }\`

Can 'minQty', 'maxQty' be  extracted in a straightforward way with CoinGecko-API? If true, how?
If not, do the above items have equivalents in CoinGecko-API ? Thank you.

All I could do with CoinGecko-API was

    cg = CoinGeckoAPI()
    bitcoin_price = cg.get_price(ids='bitcoin', vs_currencies='usd')
    futures_info_dict = cg.get_exchanges_by_id('binance')

, getting a totally different output from 'exchange-information' ...


问:
how to open Tomcat tcp fast open in springboot？
I want to use tcp fast open in springboot, in order to client can take request in tcp syn packet. But how can I open tfo in springboot as a server.

I search the question in Google but can not find any infomation


问:
MUI DatePicker + date-fns localization problem
The problem occours when I'm using MUI DatePicker with LocalizationProvider and AdapterDateFns with Hungarian local.

```<code><LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={hu}>
      <DesktopDatePicker
        value={value}
        onChange={(newValue) => {
          setValue(newValue);
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            inputProps={{
              ...params.inputProps,
              placeholder: "yyyy. MM. dd."
            }}
          />
        )}
      />
</LocalizationProvider>
</code>```

All latest dependencies.

The problem is when I'm trying to type in the date manually the curzor jumps around wierd in the month and day part. The LocalizationProvider transforms the input mask to "yyyy. MM. dd." and that is what I want to have, but it seems like the curzor doesn't adapt to the new format and bugs out.

You can try it here:

CodeSandbox

Is there any way to fix this or work around it?

NOTE: The cause seems to be the date-fns. It works fine with dayjs, but I have to use date-fns, so I have to make that work somehow.

Body:
The problem occours when I'm using MUI DatePicker with LocalizationProvider and AdapterDateFns with Hungarian local.

<LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={hu}>
      <DesktopDatePicker
        value={value}
        onChange={(newValue) => {
          setValue(newValue);
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            inputProps={{
              ...params.inputProps,
              placeholder: "yyyy. MM. dd."
            }}
          />
        )}
      />
</LocalizationProvider>

All latest dependencies.

The problem is when I'm trying to type in the date manually the curzor jumps around wierd in the month and day part. The LocalizationProvider transforms the input mask to "yyyy. MM. dd." and that is what I want to have, but it seems like the curzor doesn't adapt to the new format and bugs out.

You can try it here:

CodeSandbox

Is there any way to fix this or work around it?

NOTE: The cause seems to be the date-fns. It works fine with dayjs, but I have to use date-fns, so I have to make that work somehow.


问:
how to send widevine data from webview to external player
i have webview where if you create a url ending in m3u8 it will open an external player,

```<code>@Override
        // Force links to be opened inside WebView and not in Default Browser
        // Thanks http://stackoverflow.com/a/33681975/1815624
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.endsWith(".m3u8") || url.endsWith(".ts") || url.endsWith(".mpd") || url.endsWith(".mp4"))
            {
                try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse(url), "video/*");
                intent.setPackage("com.genuine.leone");
                view.getContext().startActivity(intent);
                return true; // to tell the WebView that it should not load the URL because you handled it by yourself
            }

                catch (ActivityNotFoundException e) {
// Player is not installed, you may want to open the play store link
                    }
    }
</code>```

the problem now, m3u8 requires a widevine license to play, how to send a widevine license url to the external player

i have to research but not find anything, any idea?

Body:
i have webview where if you create a url ending in m3u8 it will open an external player,

@Override
        // Force links to be opened inside WebView and not in Default Browser
        // Thanks http://stackoverflow.com/a/33681975/1815624
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.endsWith(".m3u8") || url.endsWith(".ts") || url.endsWith(".mpd") || url.endsWith(".mp4"))
            {
                try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse(url), "video/*");
                intent.setPackage("com.genuine.leone");
                view.getContext().startActivity(intent);
                return true; // to tell the WebView that it should not load the URL because you handled it by yourself
            }

                catch (ActivityNotFoundException e) {
// Player is not installed, you may want to open the play store link
                    }
    }

the problem now, m3u8 requires a widevine license to play, how to send a widevine license url to the external player

i have to research but not find anything, any idea?


问:
My App has rejected because of social account in authentication
My app require user sign in. and only social login is available. (google/apple)

for request review, I provide test account, but when they couldn't log in due to the authentication or 2-step verification process. so my app was rejected.
(Even though I create new google account and didn't set any security settings including the 2-step verification, however the identity verification process is included)

As an old memory, I know that Facebook was able to create test accounts for review
Is there a way to create a test account without any security settings provided by Google or Apple?

Please give me an idea...


问:
Make a Api Call with make.com and GoodBarber stuck
I would like to display information on Google Sheet, I have connected my GoodBarber API to my Google Sheet, however some data does not appear in the fields of Makes.com, I must therefore make a "Make a API Call" in order to get this information.

To do this, I installed this plugin, but I'm stuck on the code part for the API.

Here is a part:

Here is the feedback from the database, but the data that is not viisible on the sheet is:

```<code>"selected_delivery_slot": {

    "date": "2025-04-15",
    "slot_end": "08:40",
    "slot_start": "08:30"

},
</code>```

The configuration of the fields below are:

Can you help me please ?

Best regards,

I want with the Make.com solution to display all the data on a Google Sheet, but some data does not appear. So you have to call the "Make a API Call" module but I'm stuck at this step.

Body:
I would like to display information on Google Sheet, I have connected my GoodBarber API to my Google Sheet, however some data does not appear in the fields of Makes.com, I must therefore make a "Make a API Call" in order to get this information.

To do this, I installed this plugin, but I'm stuck on the code part for the API.

Here is a part:

Here is the feedback from the database, but the data that is not viisible on the sheet is:

"selected_delivery_slot": {

    "date": "2025-04-15",
    "slot_end": "08:40",
    "slot_start": "08:30"

},

The configuration of the fields below are:

Can you help me please ?

Best regards,

I want with the Make.com solution to display all the data on a Google Sheet, but some data does not appear. So you have to call the "Make a API Call" module but I'm stuck at this step.


问:
Can't run KMeans algorithm because Pandas DataFrame is loading decimal point numbers as strings
I drop all columns but the two I am interested in. When I try to convert my dataframe to a 2d numpy array from the two columns it turns into an object type that contains strings. I believe this is because the Data_Values has values such as "23.6." Is there anyway I can get rid of the decimal point and trailing numbers in this data as they are all different values.</p>
```<code>import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist
from scipy.spatial.distance import squareform
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from kneed import KneeLocator
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.metrics import pairwise_distances_argmin

data = pd.read_csv('Alzheimer_s_Disease_and_Healthy_Aging_Data.csv', engine='python', header=None)
data.columns = ['RowId', 'YearStart', 'YearEnd', 'LocationAbbr', 'LocationDesc', 'Datasource',  'Class',    'Topic',    'Question', 'Response',
                'Data_Value_Unit',  'DataValueTypeID', 'Data_Value_Type', 'Data_Value', 'Data_Value_Alt', 'Data_Value_Footnote_Symbol',
                'Data_Value_Footnote',  'Low_Confidence_Limit', 'High_Confidence_Limit',    'Sample_Size',  'StratificationCategory1',
                'Stratification1',  'StratificationCategory2',  'Stratification2',  'StratificationCategory3',  'Stratification3',  'Geolocation',
                'ClassID',  'TopicID',  'QuestionID',   'ResponseID',   'LocationID',   'StratificationCategoryID1',    'StratificationID1',
                'StratificationCategoryID2',    'StratificationID2',    'StratificationCategoryID3',    'StratificationID3',    'Report']
pd.set_option('display.max_columns', 10)
pd.set_option('display.max_rows', 10)
pd.set_option('display.width', 10)

data1 = data.iloc[1:]
df = data1[data1["Data_Value_Type"].str.contains("Mean") == False]
df = data1[data1["Data_Value"].str.contains("NaN") == False]

df.dropna()
df = df.drop(columns=['RowId', 'YearStart', 'YearEnd', 'LocationAbbr', 'LocationDesc', 'Datasource',    'Class',    'Topic',    'Question', 'Response',
                'Data_Value_Unit',  'DataValueTypeID', 'Data_Value_Type',   'Data_Value_Alt', 'Data_Value_Footnote_Symbol',
                'Data_Value_Footnote',  'Low_Confidence_Limit', 'High_Confidence_Limit',    'Sample_Size',  'StratificationCategory1',
                'Stratification1',  'StratificationCategory2',  'Stratification2',  'StratificationCategory3',  'Stratification3',  'Geolocation',
                'ClassID',  'TopicID',  'QuestionID',   'ResponseID',   'StratificationCategoryID1',    'StratificationID1',
                'StratificationCategoryID2',    'StratificationID2',    'StratificationCategoryID3',    'StratificationID3',    'Report'])

x = df.to_numpy()

print(x.dtype)
</code>```

Body:
I drop all columns but the two I am interested in. When I try to convert my dataframe to a 2d numpy array from the two columns it turns into an object type that contains strings. I believe this is because the Data_Values has values such as "23.6." Is there anyway I can get rid of the decimal point and trailing numbers in this data as they are all different values.

import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist
from scipy.spatial.distance import squareform
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from kneed import KneeLocator
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.metrics import pairwise_distances_argmin

data = pd.read_csv('Alzheimer_s_Disease_and_Healthy_Aging_Data.csv', engine='python', header=None)
data.columns = ['RowId', 'YearStart', 'YearEnd', 'LocationAbbr', 'LocationDesc', 'Datasource',  'Class',    'Topic',    'Question', 'Response',
                'Data_Value_Unit',  'DataValueTypeID', 'Data_Value_Type', 'Data_Value', 'Data_Value_Alt', 'Data_Value_Footnote_Symbol',
                'Data_Value_Footnote',  'Low_Confidence_Limit', 'High_Confidence_Limit',    'Sample_Size',  'StratificationCategory1',
                'Stratification1',  'StratificationCategory2',  'Stratification2',  'StratificationCategory3',  'Stratification3',  'Geolocation',
                'ClassID',  'TopicID',  'QuestionID',   'ResponseID',   'LocationID',   'StratificationCategoryID1',    'StratificationID1',
                'StratificationCategoryID2',    'StratificationID2',    'StratificationCategoryID3',    'StratificationID3',    'Report']
pd.set_option('display.max_columns', 10)
pd.set_option('display.max_rows', 10)
pd.set_option('display.width', 10)

data1 = data.iloc[1:]
df = data1[data1["Data_Value_Type"].str.contains("Mean") == False]
df = data1[data1["Data_Value"].str.contains("NaN") == False]

df.dropna()
df = df.drop(columns=['RowId', 'YearStart', 'YearEnd', 'LocationAbbr', 'LocationDesc', 'Datasource',    'Class',    'Topic',    'Question', 'Response',
                'Data_Value_Unit',  'DataValueTypeID', 'Data_Value_Type',   'Data_Value_Alt', 'Data_Value_Footnote_Symbol',
                'Data_Value_Footnote',  'Low_Confidence_Limit', 'High_Confidence_Limit',    'Sample_Size',  'StratificationCategory1',
                'Stratification1',  'StratificationCategory2',  'Stratification2',  'StratificationCategory3',  'Stratification3',  'Geolocation',
                'ClassID',  'TopicID',  'QuestionID',   'ResponseID',   'StratificationCategoryID1',    'StratificationID1',
                'StratificationCategoryID2',    'StratificationID2',    'StratificationCategoryID3',    'StratificationID3',    'Report'])

x = df.to_numpy()

print(x.dtype)


问:
changeVisibilityTimeout() call to SQS from Lambda fails without throwing exception
I have a lambda set up with event bridge to receive messages from an SQS with default vis timeout set to 5 minutes.

Inside the lambda, certain messages are supposed to be updated so that the vis timeout is increased to 10 minutes, and then an error is thrown on purpose to resend message (with the 10 min timeout) back to the SQS queue. The code logic in the lambda is as follows:

Check that message meets conditions

Set Visibility timeout to 10 minutes using synchronous (default) SQS client. Ignore the response object (but it should throw an error on timeout or failure, any response should imply success).

Write "New invisibility timeout" to log (this always appears, meaning the call must be completed)

Throw an exception to send the message back to the queue

This does work 99% of the time but I am seeing edge cases (often during heavy traffic) where the message comes back to the lambda after the default visibility timeout of 5 minutes (and they are not timing out because logs show complete processing). Additional info:

Lambda timeout: 5 minutes

Lambda retries: 2

SQS max receives: 5

Using Java 11

I will try setting the default visibility timeout to 10 minutes to circumnavigate the issue but hope it is a temp fix until I can understand root cause. How can the synchronous call to SQS not work but also not throw any exception?


问:
Plotly "melting" one trace onto another
Superimposing a trace onto another using plotly.

I've made a line trace in plotly for a dataframe, and I want to be able to superimpose a second trace on it, a way that makes the final product look like below, but as a line trace.

Trace with superimposed trace on it in scatter form:

Currently it looks like this (Single trace, no added traced):

I'd like to be able to do that in plotly!

Title: Plotly "melting" one trace onto another


问:
How to bind individual UrlPrefix to a particular network interface?
I am asking how to bind an UrlPrefix to a particular network interface via HTTP Server API (aka http.sys).
It seems IIS somehow can do this.

Netsh shows the interface IP as part of the UrlPrefix

```<code>> netsh http show servicestate view="requestq"
...
Number of registered URLs: 1
Registered URLs:
    HTTP://TEST.SITE.INVALID:80:192.168.202.142/
...                             ^^^^^^^^^^^^^^^
</code>```

And it works - curl returns error when i am trying to access the site via the localhost interface

```<code>> curl.exe -vi --connect-to "test.site.invalid:80:192.168.202.142:80"  http://test.site.invalid/something.html
... 200 OK

> curl.exe -vi --connect-to "test.site.invalid:80:127.0.0.1:80"  http://test.site.invalid/something.html
... 404 Not Found
</code>```

I couldn't find any mentions about such type of binding in the http server api docs. Moveover it says completely opposite

By default, once a registration is entered in the request queue, the HTTP Server API binds to the port specified in the UrlPrefix (for example port 80) for all IP addresses (INADDR_ANY or INADDR6_ANY) available on the machine.

You can add/delete a particular interface ip to the ip listen list on a whole host level but not for the individual urlprefix. Anyway the list is empty on my machine:

```<code>> netsh http show iplist

IP addresses present in the IP listen list:
-------------------------------------------

... nothing in the list
</code>```

It is puzzling me, does IIS use some undocumented API? Anybody know?

Body:
I am asking how to bind an UrlPrefix to a particular network interface via HTTP Server API (aka http.sys).
It seems IIS somehow can do this.

Netsh shows the interface IP as part of the UrlPrefix

> netsh http show servicestate view="requestq"
...
Number of registered URLs: 1
Registered URLs:
    HTTP://TEST.SITE.INVALID:80:192.168.202.142/
...                             ^^^^^^^^^^^^^^^

And it works - curl returns error when i am trying to access the site via the localhost interface

> curl.exe -vi --connect-to "test.site.invalid:80:192.168.202.142:80"  http://test.site.invalid/something.html
... 200 OK

> curl.exe -vi --connect-to "test.site.invalid:80:127.0.0.1:80"  http://test.site.invalid/something.html
... 404 Not Found

I couldn't find any mentions about such type of binding in the http server api docs. Moveover it says completely opposite

By default, once a registration is entered in the request queue, the HTTP Server API binds to the port specified in the UrlPrefix (for example port 80) for all IP addresses (INADDR_ANY or INADDR6_ANY) available on the machine.

You can add/delete a particular interface ip to the ip listen list on a whole host level but not for the individual urlprefix. Anyway the list is empty on my machine:

> netsh http show iplist

IP addresses present in the IP listen list:
-------------------------------------------

... nothing in the list

It is puzzling me, does IIS use some undocumented API? Anybody know?


问:
Apache camel aggregate by fized size
Using Apache camel, version: 3.19.0

I have a route that receives a body as a list with many elements.

I process each element of this list (MyProcessor).

I would like to send to the next route the messages grouped by 10 elements. I don't know  how to do it, I tried using aggregate but with no success.

```<code>from("direct:process-json")
        .process(new MyProcessor()).marshal().json().to("direct:route2");
</code>```

How can I send to route2 body items grouped by up to 10 elements?

Title: Apache camel aggregate by fized size

Body:
Using Apache camel, version: 3.19.0

I have a route that receives a body as a list with many elements.

I process each element of this list (MyProcessor).

I would like to send to the next route the messages grouped by 10 elements. I don't know  how to do it, I tried using aggregate but with no success.

from("direct:process-json")
        .process(new MyProcessor()).marshal().json().to("direct:route2");

How can I send to route2 body items grouped by up to 10 elements?


问:
Simple healthcheck endpoint in kong gateway
I have a docker container running with kong gateway.

I want to provide a rest interface/endpoint to check the health of the server and container. E.g. GET http://container.com/health/ which delivers

200 OK
'{"status":"UP"}';

What is the simplest and quickest solution or best practice?


问:
Android Connect to Bluetooth Printer
I have a bluetooth label printer that I want my app to connect to.  However, I am having a hard time connecting over the socket.  I keep getting this error:

java.io.IOException: read failed, socket might closed or timeout, read ret: -1

I have written this code to try and connect:

```<code>BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bluetoothDevicesList = bluetoothAdapter.getBondedDevices();
String deviceHardwareAddress = device.getAddress(); // MAC address

for (BluetoothDevice device : bluetoothDevicesList) {
    ParcelUuid[] uuids = device.getUuids();
    UUID uuid = (uuids != null && uuids.length > 0) ? uuids[0].getUuid() : UUID.randomUUID();

    BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
    socket.connect();
    OutputStream stream = socket.getOutputStream();
    byte[] data = new byte[0];
}
</code>```

The exception is being thrown on the socket.connect() line.  Any suggestions would be appreciated.

Title: Android Connect to Bluetooth Printer

Body:
I have a bluetooth label printer that I want my app to connect to.  However, I am having a hard time connecting over the socket.  I keep getting this error:

java.io.IOException: read failed, socket might closed or timeout, read ret: -1

I have written this code to try and connect:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bluetoothDevicesList = bluetoothAdapter.getBondedDevices();
String deviceHardwareAddress = device.getAddress(); // MAC address

for (BluetoothDevice device : bluetoothDevicesList) {
    ParcelUuid[] uuids = device.getUuids();
    UUID uuid = (uuids != null && uuids.length > 0) ? uuids[0].getUuid() : UUID.randomUUID();

    BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
    socket.connect();
    OutputStream stream = socket.getOutputStream();
    byte[] data = new byte[0];
}

The exception is being thrown on the socket.connect() line.  Any suggestions would be appreciated.