问:
java.lang.NoClassDefFoundError: Could not initialize class com.blacklight.common.DBManager
I am trying to connect my service file to cloud sql instance. But I am geeting java.lang.NoClassDefFoundError: Could not initialize class com.blacklight.common.DBManager

Here is my class

```<code>package com.blacklight.common;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

@WebListener("Initialize db upon initialization of application context")
public class DBManager implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(DBManager.class);

    private static final Object dataSourceLock = new Object();
    private static DataSource dataSource = null;

    static {
        dataSource = initDataSource();
    }

    private static DataSource initDataSource() {
        synchronized (dataSourceLock) {
            try  {
                String username = "aaaa";
                String password = "bbbb";

                String driverName = "com.mysql.jdbc.Driver";
                String instance = "project-Id:location:database-name";

                if (dataSource == null) {

                    HikariConfig config = new HikariConfig();
                    config.setUsername(username);
                    config.setPassword(password);

                    config.setJdbcUrl("jdbc:mysql:///Features");
                    config.setUsername(username);
                    config.setPassword(password);

                    config.setDriverClassName(driverName);
                    config.setConnectionInitSql("SET NAMES 'utf8mb4'");
                    config.addDataSourceProperty("socketFactory","com.google.cloud.sql.mysql.SocketFactory");
                    config.addDataSourceProperty("cloudSqlInstance", instance);
                    config.addDataSourceProperty("characterEncoding", "UTF-8");
                    config.addDataSourceProperty("useUnicode", "true");
//                    config.addDataSourceProperty("noAccessToProcedureBodies", "true");

                    config.addDataSourceProperty("useSSL", "true");
                    config.addDataSourceProperty("ipTypes", "PRIVATE,PUBLIC");

                    config.setMaximumPoolSize(50);
                    config.setMinimumIdle(5);
                    config.setConnectionTimeout(10000);
                    config.setIdleTimeout(600000);
                    config.setMaxLifetime(1800000);

                    dataSource = new HikariDataSource(config);
                }
                return dataSource;
            } catch (Exception e) {
                System.out.println("Error");
                LOGGER.error(e.getMessage(), e);
            }
            throw new RuntimeException("Couldn't initialize datasource");
        }
    }

    public static Connection getConnection() throws SQLException {
        if (dataSource == null) {
            dataSource = initDataSource();
        }
        return dataSource.getConnection();
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        dataSource = initDataSource();
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        if (dataSource != null) {
            ((HikariDataSource) dataSource).close();
        }
    }

}
</code>```

and my error logs are
com.blacklight.common.DBManager initDataSource: Failed to initialize pool: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.zaxxer.hikari.pool.HikariPool.throwPoolInitializationException(HikariPool.java:596)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:582)
at com.zaxxer.hikari.pool.HikariPool.(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.(HikariDataSource.java:81)
at com.blacklight.common.DBManager.initDataSource(DBManager.java:71)
at com.blacklight.common.DBManager.(DBManager.java:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.eclipse.jetty.server.handler.ContextHandler$StaticContext.createInstance(ContextHandler.java:2902)
at org.eclipse.jetty.servlet.ServletContextHandler$Context.createInstance(ServletContextHandler.java:1299)
at org.eclipse.jetty.server.handler.ContextHandler$StaticContext.createListener(ContextHandler.java:2913)
at org.eclipse.jetty.servlet.ListenerHolder.doStart(ListenerHolder.java:94)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:369)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449)
at com.google.apphosting.runtime.jetty94.AppEngineWebAppContext.startWebapp(AppEngineWebAppContext.java:274)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:916)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524)
at com.google.apphosting.runtime.jetty94.AppEngineWebAppContext.doStart(AppEngineWebAppContext.java:218)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerFactory.doCreateHandler(AppVersionHandlerFactory.java:207)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerFactory.createHandler(AppVersionHandlerFactory.java:125)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:82)
at com.google.apphosting.runtime.jetty94.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:176)
at com.google.apphosting.runtime.RequestRunner.dispatchServletRequest(RequestRunner.java:264)
at com.google.apphosting.runtime.RequestRunner.dispatchRequest(RequestRunner.java:229)
at com.google.apphosting.runtime.RequestRunner.run(RequestRunner.java:194)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:273)
at java.lang.Thread.run(Thread.java:750)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:350)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2416)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2450)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2235)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:818)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:307)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561)
... 31 more
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:293)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
at com.google.cloud.sql.core.CoreSocketFactory.createSslSocket(CoreSocketFactory.java:275)
at com.google.cloud.sql.core.CoreSocketFactory.connect(CoreSocketFactory.java:229)
at com.google.cloud.sql.core.CoreSocketFactory.connect(CoreSocketFactory.java:188)
at com.google.cloud.sql.mysql.SocketFactory.connect(SocketFactory.java:41)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:300)

Body:
I am trying to connect my service file to cloud sql instance. But I am geeting java.lang.NoClassDefFoundError: Could not initialize class com.blacklight.common.DBManager

Here is my class

package com.blacklight.common;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

@WebListener("Initialize db upon initialization of application context")
public class DBManager implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(DBManager.class);

    private static final Object dataSourceLock = new Object();
    private static DataSource dataSource = null;

    static {
        dataSource = initDataSource();
    }

    private static DataSource initDataSource() {
        synchronized (dataSourceLock) {
            try  {
                String username = "aaaa";
                String password = "bbbb";

                String driverName = "com.mysql.jdbc.Driver";
                String instance = "project-Id:location:database-name";

                if (dataSource == null) {

                    HikariConfig config = new HikariConfig();
                    config.setUsername(username);
                    config.setPassword(password);

                    config.setJdbcUrl("jdbc:mysql:///Features");
                    config.setUsername(username);
                    config.setPassword(password);

                    config.setDriverClassName(driverName);
                    config.setConnectionInitSql("SET NAMES 'utf8mb4'");
                    config.addDataSourceProperty("socketFactory","com.google.cloud.sql.mysql.SocketFactory");
                    config.addDataSourceProperty("cloudSqlInstance", instance);
                    config.addDataSourceProperty("characterEncoding", "UTF-8");
                    config.addDataSourceProperty("useUnicode", "true");
//                    config.addDataSourceProperty("noAccessToProcedureBodies", "true");

                    config.addDataSourceProperty("useSSL", "true");
                    config.addDataSourceProperty("ipTypes", "PRIVATE,PUBLIC");

                    config.setMaximumPoolSize(50);
                    config.setMinimumIdle(5);
                    config.setConnectionTimeout(10000);
                    config.setIdleTimeout(600000);
                    config.setMaxLifetime(1800000);

                    dataSource = new HikariDataSource(config);
                }
                return dataSource;
            } catch (Exception e) {
                System.out.println("Error");
                LOGGER.error(e.getMessage(), e);
            }
            throw new RuntimeException("Couldn't initialize datasource");
        }
    }

    public static Connection getConnection() throws SQLException {
        if (dataSource == null) {
            dataSource = initDataSource();
        }
        return dataSource.getConnection();
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        dataSource = initDataSource();
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        if (dataSource != null) {
            ((HikariDataSource) dataSource).close();
        }
    }

}

and my error logs are
com.blacklight.common.DBManager initDataSource: Failed to initialize pool: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.zaxxer.hikari.pool.HikariPool.throwPoolInitializationException(HikariPool.java:596)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:582)
at com.zaxxer.hikari.pool.HikariPool.(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.(HikariDataSource.java:81)
at com.blacklight.common.DBManager.initDataSource(DBManager.java:71)
at com.blacklight.common.DBManager.(DBManager.java:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.eclipse.jetty.server.handler.ContextHandler$StaticContext.createInstance(ContextHandler.java:2902)
at org.eclipse.jetty.servlet.ServletContextHandler$Context.createInstance(ServletContextHandler.java:1299)
at org.eclipse.jetty.server.handler.ContextHandler$StaticContext.createListener(ContextHandler.java:2913)
at org.eclipse.jetty.servlet.ListenerHolder.doStart(ListenerHolder.java:94)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:369)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449)
at com.google.apphosting.runtime.jetty94.AppEngineWebAppContext.startWebapp(AppEngineWebAppContext.java:274)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:916)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524)
at com.google.apphosting.runtime.jetty94.AppEngineWebAppContext.doStart(AppEngineWebAppContext.java:218)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerFactory.doCreateHandler(AppVersionHandlerFactory.java:207)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerFactory.createHandler(AppVersionHandlerFactory.java:125)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:82)
at com.google.apphosting.runtime.jetty94.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:176)
at com.google.apphosting.runtime.RequestRunner.dispatchServletRequest(RequestRunner.java:264)
at com.google.apphosting.runtime.RequestRunner.dispatchRequest(RequestRunner.java:229)
at com.google.apphosting.runtime.RequestRunner.run(RequestRunner.java:194)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:273)
at java.lang.Thread.run(Thread.java:750)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:350)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2416)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2450)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2235)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:818)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:307)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561)
... 31 more
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:293)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
at com.google.cloud.sql.core.CoreSocketFactory.createSslSocket(CoreSocketFactory.java:275)
at com.google.cloud.sql.core.CoreSocketFactory.connect(CoreSocketFactory.java:229)
at com.google.cloud.sql.core.CoreSocketFactory.connect(CoreSocketFactory.java:188)
at com.google.cloud.sql.mysql.SocketFactory.connect(SocketFactory.java:41)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:300)


来源: stackexchange

问:
How can I use the selected prop in a <select> that has a v-model?
Problem:
I have a <select> that uses a v-model to save the selected options into an array. The problem is that I can't use the selected properties on one of the <options> because the v-model ingores that and instead uses the bound JavaScript as it's source of truth.

What I have tried:
I tried looking up my problem on StackOverflow and I have found two questions but they didn't really help nor explain why and how. Here are the posts I have looked at:

using v-model on  makes first option not appear in select - I tried this but nothing changed. My selected appear as selected but it was disabled.

Vue v-model with select input - the accepted answer wants me to define it in data and set it to null but that doesn't work when you take a quick glance at my code.

Code:

```<code><select v-model="payload[index]" type="text">
    <option v-if="entry.system_role !== null" selected :value="entry.system_role">
        {{ entry.system_role }}
    </option>
    <option v-for="role in entry.roles" :key="entry.id" :value="role">
        {{ role }}
    </option>
</select>
</code>```

That is the section with the select and as you can see the v-model is an array which I simply can't set to null. index is from a higher up v-for that renders the amount of <select>.
I tried setting selected to disabled and :value="entry.system_role" to value="" and leaving it empty (but I need the value of this option). Is there anything I can do to make it work? Maybe with a computed or method?

ContentLicense: CC BY-SA 4.0

Body:
Problem:
I have a <select> that uses a v-model to save the selected options into an array. The problem is that I can't use the selected properties on one of the <options> because the v-model ingores that and instead uses the bound JavaScript as it's source of truth.

What I have tried:
I tried looking up my problem on StackOverflow and I have found two questions but they didn't really help nor explain why and how. Here are the posts I have looked at:

using v-model on  makes first option not appear in select - I tried this but nothing changed. My selected appear as selected but it was disabled.

Vue v-model with select input - the accepted answer wants me to define it in data and set it to null but that doesn't work when you take a quick glance at my code.

Code:

<select v-model="payload[index]" type="text">
    <option v-if="entry.system_role !== null" selected :value="entry.system_role">
        {{ entry.system_role }}
    </option>
    <option v-for="role in entry.roles" :key="entry.id" :value="role">
        {{ role }}
    </option>
</select>

That is the section with the select and as you can see the v-model is an array which I simply can't set to null. index is from a higher up v-for that renders the amount of <select>.
I tried setting selected to disabled and :value="entry.system_role" to value="" and leaving it empty (but I need the value of this option). Is there anything I can do to make it work? Maybe with a computed or method?


问:
Unable to convert dataset column to string
I have a dataset with an 'id' column that needs to be converted to String. I have tried all the available options to convert it to String, but it still comes out Object. (I can't provide a sample DataFrame, as my dataset is quite big and the problem goes away in the sample DataFrame.)

I have tried all the following commands:

```<code>df['id'] = df['id'].astype(str)
df['id'] = df['id'].values.astype(str)
df['id'] = df['id'].apply(str)
df['id'] = df['id'].map(str)
df['id'] = df['id'].apply(lambda x: str(x))
pd.Series(df['id'], dtype = "string")
</code>```

I would appreciate any helpful leads.

Body:
I have a dataset with an 'id' column that needs to be converted to String. I have tried all the available options to convert it to String, but it still comes out Object. (I can't provide a sample DataFrame, as my dataset is quite big and the problem goes away in the sample DataFrame.)

I have tried all the following commands:

df['id'] = df['id'].astype(str)
df['id'] = df['id'].values.astype(str)
df['id'] = df['id'].apply(str)
df['id'] = df['id'].map(str)
df['id'] = df['id'].apply(lambda x: str(x))
pd.Series(df['id'], dtype = "string")

I would appreciate any helpful leads.


问:
RandomizedSearchCV Takes Long Time to Finish
I'm trying to do hyperparameter tuning using RandomizedSearchCV() where I have 6244 rows of data to be processed. At first, I used GridSearchCV() with 11 different estimators but it took so long and I gave up waiting for the result then changed GridSearchCV() into RandomizedSearchCV() and I also reduced the estimators from 11 to 6. However it still takes too long to get the results. Is there any other way to reduce the processing time?

Anyway besides using MLPClassifier() I also tried to run the same code on GaussianNB() and KNeighborsClassifiers() but those base_estimators only need approximately 30 seconds to run, when MLPClassifier() needs more than 2 hours to run and I even haven't get the result.

```<code>#Tuning bagging here

distributions = dict(n_estimators = [10,20,50,100,150,200])
bagging_nb = BaggingClassifier(base_estimator=MLPClassifier(max_iter=10000), n_jobs=-1)
kfold = KFold(n_splits=fold, random_state=seed, shuffle=True)
grid = RandomizedSearchCV(estimator=bagging_nb, param_distributions=distributions, scoring=scoring, cv=kfold)
grid_result = grid.fit(X_train, y_train)
print('Best %f using %s' % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip (means, stds, params):
    print("%f (%f) with %r" % (mean, stdev, param))
</code>```

Body:
I'm trying to do hyperparameter tuning using RandomizedSearchCV() where I have 6244 rows of data to be processed. At first, I used GridSearchCV() with 11 different estimators but it took so long and I gave up waiting for the result then changed GridSearchCV() into RandomizedSearchCV() and I also reduced the estimators from 11 to 6. However it still takes too long to get the results. Is there any other way to reduce the processing time?

Anyway besides using MLPClassifier() I also tried to run the same code on GaussianNB() and KNeighborsClassifiers() but those base_estimators only need approximately 30 seconds to run, when MLPClassifier() needs more than 2 hours to run and I even haven't get the result.

#Tuning bagging here

distributions = dict(n_estimators = [10,20,50,100,150,200])
bagging_nb = BaggingClassifier(base_estimator=MLPClassifier(max_iter=10000), n_jobs=-1)
kfold = KFold(n_splits=fold, random_state=seed, shuffle=True)
grid = RandomizedSearchCV(estimator=bagging_nb, param_distributions=distributions, scoring=scoring, cv=kfold)
grid_result = grid.fit(X_train, y_train)
print('Best %f using %s' % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip (means, stds, params):
    print("%f (%f) with %r" % (mean, stdev, param))


问:
can we get Azure mysql flexible server replication lag in seconds metric through API ? I am not sure if Azure provides an API to get that metric data
Is there an API to get mysql flexible server read replication lag in seconds metric data ?. We have an implementation in AWS where we are using the AWS api to get replication lag data to disable/enable  mysql replica and we want to do the same in Azure. I have explored the Azure API documentation but was not able to get a clear solution if this is possible.

Please let me know if that is possible.


问:
pip3 + is not a supported wheel on this platform
We tried to install different kind of lxml-python modules on rhel 7.X but without success as the following

```<code>pip3 install --no-index --find-links /tmp lxml-4.9.2-cp39-cp39-musllinux_1_1_x86_64.whl
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
ERROR: lxml-4.9.2-cp39-cp39-musllinux_1_1_x86_64.whl is not a supported wheel on this platform.

pip3 install --no-index --find-links /tmp lxml-4.9.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
ERROR: lxml-4.9.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl is not a supported wheel on this platform.

pip3 install --no-index --find-links /tmp lxml-4.9.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
ERROR: lxml-4.9.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl is not a supported wheel on this platform.
</code>```

pip3 version is

```<code>pip3 --version
pip 19.3.1 from /etc/rh/rh-python38/root/usr/lib/python3.8/site-packages/pip (python 3.8)
</code>```

rhel release is:

```<code>more /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)

uname -r
3.10.0-1160.el7.x86_64

python3 --version
Python 3.8.0
</code>```

Any idea how to solve the problem about  “ is not a supported wheel on this platform “

Note - the machine Linux RHEL 7.X is without external network so the modules installation are off line

Body:
We tried to install different kind of lxml-python modules on rhel 7.X but without success as the following

pip3 install --no-index --find-links /tmp lxml-4.9.2-cp39-cp39-musllinux_1_1_x86_64.whl
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
ERROR: lxml-4.9.2-cp39-cp39-musllinux_1_1_x86_64.whl is not a supported wheel on this platform.

pip3 install --no-index --find-links /tmp lxml-4.9.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
ERROR: lxml-4.9.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl is not a supported wheel on this platform.

pip3 install --no-index --find-links /tmp lxml-4.9.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
ERROR: lxml-4.9.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl is not a supported wheel on this platform.

pip3 version is

pip3 --version
pip 19.3.1 from /etc/rh/rh-python38/root/usr/lib/python3.8/site-packages/pip (python 3.8)

rhel release is:

more /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)

uname -r
3.10.0-1160.el7.x86_64

python3 --version
Python 3.8.0

Any idea how to solve the problem about  “ is not a supported wheel on this platform “

Note - the machine Linux RHEL 7.X is without external network so the modules installation are off line


问:
How to reinstall Elasticsearch
I have installed Elasticsearch.
How can I reinstall it so that I get a new and clean elastic, a new password, fingerprint and token for kibana?
I'm asking because I use the same bat file for installing and starting. I tried deleting the file under Appdata, but it makes no difference.

Title: How to reinstall Elasticsearch


问:
Coefplot confidence intervals by colour
I want to create a coefficient plot where each confidence intervals shows three significance levels: 99, 95, 90. Moreover, I would like the confidence interval line to vary by colour depending on the significance level it is showing. My code is as follows:

```<code>sysuse auto
eststo reg_1: reg price mpg
eststo reg_2: reg price mpg headroom
coefplot reg_1 reg_2, keep(mpg) levels(99 95 90)
</code>```

I tried to do this by adding the following mcolor and ciopts:

```<code>coefplot (reg_1, mcolor(ebblue) ciopts(color(ebblue))) (reg_2, mcolor(ebblue) ciopts(color(ebblue))), keep(mpg) levels(99 95 90)
</code>```

but it seems only the 99% confidence interval is affected. How can I tell Stata which confidence interval should be which colour?

Title: Coefplot confidence intervals by colour

Body:
I want to create a coefficient plot where each confidence intervals shows three significance levels: 99, 95, 90. Moreover, I would like the confidence interval line to vary by colour depending on the significance level it is showing. My code is as follows:

sysuse auto
eststo reg_1: reg price mpg
eststo reg_2: reg price mpg headroom
coefplot reg_1 reg_2, keep(mpg) levels(99 95 90)

I tried to do this by adding the following mcolor and ciopts:

coefplot (reg_1, mcolor(ebblue) ciopts(color(ebblue))) (reg_2, mcolor(ebblue) ciopts(color(ebblue))), keep(mpg) levels(99 95 90)

but it seems only the 99% confidence interval is affected. How can I tell Stata which confidence interval should be which colour?


问:
Finding out the size of an Asset file in Android Kotlin
Is there a way to find out the size of an asset file in kotlin android? I am wanting to know the size of a group of files so as I can then confirm the device has enough free space to copy the files to internal memory.

I have searched on Google and Stack Overflow, however I have not found anything that was able to assist

UPDATE:

I have figured out two possible solutions:

context.assets.open("FILE").available()

context.assets.open("FILE").readBytes().size

Which is a better way and more efficient and accurate? I have read that available() is not completely accurate. Is this true? Link Here. If this is truly the case, does that mean reading the bytes from the inputstream (as shown in case number 2) is the best way?


问:
On form submit trigger to assign numbers to records
Updated:

Please see the sample google spreadsheet link below
https://docs.google.com/spreadsheets/d/1YLM8ydXWalvCzsyMkQ20-dgAPBFeVKKUtHp_53KybbY/edit?usp=sharing

Please take a look at
Row 1514,1767,1971,2619,2654

I am trying to use a Google Form to record a membership database.
I want to assign a membership number to each submitted record, starting from 1 then 2 then 3 etc...
It works well but I got occasional missing numbers and I got something like this

Case 1 - completely missed assignment

Members E ---1

Members F ---2

Members G ---

Members H ---3

Or

Case 2 - partly missed assignment

Members A ---1

Members B ---2

Members C ---

Members D ---4

Member C got an "empty" membership number. It seems like the following code failed to run

```<code>dbs.getRange(dbs.getLastRow(),7).setValue(lastMembershipID)
</code>```

But membershipIdCell.setValue(membershipCountID +1) will still run so the membership number is added by 1 although it was not assigned to member C. How can I solve it? Now I will just manually put "3" on the member C membership number cell. Below is the full code and with trigger on form submit. Thank you!

```<code>const ws = SpreadsheetApp.openById("xxxxxxxxxxxx");
const ss = ws.getSheetByName("Option")
const dbs = ws.getSheetByName("Membership DB")

    function assignMembershipID (){
      var membershipIdCell = ss.getRange("C2")
      var membershipCountID = membershipIdCell.getValue()

      var fullMembershipIdCell = ss.getRange("D2")
      var lastMembershipID = fullMembershipIdCell.getValue()
      dbs.getRange(dbs.getLastRow(),7).setValue(lastMembershipID)

      membershipIdCell.setValue(membershipCountID +1)

    }
</code>```

Body:
Updated:

Please see the sample google spreadsheet link below
https://docs.google.com/spreadsheets/d/1YLM8ydXWalvCzsyMkQ20-dgAPBFeVKKUtHp_53KybbY/edit?usp=sharing

Please take a look at
Row 1514,1767,1971,2619,2654

I am trying to use a Google Form to record a membership database.
I want to assign a membership number to each submitted record, starting from 1 then 2 then 3 etc...
It works well but I got occasional missing numbers and I got something like this

Case 1 - completely missed assignment

Members E ---1

Members F ---2

Members G ---

Members H ---3

Or

Case 2 - partly missed assignment

Members A ---1

Members B ---2

Members C ---

Members D ---4

Member C got an "empty" membership number. It seems like the following code failed to run

dbs.getRange(dbs.getLastRow(),7).setValue(lastMembershipID)

But membershipIdCell.setValue(membershipCountID +1) will still run so the membership number is added by 1 although it was not assigned to member C. How can I solve it? Now I will just manually put "3" on the member C membership number cell. Below is the full code and with trigger on form submit. Thank you!

const ws = SpreadsheetApp.openById("xxxxxxxxxxxx");
const ss = ws.getSheetByName("Option")
const dbs = ws.getSheetByName("Membership DB")

    function assignMembershipID (){
      var membershipIdCell = ss.getRange("C2")
      var membershipCountID = membershipIdCell.getValue()

      var fullMembershipIdCell = ss.getRange("D2")
      var lastMembershipID = fullMembershipIdCell.getValue()
      dbs.getRange(dbs.getLastRow(),7).setValue(lastMembershipID)

      membershipIdCell.setValue(membershipCountID +1)

    }


问:
socat is missing commands for haproxy on ubuntu 20.04
I have installed haproxy 2.6.6, socat 1.7.4.1 and have a working load balancer for Exchange. I want to be able to turn off a node for maintenance and have unsuccessfully tried to use socat to do this.

In my haproxy.cfg global section I have:

```<code>stats socket /run/haproxy-master.sock mode 660 level admin expose-fd listeners
stats timeout 30s
user haproxy
group haproxy
daemon
</code>```

When I am using this command

```<code>echo "disable server exch01" | sudo socat stdio unix-connect:/run/haproxy-master.sock
</code>```

I get

```<code>unknown command, but maybe one of the following ones is a better match:
show cli level
show cli sockets
show proc
show version
help
prompt
quit
</code>```

By sending show cli level it returns admin

If I sudo to root I get a few more commands, like

```<code>@master
@!
@
operator
reload
user
prompt
</code>```

But I am missing disable server, show info, etc

So it looks like it is a permission thing, but it doesnt matter whether I am root or admin. It can also be some faulty initiation of stats socket in haproxy?

I have tried different configurations in haproxy.cfg like

```<code>stats socket /run/haproxy-master.sock mode 660 level admin expose-fd listeners
stats socket /run/haproxy-master.sock level admin expose-fd listeners
stats socket /run/haproxy-master.sock mode 660 level admin #expose-fd listeners

</code>```

I have also tried to change permissions on the haproxy-master.sock file and it is currently 777

I am using bash

Body:
I have installed haproxy 2.6.6, socat 1.7.4.1 and have a working load balancer for Exchange. I want to be able to turn off a node for maintenance and have unsuccessfully tried to use socat to do this.

In my haproxy.cfg global section I have:

stats socket /run/haproxy-master.sock mode 660 level admin expose-fd listeners
stats timeout 30s
user haproxy
group haproxy
daemon

When I am using this command

echo "disable server exch01" | sudo socat stdio unix-connect:/run/haproxy-master.sock

I get

unknown command, but maybe one of the following ones is a better match:
show cli level
show cli sockets
show proc
show version
help
prompt
quit

By sending show cli level it returns admin

If I sudo to root I get a few more commands, like

@master
@!
@
operator
reload
user
prompt

But I am missing disable server, show info, etc

So it looks like it is a permission thing, but it doesnt matter whether I am root or admin. It can also be some faulty initiation of stats socket in haproxy?

I have tried different configurations in haproxy.cfg like

stats socket /run/haproxy-master.sock mode 660 level admin expose-fd listeners
stats socket /run/haproxy-master.sock level admin expose-fd listeners
stats socket /run/haproxy-master.sock mode 660 level admin #expose-fd listeners

I have also tried to change permissions on the haproxy-master.sock file and it is currently 777

I am using bash


问:
How get query execution return code to handle notification in NodeJS?
I want to handle query (insert, update, delete) result and mongodb server error when i query database and show it in toast notification in Front-End. I seen this page in net, but i can't find way to use this return codes to handle notifications in NodeJS.

For example I use this code in NodeJS to insert data to mongodb:

```<code>MongoClient.connect(url, (err, db) => {
    if (err) throw err;
    const dbo = db.db("platform");
    dbo.collection("users").insertOne(user, (err, res) => {
      ...
    });
});
</code>```

How can i receive this codes in my code?

Body:
I want to handle query (insert, update, delete) result and mongodb server error when i query database and show it in toast notification in Front-End. I seen this page in net, but i can't find way to use this return codes to handle notifications in NodeJS.

For example I use this code in NodeJS to insert data to mongodb:

MongoClient.connect(url, (err, db) => {
    if (err) throw err;
    const dbo = db.db("platform");
    dbo.collection("users").insertOne(user, (err, res) => {
      ...
    });
});

How can i receive this codes in my code?


问:
Windows10: Installing pyenv-managed python versions under custom path using localadmin-user
I am working on a Windows10 machine which is restricted by centrally managed guidelines and rules. For example, it is not possible for a normal user to run programs residing in other directories than C:\Program Files... which prevents normal users from installing software on our Windows machines. I do have a localadmin user allowing me to run programs residing in other directories and install software. With the help of the localadmin user I managed to install pyenv-win following the instructions given at official PyPi documentation. As it seems, pyenv is running well, at least I can call pyenv in the PowerShell and it reacts like expected.

Now, I want to install Python versions using pyenv for my normal user (as I do not want to work/program as localadmin). However, if I try pyenv install <version> as a normal user, I get an error message that the execution of pyenv-install.vbs is blocked due to group rules. I can install Python versions using the localadmin, but the Python installed in this way ends up in the localadmin's directory ...\localadmin user directory\.pyenv\pyenv-win\install-chache\python-...exe which is not accessible for normal users.

Question is, how can I make pyenv Python environments accessible to normal users? One workaround seems to me that I use the localadmin user and perform pyenv install pointing to some custom directory - e.g. pointing to my normal user's .pyenv\ directory. Is that possible? What would be the command for this?


问:
Will spring jms listener automatically start listening when it is declared though spring-*.xml and MessageDispatcherServlet is the entry point?
I am the code in a legacy project where a jms listener is declared in the following way:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jms="http://www.springframework.org/schema/jms"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd">

    <jms:listener-container connection-factory="queueConnectionFactory" concurrency="1" acknowledge="transacted"
                            destination-resolver="jndiDestinationResolver" message-converter="envelopConverter">
        <jms:listener destination="xyz/jms/SomeQueue" ref="processor"
                      method="processElement" id="messageListener"/>
    </jms:listener-container>

</beans>

```
<p>and inside <code>web.xml</code> spring is registered via <code>MessageDispatcherServlet</code>:</p>
<pre class="lang-xml prettyprint-override"><code>    <servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</code>```

I have added a some logs on @PostConstruct of the listener class but I never see them.

Will the listener be constructed and used at some point or this will never happen with the specific setup?

Spring versions used:

spring: 4.3.27.RELEASE

spring-ws: 3.0.9.RELEASE

Body:
I am the code in a legacy project where a jms listener is declared in the following way:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jms="http://www.springframework.org/schema/jms"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd">

    <jms:listener-container connection-factory="queueConnectionFactory" concurrency="1" acknowledge="transacted"
                            destination-resolver="jndiDestinationResolver" message-converter="envelopConverter">
        <jms:listener destination="xyz/jms/SomeQueue" ref="processor"
                      method="processElement" id="messageListener"/>
    </jms:listener-container>

</beans>

and inside web.xml spring is registered via MessageDispatcherServlet:

    <servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

I have added a some logs on @PostConstruct of the listener class but I never see them.

Will the listener be constructed and used at some point or this will never happen with the specific setup?

Spring versions used:

spring: 4.3.27.RELEASE

spring-ws: 3.0.9.RELEASE


问:
pyspark filter get java.lang.UnsupportedOperationException: Cannot evaluate expression after using pandas udf
The code:

```<code>    spark = SparkBase().spark

    data = [(1, 102193, 10, "2021-01-22", "2021-01-22 10:44:31"),
            (1, 103525, 20, "2021-01-22", "2021-01-22 10:44:32"),
            (3, 103685, 30, "2021-01-22", "2021-01-22 10:44:31"),
            (2, 102193, 40, "2021-01-22", "2021-01-22 10:43:41"),
            (2, 103525, 50, "2021-01-22", "2021-01-22 10:43:42"),
            (2, 103685, 60, "2021-01-22", "2021-01-22 10:43:43"),
            ]
    df = spark.createDataFrame(data, ["id", "uid", "profit", "start_date", "start_time"])

    @F.pandas_udf("int", F.PandasUDFType.GROUPED_AGG)
    def profit_in_30_hand(profit, start_time):
        d = pd.concat([profit, start_time], axis=1)
        d = d.rename(columns={"_0": "profit", "_1": "start_time"})
        d = d.sort_values("start_time", ascending=False)
        profits = d.profit.iloc[:3].sum()
        return int(profits)

    df = df.groupby(["id", "start_date"]).agg(profit_in_30_hand(df.profit, df.start_time).alias("profits"))
    df.show()

    df.where("profits > 30").show() # this get wrong
</code>```

After using pandas udf, df.where("profits > 30").show() get exceptions:

```<code>py4j.protocol.Py4JJavaError: An error occurred while calling o146.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
Exchange hashpartitioning(id#6L, start_date#9, 200)
+- *(1) Project [id#6L, profit#8L, start_date#9, start_time#10]
   +- *(1) Filter (profit_in_30_hand(profit#8L, start_time#10) > 30)
      +- Scan ExistingRDD[id#6L,uid#7L,profit#8L,start_date#9,start_time#10]

    at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:56)
    at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec.doExecute(ShuffleExchangeExec.scala:119)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.InputAdapter.inputRDDs(WholeStageCodegenExec.scala:379)
    at org.apache.spark.sql.execution.SortExec.inputRDDs(SortExec.scala:121)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:615)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.python.AggregateInPandasExec.doExecute(AggregateInPandasExec.scala:80)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:247)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:339)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collectFromPlan(Dataset.scala:3383)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset$$anonfun$53.apply(Dataset.scala:3364)
    at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:78)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
    at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3363)
    at org.apache.spark.sql.Dataset.head(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset.take(Dataset.scala:2758)
    at org.apache.spark.sql.Dataset.getRows(Dataset.scala:254)
    at org.apache.spark.sql.Dataset.showString(Dataset.scala:291)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.UnsupportedOperationException: Cannot evaluate expression: profit_in_30_hand(input[2, bigint, true], input[4, string, true])
    at org.apache.spark.sql.catalyst.expressions.Unevaluable$class.doGenCode(Expression.scala:261)
    at org.apache.spark.sql.catalyst.expressions.PythonUDF.doGenCode(PythonUDF.scala:50)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:108)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:105)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.sql.catalyst.expressions.Expression.genCode(Expression.scala:105)
    at org.apache.spark.sql.catalyst.expressions.BinaryExpression.nullSafeCodeGen(Expression.scala:525)
    at org.apache.spark.sql.catalyst.expressions.BinaryExpression.defineCodeGen(Expression.scala:508)
    at org.apache.spark.sql.catalyst.expressions.BinaryComparison.doGenCode(predicates.scala:566)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:108)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:105)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.sql.catalyst.expressions.Expression.genCode(Expression.scala:105)
    at org.apache.spark.sql.execution.FilterExec.org$apache$spark$sql$execution$FilterExec$$genPredicate$1(basicPhysicalOperators.scala:139)
    at org.apache.spark.sql.execution.FilterExec$$anonfun$13.apply(basicPhysicalOperators.scala:179)
    at org.apache.spark.sql.execution.FilterExec$$anonfun$13.apply(basicPhysicalOperators.scala:163)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.immutable.List.map(List.scala:296)
    at org.apache.spark.sql.execution.FilterExec.doConsume(basicPhysicalOperators.scala:163)
    at org.apache.spark.sql.execution.CodegenSupport$class.consume(WholeStageCodegenExec.scala:189)
    at org.apache.spark.sql.execution.InputAdapter.consume(WholeStageCodegenExec.scala:362)
    at org.apache.spark.sql.execution.InputAdapter.doProduce(WholeStageCodegenExec.scala:391)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:90)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.CodegenSupport$class.produce(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.InputAdapter.produce(WholeStageCodegenExec.scala:362)
    at org.apache.spark.sql.execution.FilterExec.doProduce(basicPhysicalOperators.scala:125)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:90)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.CodegenSupport$class.produce(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.FilterExec.produce(basicPhysicalOperators.scala:85)
    at org.apache.spark.sql.execution.ProjectExec.doProduce(basicPhysicalOperators.scala:45)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:90)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.CodegenSupport$class.produce(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.ProjectExec.produce(basicPhysicalOperators.scala:35)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doCodeGen(WholeStageCodegenExec.scala:532)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:586)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec.prepareShuffleDependency(ShuffleExchangeExec.scala:92)
    at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$$anonfun$doExecute$1.apply(ShuffleExchangeExec.scala:128)
    at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$$anonfun$doExecute$1.apply(ShuffleExchangeExec.scala:119)
    at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:52)
    ... 49 more

</code>```

spark version: 2.4.0

requirements:

```<code>pandas==1.3.5
pyarrow==0.13.0
pyspark==2.4.0
</code>```

Body:
The code:

    spark = SparkBase().spark

    data = [(1, 102193, 10, "2021-01-22", "2021-01-22 10:44:31"),
            (1, 103525, 20, "2021-01-22", "2021-01-22 10:44:32"),
            (3, 103685, 30, "2021-01-22", "2021-01-22 10:44:31"),
            (2, 102193, 40, "2021-01-22", "2021-01-22 10:43:41"),
            (2, 103525, 50, "2021-01-22", "2021-01-22 10:43:42"),
            (2, 103685, 60, "2021-01-22", "2021-01-22 10:43:43"),
            ]
    df = spark.createDataFrame(data, ["id", "uid", "profit", "start_date", "start_time"])

    @F.pandas_udf("int", F.PandasUDFType.GROUPED_AGG)
    def profit_in_30_hand(profit, start_time):
        d = pd.concat([profit, start_time], axis=1)
        d = d.rename(columns={"_0": "profit", "_1": "start_time"})
        d = d.sort_values("start_time", ascending=False)
        profits = d.profit.iloc[:3].sum()
        return int(profits)

    df = df.groupby(["id", "start_date"]).agg(profit_in_30_hand(df.profit, df.start_time).alias("profits"))
    df.show()

    df.where("profits > 30").show() # this get wrong

After using pandas udf, df.where("profits > 30").show() get exceptions:

py4j.protocol.Py4JJavaError: An error occurred while calling o146.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
Exchange hashpartitioning(id#6L, start_date#9, 200)
+- *(1) Project [id#6L, profit#8L, start_date#9, start_time#10]
   +- *(1) Filter (profit_in_30_hand(profit#8L, start_time#10) > 30)
      +- Scan ExistingRDD[id#6L,uid#7L,profit#8L,start_date#9,start_time#10]

    at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:56)
    at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec.doExecute(ShuffleExchangeExec.scala:119)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.InputAdapter.inputRDDs(WholeStageCodegenExec.scala:379)
    at org.apache.spark.sql.execution.SortExec.inputRDDs(SortExec.scala:121)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:615)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.python.AggregateInPandasExec.doExecute(AggregateInPandasExec.scala:80)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:247)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:339)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collectFromPlan(Dataset.scala:3383)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset$$anonfun$53.apply(Dataset.scala:3364)
    at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:78)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
    at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3363)
    at org.apache.spark.sql.Dataset.head(Dataset.scala:2544)
    at org.apache.spark.sql.Dataset.take(Dataset.scala:2758)
    at org.apache.spark.sql.Dataset.getRows(Dataset.scala:254)
    at org.apache.spark.sql.Dataset.showString(Dataset.scala:291)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.UnsupportedOperationException: Cannot evaluate expression: profit_in_30_hand(input[2, bigint, true], input[4, string, true])
    at org.apache.spark.sql.catalyst.expressions.Unevaluable$class.doGenCode(Expression.scala:261)
    at org.apache.spark.sql.catalyst.expressions.PythonUDF.doGenCode(PythonUDF.scala:50)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:108)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:105)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.sql.catalyst.expressions.Expression.genCode(Expression.scala:105)
    at org.apache.spark.sql.catalyst.expressions.BinaryExpression.nullSafeCodeGen(Expression.scala:525)
    at org.apache.spark.sql.catalyst.expressions.BinaryExpression.defineCodeGen(Expression.scala:508)
    at org.apache.spark.sql.catalyst.expressions.BinaryComparison.doGenCode(predicates.scala:566)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:108)
    at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:105)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.sql.catalyst.expressions.Expression.genCode(Expression.scala:105)
    at org.apache.spark.sql.execution.FilterExec.org$apache$spark$sql$execution$FilterExec$$genPredicate$1(basicPhysicalOperators.scala:139)
    at org.apache.spark.sql.execution.FilterExec$$anonfun$13.apply(basicPhysicalOperators.scala:179)
    at org.apache.spark.sql.execution.FilterExec$$anonfun$13.apply(basicPhysicalOperators.scala:163)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.immutable.List.map(List.scala:296)
    at org.apache.spark.sql.execution.FilterExec.doConsume(basicPhysicalOperators.scala:163)
    at org.apache.spark.sql.execution.CodegenSupport$class.consume(WholeStageCodegenExec.scala:189)
    at org.apache.spark.sql.execution.InputAdapter.consume(WholeStageCodegenExec.scala:362)
    at org.apache.spark.sql.execution.InputAdapter.doProduce(WholeStageCodegenExec.scala:391)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:90)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.CodegenSupport$class.produce(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.InputAdapter.produce(WholeStageCodegenExec.scala:362)
    at org.apache.spark.sql.execution.FilterExec.doProduce(basicPhysicalOperators.scala:125)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:90)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.CodegenSupport$class.produce(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.FilterExec.produce(basicPhysicalOperators.scala:85)
    at org.apache.spark.sql.execution.ProjectExec.doProduce(basicPhysicalOperators.scala:45)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:90)
    at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.CodegenSupport$class.produce(WholeStageCodegenExec.scala:85)
    at org.apache.spark.sql.execution.ProjectExec.produce(basicPhysicalOperators.scala:35)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doCodeGen(WholeStageCodegenExec.scala:532)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:586)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec.prepareShuffleDependency(ShuffleExchangeExec.scala:92)
    at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$$anonfun$doExecute$1.apply(ShuffleExchangeExec.scala:128)
    at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$$anonfun$doExecute$1.apply(ShuffleExchangeExec.scala:119)
    at org.apache.spark.sql.catalyst.errors.package$.attachTree(package.scala:52)
    ... 49 more

spark version: 2.4.0

requirements:

pandas==1.3.5
pyarrow==0.13.0
pyspark==2.4.0


问:
Read env variable from logback.xml file in order to enable json encoder on Spring boot
I am trying to enable a json encoder on my logback.xml file which will allow me to log in json based on an environment variable called JSON_LOGGING.
If JSON_LOGGING=true then I would like to activate the json encoder, other wise I would like it to be deactivated. I am just not sure how to read exactly the env variable on my logback file. This is what I have so far:

```<code> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  <if condition= MY JSON_LOGGING VARIABLE IS TRUE>
    <then>
      <encoder class="net.logstash.logback.encoder.LogstashEncoder">
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
      </encoder>
    </then>
  <else>
     <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </else>
</appender>
</code>```

Would anyone know how I could read the JSON_LOGGING env var value on my logback file? I am kinda clueless..

Body:
I am trying to enable a json encoder on my logback.xml file which will allow me to log in json based on an environment variable called JSON_LOGGING.
If JSON_LOGGING=true then I would like to activate the json encoder, other wise I would like it to be deactivated. I am just not sure how to read exactly the env variable on my logback file. This is what I have so far:

 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  <if condition= MY JSON_LOGGING VARIABLE IS TRUE>
    <then>
      <encoder class="net.logstash.logback.encoder.LogstashEncoder">
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
      </encoder>
    </then>
  <else>
     <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </else>
</appender>

Would anyone know how I could read the JSON_LOGGING env var value on my logback file? I am kinda clueless..


问:
Fullstack project monorepo - development with multiple docker containers
I have this folder structure:

```<code>client/
  Dockerfile
  src/

server/
  Dockerfile
  src/

packages/
  shared/
    enums.ts
</code>```

As you can see there are two docker containers: for client and for server

I import some enums from packages/shared/enums.ts both in client/src and server/src folders. How to make it changes in enum.ts affected on client/src and server/src?

Now I have a bad solution. I create volume for packages/shared both in client and server containers. Think it shouldn't work like this, also this solution prevents to setup dev containers env in vscode.

Body:
I have this folder structure:

client/
  Dockerfile
  src/

server/
  Dockerfile
  src/

packages/
  shared/
    enums.ts

As you can see there are two docker containers: for client and for server

I import some enums from packages/shared/enums.ts both in client/src and server/src folders. How to make it changes in enum.ts affected on client/src and server/src?

Now I have a bad solution. I create volume for packages/shared both in client and server containers. Think it shouldn't work like this, also this solution prevents to setup dev containers env in vscode.


问:
How to connect to a mysql database on aws lightsail server from mysql work bench on a windows 10 from Nigeria

I'm trying to connect to an AWS lightsail server using mysql workbench and it's not working, I also tried connecting with a vpn service  to make this connection work and still it doesn't work but when someone outside Nigeria (US precisely) tries to connect using the same credentials for this aws lightsail server it connects but refuses me to connect, my IP addresss has been added to the security rules on the aws server end but I still can't connect. I thought maybe there's a geographic restriction but I could be wrong.


问:
Im using laravel 9,42 but when i press the store infomation which pushes the data to the db the system logs me out
im using laravel 9.42 but the problem im facing is whwn i click the button that is supposed to push data to the database its loging me out of the system ive create creating new routes for the button and adding the action of the button inside the form but its not working

My categoryController

```<code><?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories =Category::all();
        return view('admin.categories.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.categories.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CategoryStoreRequest $request)
    {
        $image = $request->file('image')->store('public/categories');

        Category::create([

            'name' => $request->name,
            'description' => $request->description,
            'image' => $image

        ]);

        return to_route('admin.categories.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

</code>```

My CategoryStoreRequest

```<code><?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\Category;

class CategoryStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'name' =>['required'],
            'image' =>['required','image'],
            'description' =>['required'],

        ];
    }
}

</code>```

My create.blade.php

```<code><x-admin-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">

            <div class=" flex justify-items-end m-2 p-2">
                <a href="{{ route('admin.categories.index') }}" class="px-4 py-2 bg-indigo-500 hover:bg-indigo-600 rounded-lg text-white">Categories Index</a>
            </div>

            <div class="m-2 p-2 bg-slate-100 rounded">
                <div class="space-y-8 divide-y divide-gray-200 w-1/2 mt-10">
                    <form  method="POST" action={{ route('admin.categories.store') }} enctype="multipart/form-data">
                      @csrf

                      <div class="sm:col-span-6">
                        <label for="name" class="block text-sm font-medium text-gray-700"> Name </label>
                        <div class="mt-1">
                          <input type="text" id="name"  name="name"
                          class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
                        </div>
                      </div>
                      <div class="sm:col-span-6">
                        <label for="image" class="block text-sm font-medium text-gray-700"> Image </label>
                        <div class="mt-1">
                          <input type="file" id="image" " name="image" class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
                        </div>
                      </div>
                      <div class="sm:col-span-6 pt-5">
                        <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
                        <div class="mt-1">
                          <textarea id="description" rows="3" name="description"
                          class="shadow-sm focus:ring-indigo-500 appearance-none bg-white border  py-2 px-3 text-base leading-normal transition duration-150 ease-in-out focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"></textarea>
                        </div>
                      </div>

                      <div class="mt-6 p-4">

                        <button type="submit"
                        class="py-2 px-4  bg-indigo-500 hover:bg-indigo-700 rounded-lg text-white">
                            Stores
                        </button>

                      </div>

                    </form>
                  </div>

            </div>

        </div>
    </div>
</x-admin-layout>

</code>```

and my routes

```<code><?php

use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\AdminController;

//My controllers

use App\Http\Controllers\Admin\MenuController;
use App\Http\Controllers\Admin\HouseController;
use App\Http\Controllers\Admin\RentingController;
use App\Http\Controllers\Admin\CategoryController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

    Route::middleware(['auth', 'admin'])->name('admin.')->prefix('admin')->group(function () {

        Route::get('/', [AdminController::class, 'index'])->name('index');
        Route::resource('/categories', CategoryController::class);
        Route::resource('/menus', MenuController::class);
        Route::resource('/houses', HouseController::class);
        Route::resource('/rentings', RentingController::class);

});

require __DIR__.'/auth.php';

</code>```

I've create creating new routes for the button and adding the action of the button inside the form but its not working

am expecting if i press the store button its supposed to push the data i entered to the database
but its logging me out

Body:
im using laravel 9.42 but the problem im facing is whwn i click the button that is supposed to push data to the database its loging me out of the system ive create creating new routes for the button and adding the action of the button inside the form but its not working

My categoryController

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories =Category::all();
        return view('admin.categories.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.categories.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CategoryStoreRequest $request)
    {
        $image = $request->file('image')->store('public/categories');

        Category::create([

            'name' => $request->name,
            'description' => $request->description,
            'image' => $image

        ]);

        return to_route('admin.categories.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

My CategoryStoreRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\Category;

class CategoryStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'name' =>['required'],
            'image' =>['required','image'],
            'description' =>['required'],

        ];
    }
}

My create.blade.php

<x-admin-layout>
    <x-slot name="header">

            {{ __('Dashboard') }}

    </x-slot>

                Categories Index

                    <form  method="POST" action={{ route('admin.categories.store') }} enctype="multipart/form-data">
                      @csrf

                         Name

                          <input type="text" id="name"  name="name"
                          class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />

                         Image

                          <input type="file" id="image" " name="image" class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />

                        Description

                          <textarea id="description" rows="3" name="description"
                          class="shadow-sm focus:ring-indigo-500 appearance-none bg-white border  py-2 px-3 text-base leading-normal transition duration-150 ease-in-out focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"></textarea>

                        <button type="submit"
                        class="py-2 px-4  bg-indigo-500 hover:bg-indigo-700 rounded-lg text-white">
                            Stores
                        </button>

                    </form>

</x-admin-layout>

and my routes

<?php

use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\AdminController;

//My controllers

use App\Http\Controllers\Admin\MenuController;
use App\Http\Controllers\Admin\HouseController;
use App\Http\Controllers\Admin\RentingController;
use App\Http\Controllers\Admin\CategoryController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

    Route::middleware(['auth', 'admin'])->name('admin.')->prefix('admin')->group(function () {

        Route::get('/', [AdminController::class, 'index'])->name('index');
        Route::resource('/categories', CategoryController::class);
        Route::resource('/menus', MenuController::class);
        Route::resource('/houses', HouseController::class);
        Route::resource('/rentings', RentingController::class);

});

require __DIR__.'/auth.php';

I've create creating new routes for the button and adding the action of the button inside the form but its not working

am expecting if i press the store button its supposed to push the data i entered to the database
but its logging me out


问:
Google Map Cluster not working zoom in/out iOS
I am trying to work with Google map clustering in iOS. I am fetching a massive chunk of data from the database in the lot of 100 per call and then rendering the set on google Maps by sending the lat-long array to the marker cluster. When I try to zoom in cluster expands into further small groups. But the cluster counts not updating automatically.

ScreenShot:-

Zoom out:-

Zoom In:-

**Code:-**
```<code>//MARK: - Setup Map Cluster
func setClusterMap() {
    // Set up the cluster manager with default icon generator and renderer.
    clusterArr.removeAll()

    for i in 0..<self.isLicensedArr.count {
        if self.isLicensedArr[i] == 0 {
            clusterArr.append(self.isLicensedArr[i])
        }
    }

    let clusterCount = NSNumber(value: clusterArr.count)
    let iconGenerator = GMUDefaultClusterIconGenerator(buckets: [clusterCount], backgroundColors: [UIColor(red: 33/255, green: 174/255, blue: 108/255, alpha: 1.0)])
    let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
    let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator)
    renderer.animatesClusters = true
    clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer)

    //Register self to listen to GMSMapViewDelegate events.
    clusterManager.setMapDelegate(self)
    clusterManager.setDelegate(self, mapDelegate: self)

    // Generate and add random items to the cluster manager.
    self.generateClusterItems()
    // Call cluster() after items have been added to perform the clustering and rendering on map.
    self.clusterManager.cluster()
}
</code>```

Following url for map clustering :- https://developers.google.com/maps/documentation/ios-sdk/utility/marker-clustering,

Can someone please explain to me how to update cluster count when zooming in and zooming out. I've tried to implement by above code but no results yet.

Any help would be greatly appreciated.

Thanks in advance.

Body:
I am trying to work with Google map clustering in iOS. I am fetching a massive chunk of data from the database in the lot of 100 per call and then rendering the set on google Maps by sending the lat-long array to the marker cluster. When I try to zoom in cluster expands into further small groups. But the cluster counts not updating automatically.

ScreenShot:-

Zoom out:-

Zoom In:-

**Code:-**

//MARK: - Setup Map Cluster
func setClusterMap() {
    // Set up the cluster manager with default icon generator and renderer.
    clusterArr.removeAll()

    for i in 0..<self.isLicensedArr.count {
        if self.isLicensedArr[i] == 0 {
            clusterArr.append(self.isLicensedArr[i])
        }
    }

    let clusterCount = NSNumber(value: clusterArr.count)
    let iconGenerator = GMUDefaultClusterIconGenerator(buckets: [clusterCount], backgroundColors: [UIColor(red: 33/255, green: 174/255, blue: 108/255, alpha: 1.0)])
    let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
    let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator)
    renderer.animatesClusters = true
    clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer)

    //Register self to listen to GMSMapViewDelegate events.
    clusterManager.setMapDelegate(self)
    clusterManager.setDelegate(self, mapDelegate: self)

    // Generate and add random items to the cluster manager.
    self.generateClusterItems()
    // Call cluster() after items have been added to perform the clustering and rendering on map.
    self.clusterManager.cluster()
}

Following url for map clustering :- https://developers.google.com/maps/documentation/ios-sdk/utility/marker-clustering,

Can someone please explain to me how to update cluster count when zooming in and zooming out. I've tried to implement by above code but no results yet.

Any help would be greatly appreciated.

Thanks in advance.


问:
Using external script for Blogger Template
I am modifying a template on Blogger and I want to transfer this script

```<code>  <script defer='defer'><b:if cond='data:view.isPost'>
         //<![CDATA[
$(document).ready(function(){$(tocList).empty();var t=null,a=null,e=0;$(".amp-content h2, .amp-content h3").each(function(){var n="<a name='"+e+"'></a>";$(this).before(n);var o="<li><a href='#"+e+"'>"+$(this).text()+"</a></li>";$(this).is("h2 , h3")?(a=$("<ul></ul>"),(t=$(o)).append(a),t.appendTo("#tocList")):a.append(o),e++})});
if (document['getElementById']('a3lan-title')) {
    document['getElementsByClassName']('a3lan-title')[0]['innerHTML'] = document['getElementById']('a3lan-title')['innerHTML'];
    document['getElementById']('a3lan-title')['remove']()
};
if (document['getElementById']('a3lan-first')) {
    document['getElementsByClassName']('a3lan-first')[0]['innerHTML'] = document['getElementById']('a3lan-first')['innerHTML'];
    document['getElementById']('a3lan-first')['remove']()
};
if (document['getElementById']('a3lan-Center')) {
    document['getElementsByClassName']('a3lan-Center')[0]['innerHTML'] = document['getElementById']('a3lan-Center')['innerHTML'];
    document['getElementById']('a3lan-Center')['remove']()
};
if (document['getElementById']('a3lan-End')) {
    document['getElementsByClassName']('a3lan-End')[0]['innerHTML'] = document['getElementById']('a3lan-End')['innerHTML'];
    document['getElementById']('a3lan-End')['remove']()
};
if (document['getElementById']('a3lan-lates')) {
    document['getElementsByClassName']('a3lan-lates')[0]['innerHTML'] = document['getElementById']('a3lan-lates')['innerHTML'];
    document['getElementById']('a3lan-lates')['remove']()
};
(function(a){a.fn.lazyload=function(b){var c={threshold:0,failurelimit:0,event:"scroll",effect:"show",container:window};if(b){a.extend(c,b)}var d=this;if("scroll"==c.event){a(c.container).bind("scroll",function(b){var e=0;d.each(function(){if(a.abovethetop(this,c)||a.leftofbegin(this,c)){}else if(!a.belowthefold(this,c)&&!a.rightoffold(this,c)){a(this).trigger("appear")}else{if(e++>c.failurelimit){return false}}});var f=a.grep(d,function(a){return!a.loaded});d=a(f)})}this.each(function(){var b=this;if(undefined==a(b).attr("original")){a(b).attr("original",a(b).attr("src"))}if("scroll"!=c.event||undefined==a(b).attr("src")||c.placeholder==a(b).attr("src")||a.abovethetop(b,c)||a.leftofbegin(b,c)||a.belowthefold(b,c)||a.rightoffold(b,c)){if(c.placeholder){a(b).attr("src",c.placeholder)}else{a(b).removeAttr("src")}b.loaded=false}else{b.loaded=true}a(b).one("appear",function(){if(!this.loaded){a("<img />").bind("load",function(){a(b).hide().attr("src",a(b).attr("original"))[c.effect](c.effectspeed);b.loaded=true}).attr("src",a(b).attr("original"))}});if("scroll"!=c.event){a(b).bind(c.event,function(c){if(!b.loaded){a(b).trigger("appear")}})}});a(c.container).trigger(c.event);return this};a.belowthefold=function(b,c){if(c.container===undefined||c.container===window){var d=a(window).height()+a(window).scrollTop()}else{var d=a(c.container).offset().top+a(c.container).height()}return d<=a(b).offset().top-c.threshold};a.rightoffold=function(b,c){if(c.container===undefined||c.container===window){var d=a(window).width()+a(window).scrollLeft()}else{var d=a(c.container).offset().left+a(c.container).width()}return d<=a(b).offset().left-c.threshold};a.abovethetop=function(b,c){if(c.container===undefined||c.container===window){var d=a(window).scrollTop()}else{var d=a(c.container).offset().top}return d>=a(b).offset().top+c.threshold+a(b).height()};a.leftofbegin=function(b,c){if(c.container===undefined||c.container===window){var d=a(window).scrollLeft()}else{var d=a(c.container).offset().left}return d>=a(b).offset().left+c.threshold+a(b).width()};a.extend(a.expr[":"],{"below-the-fold":"$.belowthefold(a, {threshold : 0, container: window})","above-the-fold":"!$.belowthefold(a, {threshold : 0, container: window})","right-of-fold":"$.rightoffold(a, {threshold : 0, container: window})","left-of-fold":"!$.rightoffold(a, {threshold : 0, container: window})"})})(jQuery);$(function(){$("img").lazyload({placeholder:"https://4.bp.blogspot.com/-oA8G9t61JXk/VtLrtkAzObI/AAAAAAAAFTY/EjT6jl2MEFM/s1600/bloggersstand.gif",effect:"fadeIn",threshold:"-50"})});
var lazyadsense=!1;window.addEventListener("scroll",function(){(0!=document.documentElement.scrollTop&&!1===lazyadsense||0!=document.body.scrollTop&&!1===lazyadsense)&&(!function(){var e=document.createElement("script");e.type="text/javascript",e.async=!0,e.src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(e,a)}(),lazyadsense=!0)},!0);
//]]></b:if>
<b:if cond='not data:view.isSingleItem'>    //<![CDATA[
var olderLink=$("a.blog-pager-older-link").attr("href");olderLink&&$(".loadMorePosts").show(),$(".loadMorePosts a").on("click",(function(o){$(".loadMorePosts").hide(),$.ajax({url:olderLink,success:function(o){var e=$(o).find(".blog-posts");e.children(".status-msg-wrap").remove(),$(".blog-posts").append(e.html()),(olderLink=$(o).find(".blog-pager-older-link").attr("href"))?$(".loadMorePosts").show():$(".noMorePosts").show()},beforeSend:function(){$(".loadMore > #loader").show()},complete:function(){$(".loadMore > #loader").hide()}}),o.preventDefault()}));
//]]></b:if><b:if cond='data:view.isHomepage or data:view.isPost or data:view.isError'>//<![CDATA[
$(document).ready((function(){const o=$(".to-top");$(window).scroll((function(){$(window).scrollTop()>100?o.addClass("active"):o.removeClass("active")}))}));
$(document).ready(function(){$("body").toggleClass(localStorage.toggled),$("#arabes1").on("click",function(){"nightmode"!=localStorage.toggled?($("body").toggleClass("nightmode",!0),localStorage.toggled="nightmode",$(".section-center").css("display","block")):($("body").toggleClass("nightmode",!1),localStorage.toggled="",$(".section-center").css("display",""))}),$("body").hasClass("nightmode")?$("#arabes1").prop("checked",!0):$("#arabes1").prop("checked",!1)});
//]]></b:if>
</script>
</code>```

to an external script, for example on Github, in order to reduce the size of the page. Is there anyone who can help me?

Note: I have previously put it in an external script without making changes, but it did not work

Note: I have previously put it in an external script without making changes, but it did not work

Body:
I am modifying a template on Blogger and I want to transfer this script

to an external script, for example on Github, in order to reduce the size of the page. Is there anyone who can help me?

Note: I have previously put it in an external script without making changes, but it did not work

Note: I have previously put it in an external script without making changes, but it did not work