问:
How to create and share navGraph scopped ViewModel instance to navigate between UI states in Jetpack Compose in Android?
I have the below navigation graph with Jetpack Compose:

```<code>fun NavGraphBuilder.authGraph(navController: NavController) {
    navigation(startDestination = "login", route = "auth") {
        composable("login") {
            val authEntry = remember(it) {
                navController.getBackStackEntry("auth")
            }

            val vm: AuthViewModel = hiltViewModel(authEntry)
            LoginScreen(vm)
        }
        composable("register") {
            val authEntry = remember(it) {
                navController.getBackStackEntry("auth")
            }

            val vm: AuthViewModel = hiltViewModel(authEntry)
            RegisterScreen(vm)
        }
        composable("confirm") {
            val authEntry = remember(it) {
                navController.getBackStackEntry("auth")
            }

            val vm: AuthViewModel = hiltViewModel(authEntry)
            ConfirmRegisterScreen(vm)
        }
    }
}
</code>```

The AuthViewModel has the below UI state which I update as the user progress from sign up to confirm sign up and its workflows

```<code>sealed class AuthUiState {
    object SignedOut : AuthUiState()
    object InProgress : AuthUiState()
    object SignIn : AuthUiState()
    object SignedIn: AuthUiState()
    object ConfirmSignIn: AuthUiState()
    object ConfirmSignUp: AuthUiState()
    object Registered: AuthUiState()
}

private val _uiState = mutableStateOf<AuthUiState>(SignedOut)
val uiState: State<AuthUiState> get() = _uiState
</code>```

I wanted to observe this uiState state change inside the AuthGraph and navigate to the appropriate destination. How do I find the AuthViewModel instance outside of the composable?

```<code>fun NavGraphBuilder.authGraph(navController: NavController) {
    val vm: AuthViewModel = hiltViewModel(`common viewmodelstore object`)
    when (vm.uiState) {
        .... navController.navigate("login")
        .... navController.navigate("register")
    }

    navigation(startDestination = "login", route = "auth") {
        composable("login") {
            val authEntry = remember(it) {
                navController.getBackStackEntry("auth")
            }

            val vm: AuthViewModel = hiltViewModel(authEntry)
            LoginScreen(vm)
        }

        ..... other auth flow routes
    }
}

</code>```

I do know that there is a back stack entry which can be used to obtain the same viewmodel instance within the composibles for the nested graphs as documented here. However, what viewmodel store key can I use to obtain the viewmodel instance outside of the composible route to navigate between the nested routes with the Hilt DI? hiltViewModel() is a composable function which only works inside the composible route function.

Body:
I have the below navigation graph with Jetpack Compose:

fun NavGraphBuilder.authGraph(navController: NavController) {
    navigation(startDestination = "login", route = "auth") {
        composable("login") {
            val authEntry = remember(it) {
                navController.getBackStackEntry("auth")
            }

            val vm: AuthViewModel = hiltViewModel(authEntry)
            LoginScreen(vm)
        }
        composable("register") {
            val authEntry = remember(it) {
                navController.getBackStackEntry("auth")
            }

            val vm: AuthViewModel = hiltViewModel(authEntry)
            RegisterScreen(vm)
        }
        composable("confirm") {
            val authEntry = remember(it) {
                navController.getBackStackEntry("auth")
            }

            val vm: AuthViewModel = hiltViewModel(authEntry)
            ConfirmRegisterScreen(vm)
        }
    }
}

The AuthViewModel has the below UI state which I update as the user progress from sign up to confirm sign up and its workflows

sealed class AuthUiState {
    object SignedOut : AuthUiState()
    object InProgress : AuthUiState()
    object SignIn : AuthUiState()
    object SignedIn: AuthUiState()
    object ConfirmSignIn: AuthUiState()
    object ConfirmSignUp: AuthUiState()
    object Registered: AuthUiState()
}

private val _uiState = mutableStateOf<AuthUiState>(SignedOut)
val uiState: State<AuthUiState> get() = _uiState

I wanted to observe this uiState state change inside the AuthGraph and navigate to the appropriate destination. How do I find the AuthViewModel instance outside of the composable?

fun NavGraphBuilder.authGraph(navController: NavController) {
    val vm: AuthViewModel = hiltViewModel(`common viewmodelstore object`)
    when (vm.uiState) {
        .... navController.navigate("login")
        .... navController.navigate("register")
    }

    navigation(startDestination = "login", route = "auth") {
        composable("login") {
            val authEntry = remember(it) {
                navController.getBackStackEntry("auth")
            }

            val vm: AuthViewModel = hiltViewModel(authEntry)
            LoginScreen(vm)
        }

        ..... other auth flow routes
    }
}

I do know that there is a back stack entry which can be used to obtain the same viewmodel instance within the composibles for the nested graphs as documented here. However, what viewmodel store key can I use to obtain the viewmodel instance outside of the composible route to navigate between the nested routes with the Hilt DI? hiltViewModel() is a composable function which only works inside the composible route function.


来源: stackexchange

问:
How to handle dynamic number of input elements in React (Functional component)
I am trying to place dynamic number of inputs using array.map like followings.
Screenshot

The problem is that the length of array can exceed more than several Ks, so I think using state of string array is not the better choice then using Dom.
I tried to use unique ID to every input like id={withdraw_input_${index}} and it worked fine.
Is there any other solution?

ContentLicense: CC BY-SA 4.0


问:
Iterating over a nested json field in pyspark dataframe
I am trying to iterate over a field in pyspark dataframe which is in json format. In some cases it can be empty like this '[]' and other may have a nested structure. Can someone please help me out on how can I iterate over the column given the condition that I only want the rows that aren't empty and rather having values. Also I want to fetch specific fields from it.
Structure of the json field dataframe

I tried to iterate over the column using collect function. But this was helpful only when the field was having empty values. This is the code.
`

```<code>data = []
columns = ['created_date','description','id','last_modified_date','links','name','order','parent_id','pid','recursive','project_id']
for i in landing_df.collect():

  if(len(i["children"]) == 0):
    data.append([i["created_date"],i["description"],i["id"],i["last_modified_date"],i["links"],i["name"],i["order"],-1,i["pid"],i["recursive"],i["project_id"]])
#     if(landing_df.shared):
#       sourceDF.shared = landing_df.shared

    print(i["id"])

sourceDF1 = spark.createDataFrame(data,columns)
</code>```

`

I want to fetch the data from the children field and append it to the data variable just like I did it above.

Body:
I am trying to iterate over a field in pyspark dataframe which is in json format. In some cases it can be empty like this '[]' and other may have a nested structure. Can someone please help me out on how can I iterate over the column given the condition that I only want the rows that aren't empty and rather having values. Also I want to fetch specific fields from it.
Structure of the json field dataframe

I tried to iterate over the column using collect function. But this was helpful only when the field was having empty values. This is the code.
`

data = []
columns = ['created_date','description','id','last_modified_date','links','name','order','parent_id','pid','recursive','project_id']
for i in landing_df.collect():

  if(len(i["children"]) == 0):
    data.append([i["created_date"],i["description"],i["id"],i["last_modified_date"],i["links"],i["name"],i["order"],-1,i["pid"],i["recursive"],i["project_id"]])
#     if(landing_df.shared):
#       sourceDF.shared = landing_df.shared

    print(i["id"])

sourceDF1 = spark.createDataFrame(data,columns)

`

I want to fetch the data from the children field and append it to the data variable just like I did it above.


问:
What will be the query for searching 'Bachelor of Technology [B. Tech]' in Apache Solr
I want to get records containing 'Bachelor of Technology [B. Tech]' from text in Apache Solr.
For Example let say there is a record solr, {id:1, description: "Kickstart your career with Bachelor of Technology [B. Tech] in any stream you like"}. Then I want the query to get the above records.

I have tried with wild card like, description:Bachelor of Technology [B. Tech] but then it is throwing the parsing error and when sending the query with quotes like  description:"*Bachelor of Technology [B. Tech]" then I am getting all the records which also not contains 'Bachelor of Technology [B. Tech]'.


问:
Attaching zip file in Jenkins Editable Email Notification is not working
I am trying to add report.zip file (which is present in workspace) in Jenkins Email notification attachment,  but not receiving emails whereas When I attach report.html file(which is also present in Jenkins workspace), I am able to receive the emails and attachment.

Zip File size : 334KB

I tried report.zip, **/.zip, /.zip. But nothing works. Can anyone please help!

In Jenkins console, not seeing any failures, seeing the success message.

```<code>Archiving artifacts
Started calculate disk usage of build
Finished Calculation of disk usage of build in 0 seconds
Started calculate disk usage of workspace
Finished Calculation of disk usage of workspace in 0 seconds
Email was triggered for: Always
Sending email for trigger: Always
Sending email to: abc@gmail.com
Finished: SUCCESS
</code>```

Body:
I am trying to add report.zip file (which is present in workspace) in Jenkins Email notification attachment,  but not receiving emails whereas When I attach report.html file(which is also present in Jenkins workspace), I am able to receive the emails and attachment.

Zip File size : 334KB

I tried report.zip, **/.zip, /.zip. But nothing works. Can anyone please help!

In Jenkins console, not seeing any failures, seeing the success message.

Archiving artifacts
Started calculate disk usage of build
Finished Calculation of disk usage of build in 0 seconds
Started calculate disk usage of workspace
Finished Calculation of disk usage of workspace in 0 seconds
Email was triggered for: Always
Sending email for trigger: Always
Sending email to: abc@gmail.com
Finished: SUCCESS


问:
Turtle file contains 0 triples
I want to upload turtle file into apache jena fuseki server. But when i upload , there is 0 triples uploaded

I have an ontology. I want to make some query on apache jena fuseki server. I upload the ontology file as turtle format. But there's 0 triples uploaded.

When i tried to upload with rdf format , there's triples uploaded as the picture below

Upload ontology file

Is there something i miss? why when i upload ontology in turtle format it says 0 triples uploaded , but when i upload in rdf format , it says there's triples in it? How can i fix this?
Thanks

Title: Turtle file contains 0 triples


问:
how to convert the thymeleaf html to pdf containing google chart?
I want to create a PDF version of the Thymeleaf HTML page, which includes a Google Chart to create charts in the script area. I can view the chart in the browser because the browser loaded the javascript, but when I converted it to a pdf, I only got the title; the chart was not included.
Can somebody assist me?

I've tried using Itext to convert to PDF and the system's template engine to transform HTML incorporating Google Charts into PDFs.


问:
Using StackView to push a page based on succesful authentication
I have written code for Firebase Authentication for a desktop application. The authentication is working fine, I am having issues using StackView to push the next page based on successful authentication. Here's my code:
h file:

```<code>#ifndef AUTHHANDLER_H
#define AUTHHANDLER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QtQml/qqml.h>

class AuthHandler : public QObject
{
    Q_OBJECT
public:
    explicit AuthHandler(QObject *parent = nullptr);
    ~AuthHandler();
    void setAPIKey(const QString & apiKey);
    //void signUserUp(const QString & emailAddress, const QString & password);
    //void signUserIn(const QString & emailAddress, const QString & password);

public slots:
    void networkReplyReadyRead();
    void signUserIn(const QString & emailAddress, const QString & password);
    void signUserUp(const QString & emailAddress, const QString & password);
    void performAuthenticatedDatabaseCall();

    // New slot function
    void onUserSignedIn()
    {
        qDebug() << "onUserSignedIn called";

        // Get a reference to the StackView object
        QObject* stackView = this->parent()->findChild<QObject*>("stackView");  //problem here most likely
        if (stackView)
        {
            qDebug() << "Calling push() on StackView";
             //Push the main root window onto the StackView
            QMetaObject::invokeMethod(stackView, "push", Q_ARG(QVariant, "qrc:/qml/MainRootWindow.qml"));
        }
    }

signals:
    void userSignedIn();      //void

private:
   void performPOST( const QString & url, const QJsonDocument & payload);
   void parseResponse( const QByteArray & response);
   QString m_apiKey;
   QNetworkAccessManager * m_networkAccessManager;
   QNetworkReply * m_networkReply;
   QString m_idToken;

};

#endif // AUTHHANDLER_H
</code>```

cpp file:

```<code>#include "authhandler.h"
#include <QDebug>
#include <QVariantMap>
#include <QNetworkRequest>
#include <QJsonObject>
#include <QQmlApplicationEngine>
#include <QQmlContext>

AuthHandler::AuthHandler(QObject *parent)
    : QObject{parent}
    , m_apiKey( QString() )
{
    m_networkAccessManager = new QNetworkAccessManager( this );
    connect( this, &AuthHandler::userSignedIn, this, &AuthHandler::performAuthenticatedDatabaseCall );
    connect(this, &AuthHandler::userSignedIn, this, &AuthHandler::onUserSignedIn);
}

AuthHandler::~AuthHandler()
{
   m_networkAccessManager->deleteLater();
}

void AuthHandler::setAPIKey(const QString &apiKey)
{
    m_apiKey = apiKey;
}

void AuthHandler::signUserUp(const QString &emailAddress, const QString &password)
{
    QString signUpEndpoint = "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=" + m_apiKey;

    QVariantMap variantPayload;
    variantPayload["email"] = emailAddress;
    variantPayload["password"] = password;
    variantPayload["returnSecureToken"] = true;

    QJsonDocument jsonPayload = QJsonDocument::fromVariant( variantPayload );
    performPOST( signUpEndpoint, jsonPayload);

}

void AuthHandler::signUserIn(const QString &emailAddress, const QString &password)
{
    QString signInEndpoint = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=" + m_apiKey;

    QVariantMap variantPayload;
    variantPayload["email"] = emailAddress;
    variantPayload["password"] = password;
    variantPayload["returnSecureToken"] = true;

    QJsonDocument jsonPayload = QJsonDocument::fromVariant( variantPayload );
    performPOST( signInEndpoint, jsonPayload);

}

void AuthHandler::networkReplyReadyRead()
{
    QByteArray response = m_networkReply->readAll();
    qDebug() << response;
    m_networkReply->deleteLater();

    parseResponse( response);
}

void AuthHandler::performAuthenticatedDatabaseCall()
{
    QString endPoint = "https://karmandrones-7da76-default-rtdb.asia-southeast1.firebasedatabase.app/Pets.json?auth=" +m_idToken;
    m_networkReply = m_networkAccessManager->get( QNetworkRequest(QUrl(endPoint)));
    connect( m_networkReply, &QNetworkReply::readyRead, this, &AuthHandler::networkReplyReadyRead );
}

void AuthHandler::performPOST(const QString &url, const QJsonDocument &payload)
{
    QNetworkRequest newRequest( (QUrl(url)));
    newRequest.setHeader( QNetworkRequest::ContentTypeHeader, QString( "application/json"));
    m_networkReply = m_networkAccessManager->post( newRequest, payload.toJson());
    connect( m_networkReply, &QNetworkReply::readyRead, this, &AuthHandler::networkReplyReadyRead );
}

void AuthHandler::parseResponse(const QByteArray &response)
{
    QJsonDocument jsonDocument = QJsonDocument::fromJson(( response ));
   if ( jsonDocument.object().contains("error"))
   {
       qDebug() << "Error occured!" << response;
   }
   else if (jsonDocument.object().contains("kind"))
   {
       QString idToken = jsonDocument.object().value("idToken").toString();
       qDebug() << "Obtained user ID Token: " << idToken;
       qDebug() << "User signed in successfully!";
       m_idToken = idToken;
       emit userSignedIn();

   }
   else
       qDebug() << "The response was: " << response;
}

</code>```

qml file:

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.1
import QtQuick.LocalStorage 2.0

//import "AccountToolbar/Backend.js" as Backend
import "AuthBackend.js" as Backend

//////////

import QtQuick.Dialogs  1.3
import QtQuick.Window   2.11
import QGroundControl               1.0
import QGroundControl.Palette       1.0
import QGroundControl.Controls      1.0
import QGroundControl.ScreenTools   1.0
import QGroundControl.FlightDisplay 1.0
import QGroundControl.FlightMap     1.0
import QGroundControl.MultiVehicleManager   1.0
import QGroundControl.Controllers           1.0
import QtQuick.Controls.Styles 1.4

ApplicationWindow {
    id: authWindow
    visible: true
    width: Screen.width
    height: Screen.height
    minimumWidth:   ScreenTools.isMobile ? Screen.width  : Math.min(ScreenTools.defaultFontPixelWidth * 100, Screen.width)
    minimumHeight:  ScreenTools.isMobile ? Screen.height : Math.min(ScreenTools.defaultFontPixelWidth * 50, Screen.height)
    title: qsTr("KarmanGCS")

    property color backGroundColor : "white" // "#434343" //"#394454" // navy
    property color mainAppColor:  "#434343"// "#EBEBEB" //"#6fda9c" // green
    property color mainTextCOlor: "grey" // gray
    property color popupBackGroundColor: "#b44"
    property color popupTextCOlor: "#ffffff"
    property var dataBase

    FontLoader {
        id: fontAwesome
        name: "fontawesome"
        source: "qrc:/qml/fontawesome-webfont.ttf"
    }

    // Main stackview
    StackView{
        id: stackView
        focus: true
        anchors.fill: parent
    }

    // After loading show initial Login Page
    Component.onCompleted: {
        stackView.push("qrc:/qml/LoginPage.qml")   //initial page
        dataBase = userDataBase()
        console.log(dataBase.version)
    }
</code>```

As you can see the AuthWindow.qml loads the login page qml correctly.
The userSigneIn() signal is also emitted correctly on successful login. This can be checked by the qdebug statement that I have put in the cpp file. I tried making a new slot function, which would push the MainRootWindow.qml if the userSignedIn() signal is emitted. The connection is in the cpp file. It is being called as the first qdebug statement works, but the push is not happening. Can someone help me debug or suggest an alterantive approach to push a new page to stackview?

Body:
I have written code for Firebase Authentication for a desktop application. The authentication is working fine, I am having issues using StackView to push the next page based on successful authentication. Here's my code:
h file:

#ifndef AUTHHANDLER_H
#define AUTHHANDLER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QtQml/qqml.h>

class AuthHandler : public QObject
{
    Q_OBJECT
public:
    explicit AuthHandler(QObject *parent = nullptr);
    ~AuthHandler();
    void setAPIKey(const QString & apiKey);
    //void signUserUp(const QString & emailAddress, const QString & password);
    //void signUserIn(const QString & emailAddress, const QString & password);

public slots:
    void networkReplyReadyRead();
    void signUserIn(const QString & emailAddress, const QString & password);
    void signUserUp(const QString & emailAddress, const QString & password);
    void performAuthenticatedDatabaseCall();

    // New slot function
    void onUserSignedIn()
    {
        qDebug() << "onUserSignedIn called";

        // Get a reference to the StackView object
        QObject* stackView = this->parent()->findChild<QObject*>("stackView");  //problem here most likely
        if (stackView)
        {
            qDebug() << "Calling push() on StackView";
             //Push the main root window onto the StackView
            QMetaObject::invokeMethod(stackView, "push", Q_ARG(QVariant, "qrc:/qml/MainRootWindow.qml"));
        }
    }

signals:
    void userSignedIn();      //void

private:
   void performPOST( const QString & url, const QJsonDocument & payload);
   void parseResponse( const QByteArray & response);
   QString m_apiKey;
   QNetworkAccessManager * m_networkAccessManager;
   QNetworkReply * m_networkReply;
   QString m_idToken;

};

#endif // AUTHHANDLER_H

cpp file:

#include "authhandler.h"
#include <QDebug>
#include <QVariantMap>
#include <QNetworkRequest>
#include <QJsonObject>
#include <QQmlApplicationEngine>
#include <QQmlContext>

AuthHandler::AuthHandler(QObject *parent)
    : QObject{parent}
    , m_apiKey( QString() )
{
    m_networkAccessManager = new QNetworkAccessManager( this );
    connect( this, &AuthHandler::userSignedIn, this, &AuthHandler::performAuthenticatedDatabaseCall );
    connect(this, &AuthHandler::userSignedIn, this, &AuthHandler::onUserSignedIn);
}

AuthHandler::~AuthHandler()
{
   m_networkAccessManager->deleteLater();
}

void AuthHandler::setAPIKey(const QString &apiKey)
{
    m_apiKey = apiKey;
}

void AuthHandler::signUserUp(const QString &emailAddress, const QString &password)
{
    QString signUpEndpoint = "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=" + m_apiKey;

    QVariantMap variantPayload;
    variantPayload["email"] = emailAddress;
    variantPayload["password"] = password;
    variantPayload["returnSecureToken"] = true;

    QJsonDocument jsonPayload = QJsonDocument::fromVariant( variantPayload );
    performPOST( signUpEndpoint, jsonPayload);

}

void AuthHandler::signUserIn(const QString &emailAddress, const QString &password)
{
    QString signInEndpoint = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=" + m_apiKey;

    QVariantMap variantPayload;
    variantPayload["email"] = emailAddress;
    variantPayload["password"] = password;
    variantPayload["returnSecureToken"] = true;

    QJsonDocument jsonPayload = QJsonDocument::fromVariant( variantPayload );
    performPOST( signInEndpoint, jsonPayload);

}

void AuthHandler::networkReplyReadyRead()
{
    QByteArray response = m_networkReply->readAll();
    qDebug() << response;
    m_networkReply->deleteLater();

    parseResponse( response);
}

void AuthHandler::performAuthenticatedDatabaseCall()
{
    QString endPoint = "https://karmandrones-7da76-default-rtdb.asia-southeast1.firebasedatabase.app/Pets.json?auth=" +m_idToken;
    m_networkReply = m_networkAccessManager->get( QNetworkRequest(QUrl(endPoint)));
    connect( m_networkReply, &QNetworkReply::readyRead, this, &AuthHandler::networkReplyReadyRead );
}

void AuthHandler::performPOST(const QString &url, const QJsonDocument &payload)
{
    QNetworkRequest newRequest( (QUrl(url)));
    newRequest.setHeader( QNetworkRequest::ContentTypeHeader, QString( "application/json"));
    m_networkReply = m_networkAccessManager->post( newRequest, payload.toJson());
    connect( m_networkReply, &QNetworkReply::readyRead, this, &AuthHandler::networkReplyReadyRead );
}

void AuthHandler::parseResponse(const QByteArray &response)
{
    QJsonDocument jsonDocument = QJsonDocument::fromJson(( response ));
   if ( jsonDocument.object().contains("error"))
   {
       qDebug() << "Error occured!" << response;
   }
   else if (jsonDocument.object().contains("kind"))
   {
       QString idToken = jsonDocument.object().value("idToken").toString();
       qDebug() << "Obtained user ID Token: " << idToken;
       qDebug() << "User signed in successfully!";
       m_idToken = idToken;
       emit userSignedIn();

   }
   else
       qDebug() << "The response was: " << response;
}

qml file:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.1
import QtQuick.LocalStorage 2.0

//import "AccountToolbar/Backend.js" as Backend
import "AuthBackend.js" as Backend

//////////

import QtQuick.Dialogs  1.3
import QtQuick.Window   2.11
import QGroundControl               1.0
import QGroundControl.Palette       1.0
import QGroundControl.Controls      1.0
import QGroundControl.ScreenTools   1.0
import QGroundControl.FlightDisplay 1.0
import QGroundControl.FlightMap     1.0
import QGroundControl.MultiVehicleManager   1.0
import QGroundControl.Controllers           1.0
import QtQuick.Controls.Styles 1.4

ApplicationWindow {
    id: authWindow
    visible: true
    width: Screen.width
    height: Screen.height
    minimumWidth:   ScreenTools.isMobile ? Screen.width  : Math.min(ScreenTools.defaultFontPixelWidth * 100, Screen.width)
    minimumHeight:  ScreenTools.isMobile ? Screen.height : Math.min(ScreenTools.defaultFontPixelWidth * 50, Screen.height)
    title: qsTr("KarmanGCS")

    property color backGroundColor : "white" // "#434343" //"#394454" // navy
    property color mainAppColor:  "#434343"// "#EBEBEB" //"#6fda9c" // green
    property color mainTextCOlor: "grey" // gray
    property color popupBackGroundColor: "#b44"
    property color popupTextCOlor: "#ffffff"
    property var dataBase

    FontLoader {
        id: fontAwesome
        name: "fontawesome"
        source: "qrc:/qml/fontawesome-webfont.ttf"
    }

    // Main stackview
    StackView{
        id: stackView
        focus: true
        anchors.fill: parent
    }

    // After loading show initial Login Page
    Component.onCompleted: {
        stackView.push("qrc:/qml/LoginPage.qml")   //initial page
        dataBase = userDataBase()
        console.log(dataBase.version)
    }

As you can see the AuthWindow.qml loads the login page qml correctly.
The userSigneIn() signal is also emitted correctly on successful login. This can be checked by the qdebug statement that I have put in the cpp file. I tried making a new slot function, which would push the MainRootWindow.qml if the userSignedIn() signal is emitted. The connection is in the cpp file. It is being called as the first qdebug statement works, but the push is not happening. Can someone help me debug or suggest an alterantive approach to push a new page to stackview?


问:
Laravel - Show update message after update using query builder
In my laravel + vue application I am trying to update the name and account_external_id column in mysql database.

Here is the code:

```<code>// Set the database name and id project
$db_name = $get_db->mysql_db_name;
$id_project = $get_db->id_project;

// Update linked account
$update_linked_account = DB::connection($db_name)
->table($db_name . '.linked_accounts')
->where('id_linked_account', $id_linked_account)
->where('id_project', $id_project )
->update([
    'name'  =>  $account_name,
    'account_external_id'   =>  $account_id
]);

// If updated
if( $update_linked_account ) {
    return response()->json([
        'success'   =>  true,
        'message'   =>  'Account updated successfully.'
    ], 200);
} else {
    return response()->json([
        'success'   =>  false,
        'message'   =>  'Could not update the account.'
    ], 200);
}
</code>```

When I change the name or account_external_id value then press the update button then I can get the $update_linked_account as true.

BUT

When I do not change the name or account_external_id value then press the update button then I can get the $update_linked_account as false. why? It should give me true too, right?

Body:
In my laravel + vue application I am trying to update the name and account_external_id column in mysql database.

Here is the code:

// Set the database name and id project
$db_name = $get_db->mysql_db_name;
$id_project = $get_db->id_project;

// Update linked account
$update_linked_account = DB::connection($db_name)
->table($db_name . '.linked_accounts')
->where('id_linked_account', $id_linked_account)
->where('id_project', $id_project )
->update([
    'name'  =>  $account_name,
    'account_external_id'   =>  $account_id
]);

// If updated
if( $update_linked_account ) {
    return response()->json([
        'success'   =>  true,
        'message'   =>  'Account updated successfully.'
    ], 200);
} else {
    return response()->json([
        'success'   =>  false,
        'message'   =>  'Could not update the account.'
    ], 200);
}

When I change the name or account_external_id value then press the update button then I can get the $update_linked_account as true.

BUT

When I do not change the name or account_external_id value then press the update button then I can get the $update_linked_account as false. why? It should give me true too, right?


问:
Creating File Template in Intellij with importing files relativly
I'm trying to build a file template for a react component for my team at work.
I have built the file template according to what Intellij offers, but I get stuck in one thing:

How can I import files into my file template, but without knowing where I am regarding the root folder?
We do use absolute imports so I do use it inside my component file, but it doesn't work in my test file and I have something that calls AppMock that mocks the behavior of our app, and I can't import absolute on it.

Any solutions will be welcomed, thanks

I tried to look for import files relatively in my file template but I couldn't find anything that matches to my problem

Here is an example of what I talk about:

```<code>import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import React from 'react';
import { $NAME } from './${NAME}';
import { noop } from 'lodash'
import { AppMock } from '../../../../../../config/jest/testHelpers/AppMock';
</code>```

As you can see, the imports are external libraries, except AppMock because we don't work with absolute imports in test files, and because of that I didn't find a way to create a file template for test file.

Body:
I'm trying to build a file template for a react component for my team at work.
I have built the file template according to what Intellij offers, but I get stuck in one thing:

How can I import files into my file template, but without knowing where I am regarding the root folder?
We do use absolute imports so I do use it inside my component file, but it doesn't work in my test file and I have something that calls AppMock that mocks the behavior of our app, and I can't import absolute on it.

Any solutions will be welcomed, thanks

I tried to look for import files relatively in my file template but I couldn't find anything that matches to my problem

Here is an example of what I talk about:

import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import React from 'react';
import { $NAME } from './${NAME}';
import { noop } from 'lodash'
import { AppMock } from '../../../../../../config/jest/testHelpers/AppMock';

As you can see, the imports are external libraries, except AppMock because we don't work with absolute imports in test files, and because of that I didn't find a way to create a file template for test file.


问:
In Dmalloc tool is there way i will give check only specific memory range?
We are running dmalloc tool for specific app but we are getting too many traces that are not from app they are from c libraries and we are getting huge log, to avoid is there any way we can feed address range or any other option we can try.

6567117: 175519:  not freed: '0x17c9c80|s1' (80 bytes) from 'unknown'
this unknown reported is filed in log file


问:
Touching Right click window in Java Selenium Chrome
I can right click on a search term in Java selenium Chrome, but I cannot click where I want in the popup menu. How can I get to the place I want in the window that opens after right-clicking?

Code example where I right click :

```<code>enter code here
</code>```

Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//h3[text()='Example']"))).contextClick().build().perform();

Body:
I can right click on a search term in Java selenium Chrome, but I cannot click where I want in the popup menu. How can I get to the place I want in the window that opens after right-clicking?

Code example where I right click :

enter code here

Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//h3[text()='Example']"))).contextClick().build().perform();


问:
Run length encoding with dynamic blocks of string?
I want to write a dynamic block size run length encoder but i am unable decide how should I implement it in python with  dynamic blocks (substring length depending on content )

For example i have a string : 1110011100001

A human can easily tell that string 11100 is repeating consecutively. Block size is 5 in above case. But I want the program to decide the optimal block size which is repeating consecutively and this block size may change as we further encounter new substrings.

One solution is to brute force every combination of substring and match it with all substring. Is there any other optimal solution.

Writing RLE compressor but runtime is higher and implementation is a bit complex.


问:
How do I convert a string sort to a Lambda?(How does Expression.Lambda convert Type to generic?)
The main purpose is to convert a string query condition into a Lambda expression.
The IQueryable sorting method: public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);
But I only have Type. How do I convert to generics?
Below is the method I wrote, more cumbersome, ask if there is a simpler.

```<code>// OrderBy = "UserId Desc"
    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string orderStr)
    {
        var orderStrArr = orderStr.ToListString();
        foreach (var item in orderStrArr)
        {
            var itemArr = item.ToListString(false,' ');
            var typeExp = Expression.Parameter(typeof(TSource), "s");
            var proExp = Expression.Property(typeExp, itemArr.First());
            if (itemArr.Count == 1)
            {
                source = source.OrderBy(typeExp, proExp);
            }
            else
            {
                source = source.OrderBy(typeExp, proExp, itemArr[1].ToLower().Trim() == "asc");
            }
        }
        return source;
    }

    private static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, ParameterExpression typeExp, MemberExpression proExp,bool isASC = true)
    {
        var typeName = proExp.Type.GetNullableName();
        switch (typeName)
        {
            case "Int32":
                var lambdaExpInt = Expression.Lambda<Func<TSource, int>>(proExp, typeExp);
                return OrderBy(source, lambdaExpInt, isASC);
            case "Int32?":
                var lambdaExpInt2 = Expression.Lambda<Func<TSource, int?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpInt2, isASC);
            case "Int64":
                var lambdaExpLong = Expression.Lambda<Func<TSource, long>>(proExp, typeExp);
                return OrderBy(source, lambdaExpLong, isASC);
            case "Int64?":
                var lambdaExpLong2 = Expression.Lambda<Func<TSource, long?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpLong2, isASC);
            case "String":
                var lambdaExpString = Expression.Lambda<Func<TSource, string>>(proExp, typeExp);
                return OrderBy(source, lambdaExpString, isASC);
            case "DateTime":
                var lambdaExpDateTime = Expression.Lambda<Func<TSource, DateTime>>(proExp, typeExp);
                return OrderBy(source, lambdaExpDateTime, isASC);
            case "DateTime?":
                var lambdaExpDateTime2 = Expression.Lambda<Func<TSource, DateTime?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpDateTime2, isASC);
            case "Guid":
                var lambdaExpGuid = Expression.Lambda<Func<TSource, Guid>>(proExp, typeExp);
                return OrderBy(source, lambdaExpGuid, isASC);
            case "Guid?":
                var lambdaExpGuid2 = Expression.Lambda<Func<TSource, Guid?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpGuid2, isASC);
            case "Decimal":
                var lambdaExpDecimal = Expression.Lambda<Func<TSource, decimal>>(proExp, typeExp);
                return OrderBy(source, lambdaExpDecimal, isASC);
            case "Decimal?":
                var lambdaExpDecimal2 = Expression.Lambda<Func<TSource, decimal?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpDecimal2, isASC);
            default:
                throw new Exception($"Type:{proExp.Type.FullName}");
        }
    }

    private static IOrderedQueryable<TSource> OrderBy<TSource,TKey>(IQueryable<TSource> source, Expression<Func<TSource, TKey>> lambda, bool isAsc)
    {
        return isAsc ? source.OrderBy(lambda) : source.OrderByDescending(lambda);
    }
</code>```

Body:
The main purpose is to convert a string query condition into a Lambda expression.
The IQueryable sorting method: public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);
But I only have Type. How do I convert to generics?
Below is the method I wrote, more cumbersome, ask if there is a simpler.

// OrderBy = "UserId Desc"
    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string orderStr)
    {
        var orderStrArr = orderStr.ToListString();
        foreach (var item in orderStrArr)
        {
            var itemArr = item.ToListString(false,' ');
            var typeExp = Expression.Parameter(typeof(TSource), "s");
            var proExp = Expression.Property(typeExp, itemArr.First());
            if (itemArr.Count == 1)
            {
                source = source.OrderBy(typeExp, proExp);
            }
            else
            {
                source = source.OrderBy(typeExp, proExp, itemArr[1].ToLower().Trim() == "asc");
            }
        }
        return source;
    }

    private static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, ParameterExpression typeExp, MemberExpression proExp,bool isASC = true)
    {
        var typeName = proExp.Type.GetNullableName();
        switch (typeName)
        {
            case "Int32":
                var lambdaExpInt = Expression.Lambda<Func<TSource, int>>(proExp, typeExp);
                return OrderBy(source, lambdaExpInt, isASC);
            case "Int32?":
                var lambdaExpInt2 = Expression.Lambda<Func<TSource, int?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpInt2, isASC);
            case "Int64":
                var lambdaExpLong = Expression.Lambda<Func<TSource, long>>(proExp, typeExp);
                return OrderBy(source, lambdaExpLong, isASC);
            case "Int64?":
                var lambdaExpLong2 = Expression.Lambda<Func<TSource, long?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpLong2, isASC);
            case "String":
                var lambdaExpString = Expression.Lambda<Func<TSource, string>>(proExp, typeExp);
                return OrderBy(source, lambdaExpString, isASC);
            case "DateTime":
                var lambdaExpDateTime = Expression.Lambda<Func<TSource, DateTime>>(proExp, typeExp);
                return OrderBy(source, lambdaExpDateTime, isASC);
            case "DateTime?":
                var lambdaExpDateTime2 = Expression.Lambda<Func<TSource, DateTime?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpDateTime2, isASC);
            case "Guid":
                var lambdaExpGuid = Expression.Lambda<Func<TSource, Guid>>(proExp, typeExp);
                return OrderBy(source, lambdaExpGuid, isASC);
            case "Guid?":
                var lambdaExpGuid2 = Expression.Lambda<Func<TSource, Guid?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpGuid2, isASC);
            case "Decimal":
                var lambdaExpDecimal = Expression.Lambda<Func<TSource, decimal>>(proExp, typeExp);
                return OrderBy(source, lambdaExpDecimal, isASC);
            case "Decimal?":
                var lambdaExpDecimal2 = Expression.Lambda<Func<TSource, decimal?>>(proExp, typeExp);
                return OrderBy(source, lambdaExpDecimal2, isASC);
            default:
                throw new Exception($"Type:{proExp.Type.FullName}");
        }
    }

    private static IOrderedQueryable<TSource> OrderBy<TSource,TKey>(IQueryable<TSource> source, Expression<Func<TSource, TKey>> lambda, bool isAsc)
    {
        return isAsc ? source.OrderBy(lambda) : source.OrderByDescending(lambda);
    }


Title: Python Pandas how to group a column into multi columns by groupby?

Body:
My raw dataframe is like this :

df = pd.read_csv('sample.csv')
df

          time               keys   values
0   2022-12-07_10:04:12 A   815.5
1   2022-12-07_10:04:12 B   1987.0
2   2022-12-07_10:04:13 A   819.0
3   2022-12-07_10:04:13 B   1987.0
4   2022-12-07_10:04:14 A   822.5
5   2022-12-07_10:04:14 B   1985.0
6   2022-12-07_10:04:15 A   825.5
7   2022-12-07_10:04:15 C   100.5

I want to plot a chart to observe A and B how to vary based on time.

I think I need to get a dataframe like this:

time                    A-values    B-values
2022-12-07_10:04:12     815.5        1987.0
2022-12-07_10:04:13     819.0        1987.0
2022-12-07_10:04:14     822.5        1985.0
2022-12-07_10:04:15     825.0        NaN

I try:

ab = df.loc[df['keys'].str.contains('A|B')]
ab.groupby('time')

And I don't know what I should do next...... there must be a way, Thanks you so much!
(Sorry for my poor English)


问:
Trouble Capturing Variable with Percent Encoded characters in Google Tag Manager
I am trying to log a variable in my sites url. As I understand it, in google tag manager I head over to the variables section, added a user defined variable as follows:

Variable Type: URL

Component Type: Query

Query Key: search_location_address[text]

(I have also tried search_location_address%5Btext%5D as it appears in the url)

URL Source: Page URL

Neither version of the query key seems to work, when previewing and testing, the Location variable shows up as undefined.

Shows Undefined Location

Any ideas or am I completely missing something here?


问:
How to update MPNowPlayingInfoCenter/MPRemoteCommandCenter play/pause controls with AVAudioPlayerNode?
I am making a simple music player app that just plays audio using AVAudioEngine. When I pause the AVAudioPlayerNode, it does not update the play/pause control of the MPNowPlayingInfoCenter/MPRemoteCommandCenter. How do I update it?

I dont want to pause the entire AVAudioEngine and then resume to update the MPNowPlayingInfoCenter/MPRemoteCommandCenter play/pause control since it lags up my UI and there's a delay when playing back audio.

Does anyone have any idea or solution regarding this topic? The documentation is absolutely atrocious and no one knows a goddamn thing about AVAudioEngine. Anyone?

```<code>func pause() {
        playerNode.pause()
        audioEngine.pause()

        displayLink?.isPaused = true

        DispatchQueue.main.async {
            self.musicPlayerControlsManager.isPlaying = false
        }
    }

    func playPlayerNode() {
        if !audioEngine.attachedNodes.isEmpty && audioFile != nil {

            DispatchQueue.main.async {
                self.musicPlayerControlsManager.isPlaying = true
                self.displayLink?.isPaused = false
            }

            do {
                try audioEngine.start()
                playerNode.play()

            } catch {
                print(error.localizedDescription)
            }
        }
    }
</code>```

Body:
I am making a simple music player app that just plays audio using AVAudioEngine. When I pause the AVAudioPlayerNode, it does not update the play/pause control of the MPNowPlayingInfoCenter/MPRemoteCommandCenter. How do I update it?

I dont want to pause the entire AVAudioEngine and then resume to update the MPNowPlayingInfoCenter/MPRemoteCommandCenter play/pause control since it lags up my UI and there's a delay when playing back audio.

Does anyone have any idea or solution regarding this topic? The documentation is absolutely atrocious and no one knows a goddamn thing about AVAudioEngine. Anyone?

func pause() {
        playerNode.pause()
        audioEngine.pause()

        displayLink?.isPaused = true

        DispatchQueue.main.async {
            self.musicPlayerControlsManager.isPlaying = false
        }
    }

    func playPlayerNode() {
        if !audioEngine.attachedNodes.isEmpty && audioFile != nil {

            DispatchQueue.main.async {
                self.musicPlayerControlsManager.isPlaying = true
                self.displayLink?.isPaused = false
            }

            do {
                try audioEngine.start()
                playerNode.play()

            } catch {
                print(error.localizedDescription)
            }
        }
    }


问:
KeyError: 'The `start` argument could not be matched to a location related to the index of the data.' while implementing ARIMA .predict()
KeyError: 'The start argument could not be matched to a location related to the index of the data.' while implementing ARIMA .predict()

I was try to implement the ARIMA model on one of the stationary dataset. I firstly split the data into tarin n test and try to pass the test data in .predict() fun. then im getting this error.


问:
Why do some pixels in JPanel look stretched giving a pixelated look to this curve
I'm trying to print a smooth curve but it seems that some of the pixels are stretched. I tried to debug this by printing the pixel array but it looked smooth. The JPanel created has width and height 800.

This is the printed pixels of the double array:

This is the image drawn:

I have found this function that does the same thing and is really smooth but I want to figure out how to make this from an array of pixels.

```<code>grf.drawRoundRect(50, 50, 400, 400, 200, 200);
</code>```
```<code>public void draw(){
  Graphics grf = screen.get_graphics();
  int width = 400;
  int height = 400;
  int scale = 1;
  BufferedImage red_fill = BufferedImageFactory.fill(width, height, Color.RED);
  Matrixi2d square_mask = new Soft_Square().get_filled_in_mask(width, height);
  BufferedImage hue_soft_square = square_mask.mask_image(red_fill);
  grf.drawImage(hue_soft_square, 50, 50, null);
}
</code>```
```<code>public BufferedImage mask_image(BufferedImage input){
  //BufferedImage result = new BufferedImage(width + edge*2, height + edge*2, BufferedImage.TYPE_INT_ARGB);
  BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  //for(int x = edge, mask_x = 0; x < width; x++, mask_x++){
    //for(int y = edge, mask_y = 0; y < height; y++, mask_y++){
  for(int x = 0, mask_x = 0; x < width; x++, mask_x++){
    for(int y = 0, mask_y = 0; y < height; y++, mask_y++){
      if(get(mask_x, mask_y) != 0){
        int mask_alpha = get(mask_x, mask_y);
        int color = input.getRGB(x, y);
        int red = (0xFF & ( color >> 16));
        int alpha = (0xFF & (color >> 24));
        int blue = (0xFF & (color >> 0 ));
        int green = (0xFF & (color >> 8 ));
        //System.out.println("mask value: "+get(mask_x, mask_y));
        //System.out.println("initial alpha: " + alpha);
        alpha = (int)(alpha * mask_alpha / 255.0);
        int sum = ((alpha & 0xff) << 24 | (red & 0xff) << 16 | (blue & 0xff) << 8 | (green & 0xff));
        //System.out.println("alpha: " + alpha);
        //System.out.println("mask alpha: " + mask_alpha);
        result.setRGB(x, y, sum);
        //System.out.println("setting result: "+sum);
      }
    }
  }
  return result;
}
</code>```

Edit:
Downloading the image shows that the BufferedImage doesn't have the stretching. How do you eliminate the stretching in JPanel?
Here's the BufferedImage as png

Edit:
This SO-Question fixed the problem.

Body:
I'm trying to print a smooth curve but it seems that some of the pixels are stretched. I tried to debug this by printing the pixel array but it looked smooth. The JPanel created has width and height 800.

This is the printed pixels of the double array:

This is the image drawn:

I have found this function that does the same thing and is really smooth but I want to figure out how to make this from an array of pixels.

grf.drawRoundRect(50, 50, 400, 400, 200, 200);

public void draw(){
  Graphics grf = screen.get_graphics();
  int width = 400;
  int height = 400;
  int scale = 1;
  BufferedImage red_fill = BufferedImageFactory.fill(width, height, Color.RED);
  Matrixi2d square_mask = new Soft_Square().get_filled_in_mask(width, height);
  BufferedImage hue_soft_square = square_mask.mask_image(red_fill);
  grf.drawImage(hue_soft_square, 50, 50, null);
}

public BufferedImage mask_image(BufferedImage input){
  //BufferedImage result = new BufferedImage(width + edge*2, height + edge*2, BufferedImage.TYPE_INT_ARGB);
  BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  //for(int x = edge, mask_x = 0; x < width; x++, mask_x++){
    //for(int y = edge, mask_y = 0; y < height; y++, mask_y++){
  for(int x = 0, mask_x = 0; x < width; x++, mask_x++){
    for(int y = 0, mask_y = 0; y < height; y++, mask_y++){
      if(get(mask_x, mask_y) != 0){
        int mask_alpha = get(mask_x, mask_y);
        int color = input.getRGB(x, y);
        int red = (0xFF & ( color >> 16));
        int alpha = (0xFF & (color >> 24));
        int blue = (0xFF & (color >> 0 ));
        int green = (0xFF & (color >> 8 ));
        //System.out.println("mask value: "+get(mask_x, mask_y));
        //System.out.println("initial alpha: " + alpha);
        alpha = (int)(alpha * mask_alpha / 255.0);
        int sum = ((alpha & 0xff) << 24 | (red & 0xff) << 16 | (blue & 0xff) << 8 | (green & 0xff));
        //System.out.println("alpha: " + alpha);
        //System.out.println("mask alpha: " + mask_alpha);
        result.setRGB(x, y, sum);
        //System.out.println("setting result: "+sum);
      }
    }
  }
  return result;
}

Edit:
Downloading the image shows that the BufferedImage doesn't have the stretching. How do you eliminate the stretching in JPanel?
Here's the BufferedImage as png

Edit:
This SO-Question fixed the problem.


问:
React-hook-form never updates as dirty after user has made changes
We're running a project in which react-hook-form has worked fine, however the dirtying doesn't function, and never has. It should activate once the useForm has gotten default values after which the user changes some of the fields.

What are some of the situations where the library might have the problem of not behaving correctly with dirtying?


问:
how to implement angular CDK drag and drop in Calendar events?
I want to apply drag-and-drop  to the calendar using Angular CDK I tried the Following code:

AppComponent.html

```<code><div style="height: 100%; width: 100%;border: 1px solid gray;"  (cdkDropListDropped)="drop($event)" >

    <ngx-event-calendar
    [showAddButton]="true"
    [language]="'en'"
    [dataSource]="dataArray"
    (dayEvents)="selectDay($event)"
    (newEvent)="addEvent($event)"
    cdkDrag
    cdkDropList
    [cdkDragData]="dataArray">
    </ngx-event-calendar>
</div>
</code>```

AppComponent.ts

```<code>export class AppComponent {
  title = 'calendar';
  language: string = 'en';
  newEvent = {} as IEventData;
  dataArray;

  constructor(public dialog: MatDialog) {
    const testData: IEventData[] = [ ];
    this.dataArray=testData;
    this.newEvent.id=13;
    this.newEvent.title='Title';
    this.newEvent.desc='Description';
    this.newEvent.startDate= new Date("2022-12-22T21:00:00");
    this.newEvent.endDate= new Date("2022-12-22T21:00:00");
    this.newEvent.createdBy='Mark';
    this.newEvent.createdAt=new Date("2022-12-22T10:00:00");
    this.newEvent.type=2;
    this.newEvent.color='red';
    testData.push(this.newEvent);
   }

  addEvent(event) {

  }

  selectDay(event) {
    //drag and drap should implement when user select event for specific day
  }
drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.dataArray, event.previousIndex, event.currentIndex);
  }
</code>```

I am new in Angular CDK and do not know how to use CDK drop and drag in Calendar, my code does not work can anyone compelete my code what change should I bring to my codes???
I want when the user clicks on the event in the calendar, and the user can drag and drop the event to different days throw the calendar.

Body:
I want to apply drag-and-drop  to the calendar using Angular CDK I tried the Following code:

AppComponent.html

    <ngx-event-calendar
    [showAddButton]="true"
    [language]="'en'"
    [dataSource]="dataArray"
    (dayEvents)="selectDay($event)"
    (newEvent)="addEvent($event)"
    cdkDrag
    cdkDropList
    [cdkDragData]="dataArray">
    </ngx-event-calendar>

AppComponent.ts

export class AppComponent {
  title = 'calendar';
  language: string = 'en';
  newEvent = {} as IEventData;
  dataArray;

  constructor(public dialog: MatDialog) {
    const testData: IEventData[] = [ ];
    this.dataArray=testData;
    this.newEvent.id=13;
    this.newEvent.title='Title';
    this.newEvent.desc='Description';
    this.newEvent.startDate= new Date("2022-12-22T21:00:00");
    this.newEvent.endDate= new Date("2022-12-22T21:00:00");
    this.newEvent.createdBy='Mark';
    this.newEvent.createdAt=new Date("2022-12-22T10:00:00");
    this.newEvent.type=2;
    this.newEvent.color='red';
    testData.push(this.newEvent);
   }

  addEvent(event) {

  }

  selectDay(event) {
    //drag and drap should implement when user select event for specific day
  }
drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.dataArray, event.previousIndex, event.currentIndex);
  }

I am new in Angular CDK and do not know how to use CDK drop and drag in Calendar, my code does not work can anyone compelete my code what change should I bring to my codes???
I want when the user clicks on the event in the calendar, and the user can drag and drop the event to different days throw the calendar.


问:
Republishing maven artifacts fails the build with GitHub Packages
I have a repository on GitHub that publishes through the maven-publish gradle plugin a few artifacts to a Nexus repository and GitHub Packages (with the help of GitHub Actions). Republishing the maven artifacts fails the build with GitHub Packages because the artifacts can't be republished  with the same version.

For every version there exists a branch e.g. version/X that gets created when a new version
of a software is released. A PR for this branch gets created and then merged into the master branch. The problem is that the branches should publish only once as specific jars are downloaded from a server for that version of the software e.g. 11.1 for version/1 , 17.5 for version/2 etc. A few problems exist:

When I push the branch, GitHub actions is triggered, the artifacts get published and the build is green. When I merge the branch into master, the build fails because I can't republish an artifact with the same version to Github Packages (Received status code 409 from server: Conflict). The nexus server is probably configured to ignore it, so it is not a problem.

Every artifact is published through a dedicated Gradle task. Let's say task 5 fails, because the download location for the jar has changed or the jar that should be published doesn't exist in the new version. As a result the full build fails. I could make Gradle continue except failing a task, but task 5 maybe has to be published anyways, so I have to manually remove artifacts 1-4 from Github Packages, make the changes and push the branch again. In the worst case, I have to delete 10 artifacts manually.

I know that published artifacts shouldn't be deleted and they should have unique names. Is there a way to deal with both these scenarios anyways (like deleting the artifacts first) or is a unique name for every time the publication is triggered the only solution? I'd really like to avoid that option as there is no reason to publish the exact same artifacts with different suffixes as there is already no correlation between the software version and the name of the artifacts. I also don't want to pollute the nexus server with half published artifacts as people navigate it through the UI and wouldn't know that one set of artifacts were not fully published. Additional information: these artifacts are only published about three times a year. I am mainly concerned by the failing build and the troubles that are theoretically possible when a single branch has to be republished for some reason (e.g. a bug fix version of an old version of the software introduces a new artifact). The publishing process itself could also change, that means that a change to the publishing script also fails the build.


问:
Why SOME/IP-TP required?
If the message size is larger than the MTU, I know that fragmentation occurs in the IP layer. Why still need SOME/IP-TP?

I couldn't find the reason why SOME/IP-TP is needed even in AUTOSAR Spec.

Title: Why SOME/IP-TP required?


问:
Spring Boot 2.1 JpaBaseConfiguration Constructor update to Spring Boot 2.2
```<code>I configured the JpaConfiguration by init the Constructor of JpaConfiguration liek the example below:

@Configuration
@EnableJpaAuditing
@EnableJpaRepositories(basePackages = {"com.foo.bar"})
@EntityScan(basePackages = {"com.foo.bar"})
public class JpaConfiguration extends JpaBaseConfiguration implements TransactionManagementConfigurer {
    private final HibernateProperties hibernateProperties;

    @Autowired
    public JpaConfiguration(DataSource dataSource, JpaProperties jpaProperties,
                            ObjectProvider<JtaTransactionManager> jtaTransactionManager,
                            **ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers**, HibernateProperties hibernateProperties) {
        super(dataSource, jpaProperties, jtaTransactionManager, **transactionManagerCustomizers**);
        this.hibernateProperties = hibernateProperties;
    }
</code>```

Now i updated the App and the constructor doesnt accept ObjectProvider transactionManagerCustomizers anymore. How can i configure this? I couldnt find any release notes for this or similar problems?

```<code>

Finding release notes for this issue to solve it. Also rewrite the whole class.
</code>```

Body:
I configured the JpaConfiguration by init the Constructor of JpaConfiguration liek the example below:

@Configuration
@EnableJpaAuditing
@EnableJpaRepositories(basePackages = {"com.foo.bar"})
@EntityScan(basePackages = {"com.foo.bar"})
public class JpaConfiguration extends JpaBaseConfiguration implements TransactionManagementConfigurer {
    private final HibernateProperties hibernateProperties;

    @Autowired
    public JpaConfiguration(DataSource dataSource, JpaProperties jpaProperties,
                            ObjectProvider<JtaTransactionManager> jtaTransactionManager,
                            **ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers**, HibernateProperties hibernateProperties) {
        super(dataSource, jpaProperties, jtaTransactionManager, **transactionManagerCustomizers**);
        this.hibernateProperties = hibernateProperties;
    }

Now i updated the App and the constructor doesnt accept ObjectProvider transactionManagerCustomizers anymore. How can i configure this? I couldnt find any release notes for this or similar problems?

Finding release notes for this issue to solve it. Also rewrite the whole class.


问:
Possible methods of solving this question, understanding this captcha
Keep in mind that this is a challenge, I am not expecting a full answer, just a bit of help.

On the image archived you are able to see a complex captcha that I am attempting to solve using code.

The captcha has a column for # and another composed of a random string.

The captcha itself is actually identifying which string row has the different color in it, once you identify that then you can input the # of that string row.

For the image below the string row #4. has a smaller portion of str colored differently, and #4 is the correct answer.

How could I solve this programmatically?

I thought of using AI but I think that is overkill, I should be able to do this with OpenCV.

Note: The background is also a random image, it can be anything.
Fortuntely, the foreground is very noticeable and clear making it easy to ignore the background with code

I am mostly researching possible methods of solving this captcha, fortunately I think I'm on the right path, which involves using OpenCV, but I'm not sure which functionalities of OpenCV I should use for this.

The challenge requires the app to return an integer, in this case it is the # of the correct 'messed' up string.


问:
How to add video to youtube playlist realtime while playing that playlist?
I am developing a chrome extension where there are two screens. On one of the screens we will choose a video to be added to a specific playlist using arrows and hot key. The video is being added successfully but the problem is that I have to reload the playlist page.

Is there any way that this whole process could work real time?

Here is my whole content script if you want to test the app

```<code>let thumbnails = [];
let currentSelection = 0;
const query = "ytd-thumbnail:not(.ytd-rich-grid-slim-media)";

let name1 = "playlist1";
let name2 = "playlist2";

window.addEventListener("load", (e) => {
   setTimeout(initiate, 2000);
});
const updateThumbnails = () => {
   thumbnails = [...document.querySelectorAll(query)].slice(1, -1);
};
window.addEventListener("scroll", (e) => {
   updateThumbnails();
});
const waitForTime = (ms) => new Promise((res, rej) => setTimeout(res, ms));

const addToPlayList = async () => {
   document
      .querySelector(".selected-thumbnail")
      .parentNode.querySelector("#menu ytd-menu-renderer #button #button")
      .click();

   const menu = document.querySelector("ytd-menu-popup-renderer");
   menu.style.opacity = 0;
   await waitForTime(500);
   const items = document.querySelectorAll(
      "tp-yt-iron-dropdown tp-yt-paper-listbox ytd-menu-service-item-renderer"
   );
   items[2].click();
   await waitForTime(1000);
   const playlists = document.querySelectorAll(
      "ytd-playlist-add-to-option-renderer yt-formatted-string#label"
   );
   const playlist1 = [...playlists].find((x) => x.innerHTML === name1);

   playlist1.click();
};

function initiate() {
   updateThumbnails();

   thumbnails[currentSelection].classList.add("selected-thumbnail");
   window.addEventListener("keyup", (e) => {
      if (e.key === "ArrowRight") {
         updateThumbnails();
         if (currentSelection === thumbnails.length - 1) return;
         document
            .querySelector(".selected-thumbnail")
            .classList.remove("selected-thumbnail");

         currentSelection++;
         thumbnails[currentSelection].classList.add("selected-thumbnail");
         scrollToElement(thumbnails[currentSelection]);
      }
      if (e.key === "ArrowLeft") {
         if (currentSelection === 0) return;
         document
            .querySelector(".selected-thumbnail")
            .classList.remove("selected-thumbnail");

         currentSelection--;
         thumbnails[currentSelection].classList.add("selected-thumbnail");
         scrollToElement(thumbnails[currentSelection]);
      }
      if (e.key === "F2") {
         addToPlayList();
      }
   });
}
function scrollToElement(elm) {
   if (elementInViewport(elm)) return;
   const { top, height } = elm.getBoundingClientRect();
   window.scrollTo({ behavior: "auto", top: top + window.scrollY - 200 });
}

function elementInViewport(el) {
   var top = el.offsetTop;
   var left = el.offsetLeft;
   var width = el.offsetWidth;
   var height = el.offsetHeight;

   while (el.offsetParent) {
      el = el.offsetParent;
      top += el.offsetTop;
      left += el.offsetLeft;
   }

   return (
      top >= window.pageYOffset &&
      left >= window.pageXOffset &&
      top + height <= window.pageYOffset + window.innerHeight &&
      left + width <= window.pageXOffset + window.innerWidth
   );
}
</code>```

Kindly let me know if this thing is even possible with youtube or not?

Body:
I am developing a chrome extension where there are two screens. On one of the screens we will choose a video to be added to a specific playlist using arrows and hot key. The video is being added successfully but the problem is that I have to reload the playlist page.

Is there any way that this whole process could work real time?

Here is my whole content script if you want to test the app

let thumbnails = [];
let currentSelection = 0;
const query = "ytd-thumbnail:not(.ytd-rich-grid-slim-media)";

let name1 = "playlist1";
let name2 = "playlist2";

window.addEventListener("load", (e) => {
   setTimeout(initiate, 2000);
});
const updateThumbnails = () => {
   thumbnails = [...document.querySelectorAll(query)].slice(1, -1);
};
window.addEventListener("scroll", (e) => {
   updateThumbnails();
});
const waitForTime = (ms) => new Promise((res, rej) => setTimeout(res, ms));

const addToPlayList = async () => {
   document
      .querySelector(".selected-thumbnail")
      .parentNode.querySelector("#menu ytd-menu-renderer #button #button")
      .click();

   const menu = document.querySelector("ytd-menu-popup-renderer");
   menu.style.opacity = 0;
   await waitForTime(500);
   const items = document.querySelectorAll(
      "tp-yt-iron-dropdown tp-yt-paper-listbox ytd-menu-service-item-renderer"
   );
   items[2].click();
   await waitForTime(1000);
   const playlists = document.querySelectorAll(
      "ytd-playlist-add-to-option-renderer yt-formatted-string#label"
   );
   const playlist1 = [...playlists].find((x) => x.innerHTML === name1);

   playlist1.click();
};

function initiate() {
   updateThumbnails();

   thumbnails[currentSelection].classList.add("selected-thumbnail");
   window.addEventListener("keyup", (e) => {
      if (e.key === "ArrowRight") {
         updateThumbnails();
         if (currentSelection === thumbnails.length - 1) return;
         document
            .querySelector(".selected-thumbnail")
            .classList.remove("selected-thumbnail");

         currentSelection++;
         thumbnails[currentSelection].classList.add("selected-thumbnail");
         scrollToElement(thumbnails[currentSelection]);
      }
      if (e.key === "ArrowLeft") {
         if (currentSelection === 0) return;
         document
            .querySelector(".selected-thumbnail")
            .classList.remove("selected-thumbnail");

         currentSelection--;
         thumbnails[currentSelection].classList.add("selected-thumbnail");
         scrollToElement(thumbnails[currentSelection]);
      }
      if (e.key === "F2") {
         addToPlayList();
      }
   });
}
function scrollToElement(elm) {
   if (elementInViewport(elm)) return;
   const { top, height } = elm.getBoundingClientRect();
   window.scrollTo({ behavior: "auto", top: top + window.scrollY - 200 });
}

function elementInViewport(el) {
   var top = el.offsetTop;
   var left = el.offsetLeft;
   var width = el.offsetWidth;
   var height = el.offsetHeight;

   while (el.offsetParent) {
      el = el.offsetParent;
      top += el.offsetTop;
      left += el.offsetLeft;
   }

   return (
      top >= window.pageYOffset &&
      left >= window.pageXOffset &&
      top + height <= window.pageYOffset + window.innerHeight &&
      left + width <= window.pageXOffset + window.innerWidth
   );
}

Kindly let me know if this thing is even possible with youtube or not?


问:
Finding the index of a particular element
Var ListName=[5, 6,7,8,9,10,12,1,2,3,4]
Assuming, this list is hidden from me and I was asked to find the index of the element 9 and the next two elements that follows. Please how do I go about it.

I haven't tried anything because I'm new to list


问:
Different threads try to handle the same TCP socket: can this cause instability?
I'm working on a C# Docker application, where I am creating a microservice in order to handle TCP socket communication. This works, but it seems to be very unstable (some packets pass, some not). I have added a log entry, which might explain something (it's about sending a message over a TCP socket):

Source code (shown on multiple lines, but it's a oneliner):

```<code>Debug.WriteLine(
  $"T[{System.Threading.Thread.CurrentThread.ManagedThreadId}],
  {DateTime.UtcNow}: Handle().
  Trying to send [{Message}] to [{ConnectionName}]");
</code>```

Results:

```<code>T[14], 12/14/2022 15:26:08: Handle(). Trying to send [abc] to [XL_Test]
T[19], 12/14/2022 15:26:32: Handle(). Trying to send [abc] to [XL_Test]
</code>```

As you can see, apparently my application always uses another thread to handle the requests. So, I'm left with a very simple question: is multithreaded programming allowed when working with TCP sockets?

For your information: I have already worked with multithreaded applications on TCP sockets before, where one thread was used for regular checking the connection and another for sending the messages, but here I have one thread which regularly checks the connection, while for sending messages, always another thread gets opened.

Edit: I don't know if this is helpful, but the name of the thread, handling the message, is .Net ThreadPool Worker.

Edit2: this is the way this Send() method is called:

```<code>await _mediator.Send(command);
</code>```

... where _mediator is an IMediator from the MediatR library.

The first comment refers to another StackOverflow post which is using locks, but while trying this, I got a compilation error:

```<code>object lockobject = new object();
lock(lockobject)
{
    await _mediator.Send(command);
}
</code>```

The compiler message is CS1996: Cannot await in the body of a lock statement. (Pardon my ignorance, but I'm very new at this)

Body:
I'm working on a C# Docker application, where I am creating a microservice in order to handle TCP socket communication. This works, but it seems to be very unstable (some packets pass, some not). I have added a log entry, which might explain something (it's about sending a message over a TCP socket):

Source code (shown on multiple lines, but it's a oneliner):

Debug.WriteLine(
  $"T[{System.Threading.Thread.CurrentThread.ManagedThreadId}],
  {DateTime.UtcNow}: Handle().
  Trying to send [{Message}] to [{ConnectionName}]");

Results:

T[14], 12/14/2022 15:26:08: Handle(). Trying to send [abc] to [XL_Test]
T[19], 12/14/2022 15:26:32: Handle(). Trying to send [abc] to [XL_Test]

As you can see, apparently my application always uses another thread to handle the requests. So, I'm left with a very simple question: is multithreaded programming allowed when working with TCP sockets?

For your information: I have already worked with multithreaded applications on TCP sockets before, where one thread was used for regular checking the connection and another for sending the messages, but here I have one thread which regularly checks the connection, while for sending messages, always another thread gets opened.

Edit: I don't know if this is helpful, but the name of the thread, handling the message, is .Net ThreadPool Worker.

Edit2: this is the way this Send() method is called:

await _mediator.Send(command);

... where _mediator is an IMediator from the MediatR library.

The first comment refers to another StackOverflow post which is using locks, but while trying this, I got a compilation error:

object lockobject = new object();
lock(lockobject)
{
    await _mediator.Send(command);
}

The compiler message is CS1996: Cannot await in the body of a lock statement. (Pardon my ignorance, but I'm very new at this)


问:
Want to track the uptime and downtime of EC2 Instance on Slack?
I want to get the uptime and downtime alerts of ec2 Instances on slack, I have tried SNS topics creating and Alarm, but would like to get notifications on Slack so can anyone help me with this, can add SNS or any other service with slack or any third party service.
Looking forward to an answer. Thanks in advance.</p>