问:
Resizabble rubber band doesn't resize with QmainWindow
For an AI application, I need to define some overlays over images.

I am using the following code to draw a resizable rubberband on an image (Thanks to https://stackoverflow.com/users/11021720/vesa95 and https://stackoverflow.com/users/11162165/nathancy).

My problem is that when I resize the main window, the rubberband doesn't resize.

I have added a resize envent on the main window but the problem remains.

What did I missed ?

Here is the code I'm using:

```<code>import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class ResizableRubberBand(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ResizableRubberBand, self).__init__(parent)

        self.parentWidth = parent.width()
        self.parentHeight = parent.height()
        self.draggable = True
        self.dragging_threshold = 5
        self.mousePressPos = None
        self.mouseMovePos = None

        self.setWindowFlags(QtCore.Qt.SubWindow)
        layout = QtWidgets.QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(QtWidgets.QSizeGrip(self), 0, QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)
        self._band = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)
        self._band.show()
        self.show()

    def resizeEvent(self, event):
        self._band.resize(self.size())

    def paintEvent(self, event):
        # Get current window size
        window_size = self.size()
        qp = QtGui.QPainter()
        qp.begin(self)
        qp.setRenderHint(QtGui.QPainter.Antialiasing, True)
        qp.drawRect(0, 0, window_size.width(), window_size.height())
        qp.end()

    def mousePressEvent(self, event):
        if self.draggable and event.button() == QtCore.Qt.MiddleButton:
            self.mousePressPos = event.globalPos()                # global
            self.mouseMovePos = event.globalPos() - self.pos()    # local
        super(ResizableRubberBand, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self.draggable and event.buttons() & QtCore.Qt.MiddleButton:
            globalPos = event.globalPos()
            moved = globalPos - self.mousePressPos
            if moved.manhattanLength() > self.dragging_threshold:
                # Move when user drag window more than dragging_threshold
                diff = globalPos - self.mouseMovePos
                # Forbids the selection to go out of the frame
                if diff.x() <= 0 or diff.x() > self.parentWidth-self.width() :
                    diff = QtCore.QPoint(0 if diff.x()<=0 else self.parentWidth-self.width(),diff.y())
                if diff.y() <= 0 or diff.y() > self.parentHeight-self.height():
                    diff = QtCore.QPoint(diff.x(), 0 if diff.y()<=0 else self.parentHeight-self.height())
                self.move(diff)
                self.mouseMovePos = globalPos - self.pos()

        super(ResizableRubberBand, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if self.mousePressPos is not None:
            if event.button() == QtCore.Qt.MiddleButton:
                moved = event.globalPos() - self.mousePressPos
                if moved.manhattanLength() > self.dragging_threshold:
                    # Do not call click event or so on
                    event.ignore()
                self.mousePressPos = None
        super(ResizableRubberBand, self).mouseReleaseEvent(event)

class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtWidgets.QPushButton('Show Rubber Band')
        self.button.clicked.connect(self.handleButton)
        self.label = QtWidgets.QLabel()
        self.label.setScaledContents(True)
        self.label.setPixmap(QtGui.QPixmap('image.JPG'))
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.label)
        layout.addWidget(self.button)
        self.band = None

        imagePath = r"Linux-Logo.png"
        # Pixmap
        self.pixmap = QtGui.QPixmap(imagePath)
        self.qp = QtGui.QPainter(self.pixmap)
        self.label.setPixmap(self.pixmap)

    def handleButton(self):
        self.band = ResizableRubberBand(self.label)
        self.band.setGeometry(150, 150, 100, 100)

    def resizeEvent(self, event: QtGui.QResizeEvent):
        if self.band is not None:
            self.band.parentWidth = self.label.width()
            self.band.parentHeight = self.label.height()
        QtWidgets.QWidget.resizeEvent(self, event)

if __name__ == '__main__':

    # Test ResizableRubberBand
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setGeometry(300, 100, 600, 500)
    window.show()
    sys.exit(app.exec_())
</code>```

Here is my issue:

Rubberband creation

Result after resizing the main window => the rubberband has not been resized accordingly

Body:
For an AI application, I need to define some overlays over images.

I am using the following code to draw a resizable rubberband on an image (Thanks to https://stackoverflow.com/users/11021720/vesa95 and https://stackoverflow.com/users/11162165/nathancy).

My problem is that when I resize the main window, the rubberband doesn't resize.

I have added a resize envent on the main window but the problem remains.

What did I missed ?

Here is the code I'm using:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class ResizableRubberBand(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ResizableRubberBand, self).__init__(parent)

        self.parentWidth = parent.width()
        self.parentHeight = parent.height()
        self.draggable = True
        self.dragging_threshold = 5
        self.mousePressPos = None
        self.mouseMovePos = None

        self.setWindowFlags(QtCore.Qt.SubWindow)
        layout = QtWidgets.QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(QtWidgets.QSizeGrip(self), 0, QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)
        self._band = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)
        self._band.show()
        self.show()

    def resizeEvent(self, event):
        self._band.resize(self.size())

    def paintEvent(self, event):
        # Get current window size
        window_size = self.size()
        qp = QtGui.QPainter()
        qp.begin(self)
        qp.setRenderHint(QtGui.QPainter.Antialiasing, True)
        qp.drawRect(0, 0, window_size.width(), window_size.height())
        qp.end()

    def mousePressEvent(self, event):
        if self.draggable and event.button() == QtCore.Qt.MiddleButton:
            self.mousePressPos = event.globalPos()                # global
            self.mouseMovePos = event.globalPos() - self.pos()    # local
        super(ResizableRubberBand, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self.draggable and event.buttons() & QtCore.Qt.MiddleButton:
            globalPos = event.globalPos()
            moved = globalPos - self.mousePressPos
            if moved.manhattanLength() > self.dragging_threshold:
                # Move when user drag window more than dragging_threshold
                diff = globalPos - self.mouseMovePos
                # Forbids the selection to go out of the frame
                if diff.x() <= 0 or diff.x() > self.parentWidth-self.width() :
                    diff = QtCore.QPoint(0 if diff.x()<=0 else self.parentWidth-self.width(),diff.y())
                if diff.y() <= 0 or diff.y() > self.parentHeight-self.height():
                    diff = QtCore.QPoint(diff.x(), 0 if diff.y()<=0 else self.parentHeight-self.height())
                self.move(diff)
                self.mouseMovePos = globalPos - self.pos()

        super(ResizableRubberBand, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if self.mousePressPos is not None:
            if event.button() == QtCore.Qt.MiddleButton:
                moved = event.globalPos() - self.mousePressPos
                if moved.manhattanLength() > self.dragging_threshold:
                    # Do not call click event or so on
                    event.ignore()
                self.mousePressPos = None
        super(ResizableRubberBand, self).mouseReleaseEvent(event)

class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtWidgets.QPushButton('Show Rubber Band')
        self.button.clicked.connect(self.handleButton)
        self.label = QtWidgets.QLabel()
        self.label.setScaledContents(True)
        self.label.setPixmap(QtGui.QPixmap('image.JPG'))
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.label)
        layout.addWidget(self.button)
        self.band = None

        imagePath = r"Linux-Logo.png"
        # Pixmap
        self.pixmap = QtGui.QPixmap(imagePath)
        self.qp = QtGui.QPainter(self.pixmap)
        self.label.setPixmap(self.pixmap)

    def handleButton(self):
        self.band = ResizableRubberBand(self.label)
        self.band.setGeometry(150, 150, 100, 100)

    def resizeEvent(self, event: QtGui.QResizeEvent):
        if self.band is not None:
            self.band.parentWidth = self.label.width()
            self.band.parentHeight = self.label.height()
        QtWidgets.QWidget.resizeEvent(self, event)

if __name__ == '__main__':

    # Test ResizableRubberBand
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setGeometry(300, 100, 600, 500)
    window.show()
    sys.exit(app.exec_())

Here is my issue:

Rubberband creation

Result after resizing the main window => the rubberband has not been resized accordingly


来源: stackexchange

问:
Language and region combinations to distinguish GB from Northern Ireland content
We've gone down the route of using different locales files to separate out different content to display on pages that require specific content for Northern Ireland users.

So we have locales called 'en' and 'ni' currently. The problem is that these values are reflected in the language tag on the html page and we get an accessibility error for lang=ni.

While we could bundle all the NI content into the 'en' locale files and use the value of the region to conditionally display certain content, the changes we'd need to make would be less if we could rename the locales.

'en-GB' could be the choice for the bulk of the content.

I'd considered leaving the NI content in an 'en' locale, but a colleague wondered if for consistency we could use 'en-IE;.

For 'en-IE', would the 'IE' just mean Eire/the Republic of Ireland or could it be applied to Northern Ireland without offending anyone?

ContentLicense: CC BY-SA 4.0


问:
flutter firebase push notification not working when iOS app is open
When I try to send a notification in iOS with open app, the badge not showing but when app is in background or foreground, the notification appear correctly.
I try this on my iPhone and not on simulator!

On android work correctly.

I have this code in my main.dart:

```<code>Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');
}

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  description:
      'This channel is used for important notifications.', // description
  importance: Importance.high,
);

const IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  const storage = FlutterSecureStorage();
  String? token = await storage.read(key: 'token');
  String? isFirstTime = await storage.read(key: 'isFirstTime');
  String? verify = await storage.read(key: 'verify');

  await Firebase.initializeApp();

  if (isFirstTime == null || isFirstTime == "true") {
    await Permission.notification.request();
  }
  await FirebaseMessaging.instance.subscribeToTopic("NEWS");
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    print('User granted permission');
  } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
    print('User granted provisional permission');
  } else {
    print('User declined or has not accepted permission');
  }
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  runApp(App());
}
</code>```

If I try to print local message in my FirebaseMessaging.onMessage.listen, the response in correct, so this is the event.

In my app.dart:

```<code>Future<void> getToken() async {
  final FirebaseMessaging _fcm = FirebaseMessaging.instance;
  final token = await _fcm.getToken();
  print("#####################################################");
  print(token.toString());
  print("#####################################################");
}

class _AppState extends State<App> {
  @override
  void initState() {
    var initialzationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettings = InitializationSettings(
      android: initialzationSettingsAndroid,
      iOS: IOSInitializationSettings(),
    );

    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      AppleNotification? ios = message.notification?.apple;
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
                android: AndroidNotificationDetails(
                  channel.id,
                  channel.name,
                  channelDescription: channel.description,
                  icon: android.smallIcon,
                ),
                iOS: IOSNotificationDetails()),
            payload: message.data['click_action']);
      }
    });

    FirebaseMessaging.instance.getInitialMessage().then((value) async {
      if (value != null) {
        String ask = value.data['click_action'];
        if (ask.contains('www') || ask.contains('http')) {
          openLink(Uri.parse(ask));
        }
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      if (message != null) {
        String ask = message.data['click_action'];
        if (ask.contains('www') || ask.contains('http')) {
          openLink(Uri.parse(ask));
        }
      }
    });

    getToken();
    super.initState();
  }
}

</code>```

Body:
When I try to send a notification in iOS with open app, the badge not showing but when app is in background or foreground, the notification appear correctly.
I try this on my iPhone and not on simulator!

On android work correctly.

I have this code in my main.dart:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');
}

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  description:
      'This channel is used for important notifications.', // description
  importance: Importance.high,
);

const IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  const storage = FlutterSecureStorage();
  String? token = await storage.read(key: 'token');
  String? isFirstTime = await storage.read(key: 'isFirstTime');
  String? verify = await storage.read(key: 'verify');

  await Firebase.initializeApp();

  if (isFirstTime == null || isFirstTime == "true") {
    await Permission.notification.request();
  }
  await FirebaseMessaging.instance.subscribeToTopic("NEWS");
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    print('User granted permission');
  } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
    print('User granted provisional permission');
  } else {
    print('User declined or has not accepted permission');
  }
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  runApp(App());
}

If I try to print local message in my FirebaseMessaging.onMessage.listen, the response in correct, so this is the event.

In my app.dart:

Future<void> getToken() async {
  final FirebaseMessaging _fcm = FirebaseMessaging.instance;
  final token = await _fcm.getToken();
  print("#####################################################");
  print(token.toString());
  print("#####################################################");
}

class _AppState extends State<App> {
  @override
  void initState() {
    var initialzationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettings = InitializationSettings(
      android: initialzationSettingsAndroid,
      iOS: IOSInitializationSettings(),
    );

    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      AppleNotification? ios = message.notification?.apple;
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
                android: AndroidNotificationDetails(
                  channel.id,
                  channel.name,
                  channelDescription: channel.description,
                  icon: android.smallIcon,
                ),
                iOS: IOSNotificationDetails()),
            payload: message.data['click_action']);
      }
    });

    FirebaseMessaging.instance.getInitialMessage().then((value) async {
      if (value != null) {
        String ask = value.data['click_action'];
        if (ask.contains('www') || ask.contains('http')) {
          openLink(Uri.parse(ask));
        }
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      if (message != null) {
        String ask = message.data['click_action'];
        if (ask.contains('www') || ask.contains('http')) {
          openLink(Uri.parse(ask));
        }
      }
    });

    getToken();
    super.initState();
  }
}


问:
Refused to execute script from '' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
Refused to execute script from 'http://localhost:4000/js/main.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Please take a look at my code and help me figure out the problem. I'm stuck with this

index.js

```<code>const express = require('express');
const app = express();
const socketio = require('socket.io');

const userRoutes = require('../routes/user');
const bodyParser = require('body-parser');
const player = require('play-sound')(opts = {});
const formatMessage = require('../utils/formatMessage');

app.use(bodyParser.json())
app.use(
    bodyParser.urlencoded({
        extended: true
    })
);
//app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

const expressServer = app.listen(process.env.PORT || 4000, () => {
    console.log(`Server's up & running on http://localhost:4000/`)
})

const io = socketio(expressServer);

//socket.io listening for connections events
io.on("connection", (socket) => {

    //if any error occurs on connection
    socket.on("connect_error", (err) => {
        console.log(err.message);
    });

    const userId = socket.id;
    console.log('userID: ' + userId);

    socket.broadcast.emit('message', formatMessage('newUser', `${userId} joined the chat`));

    socket.on('disconnect', () => {
        io.emit('message', formatMessage('human', `${userId} left the chat`));
    });

    //catching the chatMessage coming from client input
    socket.on('sendChatMessage', (message) => {
        console.log("received from client: " + message);

        //sending chatMessage back to client after receiving on server
        io.emit('message', formatMessage('chatbot', message));

        //playing notification sound
        // player.play('../audio/hnm.mp3', (err) => {
        //     if(err) {
        //         throw err;
        //     }
        // });
    });
})
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- <link rel="stylesheet" href="./css/style.css"> -->

    <title>chatroom</title>
</head>
<body>

    <div class="container">
        <div class="chat-box">
            <div class="messages">

                <ul class="msg-list" id="msg-list">

                </ul>
            </div>
            <div class="sender-input">
                <form action="" id="form">
                    <input type="text" id="msg" placeholder="message goes here...">
                    <button type="submit">send</button>
                </form>
            </div>
        </div>
        <div class="users">
            <ul class="user-list">
            </ul>
        </div>
    </div>

</body>

    <script src="/socket.io/socket.io.js"> </script>
    <script src="./js/main.js">
        export default name = prompt(`What's your Name boi?`);
        // const socket = io('http://localhost:4000');
        const socket = io();

        const form = document.getElementById('form');
        const messageBody = document.querySelector('.messages');

        //output message to DOM
        const outputMessage = (message) => {
            const list = document.createElement('li');
            list.classList.add('list-item');
            list.innerHTML = `
                        <p class="meta"> ${message.username} <span> ${message.time} </span> </p>
                        <P class="text">${message.text}</P>
            `;
            document.getElementById('msg-list').appendChild(list);
        }

        socket.on('message', (message) => {
            console.log("send by the server: " + message.text);
            outputMessage(message);

            //scroll to top
            messageBody.scrollTop = messageBody.scrollHeight;
        });

        //listening for submit event when user will send chat
        form.addEventListener('submit', (event) => {
            event.preventDefault()

            //catching chat-message from the input box
            const chatMessageBox = document.getElementById('msg');
            const chatMessage = chatMessageBox.value;

            //emitting chatMessage to server
            socket.emit('sendChatMessage', chatMessage);

            //clear input box and focus
            chatMessageBox.value = "";
            chatMessageBox.focus();
        });

    </script>

</html>
</code>```

folder structure

I tried many things but i'm unable to find the exact problem

Body:
Refused to execute script from 'http://localhost:4000/js/main.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Please take a look at my code and help me figure out the problem. I'm stuck with this

index.js

const express = require('express');
const app = express();
const socketio = require('socket.io');

const userRoutes = require('../routes/user');
const bodyParser = require('body-parser');
const player = require('play-sound')(opts = {});
const formatMessage = require('../utils/formatMessage');

app.use(bodyParser.json())
app.use(
    bodyParser.urlencoded({
        extended: true
    })
);
//app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

const expressServer = app.listen(process.env.PORT || 4000, () => {
    console.log(`Server's up & running on http://localhost:4000/`)
})

const io = socketio(expressServer);

//socket.io listening for connections events
io.on("connection", (socket) => {

    //if any error occurs on connection
    socket.on("connect_error", (err) => {
        console.log(err.message);
    });

    const userId = socket.id;
    console.log('userID: ' + userId);

    socket.broadcast.emit('message', formatMessage('newUser', `${userId} joined the chat`));

    socket.on('disconnect', () => {
        io.emit('message', formatMessage('human', `${userId} left the chat`));
    });

    //catching the chatMessage coming from client input
    socket.on('sendChatMessage', (message) => {
        console.log("received from client: " + message);

        //sending chatMessage back to client after receiving on server
        io.emit('message', formatMessage('chatbot', message));

        //playing notification sound
        // player.play('../audio/hnm.mp3', (err) => {
        //     if(err) {
        //         throw err;
        //     }
        // });
    });
})

index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>chatroom</title>

                <form action="" id="form">
                    <input type="text" id="msg" placeholder="message goes here...">
                    <button type="submit">send</button>
                </form>

folder structure

I tried many things but i'm unable to find the exact problem


问:
Parse value of the dot separated string from JSON in ruby
How to grab the value of input string this.is.string from json in ruby.

JSON file test.json looks like this:

{
  "this": {
    "is": {
      "string": "value"
    }
  }
}
```
<pre class="lang-rb prettyprint-override"><code># Opening the json file to read the data
json_file = File.open("test.json")

# Reading the data from the json file
data_from_file = JSON.load(json_file)

get_value = data_from_file["this"]["is"]["string"]
</code>```

works, but how to determine how many elements I need to use in data_from_file["this"]["is"]["string"] ?

What if the input string is this.is.yet.another.string? Is there any determinisitc way how to achieve this, please?

UPDATE

It seems that this works fine:

def get_value(data, query)
  query.split('.').inject(data) do |v, k|
    k = k.to_i if v.is_a? Array
    v.fetch(k)
  end
end

get_value(data_from_file, 'this.is.string')
=> "value"
```

Body:
How to grab the value of input string this.is.string from json in ruby.

JSON file test.json looks like this:

{
  "this": {
    "is": {
      "string": "value"
    }
  }
}

# Opening the json file to read the data
json_file = File.open("test.json")

# Reading the data from the json file
data_from_file = JSON.load(json_file)

get_value = data_from_file["this"]["is"]["string"]

works, but how to determine how many elements I need to use in data_from_file["this"]["is"]["string"] ?

What if the input string is this.is.yet.another.string? Is there any determinisitc way how to achieve this, please?

UPDATE

It seems that this works fine:

def get_value(data, query)
  query.split('.').inject(data) do |v, k|
    k = k.to_i if v.is_a? Array
    v.fetch(k)
  end
end

get_value(data_from_file, 'this.is.string')
=> "value"


问:
Is Google Ads API a sensitive Scope in Google Cloud Platform Console
I am having issued with Google Ads API scope verification in Google Cloud. It is listed as Sensitive Scope and requires additional materials (such as uploading explanation video to YouTube)

Is that true that from now on the Google Ads API is sensitive scope and I need to create a video or something is just wrong on our side (wrong scope selection etc.)

Thanks in advance!

Checked Google materials.


问:
Exporting Charts as png from excel using python
```<code>def saveExcelGraphAsPNG(comb, InputFolder):
        # Open the excel application using win32com
        o = wincl.Dispatch("Excel.Application")
        # Disable alerts and visibility to the user
        o.Visible = False
        o.DisplayAlerts = 0
        # Open workbook
        wb = o.Workbooks.Open(comb)
        # List all the sheet names
        ws=[]
        for sh in wb.Sheets:
            ws.append(sh.Name)

        # Create a Directory for storing all the images from the Excel
        try:
            os.stat(InputFolder+'/Image/')
        except:
            os.mkdir(InputFolder+'/Image/')
        for i in range(1,len(ws)):
            for n, shape in enumerate(o.Sheets(ws[i]).Shapes):
                # Save shape to clipboard, then save what is in the clipboard to the file
                shape.Copy()
                name = 'comb'+str(n)+'.png'
                image = ImageGrab.grabclipboard()
                imgFile = InputFolder+'/Image/'+name
                # '_'
                # Saves the image into the existing png file (overwriting) TODO ***** Have try except?
                image.save(imgFile,'png')
                pass
            pass
        pass
        wb.Close(True)
        o.Application.Quit()
        del o
    saveExcelGraphAsPNG(comb, InputFolder)
    print("Images Exported")
</code>```

When I try to execute this python code the following error occurs

com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221040), None)

but when i close the excel app from task manager and run it again the same code works can anyone help me with this

Body:
def saveExcelGraphAsPNG(comb, InputFolder):
        # Open the excel application using win32com
        o = wincl.Dispatch("Excel.Application")
        # Disable alerts and visibility to the user
        o.Visible = False
        o.DisplayAlerts = 0
        # Open workbook
        wb = o.Workbooks.Open(comb)
        # List all the sheet names
        ws=[]
        for sh in wb.Sheets:
            ws.append(sh.Name)

        # Create a Directory for storing all the images from the Excel
        try:
            os.stat(InputFolder+'/Image/')
        except:
            os.mkdir(InputFolder+'/Image/')
        for i in range(1,len(ws)):
            for n, shape in enumerate(o.Sheets(ws[i]).Shapes):
                # Save shape to clipboard, then save what is in the clipboard to the file
                shape.Copy()
                name = 'comb'+str(n)+'.png'
                image = ImageGrab.grabclipboard()
                imgFile = InputFolder+'/Image/'+name
                # '_'
                # Saves the image into the existing png file (overwriting) TODO ***** Have try except?
                image.save(imgFile,'png')
                pass
            pass
        pass
        wb.Close(True)
        o.Application.Quit()
        del o
    saveExcelGraphAsPNG(comb, InputFolder)
    print("Images Exported")

When I try to execute this python code the following error occurs

com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221040), None)

but when i close the excel app from task manager and run it again the same code works can anyone help me with this


问:
Class file version 61 but should be 55 in IntelliJ configuration
I have this problem where I try to build my Spring project in Java 11, but for some reason IntelliJ compiles the class in Java 17 thus the version of the class file in pom.xml file error my project structure. I also wanted to dockerize the application, but I get the same error  dockerization  java version in cmd

I need to build my Docker application but there is error in Java version files, why does IntelliJ build the class files in Java 17 (class file version 61) but not 11 when I set it.


问:
Setting up increased grip in WheelCollider in Unity
I'm making a racing mini game. I'm trying to set up the WheelCollider so that the car has a good grip on the road. By default, the car slides on the road, so I changed the ExtremumSlip and ExtremumValue in SideWays Friction to 0.6 and 3 respectively. Now, when turning, the car practically does not slide, but another problem arose, in the case of a sharp turn, the car literally turns 180 degrees, I tried to play with the Asymptote parmeters, but this did not give the proper result. Are there any standard WheelCollider setup templates for off-road racing or city racing, etc?


问:
pgbouncer is closing new login attempt, while it is trying to clear the idle connections
MCM is java application which is using pgbouncer to connect to Amazon RDS (postgreSQL)
Errors reported on different layers

Instance 1 MCM log:

```<code>Line  192: 24/Nov/2022:00:18:40 +0000 - logging uri: POST /mcm-provider/ext-rt/publishv2/onmp_dsg/dsg_order HTTP/1.1 | status code: 401 | bytes: 364 | elapsed time: 75603 | response-log: [36m{"id":"04a-6e90e350534d","requestId":"65f76699-9440-429c-aeb3-5aab82bae579","responseType":"ingestPublication-rt-Ack","responseCode":"ER204","responseDesc":"ERROR:Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection","acknowledgeId":"3b4-b42ff20dc1e1"}[0;39m
</code>```

Instance 1 pgbouncer log:

```<code>Line 11458: 2022-11-24 00:18:40.478 UTC [231189] LOG C-0xe3ca70: (nodb)/(nouser)@100.65.252.10:52716 closing because: cancel request for idle client (age=0s)
Line 11459: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe579f0: (nodb)/(nouser)@100.65.119.209:47770 closing because: cancel request for idle client (age=0s)
Line 11460: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe54c00: (nodb)/(nouser)@100.65.62.39:54562 closing because: cancel request for idle client (age=0s)
Line 11461: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe4b9c0: (nodb)/(nouser)@100.65.62.39:54564 closing because: cancel request for idle client (age=0s)
Line 11462: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe49490: (nodb)/(nouser)@100.66.226.39:30768 closing because: cancel request for idle client (age=0s)
Line 11463: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe53cb0: (nodb)/(nouser)@100.65.62.39:54594 closing because: cancel request for idle client (age=0s)
Line 11464: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe4cb40: (nodb)/(nouser)@100.65.252.10:52732 closing because: cancel request for idle client (age=0s)
Line 11465: 2022-11-24 00:18:40.484 UTC [231189] LOG C-0xe7e080: (nodb)/(nouser)@100.65.252.10:52754 closing because: cancel request for idle client (age=0s)
Line 11468: 2022-11-24 00:18:40.484 UTC [231189] LOG C-0xe510f0: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:47738 closing because: client_login_timeout (age=75s)
Line 11469: 2022-11-24 00:18:40.484 UTC [231189] WARNING C-0xe510f0: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:47738 pooler error: client_login_timeout
</code>```

Instance 2 MCM log:

```<code>Line 1715: 24/Nov/2022:02:54:43 +0000 - logging uri: POST /mcm-provider/ext-rt/publishv2/onmp_dsg/dsg_order HTTP/1.1 | status code: 401 | bytes: 364 | elapsed time: 72920 |response-log: [36m{"id":"23a-c2ce5c4e1da8","requestId":"ede584fa-600f-4d53-a04e-326d8890e306","responseType":"ingestPublication-rt-Ack","responseCode":"ER204","responseDesc":"ERROR:Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection","acknowledgeId":"409-7393bb9ef7f4"}[0;39m
</code>```

Instance 2 pgbouncer log:

```<code>Line 30781: 2022-11-24 02:54:43.929 UTC [231189] LOG C-0xe3d9c0: (nodb)/(nouser)@100.65.62.39:22744 closing because: cancel request for idle client (age=0s)
Line 30782: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe758e0: (nodb)/(nouser)@100.65.62.39:22746 closing because: cancel request for idle client (age=0s)
Line 30783: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe77320: (nodb)/(nouser)@100.66.226.39:33710 closing because: cancel request for idle client (age=0s)
Line 30784: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe4be20: (nodb)/(nouser)@100.65.252.10:57638 closing because: cancel request for idle client (age=0s)
Line 30785: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe48e00: (nodb)/(nouser)@100.65.119.209:22638 closing because: cancel request for idle client (age=0s)
Line 30786: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe79620: (nodb)/(nouser)@100.65.119.209:22640 closing because: cancel request for idle client (age=0s)
Line 30787: 2022-11-24 02:54:43.932 UTC [231189] LOG C-0xe4c6e0: (nodb)/(nouser)@100.65.119.209:22680 closing because: cancel request for idle client (age=0s)
Line 30790: 2022-11-24 02:54:43.932 UTC [231189] LOG C-0xe6c1f0: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:22596 closing because: client_login_timeout (age=72s)
Line 30791: 2022-11-24 02:54:43.932 UTC [231189] WARNING C-0xe6c1f0: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:22596 pooler error: client_login_timeout
</code>```

Instance 3 MCM log:

```<code>Line 2230: 24/Nov/2022:04:09:33 +0000 - logging uri: POST /mcm-provider/ext-rt/publishv2/onmp_dsg/dsg_order HTTP/1.1 | status code: 401 | bytes: 364 | elapsed time: 69204 | response-log: [36m{"id":"334-6195225a4413","requestId":"aef4c23c-16bd-4e8a-b465-6e574fc32cc5","responseType":"ingestPublication-rt-Ack","responseCode":"ER204","responseDesc":"ERROR:Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection","acknowledgeId":"555-2781ef4a5827"}[0;39m
</code>```

Instance 3 pgbouncer log:

```<code>Line 37456: 2022-11-24 04:09:33.109 UTC [231189] LOG C-0xe6c650: (nodb)/(nouser)@100.65.62.39:38044 closing because: cancel request for idle client (age=0s)
Line 37457: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe6a9e0: (nodb)/(nouser)@100.65.252.10:60076 closing because: cancel request for idle client (age=0s)
Line 37458: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe50ec0: (nodb)/(nouser)@100.65.62.39:38048 closing because: cancel request for idle client (age=0s)
Line 37459: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe49d50: (nodb)/(nouser)@100.65.62.39:38050 closing because: cancel request for idle client (age=0s)
Line 37460: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe6ac10: (nodb)/(nouser)@100.65.119.209:37208 closing because: cancel request for idle client (age=0s)
Line 37461: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe51e10: (nodb)/(nouser)@100.65.119.209:37220 closing because: cancel request for idle client (age=0s)
Line 37462: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe75020: (nodb)/(nouser)@100.66.226.39:35340 closing because: cancel request for idle client (age=0s)
Line 37463: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe3c610: (nodb)/(nouser)@100.65.252.10:60116 closing because: cancel request for idle client (age=0s)
Line 37466: 2022-11-24 04:09:33.111 UTC [231189] LOG C-0xe5d170: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:37176 closing because: client_login_timeout (age=69s)
Line 37467: 2022-11-24 04:09:33.111 UTC [231189] WARNING C-0xe5d170: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:37176 pooler error: client_login_timeout
</code>```

pgbouncer configuration:

```<code>server_idle_timeout = 60
server_connect_timeout = 15
client_idle_timeout = 0
client_login_timeout = 60
</code>```

This error scenario is intermitted and wherever the application is making a connection login while pgbouncer is clearing the idle connection there is a JDBC exception occurred in the client side. There were no issues reported in the RDS side.
Why pgbouncer is clearing the client login request, while clearing the idle connection. Are there any configuration changes required in pgbouncer to handle this scenario?

Body:
MCM is java application which is using pgbouncer to connect to Amazon RDS (postgreSQL)
Errors reported on different layers

Instance 1 MCM log:

Line  192: 24/Nov/2022:00:18:40 +0000 - logging uri: POST /mcm-provider/ext-rt/publishv2/onmp_dsg/dsg_order HTTP/1.1 | status code: 401 | bytes: 364 | elapsed time: 75603 | response-log: [36m{"id":"04a-6e90e350534d","requestId":"65f76699-9440-429c-aeb3-5aab82bae579","responseType":"ingestPublication-rt-Ack","responseCode":"ER204","responseDesc":"ERROR:Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection","acknowledgeId":"3b4-b42ff20dc1e1"}[0;39m

Instance 1 pgbouncer log:

Line 11458: 2022-11-24 00:18:40.478 UTC [231189] LOG C-0xe3ca70: (nodb)/(nouser)@100.65.252.10:52716 closing because: cancel request for idle client (age=0s)
Line 11459: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe579f0: (nodb)/(nouser)@100.65.119.209:47770 closing because: cancel request for idle client (age=0s)
Line 11460: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe54c00: (nodb)/(nouser)@100.65.62.39:54562 closing because: cancel request for idle client (age=0s)
Line 11461: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe4b9c0: (nodb)/(nouser)@100.65.62.39:54564 closing because: cancel request for idle client (age=0s)
Line 11462: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe49490: (nodb)/(nouser)@100.66.226.39:30768 closing because: cancel request for idle client (age=0s)
Line 11463: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe53cb0: (nodb)/(nouser)@100.65.62.39:54594 closing because: cancel request for idle client (age=0s)
Line 11464: 2022-11-24 00:18:40.483 UTC [231189] LOG C-0xe4cb40: (nodb)/(nouser)@100.65.252.10:52732 closing because: cancel request for idle client (age=0s)
Line 11465: 2022-11-24 00:18:40.484 UTC [231189] LOG C-0xe7e080: (nodb)/(nouser)@100.65.252.10:52754 closing because: cancel request for idle client (age=0s)
Line 11468: 2022-11-24 00:18:40.484 UTC [231189] LOG C-0xe510f0: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:47738 closing because: client_login_timeout (age=75s)
Line 11469: 2022-11-24 00:18:40.484 UTC [231189] WARNING C-0xe510f0: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:47738 pooler error: client_login_timeout

Instance 2 MCM log:

Line 1715: 24/Nov/2022:02:54:43 +0000 - logging uri: POST /mcm-provider/ext-rt/publishv2/onmp_dsg/dsg_order HTTP/1.1 | status code: 401 | bytes: 364 | elapsed time: 72920 |response-log: [36m{"id":"23a-c2ce5c4e1da8","requestId":"ede584fa-600f-4d53-a04e-326d8890e306","responseType":"ingestPublication-rt-Ack","responseCode":"ER204","responseDesc":"ERROR:Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection","acknowledgeId":"409-7393bb9ef7f4"}[0;39m

Instance 2 pgbouncer log:

Line 30781: 2022-11-24 02:54:43.929 UTC [231189] LOG C-0xe3d9c0: (nodb)/(nouser)@100.65.62.39:22744 closing because: cancel request for idle client (age=0s)
Line 30782: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe758e0: (nodb)/(nouser)@100.65.62.39:22746 closing because: cancel request for idle client (age=0s)
Line 30783: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe77320: (nodb)/(nouser)@100.66.226.39:33710 closing because: cancel request for idle client (age=0s)
Line 30784: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe4be20: (nodb)/(nouser)@100.65.252.10:57638 closing because: cancel request for idle client (age=0s)
Line 30785: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe48e00: (nodb)/(nouser)@100.65.119.209:22638 closing because: cancel request for idle client (age=0s)
Line 30786: 2022-11-24 02:54:43.931 UTC [231189] LOG C-0xe79620: (nodb)/(nouser)@100.65.119.209:22640 closing because: cancel request for idle client (age=0s)
Line 30787: 2022-11-24 02:54:43.932 UTC [231189] LOG C-0xe4c6e0: (nodb)/(nouser)@100.65.119.209:22680 closing because: cancel request for idle client (age=0s)
Line 30790: 2022-11-24 02:54:43.932 UTC [231189] LOG C-0xe6c1f0: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:22596 closing because: client_login_timeout (age=72s)
Line 30791: 2022-11-24 02:54:43.932 UTC [231189] WARNING C-0xe6c1f0: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:22596 pooler error: client_login_timeout

Instance 3 MCM log:

Line 2230: 24/Nov/2022:04:09:33 +0000 - logging uri: POST /mcm-provider/ext-rt/publishv2/onmp_dsg/dsg_order HTTP/1.1 | status code: 401 | bytes: 364 | elapsed time: 69204 | response-log: [36m{"id":"334-6195225a4413","requestId":"aef4c23c-16bd-4e8a-b465-6e574fc32cc5","responseType":"ingestPublication-rt-Ack","responseCode":"ER204","responseDesc":"ERROR:Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection","acknowledgeId":"555-2781ef4a5827"}[0;39m

Instance 3 pgbouncer log:

Line 37456: 2022-11-24 04:09:33.109 UTC [231189] LOG C-0xe6c650: (nodb)/(nouser)@100.65.62.39:38044 closing because: cancel request for idle client (age=0s)
Line 37457: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe6a9e0: (nodb)/(nouser)@100.65.252.10:60076 closing because: cancel request for idle client (age=0s)
Line 37458: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe50ec0: (nodb)/(nouser)@100.65.62.39:38048 closing because: cancel request for idle client (age=0s)
Line 37459: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe49d50: (nodb)/(nouser)@100.65.62.39:38050 closing because: cancel request for idle client (age=0s)
Line 37460: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe6ac10: (nodb)/(nouser)@100.65.119.209:37208 closing because: cancel request for idle client (age=0s)
Line 37461: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe51e10: (nodb)/(nouser)@100.65.119.209:37220 closing because: cancel request for idle client (age=0s)
Line 37462: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe75020: (nodb)/(nouser)@100.66.226.39:35340 closing because: cancel request for idle client (age=0s)
Line 37463: 2022-11-24 04:09:33.110 UTC [231189] LOG C-0xe3c610: (nodb)/(nouser)@100.65.252.10:60116 closing because: cancel request for idle client (age=0s)
Line 37466: 2022-11-24 04:09:33.111 UTC [231189] LOG C-0xe5d170: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:37176 closing because: client_login_timeout (age=69s)
Line 37467: 2022-11-24 04:09:33.111 UTC [231189] WARNING C-0xe5d170: onmp_dsg/onmp_dsg_psql_prod@100.65.119.209:37176 pooler error: client_login_timeout

pgbouncer configuration:

server_idle_timeout = 60
server_connect_timeout = 15
client_idle_timeout = 0
client_login_timeout = 60

This error scenario is intermitted and wherever the application is making a connection login while pgbouncer is clearing the idle connection there is a JDBC exception occurred in the client side. There were no issues reported in the RDS side.
Why pgbouncer is clearing the client login request, while clearing the idle connection. Are there any configuration changes required in pgbouncer to handle this scenario?


问:
Why python shell stores last expression in _ variable but python file does not?
I ran below code in python shell and from a python file, I expected the same output but ironically i get NameError: name '_' is not defined error in python file.

>>> 10+2
12
>>> print(_)
12
```

So i started wondering why python shell stores last expression in _ variable but it is not even defined in python file.

Body:
I ran below code in python shell and from a python file, I expected the same output but ironically i get NameError: name '_' is not defined error in python file.

>>> 10+2
12
>>> print(_)
12

So i started wondering why python shell stores last expression in _ variable but it is not even defined in python file.


问:
fedora 36, openssh 8.8 ignores PubkeyAcceptedAlgorithms option
I can't convince ssh to add ssh-rsa to its acceptable algorithms except by the use of an explicit command line option.

I can

```<code>ssh -o pubkeyacceptedalgorithms=+ssh-rsa cruddy-old-server
</code>```

just fine but I don't seem to be able to put that in any ssh config file and have it work.

I've tried setting the crypto-policy to LEGACY, I've tried putting it in both the global and my personal ssh config files. And I tried removing the 'match final all' from /etc/ssh/ssh_config.d/50-redhat.conf.

No matter where it goes, it just seems to be ignored.

This is a fresh Fedora 36 install on a pretty vanilla x86-64 box.

```<code>jon@n 108% ssh -Q pubkeyacceptedalgorithms | grep ssh-rsa
ssh-rsa
ssh-rsa-cert-v01@openssh.com

</code>```

says it's present but ...

```<code>jon@n 109% ssh -G localhost | grep pubkeyacc
pubkeyacceptedalgorithms ssh-ed25519-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ssh-ed25519@openssh.com,sk-ecdsa-sha2-nistp256@openssh.com,rsa-sha2-512,rsa-sha2-256
</code>```

says it's not and that seems to be what matters.

Yes, I could rebuild cruddy-old-server but (a) it's Christmas and (b) I'm meant to be retired for !&#@&#-sake and (c) I literally am too old for this s**t.

Anyone got any bright ideas.

jon.

Body:
I can't convince ssh to add ssh-rsa to its acceptable algorithms except by the use of an explicit command line option.

I can

ssh -o pubkeyacceptedalgorithms=+ssh-rsa cruddy-old-server

just fine but I don't seem to be able to put that in any ssh config file and have it work.

I've tried setting the crypto-policy to LEGACY, I've tried putting it in both the global and my personal ssh config files. And I tried removing the 'match final all' from /etc/ssh/ssh_config.d/50-redhat.conf.

No matter where it goes, it just seems to be ignored.

This is a fresh Fedora 36 install on a pretty vanilla x86-64 box.

jon@n 108% ssh -Q pubkeyacceptedalgorithms | grep ssh-rsa
ssh-rsa
ssh-rsa-cert-v01@openssh.com

says it's present but ...

jon@n 109% ssh -G localhost | grep pubkeyacc
pubkeyacceptedalgorithms ssh-ed25519-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ssh-ed25519@openssh.com,sk-ecdsa-sha2-nistp256@openssh.com,rsa-sha2-512,rsa-sha2-256

says it's not and that seems to be what matters.

Yes, I could rebuild cruddy-old-server but (a) it's Christmas and (b) I'm meant to be retired for !&#@&#-sake and (c) I literally am too old for this s**t.

Anyone got any bright ideas.

jon.


问:
NodeJS, mysql connection to localhost. Why is my mysql object not defined?
I am trying to use mysql with "mysql = require('mysql')" in my Nodejs server web application. Now when I try to use the mysql object (that i required with the above require command) it gives me an error saying:

message "mysql is not defined"

What am I doing wrong. Code belov. Thanks in advance for all the help <3 much love.

I tried using an mysql object (that i required) to create a connection object. I didnt expect the mysql object to be undefined. Whats wrong?

`

```<code>const mysql = require('mysql')

class Model {
  connection;

  constructor() {
    this.connection = mysql.createConnection({
      host: 'localhost',
      port: '3306',
      user: 'creativepages',
      password: 'creativepages',
      database: 'main'
    });
  }

  execute(sqlquery) {

    this.connection.connect(function(err) {
      if (err) {
        return err;
      } else {
        this.connection.query(sqlquery, function(err, result) {
          if (err) {
            return false;
          }
        });

        this.connection.end(function(err) {
          if (err) {
            return err;
          }
        });

        return true;
      }
    });
  }
</code>```

`

Body:
I am trying to use mysql with "mysql = require('mysql')" in my Nodejs server web application. Now when I try to use the mysql object (that i required with the above require command) it gives me an error saying:

message "mysql is not defined"

What am I doing wrong. Code belov. Thanks in advance for all the help <3 much love.

I tried using an mysql object (that i required) to create a connection object. I didnt expect the mysql object to be undefined. Whats wrong?

`

const mysql = require('mysql')

class Model {
  connection;

  constructor() {
    this.connection = mysql.createConnection({
      host: 'localhost',
      port: '3306',
      user: 'creativepages',
      password: 'creativepages',
      database: 'main'
    });
  }

  execute(sqlquery) {

    this.connection.connect(function(err) {
      if (err) {
        return err;
      } else {
        this.connection.query(sqlquery, function(err, result) {
          if (err) {
            return false;
          }
        });

        this.connection.end(function(err) {
          if (err) {
            return err;
          }
        });

        return true;
      }
    });
  }

`


问:
Test Geospatial Anchor app for development and debbugging purpose
I'm building an AR App with AR Core and AR Foundation with Unity that instatiate an object to a specific latitude and longitude with Geospatial Anchor API.

I have to test if that work all correctly but the coordinates are far from me, and I can't always be physically on the spot.

I'm doing some test in a place near to me but I want start to build the real app.

There are some method to debug this type of application withouth be without being physically present on site?


问:
excel to JSON file using python
I'm having a excel file which contains table names(in a column) and it's schema's in JSON format(in adjacent column).

Now I need to copy the existing JSON formatted text to a file and save it with a name as respective table names with extension ".json"

like AAA.json, BBB.json and so on.

I tried this:

import os
import openpyxl

file_name=[]
wb = openpyxl.load_workbook('C:/Users/tamil/downloads/Schema_update_Tracker.xlsx')

sheet = wb.get_sheet_by_name('osiris')

start_row = 2
end_row = 136
start_col = 2
end_col = 2

for row in range(start_row, end_row+1):
    cell_value = sheet.cell(row=row, column=2).value
    file_name.append(cell_value)

wb = openpyxl.load_workbook('C:/Users/tamil/downloads/Schema_update_Tracker.xlsx')

sheet = wb.get_sheet_by_name('osiris')

for i in file_name:
    for row in sheet.rows:
        row_data = {}

        for cell in row:
            row_data= cell.value

        data = row_data
        with open('data.json', 'w') as f:
          f.write(data)

new_name = i&".json"
os.rename('data.json', new_name)
```
<p>Results in the following error:</p>
```File "c:/Users/tamil/OneDrive/Desktop/G/trail.py", line 43, in <module>
    f.write(data)
TypeError: write() argument must be str, not None
```

Title: excel to JSON file using python

Body:
I'm having a excel file which contains table names(in a column) and it's schema's in JSON format(in adjacent column).

Now I need to copy the existing JSON formatted text to a file and save it with a name as respective table names with extension ".json"

like AAA.json, BBB.json and so on.

I tried this:

import os
import openpyxl

file_name=[]
wb = openpyxl.load_workbook('C:/Users/tamil/downloads/Schema_update_Tracker.xlsx')

sheet = wb.get_sheet_by_name('osiris')

start_row = 2
end_row = 136
start_col = 2
end_col = 2

for row in range(start_row, end_row+1):
    cell_value = sheet.cell(row=row, column=2).value
    file_name.append(cell_value)

wb = openpyxl.load_workbook('C:/Users/tamil/downloads/Schema_update_Tracker.xlsx')

sheet = wb.get_sheet_by_name('osiris')

for i in file_name:
    for row in sheet.rows:
        row_data = {}

        for cell in row:
            row_data= cell.value

        data = row_data
        with open('data.json', 'w') as f:
          f.write(data)

new_name = i&".json"
os.rename('data.json', new_name)

Results in the following error:

File "c:/Users/tamil/OneDrive/Desktop/G/trail.py", line 43, in <module>
    f.write(data)
TypeError: write() argument must be str, not None


问:
Enable tls on consul ui
I want to use to consul UI to https. I am new to consul. Here is my working docker-compose file:

```<code>
services:
  consul-server1:
    image: consul:1.9.3
    container_name: consul-server1
    restart: always
    volumes:
      - ./config:/consul/config/
    networks:
      - consul
    ports:
      - '8500:8500'
      - '8600:8600/tcp'
      - '8600:8600/udp'
    command: 'agent -server -ui -node=server-1 -bootstrap-expect=1 -client=0.0.0.0'
networks:
  consul:
    driver: bridge ```

Config folder's content:
```{
  "acl": {
    "enabled": true,
    "down_policy": "deny",
    "default_policy": "deny",
    "enable_token_persistence": true,
    "tokens":{
      "master": "dc613409-91ca-0ed94-a19c-123c4ef5f9eb"
    }
  }
}

</code>```

While i tried to working with 8501 port, it did not work.

Title: Enable tls on consul ui

Body:
I want to use to consul UI to https. I am new to consul. Here is my working docker-compose file:

services:
  consul-server1:
    image: consul:1.9.3
    container_name: consul-server1
    restart: always
    volumes:
      - ./config:/consul/config/
    networks:
      - consul
    ports:
      - '8500:8500'
      - '8600:8600/tcp'
      - '8600:8600/udp'
    command: 'agent -server -ui -node=server-1 -bootstrap-expect=1 -client=0.0.0.0'
networks:
  consul:
    driver: bridge ```

Config folder's content:
```{
  "acl": {
    "enabled": true,
    "down_policy": "deny",
    "default_policy": "deny",
    "enable_token_persistence": true,
    "tokens":{
      "master": "dc613409-91ca-0ed94-a19c-123c4ef5f9eb"
    }
  }
}

While i tried to working with 8501 port, it did not work.


问:
Correlate between OOMKilling event and the actual pod killed
I'm using the Kubernetes events API to check if my cluster have any OOM events. In the case it does, I'm sending an alert regarding this event.

Right now the only information I have to send is the node name, the event name, the reason (OOMKilling for example) and the message the event has which for OOM usually have the process killed and the name of the command line in the process, for example: "(combined from similar events): Memory cgroup out of memory: Killed process 3448515 (stress) total-vm:1536784kB, anon-rss:522964kB, file-rss:332kB, shmem-rss:0kB, UID:0 pgtables:1064kB oom_score_adj:871"

I want to be able to pinpoint which pod is being killed exactly and which pod, if possible caused this OOM (which depending on priority configurations might be two different pods).

The only way I can see right now to do this, is to correlate between the OOMKilling event and the BackOff event that a pod should have when an OOM happens. But this feels like it can lead to some wrong heuristics and timing issues (did I send the API call too soon?

Maybe I only see the OOM event now, and not the BackOff event), and even if I do this, I can only find the killed pod, and not the culprit of the event—when the culprit pod has a higher priority class, and killing one other pod is enough to satisfy the memory requirements in the node.

Is there anything in the API I am missing? Maybe some other API I can use to find this?

I also considered using kube-state-metrics, as they have a metric for OOM events, but with my system structure, KSM does not fully help me, but in the KSM they have the OOM events per POD and not per Node, so this should be also possible.

Using events API and the core API of k8s project to retrieve the OOM events.

I looked at KSM and on various other sources to try and get which pod is the culprit on the node that has the OOM event.


问:
Uncaught TypeError: root.pendingInteractionMap is undefined - React
i was happens to get into this error on my react application. Can anyone tell me what might have cause this kind of issue?</p>


问:
while installing CKAN for development Unable to create CKAN config file
Unable to generate CKAN config file which can be edited

I have run this command in my terminal
ckan generate config /etc/ckan/default/ckan.ini
but it is showing the following error
Option ckan.plugins is not declared


问:
How to apply wait processor for capture complete records before merger them
I have a scenario where am triggering API in batches (1000 records in each). from the first API I get the value of total records in attribute list X-Total-Count, i wants to merge them all.
Please let me know how i can leverage the wait processor in it to wait until we get the whole data till value of X-Total-Count.


问:
How to create global navigation from another graph
i am trying to do global navigation to fragment from activity but getting exception

```<code>    java.lang.IllegalArgumentException: Navigation action/destination com.android:id/action_global_serviceUnavailableFragment cannot be found from the current destination Destination(com.android:id/authFragment) label=fragment_auth class=com.android.ui.auth.AuthFragment
</code>```

the fragment I want to navigate to is in another graph, but I don't think it should affect

my code :

```<code><navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/service_unavailable_graph"
    app:startDestination="@id/serviceUnavailableFragment">

    <fragment
        android:id="@+id/serviceUnavailableFragment"
        android:name="com.android.ui.serviceunavailable.ServiceUnavailableFragment"
        android:label="fragment_service_unavailable"
        tools:layout="@layout/fragment_service_unavailable">
    </fragment>

    <action
        android:id="@+id/action_global_serviceUnavailableFragment"
        app:destination="@id/serviceUnavailableFragment" />

</navigation>

    override fun serviceUnavailable() {
        lifecycle.coroutineScope.launch(Dispatchers.Main) {
            navController.navigate(R.id.action_global_serviceUnavailableFragment)
        }
    }
</code>```

Body:
i am trying to do global navigation to fragment from activity but getting exception

    java.lang.IllegalArgumentException: Navigation action/destination com.android:id/action_global_serviceUnavailableFragment cannot be found from the current destination Destination(com.android:id/authFragment) label=fragment_auth class=com.android.ui.auth.AuthFragment

the fragment I want to navigate to is in another graph, but I don't think it should affect

my code :

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/service_unavailable_graph"
    app:startDestination="@id/serviceUnavailableFragment">

    <fragment
        android:id="@+id/serviceUnavailableFragment"
        android:name="com.android.ui.serviceunavailable.ServiceUnavailableFragment"
        android:label="fragment_service_unavailable"
        tools:layout="@layout/fragment_service_unavailable">
    </fragment>

    <action
        android:id="@+id/action_global_serviceUnavailableFragment"
        app:destination="@id/serviceUnavailableFragment" />

</navigation>

    override fun serviceUnavailable() {
        lifecycle.coroutineScope.launch(Dispatchers.Main) {
            navController.navigate(R.id.action_global_serviceUnavailableFragment)
        }
    }


问:
How to integrate vue tours in nested components?
I have multiple nested components, how to set the ids which should be trigged when then element belongs to child component, in Vue tours. Though i have instantiated and added all the steps in the parent component.

Using:
"vue-tour": "^2.0.0",and vue 2 with quasar framework

Tried adding id to the child component but it doesn't suffice the solution as it doesn't render , nor it works on the exact element on which i would like to render


问:
Set Date Format to Excel Cell Using Apache POI Java
I have a date field which I am exporting to Excel using Java and Apache POI.
I have set the Cell Style using the following:

private XSSFCellStyle dateFont = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontName("Calibri");
font.setFontHeightInPoints((short)12);
font.setItalic(true);
dateFont.setFont(font);
dateFont.setDataFormat(workbook.createDataFormat().getFormat("dd/MM/yyyy"));
```

The above piece of code correctly formats my date to the required format however in Excel the cell format shows as Custom (as shown in the image below).

What change do I need to make to the above code to allow me have the cell format as Date instead of Custom ?

Excepted Outcome :

Body:
I have a date field which I am exporting to Excel using Java and Apache POI.
I have set the Cell Style using the following:

private XSSFCellStyle dateFont = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontName("Calibri");
font.setFontHeightInPoints((short)12);
font.setItalic(true);
dateFont.setFont(font);
dateFont.setDataFormat(workbook.createDataFormat().getFormat("dd/MM/yyyy"));

The above piece of code correctly formats my date to the required format however in Excel the cell format shows as Custom (as shown in the image below).

What change do I need to make to the above code to allow me have the cell format as Date instead of Custom ?

Excepted Outcome :


问:
How to round off a value to 1.082 from 1.1975 using round function in sql?
How to round off a value to 1.082 from 1.1975 using round function in sql ??

How to round off a value to 1.082 from 1.1975 using round function in sql ??


问:
Minimal GDB Stub on qemu aarch64
Good day,
I have been working on my bootloader for the aarch64 for a while and I would like to implement a gdb support. I am using qemu to emulate the aarch64 architecture, so I am launching it with the "-s" option to enable debugging by connecting to the target whilst in gdb.

For that I have read the following documentation: GDB_Stub_doc

This allowed me to see how to write a parser for the requests. What it did not tell me is how to setup the serial communication between the host and the guest as well as other points that are unclear to me and that I will explain lower.

I am confused about the exception handling that is need by the stub. Doesn't QEMU already set up the exception vector, or should I do it myself? If so how should I do that?

I have had a look at the existing stub implementations like the i386-stub.c and while they seem fine, they do not show how one would proceed step by step (one simple gdb functionality at a time) to create a working stub for a custom system.

Could someone please, kindly explain on how I should proceed? The documentation really does not help much even though I have read it multiple times.

Thanks in advance!

Title: Minimal GDB Stub on qemu aarch64


问:
How can I copy functions containing a specific command and delete them from the original code?
I have javascript code that contains a lot of
functions
Some of these functions contain the code 'return N('
I want an automatic way to collect and harvest all functions that contain the code 'return N('
And make a complete copy of the functions that contain the code 'return N(') and move it to another javaScript file
Then remove all functions containing 'return N(') from the original code
How can I do this in an automatic and fast way, especially since the code is large
Example:

```<code>function mr(J,m){return N(m- -0x3d8,J);}
function mi(J,m){return N(m- -0x192,J);}
function mL(J,m){return N(J-0x2bc,m);}
</code>```

There are many of these functions in my code, and the code I am working on is very large. Is there an automatic way to copy these functions to another folder and delete them from the original code?
I will be grateful to anyone who helps me in this matter

I tried this code but it didn't give good results

```<code>// Define a regular expression to match functions that contain the code 'return N('
const regex = /function\s*\w*\s*\([^)]*\)\s*{[\s\S]*?return N\(/g;

// Define the original code as a string
const originalCode = `
  function foo() {
    // do something
    return N(value);
  }

  function bar() {
    // do something else
    return N(value);
  }

  function baz() {
    // do something else
    return otherValue;
  }
`;

// Use the regular expression to match all functions that contain the code 'return N('
const matches = originalCode.match(regex);

// If any matches were found
if (matches) {
  // Create an empty array to store the modified functions
  const modifiedFunctions = [];

  // Loop through the matches
  for (const match of matches) {
    // Use string manipulation techniques to remove the function from the original code
    const modifiedFunction = match.replace(/function\s*\w*\s*\([^)]*\)\s*{/, '').replace(/}$/, '');
    // Add the modified function to the array
    modifiedFunctions.push(modifiedFunction);
  }

  // Join the modified functions into a single string
  const modifiedCode = modifiedFunctions.join('\n');

  // Log the modified code
  console.log(modifiedCode);
}

</code>```

Body:
I have javascript code that contains a lot of
functions
Some of these functions contain the code 'return N('
I want an automatic way to collect and harvest all functions that contain the code 'return N('
And make a complete copy of the functions that contain the code 'return N(') and move it to another javaScript file
Then remove all functions containing 'return N(') from the original code
How can I do this in an automatic and fast way, especially since the code is large
Example:

function mr(J,m){return N(m- -0x3d8,J);}
function mi(J,m){return N(m- -0x192,J);}
function mL(J,m){return N(J-0x2bc,m);}

There are many of these functions in my code, and the code I am working on is very large. Is there an automatic way to copy these functions to another folder and delete them from the original code?
I will be grateful to anyone who helps me in this matter

I tried this code but it didn't give good results

// Define a regular expression to match functions that contain the code 'return N('
const regex = /function\s*\w*\s*\([^)]*\)\s*{[\s\S]*?return N\(/g;

// Define the original code as a string
const originalCode = `
  function foo() {
    // do something
    return N(value);
  }

  function bar() {
    // do something else
    return N(value);
  }

  function baz() {
    // do something else
    return otherValue;
  }
`;

// Use the regular expression to match all functions that contain the code 'return N('
const matches = originalCode.match(regex);

// If any matches were found
if (matches) {
  // Create an empty array to store the modified functions
  const modifiedFunctions = [];

  // Loop through the matches
  for (const match of matches) {
    // Use string manipulation techniques to remove the function from the original code
    const modifiedFunction = match.replace(/function\s*\w*\s*\([^)]*\)\s*{/, '').replace(/}$/, '');
    // Add the modified function to the array
    modifiedFunctions.push(modifiedFunction);
  }

  // Join the modified functions into a single string
  const modifiedCode = modifiedFunctions.join('\n');

  // Log the modified code
  console.log(modifiedCode);
}


问:
Problem Related to Android Studio, Module version not found exception
When  I try tot implementing this  ‘com.andrognito.patternlockview:patternlockview:1.0.0’ dependency it Shows could not found com.andrognito.patternlockview:patternlockview:1.0.0 Please can anyone help me to fix this error I want to create pattern lock view

I tried to import it and it can sync but when I try to run it it gives an error as I mentioned above


问:
How to change the colors of a plotly scatter plot
My question is very simple but I'm stuck. This is my code:

```<code>fig = px.scatter(df_datos, x="EAD", y="RAR", size="Margen_bruto", color="País", hover_name="Cliente", hover_data={'País':True, 'EAD':':.0f', 'RAR':':.0%', 'Margen_bruto':':.0f'}, size_max=30, trendline='lowess', trendline_color_override='black', trendline_scope='overall', title="dic 2021 - 219 clientes")

</code>```

The 4 colors for the 4 countries are assigned randomly and I want to be able to choose the color for each specific country. How can I do that?

I tried functions like add_traces and markers but I can't manage to do it.

Body:
My question is very simple but I'm stuck. This is my code:

fig = px.scatter(df_datos, x="EAD", y="RAR", size="Margen_bruto", color="País", hover_name="Cliente", hover_data={'País':True, 'EAD':':.0f', 'RAR':':.0%', 'Margen_bruto':':.0f'}, size_max=30, trendline='lowess', trendline_color_override='black', trendline_scope='overall', title="dic 2021 - 219 clientes")

The 4 colors for the 4 countries are assigned randomly and I want to be able to choose the color for each specific country. How can I do that?

I tried functions like add_traces and markers but I can't manage to do it.


问:
validating true or false from SignalR server response - if it is possible to manipulate it?
this is my ValidateObject:

```<code>    Status: @if (Model.Connected == false)
    {
        <img src="/icons/wifi_off.svg" height="45" width="45" /><span>Offline, brak połączenia z portem COM</span>
    }
    else
    {
        <img src="/icons/wifi_on.svg" height="45" width="45" /><span>Online, połączono z portem COM</span>
    }
</code>```

and i want trigger 'false' with response from server. Does someone know how and if it is possible to stick it with SignalR connection response?

```<code>switch(informations[0]){
case "Status":
status.InnerHTML = informations[1];
break
}
</code>```

Body:
this is my ValidateObject:

    Status: @if (Model.Connected == false)
    {
        Offline, brak połączenia z portem COM
    }
    else
    {
        Online, połączono z portem COM
    }

and i want trigger 'false' with response from server. Does someone know how and if it is possible to stick it with SignalR connection response?

switch(informations[0]){
case "Status":
status.InnerHTML = informations[1];
break
}


问:
Why are links being shown instead of thumbnails when I upload pdf files in my mediawiki?
I'm administrating a Mediawiki 1.38 with PdfHandler extension already included. I have added wfLoadExtension( 'PdfHandler' ); in LocalSettings.php and $wgFileExtensions[] = 'pdf'; as well. When I upload a pdf to my page I choose the thumbnail option but I only get a link like File:Example.pdf and you have to click on this link to see the pdf but I want the link to be like a thumbnail instead of words. Any ideas?</p>


问:
StringTrimmerEditor on HttpServletRequest
I'm using Spring MVC on this.

Let's say that I have a controller for generating pdfs. The request it accepts can have multiple optional parameters. I want to make sure that any parameter passed to it is trimmed of their whitespaces.

For this, I've created a controller advice to add a StringTrimmerEditor so that any parameter can be trimmed.

ControllerAdviceClass:

```<code>    @InitBinder
    public void initBinder(WebDataBinder binder) {
        StringTrimmerEditor stringTrimmer = new StringTrimmerEditor(false);

        binder.registerCustomEditor(String.class, stringTrimmer);
    }
</code>```

Controller endpoint method:

```<code> @RequestMapping(value="/api/v1/createPdf")
 public ModelAndView generate(HttpServletRequest request) {
    //Process request and generate the pdf
}
</code>```

Sample request:

```<code>    http://localhost:8080/api/v1/createPdf?timezone=       +7&language=fr   &pageType=recipe&ingredients=carrots,milk,ice&name=Carrot Shake
</code>```

In the above request, the timezone, language and pageType are required parameters.

When trying to generate the pdf, I noticed that none of the parameters I send to the endpoint have their whitespaces removed, resulting in an exception.

Any ideas/suggestions?

Thanks

Body:
I'm using Spring MVC on this.

Let's say that I have a controller for generating pdfs. The request it accepts can have multiple optional parameters. I want to make sure that any parameter passed to it is trimmed of their whitespaces.

For this, I've created a controller advice to add a StringTrimmerEditor so that any parameter can be trimmed.

ControllerAdviceClass:

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        StringTrimmerEditor stringTrimmer = new StringTrimmerEditor(false);

        binder.registerCustomEditor(String.class, stringTrimmer);
    }

Controller endpoint method:

 @RequestMapping(value="/api/v1/createPdf")
 public ModelAndView generate(HttpServletRequest request) {
    //Process request and generate the pdf
}

Sample request:

    http://localhost:8080/api/v1/createPdf?timezone=       +7&language=fr   &pageType=recipe&ingredients=carrots,milk,ice&name=Carrot Shake

In the above request, the timezone, language and pageType are required parameters.

When trying to generate the pdf, I noticed that none of the parameters I send to the endpoint have their whitespaces removed, resulting in an exception.

Any ideas/suggestions?

Thanks


问:
How to get instant video playing from url in android without any delay after being swiped to
I'm trying to make a short video app in android with java. Everything is working fine but after swipe new video takes 1 or 2 seconds to play the video. I want to play the videos instantly like Instagram reels or YouTube shorts. I have tried videoview and exoplayer both but didn't get result that I am expecting.

Expecting pause less video play on every swipe.

```<code>public class MainActivity extends AppCompatActivity {

    List<VideoItem> videoItems = new ArrayList<>();
    public static ExoPlayer player ;
    private String my_id="123";
    private String videoURL,userid,username,videoDescription,postid,like_count,dislike_count;
    private RequestQueue mRequestQueue;
    ViewPager2 videosViewPager;
    MediaItem item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videosViewPager = findViewById(R.id.viewPagerVideos);
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        sendshorts();
        player = new ExoPlayer.Builder(getApplicationContext()).build();

        player.setRepeatMode(player.REPEAT_MODE_ONE);

        videosViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.d("satyam","current position"+position);
                player.seekTo(position,1);
                player.play();

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);

            }
        });
    }

    @Override
    protected void onDestroy() {
        player.release();
        super.onDestroy();
    }

    public void sendshorts() {

        String url = "myurl";
        Map<String, String> params = new HashMap<>();
        params.put("my_id", my_id);
        params.put("url"," " );
        final JSONObject jsonObj = new JSONObject(params);
        JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {

                    JSONArray obj = response.getJSONArray("videosend");
                    for (int i = 0; i < obj.length(); i++) {

                        JSONObject jsonObject = obj.getJSONObject(i);
                        videoURL = jsonObject.getString("videoURL");

                        userid = jsonObject.getString("user");

                        username = jsonObject.getString("name");

                        videoDescription = jsonObject.getString("videoDescription");

                        postid = jsonObject.getString("postid");

                        like_count = jsonObject.getString("like_count");

                        dislike_count = jsonObject.getString("dislike_count");

                        VideoItem v = new VideoItem(videoURL,username,videoDescription,userid,postid,like_count,dislike_count);
                        videoItems.add(v);
                        item=MediaItem.fromUri(videoURL);
                        player.addMediaItem(item);
                        player.prepare();
                    }

                    videosViewPager.setAdapter(new VideosAdapter(videoItems));

                }catch (Exception ignored){
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        mRequestQueue.add(jsonObject);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
</code>```

and my adapter is

```<code>public class VideosAdapter extends RecyclerView.Adapter<VideosAdapter.VideoViewHolder>{
    private static View iv;
    private List<VideoItem> mVideoItems;

    public VideosAdapter(List<VideoItem> videoItems) {
        mVideoItems = videoItems;
    }

    @Override
    public void onViewDetachedFromWindow(@NonNull VideoViewHolder holder) {
        super.onViewDetachedFromWindow(holder);

    }

    @Override
    public void onViewAttachedToWindow(@NonNull VideoViewHolder holder) {
        super.onViewAttachedToWindow(holder);

        MainActivity.player.setVideoTextureView(holder.styledPlayerView);
        MainActivity.player.play();

    }

    @NonNull
    @Override
    public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new VideoViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_videos_container,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
        holder.setVideoData(mVideoItems.get(position));

    }

    @Override
    public int getItemCount() {
        return mVideoItems.size();
    }

    class VideoViewHolder extends RecyclerView.ViewHolder{
        TextView txtTitle,txtDesc;
        ProgressBar mProgressBar;
        TextureView styledPlayerView;
        public VideoViewHolder(@NonNull View itemView) {
            super(itemView);
            styledPlayerView = itemView.findViewById(R.id.videoView);
            txtTitle = itemView.findViewById(R.id.txtTitle);
            txtDesc = itemView.findViewById(R.id.txtDesc);

        }
        void setVideoData(VideoItem videoItem){
            txtTitle.setText(videoItem.username);
            txtDesc.setText(videoItem.videoDescription);
        }
    }
}

</code>```

After swipe up or down videos are taking one or two seconds to play. I want to play it instantly like reels or shorts.

Body:
I'm trying to make a short video app in android with java. Everything is working fine but after swipe new video takes 1 or 2 seconds to play the video. I want to play the videos instantly like Instagram reels or YouTube shorts. I have tried videoview and exoplayer both but didn't get result that I am expecting.

Expecting pause less video play on every swipe.

public class MainActivity extends AppCompatActivity {

    List<VideoItem> videoItems = new ArrayList<>();
    public static ExoPlayer player ;
    private String my_id="123";
    private String videoURL,userid,username,videoDescription,postid,like_count,dislike_count;
    private RequestQueue mRequestQueue;
    ViewPager2 videosViewPager;
    MediaItem item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videosViewPager = findViewById(R.id.viewPagerVideos);
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        sendshorts();
        player = new ExoPlayer.Builder(getApplicationContext()).build();

        player.setRepeatMode(player.REPEAT_MODE_ONE);

        videosViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.d("satyam","current position"+position);
                player.seekTo(position,1);
                player.play();

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);

            }
        });
    }

    @Override
    protected void onDestroy() {
        player.release();
        super.onDestroy();
    }

    public void sendshorts() {

        String url = "myurl";
        Map<String, String> params = new HashMap<>();
        params.put("my_id", my_id);
        params.put("url"," " );
        final JSONObject jsonObj = new JSONObject(params);
        JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {

                    JSONArray obj = response.getJSONArray("videosend");
                    for (int i = 0; i < obj.length(); i++) {

                        JSONObject jsonObject = obj.getJSONObject(i);
                        videoURL = jsonObject.getString("videoURL");

                        userid = jsonObject.getString("user");

                        username = jsonObject.getString("name");

                        videoDescription = jsonObject.getString("videoDescription");

                        postid = jsonObject.getString("postid");

                        like_count = jsonObject.getString("like_count");

                        dislike_count = jsonObject.getString("dislike_count");

                        VideoItem v = new VideoItem(videoURL,username,videoDescription,userid,postid,like_count,dislike_count);
                        videoItems.add(v);
                        item=MediaItem.fromUri(videoURL);
                        player.addMediaItem(item);
                        player.prepare();
                    }

                    videosViewPager.setAdapter(new VideosAdapter(videoItems));

                }catch (Exception ignored){
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        mRequestQueue.add(jsonObject);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}

and my adapter is

public class VideosAdapter extends RecyclerView.Adapter<VideosAdapter.VideoViewHolder>{
    private static View iv;
    private List<VideoItem> mVideoItems;

    public VideosAdapter(List<VideoItem> videoItems) {
        mVideoItems = videoItems;
    }

    @Override
    public void onViewDetachedFromWindow(@NonNull VideoViewHolder holder) {
        super.onViewDetachedFromWindow(holder);

    }

    @Override
    public void onViewAttachedToWindow(@NonNull VideoViewHolder holder) {
        super.onViewAttachedToWindow(holder);

        MainActivity.player.setVideoTextureView(holder.styledPlayerView);
        MainActivity.player.play();

    }

    @NonNull
    @Override
    public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new VideoViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_videos_container,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
        holder.setVideoData(mVideoItems.get(position));

    }

    @Override
    public int getItemCount() {
        return mVideoItems.size();
    }

    class VideoViewHolder extends RecyclerView.ViewHolder{
        TextView txtTitle,txtDesc;
        ProgressBar mProgressBar;
        TextureView styledPlayerView;
        public VideoViewHolder(@NonNull View itemView) {
            super(itemView);
            styledPlayerView = itemView.findViewById(R.id.videoView);
            txtTitle = itemView.findViewById(R.id.txtTitle);
            txtDesc = itemView.findViewById(R.id.txtDesc);

        }
        void setVideoData(VideoItem videoItem){
            txtTitle.setText(videoItem.username);
            txtDesc.setText(videoItem.videoDescription);
        }
    }
}

After swipe up or down videos are taking one or two seconds to play. I want to play it instantly like reels or shorts.


问:
<asynchronous suspension> error on web socket api calling with riverpod stream provider
I am getting this error while calling web socket api

This is the provider method i have written.
`

```<code>final recentRequestedTripProvider =
    StreamProvider.autoDispose<CurrentRequestedTrip>((ref) async* {
  final channel = IOWebSocketChannel.connect(
    Uri.parse(
        "ws://192.168.0.249:8000/driver-assignment/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjcxNjI2MzQyLCJpYXQiOjE2NzE2MjM2NDIsImp0aSI6IjE4NGYxNjE2OWM4ZTRiOWM5OTJhNGJlNzFlY2VkZDI3IiwidXNlcl9pZCI6Ijg1MTUwMmVkLTk4N2EtNDRiOS1hMDZkLWY2NzQ3YjI2NWQ5NiJ9.Gqh1eNu9NcUen9Eooqd7nBApS5U22KCXZD7iIw0M0z8"),
  );

  ref.onDispose(() => channel.sink.close());

  await for (final json in channel.stream) {
    print(json);
    yield CurrentRequestedTrip.fromJson(json);
  }
});

</code>```

`

this is who i am connecting the stream provider with ui

```<code>final requestedTrip = ref.watch(recentRequestedTripProvider);
requestedTrip.when(
              data: (data) {
                //  print(data);
                return TripOrderCardWidget(size: size);
              },
              error: (obj, error) {
                print(error.toString());
                return Center(child: Text(error.toString()));
              },
              loading: () => const Center(child: CircularProgressIndicator()),
            ),
</code>```

Body:
I am getting this error while calling web socket api

This is the provider method i have written.
`

final recentRequestedTripProvider =
    StreamProvider.autoDispose<CurrentRequestedTrip>((ref) async* {
  final channel = IOWebSocketChannel.connect(
    Uri.parse(
        "ws://192.168.0.249:8000/driver-assignment/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjcxNjI2MzQyLCJpYXQiOjE2NzE2MjM2NDIsImp0aSI6IjE4NGYxNjE2OWM4ZTRiOWM5OTJhNGJlNzFlY2VkZDI3IiwidXNlcl9pZCI6Ijg1MTUwMmVkLTk4N2EtNDRiOS1hMDZkLWY2NzQ3YjI2NWQ5NiJ9.Gqh1eNu9NcUen9Eooqd7nBApS5U22KCXZD7iIw0M0z8"),
  );

  ref.onDispose(() => channel.sink.close());

  await for (final json in channel.stream) {
    print(json);
    yield CurrentRequestedTrip.fromJson(json);
  }
});

`

this is who i am connecting the stream provider with ui

final requestedTrip = ref.watch(recentRequestedTripProvider);
requestedTrip.when(
              data: (data) {
                //  print(data);
                return TripOrderCardWidget(size: size);
              },
              error: (obj, error) {
                print(error.toString());
                return Center(child: Text(error.toString()));
              },
              loading: () => const Center(child: CircularProgressIndicator()),
            ),


问:
React Native + expo, apk build works fine but doesn't show anything when i'm using router
I'm new to react native so i might do something really bad but,
I have a problem on Expo + React Native after building apk. (I don't have any problem when building)
Problem is : When i use react-navigation/native-stack, nothing is shown on the mobile screen with the apk.
But everything works fine in dev mode.

here some exemple, i build this with juste a simple text and it is running well.
App.tsx :

```<code>import 'react-native-gesture-handler';
import {AuthProvider} from "src/Context/AuthContext";
import {RequestInterceptorProvider} from "src/Context/RequestInterceptorContext";
import {Text} from "react-native";

export default function App() {
    return (
        <AuthProvider>
            <RequestInterceptorProvider>
                <Text style={{marginTop: 50}}>Bonjour !</Text>
            </RequestInterceptorProvider>
        </AuthProvider>
    );
}

</code>```

This exemple is working fine when build.

But if i use a router in my app like this :

App.tsx :

```<code>import 'react-native-gesture-handler';
import {AuthProvider} from "src/Context/AuthContext";
import {RequestInterceptorProvider} from "src/Context/RequestInterceptorContext";
import TestSimpleRouter from "./src/Routes/TestSimpleRouter";

export default function App() {

    return (
        <AuthProvider>
            <RequestInterceptorProvider>
                <TestSimpleRouter />
            </RequestInterceptorProvider>
        </AuthProvider>
    );
}

</code>```

TestSimpleRouter.tsx :

```<code>import * as React from "react";
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {NavigationContainer} from "@react-navigation/native";
import TestOneScreen from "../Screens/TestOne/TestOneScreen";
import TestTwoScreen from "../Screens/TestTwo/TestTwoScreen";

const Stack = createNativeStackNavigator();

export default function TestSimpleRouter() {

    return (
        <NavigationContainer>
            <Stack.Navigator
            initialRouteName={"TestOne"}
            >
                <Stack.Screen
                name={"TestOne"}
                component={TestOneScreen}
                />
                <Stack.Screen
                    name={"TestTwo"}
                    component={TestTwoScreen}
                />
            </Stack.Navigator>
        </NavigationContainer>
    )
}
</code>```

This exemple is 100% working in dev mode, but i can't make it work after an apk build...
Any suggestion ?

I found this topic : App works fine in Expo-Go but doesn't work after EAS-Build

It seems to be the exact same process as me, but no answer

I manage to identified the problem, it's coming from react-navigation / native-stack.

Body:
I'm new to react native so i might do something really bad but,
I have a problem on Expo + React Native after building apk. (I don't have any problem when building)
Problem is : When i use react-navigation/native-stack, nothing is shown on the mobile screen with the apk.
But everything works fine in dev mode.

here some exemple, i build this with juste a simple text and it is running well.
App.tsx :

import 'react-native-gesture-handler';
import {AuthProvider} from "src/Context/AuthContext";
import {RequestInterceptorProvider} from "src/Context/RequestInterceptorContext";
import {Text} from "react-native";

export default function App() {
    return (
        <AuthProvider>
            <RequestInterceptorProvider>
                <Text style={{marginTop: 50}}>Bonjour !</Text>
            </RequestInterceptorProvider>
        </AuthProvider>
    );
}

This exemple is working fine when build.

But if i use a router in my app like this :

App.tsx :

import 'react-native-gesture-handler';
import {AuthProvider} from "src/Context/AuthContext";
import {RequestInterceptorProvider} from "src/Context/RequestInterceptorContext";
import TestSimpleRouter from "./src/Routes/TestSimpleRouter";

export default function App() {

    return (
        <AuthProvider>
            <RequestInterceptorProvider>
                <TestSimpleRouter />
            </RequestInterceptorProvider>
        </AuthProvider>
    );
}

TestSimpleRouter.tsx :

import * as React from "react";
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {NavigationContainer} from "@react-navigation/native";
import TestOneScreen from "../Screens/TestOne/TestOneScreen";
import TestTwoScreen from "../Screens/TestTwo/TestTwoScreen";

const Stack = createNativeStackNavigator();

export default function TestSimpleRouter() {

    return (
        <NavigationContainer>
            <Stack.Navigator
            initialRouteName={"TestOne"}
            >
                <Stack.Screen
                name={"TestOne"}
                component={TestOneScreen}
                />
                <Stack.Screen
                    name={"TestTwo"}
                    component={TestTwoScreen}
                />
            </Stack.Navigator>
        </NavigationContainer>
    )
}

This exemple is 100% working in dev mode, but i can't make it work after an apk build...
Any suggestion ?

I found this topic : App works fine in Expo-Go but doesn't work after EAS-Build

It seems to be the exact same process as me, but no answer

I manage to identified the problem, it's coming from react-navigation / native-stack.