问:
StatelessNonMultiPartForm() form give error on submit in apache wicket java
I create 3 form in a single page . initially visibility of first is true and other two is false and i on submit first form visibility of first is false and second form is true .And similarly on submit second form visibility of third is true and other two visibility is false. But when i try to submit third form it throw error

```<code>sendOtpForm = new StatelessNonMultiPartForm("sendOtpForm"){

            @Override
            protected void onSubmit() {
                verifyOtp.setVisible(true);
                sendOtpForm.setVisible(false);
                changePasswordForm.setVisible(false);
}
}
 verifyOtp = new StatelessNonMultiPartForm("verifyOtp"){

            @Override
            protected void onSubmit() {
                verifyOtp.setVisible(false);
                sendOtpForm.setVisible(false);
                changePasswordForm.setVisible(true);
}
}
 changePasswordForm = new StatelessNonMultiPartForm("changePasswordForm"){
StatelessNonMultiPartForm("verifyOtp"){

            @Override
            protected void onSubmit() {
                verifyOtp.setVisible(false);
                sendOtpForm.setVisible(true);
                changePasswordForm.setVisible(false);
}
}
</code>```

ERROR] 2022-12-27 16:39:36.344 [qtp1685538367-20] InMemoryErrorReporting - Error with id 7abe6299-b681-4480-bcbd-c54930e02756 registered for user not available:
Failed to resolve user name while generating error report. Original report follows.
[ERROR] 2022-12-27 16:39:36.364 [qtp1685538367-20] InMemoryErrorReporting - Error with id 60e3e0b9-7187-44dc-8877-ab911def30ca registered for user not available:
org.apache.wicket.core.request.handler.ListenerInvocationNotAllowedException: Component rejected interface invocationComponent: [StatelessNonMultiPartForm [Component id = changePasswordForm]]
at org.apache.wicket.core.request.handler.ListenerRequestHandler.invoke(ListenerRequestHandler.java:251)
at org.apache.wicket.core.request.handler.ListenerRequestHandler.invokeListener(ListenerRequestHandler.java:215)
at org.apache.wicket.core.request.handler.ListenerRequestHandler.respond(ListenerRequestHandler.java:208)
at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:907)
at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65)
at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:293)
at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:254)
at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:276)
at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:207)
at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:306)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:149)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:178)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1629)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:533)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:190)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1595)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1564)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:219)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:126)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:199)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:673)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:591)
at java.base/java.lang.Thread.run(Thread.java:829)

Anyone , please help in this .

Body:
I create 3 form in a single page . initially visibility of first is true and other two is false and i on submit first form visibility of first is false and second form is true .And similarly on submit second form visibility of third is true and other two visibility is false. But when i try to submit third form it throw error

sendOtpForm = new StatelessNonMultiPartForm("sendOtpForm"){

            @Override
            protected void onSubmit() {
                verifyOtp.setVisible(true);
                sendOtpForm.setVisible(false);
                changePasswordForm.setVisible(false);
}
}
 verifyOtp = new StatelessNonMultiPartForm("verifyOtp"){

            @Override
            protected void onSubmit() {
                verifyOtp.setVisible(false);
                sendOtpForm.setVisible(false);
                changePasswordForm.setVisible(true);
}
}
 changePasswordForm = new StatelessNonMultiPartForm("changePasswordForm"){
StatelessNonMultiPartForm("verifyOtp"){

            @Override
            protected void onSubmit() {
                verifyOtp.setVisible(false);
                sendOtpForm.setVisible(true);
                changePasswordForm.setVisible(false);
}
}

ERROR] 2022-12-27 16:39:36.344 [qtp1685538367-20] InMemoryErrorReporting - Error with id 7abe6299-b681-4480-bcbd-c54930e02756 registered for user not available:
Failed to resolve user name while generating error report. Original report follows.
[ERROR] 2022-12-27 16:39:36.364 [qtp1685538367-20] InMemoryErrorReporting - Error with id 60e3e0b9-7187-44dc-8877-ab911def30ca registered for user not available:
org.apache.wicket.core.request.handler.ListenerInvocationNotAllowedException: Component rejected interface invocationComponent: [StatelessNonMultiPartForm [Component id = changePasswordForm]]
at org.apache.wicket.core.request.handler.ListenerRequestHandler.invoke(ListenerRequestHandler.java:251)
at org.apache.wicket.core.request.handler.ListenerRequestHandler.invokeListener(ListenerRequestHandler.java:215)
at org.apache.wicket.core.request.handler.ListenerRequestHandler.respond(ListenerRequestHandler.java:208)
at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:907)
at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65)
at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:293)
at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:254)
at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:276)
at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:207)
at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:306)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:149)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:178)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1629)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:533)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:190)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1595)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1564)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:219)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:126)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:199)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:673)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:591)
at java.base/java.lang.Thread.run(Thread.java:829)

Anyone , please help in this .


来源: stackexchange

问:
How to set the transition out duration in unity ui builder
When i hover over the button it changes the color expectedly but when i hover off it it roughly about 3 seconds to change back to normal. Here is an image ->Picture of UI Builder Pseudo Class hover

I tried setting the transition duration and delay to 0 so that the the transition back should be instant.

ContentLicense: CC BY-SA 4.0


问:
How to give a role permissions to run getCommand({ping:1}) in MongoDB?
I need to grant access to a role in MongoDB to allow it to run getCommand({ping:1}).
What kind of action/resource is it?


问:
Update the new tags into git-svn repo and push to the gerrit
I did a migration from svn to Gerrit using the git-svn way. Everything went well and I have that workspace intact.
Now in svn some commits happened recently and a tag was generated. The same commit was done to gerrit also by the developer but the tag creation is not yet enabled.

Now, how can I take the newly created tags in svn to Gerrit? Can I use the same workspace and do something like git svn fetch or something?


问:
Using 'connect-pg-simple' npm module and getting error "Error: connect ECONNREFUSED ip_address:5432" intermittently when the RDS is restarted
I am using 'connect-pg-simple' npm module for session management for our application hosted on AWS and AWS RDS for storing session details. When the RDS is restarted, the application is unable to connect to it and shows the following error. This issue is intermittent.

```<code>Failed to prune sessions: connect ECONNREFUSED ip_address:5432
Failed to prune sessions: connect ECONNREFUSED ip_address:5432
Error: connect ECONNREFUSED ip_address:5432
     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
Error: connect ECONNREFUSED ip_address:5432
     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
</code>```

The implementation:

```<code>let session = require('express-session');

let pgSession = require('connect-pg-simple')(session);
    const pg = require('pg');
    const sessionPool = new pg.Pool({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      user: process.env.DB_USERNAME,
      password: dbPass,
      database: "bludb",
      max: 100
    });
    let sessionOptions = {
      secret: "secret",
      resave: false,
      saveUninitialized: false,
      store: new pgSession({
        pool: sessionPool,
        ttl: process.env.SESSION_TIMEOUT / 1000,
        createTableIfMissing: true,
        pruneSessionInterval: 1800
      })
    };
    app.use(session(sessionOptions));
</code>```

Can anybody help me with what may be wrong here?

npm module documentation links:

https://www.npmjs.com/package/connect-pg-simple

https://github.com/voxpelli/node-connect-pg-simple

Body:
I am using 'connect-pg-simple' npm module for session management for our application hosted on AWS and AWS RDS for storing session details. When the RDS is restarted, the application is unable to connect to it and shows the following error. This issue is intermittent.

Failed to prune sessions: connect ECONNREFUSED ip_address:5432
Failed to prune sessions: connect ECONNREFUSED ip_address:5432
Error: connect ECONNREFUSED ip_address:5432
     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
Error: connect ECONNREFUSED ip_address:5432
     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)

The implementation:

let session = require('express-session');

let pgSession = require('connect-pg-simple')(session);
    const pg = require('pg');
    const sessionPool = new pg.Pool({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      user: process.env.DB_USERNAME,
      password: dbPass,
      database: "bludb",
      max: 100
    });
    let sessionOptions = {
      secret: "secret",
      resave: false,
      saveUninitialized: false,
      store: new pgSession({
        pool: sessionPool,
        ttl: process.env.SESSION_TIMEOUT / 1000,
        createTableIfMissing: true,
        pruneSessionInterval: 1800
      })
    };
    app.use(session(sessionOptions));

Can anybody help me with what may be wrong here?

npm module documentation links:

https://www.npmjs.com/package/connect-pg-simple

https://github.com/voxpelli/node-connect-pg-simple


问:
Log4J Could not find classpath
I am using WebSphere 9 , while uploading ear using admin console its stuck quite long time and in the background its giving below error

```<code>ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
[24/12/22 13:42:57:505 IST] 00000143 SystemErr     R javax.servlet.ServletException: org.apache.commons.fileupload.FileUploadException: Processing of multipart/form-data request failed. Async IO operation failed (1), reason: RC: 55  The specified network resource or device is no longer available.
</code>```

i almost tried everything that , is there anything that I need to pass in jvm argument

like we have DSDMSConfig.build.date=12/17/2022 -DloggingFlush=true

Title: Log4J Could not find classpath

Body:
I am using WebSphere 9 , while uploading ear using admin console its stuck quite long time and in the background its giving below error

ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
[24/12/22 13:42:57:505 IST] 00000143 SystemErr     R javax.servlet.ServletException: org.apache.commons.fileupload.FileUploadException: Processing of multipart/form-data request failed. Async IO operation failed (1), reason: RC: 55  The specified network resource or device is no longer available.

i almost tried everything that , is there anything that I need to pass in jvm argument

like we have DSDMSConfig.build.date=12/17/2022 -DloggingFlush=true


问:
How to animate transition of auto height?
I have div in my template whose content are changing. Which changes height (height auto as contents are dynamic & can be of any height). How Do I animate auto height change using angular animation.

```<code>    trigger('openClose', [
      state('open', style({
        opacity: 1,
      })),
      state('closed', style({
        opacity: 0,
      })),
      transition('open<=>closed', [style({
        transform: 'translateX(-100%)'
      }),
      animate('.3s ease')
      ])
    ]),
    trigger('openClose2', [
      state('open', style({
        opacity: 1,
      })),
      state('closed', style({
        opacity: 0,
      })),
      transition('open<=>closed', [style({
        transform: 'translateX(100%)'
      }),
      animate('.3s  ease')
      ])
    ]),
    trigger('openClose3', [
      state('open', style({
        height: '*',
      })),
      state('closed', style({
        height: '*',
      })),
      transition('closed=>open', [
        query('@openClose2', [
          animateChild()
        ]),
        animate('0.3s ease')
      ]),
      transition('open=>closed', [
        query('@openClose', [
          animateChild()
        ]),
        animate('0.3s ease')
      ])
    ]),
</code>```

Tried this but two '*' in height not working

Body:
I have div in my template whose content are changing. Which changes height (height auto as contents are dynamic & can be of any height). How Do I animate auto height change using angular animation.

    trigger('openClose', [
      state('open', style({
        opacity: 1,
      })),
      state('closed', style({
        opacity: 0,
      })),
      transition('open<=>closed', [style({
        transform: 'translateX(-100%)'
      }),
      animate('.3s ease')
      ])
    ]),
    trigger('openClose2', [
      state('open', style({
        opacity: 1,
      })),
      state('closed', style({
        opacity: 0,
      })),
      transition('open<=>closed', [style({
        transform: 'translateX(100%)'
      }),
      animate('.3s  ease')
      ])
    ]),
    trigger('openClose3', [
      state('open', style({
        height: '*',
      })),
      state('closed', style({
        height: '*',
      })),
      transition('closed=>open', [
        query('@openClose2', [
          animateChild()
        ]),
        animate('0.3s ease')
      ]),
      transition('open=>closed', [
        query('@openClose', [
          animateChild()
        ]),
        animate('0.3s ease')
      ])
    ]),

Tried this but two '*' in height not working


问:
Uncaught (in promise) ReferenceError: getElementsByClassName is not defined
I'm trying to append some text data to an Elementor div using fetch and WordPress custom REST API I made. But I'm always getting this error:

Uncaught (in promise) ReferenceError: getElementsByClassName is not defined

Here is the code:

```<code>for(var i = 0; i < document.getElementsByClassName("elementor-post__title").length; i++) {
    let fetchRes = fetch("https://localhost/paperclasslk/wp-json/quiz/v1/search?name="+document.getElementsByClassName("elementor-post__title")[i].innerText);
    fetchRes.then(res => res.json()).then(d => {
        if (d['quiz_max_score'] === null) {
           const para = document.createElement("p");
           para.innerText = "Quiz " + i + " score is: No score";
           document.getElementsByClassName("elementor-post__excerpt")[i].appendChild(para);
        } else {
           const para = document.createElement("p");
           para.innerText = "Quiz " + i + " score is: " + d['quiz_max_score'];
           document.getElementsByClassName("elementor-post__excerpt")[i].appendChild(para);
        }
    })
}
</code>```

Hopefully everyone can help me. Thank you and have a good day!

Body:
I'm trying to append some text data to an Elementor div using fetch and WordPress custom REST API I made. But I'm always getting this error:

Uncaught (in promise) ReferenceError: getElementsByClassName is not defined

Here is the code:

for(var i = 0; i < document.getElementsByClassName("elementor-post__title").length; i++) {
    let fetchRes = fetch("https://localhost/paperclasslk/wp-json/quiz/v1/search?name="+document.getElementsByClassName("elementor-post__title")[i].innerText);
    fetchRes.then(res => res.json()).then(d => {
        if (d['quiz_max_score'] === null) {
           const para = document.createElement("p");
           para.innerText = "Quiz " + i + " score is: No score";
           document.getElementsByClassName("elementor-post__excerpt")[i].appendChild(para);
        } else {
           const para = document.createElement("p");
           para.innerText = "Quiz " + i + " score is: " + d['quiz_max_score'];
           document.getElementsByClassName("elementor-post__excerpt")[i].appendChild(para);
        }
    })
}

Hopefully everyone can help me. Thank you and have a good day!


问:
Python Google cloud API request location error
I have been trying to make API request woth python to googlw cloud. The target is to read data from cloud storage and write it to bigquery.

Unfortunately I get the following error when trying to do it.”cannot write to destination us as reading from EU.”

Both the cloud storage and bigquery are in EU location so I cant figure out the reason for this error.
Hi, Here is the code im using: imgur.com/a/DTj0Uhp and the error im getting when running the script is "google.api_core.exceptions.BadRequest: 400 Cannot read and write in different locations: source: EU, destination: US Location: US" –

I have check google settings and cannot find the reason why the error says Im trying to write to US location.


问:
Parsing a JSON date works differently on iOS and Android
My app is returning a date string in the string format '/Date(1672869600000)/'

When I parse the above using the below JavaScript I get a result of Thu Jan 05 2023 00:00:00 GMT+0200 (South Africa Standard Time) on Android:

```<code>var data = '/Date(1672869600000)/';
var start = new Date(parseInt(data.substr(6)))
</code>```

The same code resolves as on Wed Jan 04 2023 14:00:00:00 GMT-0800 (Ora Standard del Pacifico USA) Chromium on iOS.

Why is this occurring, and how can I adjust my parsing function to get the correct result?

Body:
My app is returning a date string in the string format '/Date(1672869600000)/'

When I parse the above using the below JavaScript I get a result of Thu Jan 05 2023 00:00:00 GMT+0200 (South Africa Standard Time) on Android:

var data = '/Date(1672869600000)/';
var start = new Date(parseInt(data.substr(6)))

The same code resolves as on Wed Jan 04 2023 14:00:00:00 GMT-0800 (Ora Standard del Pacifico USA) Chromium on iOS.

Why is this occurring, and how can I adjust my parsing function to get the correct result?


问:
Javascript Encode result after fetch
So i need to encode characters after fetch and when i  encoded show as text. here is my code

```<code> fetch('URL', {
      method: 'POST',
      headers: {
        'Content-Type': 'text/xml',
      },
    })
    .then(response => response.text())
    .then(data => {
       console.log(result)
    })
    .catch(err => console.error(err));

</code>```

its working fine but there are bad characters.

This is how can i encode

```<code>      buf = iconv.encode("PosteÄľ roĹˇtovĂˇ", 'win1250');
      str = iconv.decode(Buffer.from(buf), 'utf-8');
      console.log(str)  // Posteľ roštová
</code>```

so how can i do it in react native

Title: Javascript Encode result after fetch

Body:
So i need to encode characters after fetch and when i  encoded show as text. here is my code

 fetch('URL', {
      method: 'POST',
      headers: {
        'Content-Type': 'text/xml',
      },
    })
    .then(response => response.text())
    .then(data => {
       console.log(result)
    })
    .catch(err => console.error(err));

its working fine but there are bad characters.

This is how can i encode

      buf = iconv.encode("PosteÄľ roĹˇtovĂˇ", 'win1250');
      str = iconv.decode(Buffer.from(buf), 'utf-8');
      console.log(str)  // Posteľ roštová

so how can i do it in react native


问:
Refused to display in a frame because it set 'X-Frame-Options' to 'sameorigin'
When i'm trying to open my website in iframe.but it showing this.
i used reactjs for this project.

error on console

trying to open my website in iframe but it throwing error


问:
Converting Differen exchange rates on a dataframe

Amount
Currency
Date

45,63
GBP
23.02.2020

38,42
EUR
15.06.2019

8500
SEK
20.03.2021

Hey guys I want to convert this different currencies on different time basis to GBP. I tried following code but get the error

```<code> from forex_python.converter import CurrencyRates
        c = CurrencyRates()
        df['Amount'] = df.apply( lambda x: c.convert( x.Currency, 'GBP', x.Amount, x.Date), axis = 1)

*'Currency Rates source not ready'*
</code>```

I also tried to do that on API but it is limited to 1000 datas. My record includes 95000 rows of data. Is there any possibility to convert these Amount to GBP on datetime basis ?

Body:
Amount
Currency
Date

45,63
GBP
23.02.2020

38,42
EUR
15.06.2019

8500
SEK
20.03.2021

Hey guys I want to convert this different currencies on different time basis to GBP. I tried following code but get the error

 from forex_python.converter import CurrencyRates
        c = CurrencyRates()
        df['Amount'] = df.apply( lambda x: c.convert( x.Currency, 'GBP', x.Amount, x.Date), axis = 1)

*'Currency Rates source not ready'*

I also tried to do that on API but it is limited to 1000 datas. My record includes 95000 rows of data. Is there any possibility to convert these Amount to GBP on datetime basis ?


问:
How and with which steps can I install ReadTheDoc on my server and connect it to Gitlab?
By default, our friends use readme.mds in MarkDown format as documents on our Gitlab server. We want ReadThedocs (RTD) to be prepared as ReadThedocs (RTD) with rst extension on Gitlab server and documents can be read in RTD format in a more organized and tree structure. In order to do this, I think as a result of my research, Readthedocs needs to be installed on the server and associated with Gitlab, unless I misunderstood? I can't find it anywhere, how do I do this. In short, how do I set up this infrastructure.

My Gitlab Version : 15.02
My OS : Redhat 7.9


问:
Exclude folders from Synology Backup Task
In the Synology Drive Client, I am trying to exclude certain folders from the Backup Task in the Backup Rules tab. However, this page says "The filenames or filename extensions listed below will not be backed up:". Is there any way I can overcome this problem?

I am using DSM 7.1.

I'd like to backup my programming projects to my NAS, which I'm actively developing, where a lot of temporal folders are generated. I didn't necessarily want to create git repositories for these projects since many of them are just simple hobby projects. Do you have any suggestions or know best practices for this problem?

I have searched for this problem on a few portals, watched videos and checked the official Synology website, but not found any solutions.


问:
Error running selenium in android phone using Termux
Hii I m using selenium in my android phone using termux

This is my code

```<code>from seledroid import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option('androidPackage', 'com.android.chrome')

driver=webdriver.Chrome('./chromedriver', options=options)

driver.get('https://google.com')
driver.quit()
</code>```

This is the error I am getting;

```<code>Traceback (most recent call last):
  File "/storage/emulated/0/Download/Instagram-Bot-Scrape-DM-Users-main/Instagram-Bot-Scrape-DM-Users-main/hh.py", line 3, in <module>
    options = webdriver.ChromeOptions()                                              ^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'seledroid.webdriver' has no attribute 'ChromeOptions'
</code>```

Please help me on this

Body:
Hii I m using selenium in my android phone using termux

This is my code

from seledroid import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option('androidPackage', 'com.android.chrome')

driver=webdriver.Chrome('./chromedriver', options=options)

driver.get('https://google.com')
driver.quit()

This is the error I am getting;

Traceback (most recent call last):
  File "/storage/emulated/0/Download/Instagram-Bot-Scrape-DM-Users-main/Instagram-Bot-Scrape-DM-Users-main/hh.py", line 3, in <module>
    options = webdriver.ChromeOptions()                                              ^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'seledroid.webdriver' has no attribute 'ChromeOptions'

Please help me on this


问:
How can I open 2 chrome windows in kiosk mode on 2 monitors with WebDriver in Python (Windows)?
I have a physical kiosk station with 2 monitors running a Python app.
Each monitor should run a Chrome window in kiosk mode.

The question is
How can I open 2 kiosk windows on 2 monitors with Selenium WebDriver in Python (Windows 11)?

Right now, I can open the chromes using this code:

import webbrowser
import threading

def open_browser(url, screen: int):
    def _run():
        chrome_path = "C:/Program Files/Google/Chrome/Application/chrome.exe"
        x_position = 1920 if screen else 0
        monitor = 2 if screen else 1
        webbrowser.get(f"{chrome_path} --window-position={x_position},0 --kiosk --user-data-dir=c:/monitor{monitor} %s").open_new(url)

    threading.Thread(target=_run).start()

open_browser("https://www.google.com/", 0)
open_browser("https://www.amazon.com/", 1)

```

But I want the ability to control the browser more. Especially to monitor elements displayed on the page. For this purpose I want to switch to using WebDriver instead of webbrowser.

Body:
I have a physical kiosk station with 2 monitors running a Python app.
Each monitor should run a Chrome window in kiosk mode.

The question is
How can I open 2 kiosk windows on 2 monitors with Selenium WebDriver in Python (Windows 11)?

Right now, I can open the chromes using this code:

import webbrowser
import threading

def open_browser(url, screen: int):
    def _run():
        chrome_path = "C:/Program Files/Google/Chrome/Application/chrome.exe"
        x_position = 1920 if screen else 0
        monitor = 2 if screen else 1
        webbrowser.get(f"{chrome_path} --window-position={x_position},0 --kiosk --user-data-dir=c:/monitor{monitor} %s").open_new(url)

    threading.Thread(target=_run).start()

open_browser("https://www.google.com/", 0)
open_browser("https://www.amazon.com/", 1)

But I want the ability to control the browser more. Especially to monitor elements displayed on the page. For this purpose I want to switch to using WebDriver instead of webbrowser.


问:
C++ iterating over a class that wraps around a list
Sorry for such a bad title but I don't know how to condense what I want to say. Anyway, I have a template class that wraps around a list, something simple like this:

```<code>template<typename T>
class MyWrapper {
    std::list<T> items;
}
</code>```

I want to be able to use this wrapper in a foreach loop. As my class is simply wrapping a list (i.e. it's not really a custom collection), I think I can just use that list's iterator functions as my own:

```<code>typename _Container::iterator begin () noexcept {
    return items.begin();
}

typename _Container::iterator end () noexcept {
    return items.end();
}

typename _Container::const_iterator cbegin () const noexcept {
    return items.cbegin();
}

typename _Container::const_iterator cend () const noexcept {
    return items.cend();
}
</code>```

This works fine for non-const instantiations of my class, but not for const-ones. Example:

```<code>// this one works fine and iterates the inner list as you'd expect.
MyWrapper& mywr = someMethod(); // returns MyWrapper&
for (auto& el : mywr) {
    //...
}

// this one won't compile
const MyWrapper& myconst = someConstMethod(); // returns const MyWrapper&
for (const auto& el : myconst) {
    //...
}
</code>```

The error given is "no instance of function "MyWrapper::begin" matches the argument list and object (the object has type qualifiers that prevent a match) - object type is: const MyWrapper".

As this should be a pretty common use case, I'm sure there's a page specifying exactly which methods to implement to get this working, but I haven't been able to find it so far.

Body:
Sorry for such a bad title but I don't know how to condense what I want to say. Anyway, I have a template class that wraps around a list, something simple like this:

template<typename T>
class MyWrapper {
    std::list<T> items;
}

I want to be able to use this wrapper in a foreach loop. As my class is simply wrapping a list (i.e. it's not really a custom collection), I think I can just use that list's iterator functions as my own:

typename _Container::iterator begin () noexcept {
    return items.begin();
}

typename _Container::iterator end () noexcept {
    return items.end();
}

typename _Container::const_iterator cbegin () const noexcept {
    return items.cbegin();
}

typename _Container::const_iterator cend () const noexcept {
    return items.cend();
}

This works fine for non-const instantiations of my class, but not for const-ones. Example:

// this one works fine and iterates the inner list as you'd expect.
MyWrapper& mywr = someMethod(); // returns MyWrapper&
for (auto& el : mywr) {
    //...
}

// this one won't compile
const MyWrapper& myconst = someConstMethod(); // returns const MyWrapper&
for (const auto& el : myconst) {
    //...
}

The error given is "no instance of function "MyWrapper::begin" matches the argument list and object (the object has type qualifiers that prevent a match) - object type is: const MyWrapper".

As this should be a pretty common use case, I'm sure there's a page specifying exactly which methods to implement to get this working, but I haven't been able to find it so far.


问:
Database query external interfaces
Can I use the results of a database query directly for code refactoring?

looks like the database has many external interfaces. I have already created a set of unit tests for the existing codes.

Title: Database query external interfaces


问:
Python in Terminal, How to show long text in table format in Python?
I use tabulate to show tabled data organize better.

It makes life for Terminal junkies easier.
I have pandas dataframe with long text in each cell. The problem is tabulate wants to print/show all the text so it does not show the table pretty.
is there a way I could show just part of the text?

PS, Cannot use Jupyter or VScode or others.

Thanks


问:
SAML SSO Configuration
How to configure the SP metadata to our asp.net page to login or Redirect browser to SP Screen.

I use sso saml asp.net toolkit guide how to integrate idp_sso_target_url in our asp.net page

Title: SAML SSO Configuration


问:
Can't get NGINX to read socket created by GUNICORN via SUPERVISORD (permission error)
I'm trying to run Django on AWS/Ubuntu using NGINX/Gunicorn (via supervisord)

My Nginx logs keeps throwing a permission error when trying to access app.sock.
"app.sock" is created by gunicorn, and gunicorn is run by supervisord, and supervisord is a nightmare.

```<code>ps aux | grep nginx
root       63435  0.0  0.1  55200  1692 ?        Ss   10:56   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data   63436  0.0  0.5  55848  5424 ?        S    10:56   0:00 nginx: worker process
</code>```

As we can see www-data is the user associated with nginx.

```<code> ls -lh ~/www/app.sock
srwxrwxrwx 1 root root 0 Dec 27 11:20 /home/ubuntu/www/app.sock
</code>```

And app.sock is owned by "root", hence the permission error I'm getting.

And here is my supervisord config file

```<code>[program:gunicorn]
directory=/home/ubuntu/www
command=/usr/local/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/www/app.sock matched.wsgi:application
user=www-data
autostart=true
autorestart=true
stderr_logfile=/logs/gunicorn.err.log
stdout_logfile=/logs/gunicorn.out.log
</code>```

In my config file, I've attempted to tell supervisor to run my gunicorn command AS www-data, but its still creating app.sock as root. It seems like the "user" parameter does not do anything at all.

The only solution I see to this ridiculous problem is to run Nginx as root, which I know is a bad idea. I've searched almost every discussion on the web and I cannot find any information about why the "user" parameter on supervisord is not working. Alternatively I can bind it to a port (I think?), but I would really like to solve THIS problem since I'm already in this deep.

Body:
I'm trying to run Django on AWS/Ubuntu using NGINX/Gunicorn (via supervisord)

My Nginx logs keeps throwing a permission error when trying to access app.sock.
"app.sock" is created by gunicorn, and gunicorn is run by supervisord, and supervisord is a nightmare.

ps aux | grep nginx
root       63435  0.0  0.1  55200  1692 ?        Ss   10:56   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data   63436  0.0  0.5  55848  5424 ?        S    10:56   0:00 nginx: worker process

As we can see www-data is the user associated with nginx.

 ls -lh ~/www/app.sock
srwxrwxrwx 1 root root 0 Dec 27 11:20 /home/ubuntu/www/app.sock

And app.sock is owned by "root", hence the permission error I'm getting.

And here is my supervisord config file

[program:gunicorn]
directory=/home/ubuntu/www
command=/usr/local/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/www/app.sock matched.wsgi:application
user=www-data
autostart=true
autorestart=true
stderr_logfile=/logs/gunicorn.err.log
stdout_logfile=/logs/gunicorn.out.log

In my config file, I've attempted to tell supervisor to run my gunicorn command AS www-data, but its still creating app.sock as root. It seems like the "user" parameter does not do anything at all.

The only solution I see to this ridiculous problem is to run Nginx as root, which I know is a bad idea. I've searched almost every discussion on the web and I cannot find any information about why the "user" parameter on supervisord is not working. Alternatively I can bind it to a port (I think?), but I would really like to solve THIS problem since I'm already in this deep.


问:
Robocopy vbs script with subfolders and spaces
I'm using this script to copy files and folders from one path to another one, but right now I need to create a new one to copy folder with spaces and files with spaces (this one doesn't copy this folders/files). Could you please help me?</p>
```<code>Dim objShell, fso, folder, subfolder, sfolder

'variables
src = "Y:\Files\Dati\"
dst = "\\servername\Dati\"

Set objShell = CreateObject("WScript.shell")
set fso = CreateObject("Scripting.FileSystemObject")

Set folder = fso.GetFolder(src)
Set subfolders = folder.SubFolders

For each subfolder in subfolders

    objShell.Run("c:\windows\system32\robocopy.exe "&src&subfolder.Name&" "&dst&subfolder.Name&" *.* /mov /COPY:DT /s /R:0 /W:0 /xd *Trash")

Next 'for each subfolders
</code>```

Body:
I'm using this script to copy files and folders from one path to another one, but right now I need to create a new one to copy folder with spaces and files with spaces (this one doesn't copy this folders/files). Could you please help me?

Dim objShell, fso, folder, subfolder, sfolder

'variables
src = "Y:\Files\Dati\"
dst = "\\servername\Dati\"

Set objShell = CreateObject("WScript.shell")
set fso = CreateObject("Scripting.FileSystemObject")

Set folder = fso.GetFolder(src)
Set subfolders = folder.SubFolders

For each subfolder in subfolders

    objShell.Run("c:\windows\system32\robocopy.exe "&src&subfolder.Name&" "&dst&subfolder.Name&" *.* /mov /COPY:DT /s /R:0 /W:0 /xd *Trash")

Next 'for each subfolders


问:
My old DCGAN doesn't generate proper images. Trying to understand (again) how to implement a DCGAN
This is more of a conceptual question. I am not looking to "fix" my code.

It has been a while since I did anything with NN. I have this old code for a DCGAN (updated due to deprecated things in tf). I removed a few things to take up less space in this post.

```<code>[IMPORTS]

class DCGAN_model:
    def __init__(self, lr = 0.0002, discriminator_checkpoint = None, generator_checkpoint = None):
        self.discriminator, self.generator, self.dcgan = self.build_dcgan_models(lr, discriminator_checkpoint, generator_checkpoint)

    # Defines the Generator model
    # Input (66,) -> Output (256,256,1)
    def make_generator_model(self, load = None):
        # Input (66,)
        inputs = Input((66,))
        ...
        ...
        ...
        # Deconv to (256,256,N)
        deconv3a = Conv2DTranspose(48, (3, 3), strides=(2, 2), activation='relu', padding='same')(model)
        deconv3b = Conv2DTranspose(48, (5, 5), strides=(2, 2), activation='relu', padding='same')(model)
        model = concatenate([deconv3a, deconv3b], axis=3)

        # Conv to (256,256,1)
        model = Conv2D(1, (3,3), strides=(1,1), activation='sigmoid', padding='same')(model)

        # Build model
        model = Model(inputs=inputs, outputs=model)

        # Load checkpoint
        if(load is not None):
            ...
        return model

    # Defines the Discriminator model
    # Input (256,256,1) -> Output (1,)
    def make_discriminator_model(self, lr, load = None):
        # Input (256,256,1)
        inputs = Input((256,256,1))
        ...
        ...
        ...
        # Flatten and dense
        model = Flatten()(model)
        model = Dense(512, activation='relu')(model)
        model = Dense(1, activation='sigmoid')(model)

        # Build model
        model = Model(inputs=inputs, outputs=model)

        # Load checkpoint
        if(load is not None):
            ...
        # Compile Discriminator
        model.trainable = True
        model.compile(loss='binary_crossentropy',
                    optimizer=Adam(learning_rate=lr, beta_1 = 0.5),
                    metrics=['accuracy'])
        model.trainable = False
        return model

    # Build DCGAN
    def build_dcgan_models(self, lr, discriminator_checkpoint, generator_checkpoint):
        # Make Discriminator and Generator
        discriminator = self.make_discriminator_model(lr, discriminator_checkpoint)
        generator = self.make_generator_model(generator_checkpoint)
        # Make DCGAN
        dcgan = Sequential([generator, discriminator])

        # Compile DCGAN
        dcgan.compile(loss='binary_crossentropy',
                    optimizer=Adam(learning_rate=lr, beta_1 = 0.5),
                    metrics=['accuracy'])
        return discriminator, generator, dcgan

    # Trains a batch of images
    def train(self, batch_size, x_g, x_d_true):
            # Generate images
            x_d_gen = self.generator.predict(x_g, verbose=0)

            # Train Discriminator
            # With real images
            d_loss = self.discriminator.train_on_batch(x_d_true, y=np.ones((batch_size)))
            print("\tL(D(Real)) = ", d_loss)
            # With generated images
            d_loss = self.discriminator.train_on_batch(x_d_gen, y=np.zeros((batch_size)))
            print("\tL(D(Fake)) = ", d_loss)
            # Train Generator
            g_loss = self.dcgan.train_on_batch(x_g, np.ones((batch_size)))
            print("\tL(G(x)) = ", g_loss)
</code>```

It used to work, but now it doesn't. The loss for the Generator and Discriminator go down, but the generated images are totally wrong.

In my code, the Generator updates it weights when training the entire DCGAN (Sequential([generator, discriminator])) with the Discriminator not training at this moment. So the backpropagation for the DCGAN only updates the weights for the Generator, and not the Discriminator. This means that it uses the backpropagation of error through the Discriminator to identify "wrong" pixels in the output of the Generator, and continues the backpropagation to fix the Generator's weights. I still train the Discriminator with real images and fake images, so it should know what a real or fake image should look like.

Question 1: Is there any conceptual problem with how I am training my Discriminator or Generator?

I checkout out this Tensorflow guide for DCGAN https://www.tensorflow.org/tutorials/generative/dcgan. And I don't get how the Generator  properly updates its weights.

Question 2: In the tutorial, how are the Generator's weights being updated properly if I don't use the Discriminator backpropagation? I just have a single value for the error when compared with the whole output image. How does the generator know where it got it wrong?

Body:
This is more of a conceptual question. I am not looking to "fix" my code.

It has been a while since I did anything with NN. I have this old code for a DCGAN (updated due to deprecated things in tf). I removed a few things to take up less space in this post.

[IMPORTS]

class DCGAN_model:
    def __init__(self, lr = 0.0002, discriminator_checkpoint = None, generator_checkpoint = None):
        self.discriminator, self.generator, self.dcgan = self.build_dcgan_models(lr, discriminator_checkpoint, generator_checkpoint)

    # Defines the Generator model
    # Input (66,) -> Output (256,256,1)
    def make_generator_model(self, load = None):
        # Input (66,)
        inputs = Input((66,))
        ...
        ...
        ...
        # Deconv to (256,256,N)
        deconv3a = Conv2DTranspose(48, (3, 3), strides=(2, 2), activation='relu', padding='same')(model)
        deconv3b = Conv2DTranspose(48, (5, 5), strides=(2, 2), activation='relu', padding='same')(model)
        model = concatenate([deconv3a, deconv3b], axis=3)

        # Conv to (256,256,1)
        model = Conv2D(1, (3,3), strides=(1,1), activation='sigmoid', padding='same')(model)

        # Build model
        model = Model(inputs=inputs, outputs=model)

        # Load checkpoint
        if(load is not None):
            ...
        return model

    # Defines the Discriminator model
    # Input (256,256,1) -> Output (1,)
    def make_discriminator_model(self, lr, load = None):
        # Input (256,256,1)
        inputs = Input((256,256,1))
        ...
        ...
        ...
        # Flatten and dense
        model = Flatten()(model)
        model = Dense(512, activation='relu')(model)
        model = Dense(1, activation='sigmoid')(model)

        # Build model
        model = Model(inputs=inputs, outputs=model)

        # Load checkpoint
        if(load is not None):
            ...
        # Compile Discriminator
        model.trainable = True
        model.compile(loss='binary_crossentropy',
                    optimizer=Adam(learning_rate=lr, beta_1 = 0.5),
                    metrics=['accuracy'])
        model.trainable = False
        return model

    # Build DCGAN
    def build_dcgan_models(self, lr, discriminator_checkpoint, generator_checkpoint):
        # Make Discriminator and Generator
        discriminator = self.make_discriminator_model(lr, discriminator_checkpoint)
        generator = self.make_generator_model(generator_checkpoint)
        # Make DCGAN
        dcgan = Sequential([generator, discriminator])

        # Compile DCGAN
        dcgan.compile(loss='binary_crossentropy',
                    optimizer=Adam(learning_rate=lr, beta_1 = 0.5),
                    metrics=['accuracy'])
        return discriminator, generator, dcgan

    # Trains a batch of images
    def train(self, batch_size, x_g, x_d_true):
            # Generate images
            x_d_gen = self.generator.predict(x_g, verbose=0)

            # Train Discriminator
            # With real images
            d_loss = self.discriminator.train_on_batch(x_d_true, y=np.ones((batch_size)))
            print("\tL(D(Real)) = ", d_loss)
            # With generated images
            d_loss = self.discriminator.train_on_batch(x_d_gen, y=np.zeros((batch_size)))
            print("\tL(D(Fake)) = ", d_loss)
            # Train Generator
            g_loss = self.dcgan.train_on_batch(x_g, np.ones((batch_size)))
            print("\tL(G(x)) = ", g_loss)

It used to work, but now it doesn't. The loss for the Generator and Discriminator go down, but the generated images are totally wrong.

In my code, the Generator updates it weights when training the entire DCGAN (Sequential([generator, discriminator])) with the Discriminator not training at this moment. So the backpropagation for the DCGAN only updates the weights for the Generator, and not the Discriminator. This means that it uses the backpropagation of error through the Discriminator to identify "wrong" pixels in the output of the Generator, and continues the backpropagation to fix the Generator's weights. I still train the Discriminator with real images and fake images, so it should know what a real or fake image should look like.

Question 1: Is there any conceptual problem with how I am training my Discriminator or Generator?

I checkout out this Tensorflow guide for DCGAN https://www.tensorflow.org/tutorials/generative/dcgan. And I don't get how the Generator  properly updates its weights.

Question 2: In the tutorial, how are the Generator's weights being updated properly if I don't use the Discriminator backpropagation? I just have a single value for the error when compared with the whole output image. How does the generator know where it got it wrong?


问:
Fail to install RPM package due to libstdc++ version
When I install an RPM package, it prompted wrong message that was dependencies problem of libstdc++.so.6.  My OS is CentOS 7.9 and gcc version is 11.

[root@dist]# rpm -hiv TCGstorageAPI-1.0-1.x86_64.rpm

error: Failed dependencies:

libstdc++.so.6(CXXABI_1.3.9)(64bit) is needed by TCGstorageAPI-1.0-1.x86_64

libstdc++.so.6(GLIBCXX_3.4.21)(64bit) is needed by TCGstorageAPI-1.0-1.x86_64

libstdc++.so.6(GLIBCXX_3.4.26)(64bit) is needed by TCGstorageAPI-1.0-1.x86_64

libstdc++.so.6(GLIBCXX_3.4.29)(64bit) is needed by TCGstorageAPI-1.0-1.x86_64

But I have put newer libstdc++.so.6.0.29 into /lib64 and /usr/lib64 folders and created right soft link to libstdc++.so.6.   libstdc++.so.6.0.29 supports CXXABI_1.3.9 and GLIBCXX_3.4.29.  I don't know why still report dependencies error. Could you someone help me take a look? Thanks

[root@dist]# strings /usr/lib64/libstdc++.so.6.0.29 | grep GLIBCXX_3.4.29

GLIBCXX_3.4.29

GLIBCXX_3.4.29

[root@dist]# ls /usr/lib64/libstdc++* -l

lrwxrwxrwx. 1 root root       19 Dec 22 15:30 /usr/lib64/libstdc++.so -> libstdc++.so.6.0.29

lrwxrwxrwx. 1 root root       19 Dec 22 15:30 /usr/lib64/libstdc++.so.6 -> libstdc++.so.6.0.29

-rwxr-xr-x. 1 root root   995840 Sep 30  2020 /usr/lib64/libstdc++.so.6.0.19

-rwxr-xr-x. 1 root root 16757720 Jan 10  2022 /usr/lib64/libstdc++.so.6.0.28

-rw-r--r--. 1 root root     2386 Jan 10  2022 /usr/lib64/libstdc++.so.6.0.28-gdb.py

-rwxr-xr-x. 1 root root 14608032 Dec 22 15:30 /usr/lib64/libstdc++.so.6.0.29

-rw-r--r--. 1 root root     2382 Dec 22 15:30 /usr/lib64/libstdc++.so.6.0.29-gdb.py

[root@dist]# ls /lib64/libstdc++* -l

lrwxrwxrwx. 1 root root       19 Dec 22 15:30 /lib64/libstdc++.so -> libstdc++.so.6.0.29

lrwxrwxrwx. 1 root root       19 Dec 22 15:30 /lib64/libstdc++.so.6 -> libstdc++.so.6.0.29

-rwxr-xr-x. 1 root root   995840 Sep 30  2020 /lib64/libstdc++.so.6.0.19

-rwxr-xr-x. 1 root root 16757720 Jan 10  2022 /lib64/libstdc++.so.6.0.28

-rw-r--r--. 1 root root     2386 Jan 10  2022 /lib64/libstdc++.so.6.0.28-gdb.py

-rwxr-xr-x. 1 root root 14608032 Dec 22 15:30 /lib64/libstdc++.so.6.0.29

-rw-r--r--. 1 root root     2382 Dec 22 15:30 /lib64/libstdc++.so.6.0.29-gdb.py


问:
How to strong name assemblies when publishing to a single file (.exe) in Visual Studio
I'm writing a desktop application in .NET 6 and using the User Settings feature to store some persistent configuration values. Because the application is portable, I sign the assembly with a strong name, so that if the executable changes location the user settings are still the same (like explained here). I use strong naming in Visual Studio with the following configuration:

strong naming settings

Then I publish the application to a folder via Visual Studio with the following profile settings:

publish profile settings

If I run the application, the user settings are saved with its path as identifier instead of the strong name.

But if I publish the application without the 'Produce single file' option activated, it will output the DLL's, runtime config and executable separately. If I run the application now, then the user settings are saved with the strong name as identifier.

Also, if I verify the files with the Strong Name Tool (sn -v) via the Visual Studio Developer Command Prompt, the DLL's are valid (the executable is not, but I think that is expected).

I expected the same when publishing to a single file. What changes with this option? And how do I get the same result as publishing to separate files?


问:
How to style css tippy/react in eventMouseEnter
I want to use the html and style tags included in the tippy content but I can't do it. I used function and used content attribute in it to be able to call title from API but I want stylecss to make my interface more beautiful
Fullcalendar React component:

```<code>const CalendarContent = () => {
function handleMouseEnter (arg) {
tippy(arg.el, {
  content: `<div className="content">${arg.event.title}</div>`,
  trigger: 'click',
  allowHTML: true,});}
//getAPI
const [schedules, setSchedules] = useState([]);
const scheduleApi = "http://127.0.0.1:8000/api/get-schedule"
useEffect(() => {
async function getScheduleData () {
  const res = await axios.get(scheduleApi);
  setSchedules(res.data.data);
}
getScheduleData();
},[]);
return (
<React.Fragment>
  <div className="w-[85%] flex flex-col mx-auto ">
    <FullCalendar
    plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
        headerToolbar={{
          left: 'title',
          right: 'prev,next today'
        }}

    eventMouseEnter={handleMouseEnter}
    timeZone="none"
    initialView="dayGridMonth"
    navLinks={true}
    selectable={true}
    events={schedules}
  />
  <div className="mx-auto">
    <Link to="/booking">
      {/* <button className="w-15 h-12 rounded-3xl border-[1px] bg-
      [#a7705c] py-3 px-5 font-bold text-white duration-300 ease-in
      hover:border-[#a7705c] hover:bg-white hover:text-[#a7705c]">
        Booking now
      </button> */}
    </Link>
    </div>
  </div>
</React.Fragment>
);
};
</code>```

Can someone help me how to use tippy with css

Body:
I want to use the html and style tags included in the tippy content but I can't do it. I used function and used content attribute in it to be able to call title from API but I want stylecss to make my interface more beautiful
Fullcalendar React component:

const CalendarContent = () => {
function handleMouseEnter (arg) {
tippy(arg.el, {
  content: `<div className="content">${arg.event.title}</div>`,
  trigger: 'click',
  allowHTML: true,});}
//getAPI
const [schedules, setSchedules] = useState([]);
const scheduleApi = "http://127.0.0.1:8000/api/get-schedule"
useEffect(() => {
async function getScheduleData () {
  const res = await axios.get(scheduleApi);
  setSchedules(res.data.data);
}
getScheduleData();
},[]);
return (
<React.Fragment>

    <FullCalendar
    plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
        headerToolbar={{
          left: 'title',
          right: 'prev,next today'
        }}

    eventMouseEnter={handleMouseEnter}
    timeZone="none"
    initialView="dayGridMonth"
    navLinks={true}
    selectable={true}
    events={schedules}
  />

    <Link to="/booking">
      {/* <button className="w-15 h-12 rounded-3xl border-[1px] bg-
      [#a7705c] py-3 px-5 font-bold text-white duration-300 ease-in
      hover:border-[#a7705c] hover:bg-white hover:text-[#a7705c]">
        Booking now
      </button> */}
    </Link>

</React.Fragment>
);
};

Can someone help me how to use tippy with css


问:
Solve the 'max size limit exceeded' warning for openzeppelin's governor contract wizard
I generated a contract for governance based on the wizard provided by openzeppelin here: https://wizard.openzeppelin.com/#governor

I didn't change any values in the fields and tried compiling the contract in hardhat. But it throws the below warning:

```<code>Warning: Contract code size is 25663 bytes and exceeds 24576 bytes
(a limit introduced in Spurious Dragon). This contract may not be deployable on Mainnet.
</code>```

Kindly someone help me resolve this. I need to use the timelock feature along with other default base contracts for governance.

Body:
I generated a contract for governance based on the wizard provided by openzeppelin here: https://wizard.openzeppelin.com/#governor

I didn't change any values in the fields and tried compiling the contract in hardhat. But it throws the below warning:

Warning: Contract code size is 25663 bytes and exceeds 24576 bytes
(a limit introduced in Spurious Dragon). This contract may not be deployable on Mainnet.

Kindly someone help me resolve this. I need to use the timelock feature along with other default base contracts for governance.


问:
How to run executable in my Flutter desktop app
I want to call the executable file at startup in flutter development desktop application</p>


问:
Why does an offset trigger a use after realloc warning with gcc?
I am having trouble with a gcc 12.2 warning, and I was able to create a minimal example that triggers it. I know this code doesn't really make sense, it's only for demonstration purposes. It only seems to happens with -O1 optimizations and above. The following code triggers a use after realloc warning:

```<code>#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>

void *magic (int *start, int random)
{
  size_t offset = (uintptr_t)start % 16;
  int *end = (void*)((char*)start + offset);
  ptrdiff_t diff = (char*)end - (char*)start;

  // removing this if clause (and the random function parameter)
  // fixes the warning for some reason.
  if(random > 100) {
    return NULL;
  }

  int *new_start = realloc(start, sizeof(int)*100);

  return (char *)new_start + diff;
}
</code>```

Godbolt: https://godbolt.org/z/r54je3dqn

What exactly is happening here, is there some undefined behavior or is this a false positive?

Body:
I am having trouble with a gcc 12.2 warning, and I was able to create a minimal example that triggers it. I know this code doesn't really make sense, it's only for demonstration purposes. It only seems to happens with -O1 optimizations and above. The following code triggers a use after realloc warning:

#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>

void *magic (int *start, int random)
{
  size_t offset = (uintptr_t)start % 16;
  int *end = (void*)((char*)start + offset);
  ptrdiff_t diff = (char*)end - (char*)start;

  // removing this if clause (and the random function parameter)
  // fixes the warning for some reason.
  if(random > 100) {
    return NULL;
  }

  int *new_start = realloc(start, sizeof(int)*100);

  return (char *)new_start + diff;
}

Godbolt: https://godbolt.org/z/r54je3dqn

What exactly is happening here, is there some undefined behavior or is this a false positive?


问:
In Ffmpeg-Python how to merge Audio Track with keeping the Existing Audio Track and Subtitles
import ffmpeg

video = ffmpeg.input('input.mkv').video

audio = ffmpeg.input('audio.mp3').audio

ffmpeg.output(video, audio, 'output.mkv', vcodec='copy', acodec='copy').run()

What i need to do with this code for merging new audio track with existing audio and subtitles.

Please Help me with this Thanks!


问:
How to implement levelorder traversal function using queues with binary trees?
I wrote a C program that performs iterative inorder, preorder, postorder, and level order traversal using a stack and queue. But my levelorder() function just prints the root element but does not print anything else and postorder(), preorder() function displays the same output. I double-checked the algorithms for each function but I do not understand why I'm getting this output. I'm unsure why I'm getting logical errors.</p>
```<code>#include<stdio.h>
#include<stdlib.h>
#define MAX 20
typedef struct node{
    int data;
    struct node *left,*right;
} NODE;

typedef struct{
    NODE* arr[MAX];
    int top;
} STACK;

typedef struct{
    NODE* arr[MAX];
    int front,rear;
} QUEUE;

NODE* createNode(int ele){
    NODE* newnode = (NODE*)malloc(sizeof(NODE));
    newnode->data = ele;
    newnode->right = newnode->left = NULL;
    return newnode;
}

NODE* createTree(){
    int ele;
    printf("Enter root data(-1 to exit):\n");
    scanf("%d",&ele);
    NODE* newnode;
    if(ele == -1){
        return NULL;
    }
    newnode = createNode(ele);
    printf("\nEnter the data for the left child of %d(-1 to stop):\n",ele);
    newnode->left = createTree();
    printf("\nEnter the data for the right child of %d(-1 to stop):\n",ele);
    newnode->right = createTree();
    return newnode;
}

STACK* init(){
    STACK* s = (STACK*)malloc(sizeof(STACK));
    s->top = -1;
    return s;
}

int isEmpty(STACK* s){
    return s->top == -1;
}

int isFull(STACK* s){
    return s->top - 1 == MAX;
}

void push(STACK* s, NODE* ele){
    if(s->top == MAX - 1){
        printf("Stack is full\n");
    }
    else{
        s->arr[(++s->top)] = ele;
    }
}

NODE* pop(STACK* s){
    if(s->top == -1){
        return NULL;
    }
    else
        return s->arr[s->top--];
}

NODE* peek(STACK* s){
    if(isEmpty(s)){
        return NULL;
    }
    else
        return s->arr[s->top];
}

void inorder(NODE* root){
    STACK* s = init();
    NODE* curr = root;
    while(curr != NULL || !isEmpty(s)){
        if(curr != NULL){
            push(s,curr);
            curr = curr->left;
        }
        else{
            curr = pop(s);
            printf(" %d ",curr->data);
            curr = curr->right;
        }
    }
}

void preorder(NODE* root){
    if(root == NULL)
        return;
    STACK* s = init();
    push(s,root);
    while (!isEmpty(s)){
        NODE* current = pop(s);
        printf(" %d ",current->data);
        if(current->right)
            push(s,current->right);
        if (current->left)
            push(s,current->left);
    }
}

void postorder(NODE* root){

    if(root == NULL){
        return;
    }
    STACK* s = init();
    do
    {
        while(root){
            if(root->right)
                push(s,root->right);
            push(s,root);
            root = root->left;
        }
        root = pop(s);
        if(root->right && peek(s) == root->right){
            pop(s);
            push(s,root);
            root = root->right;
        }
        else{
            printf(" %d ",root->data);
            root = NULL;
        }

    } while (!isEmpty(s));
}

QUEUE* initq(){
    QUEUE* q = (QUEUE*)malloc(sizeof(QUEUE));
    q->front = 0;
    q->rear = 0;
    return q;
}

void enqueue(QUEUE* q, NODE* ele){
    if(q->rear == (q->rear % MAX) + 1){
        q->arr[q->rear] = ele;
    }
}

NODE* dequeue(QUEUE* q){
    if(q->front == q->rear){
        return NULL;
    }
    else{
        q->front = (q->front % MAX) + 1;
        return q->arr[q->front];
    }
}

int qisEmpty(QUEUE* q){
    if(q->front == q->rear){
        return 1;
    }
    return 0;
}

int qisFull(QUEUE* q){
    if(q->rear == (q->rear % MAX) + 1)
        return 1;
    else
        return 0;
}

void levelOrder(NODE* root){
    QUEUE* q = initq();
    NODE* temp = root;
    while(temp){
        printf(" %d ", temp->data);

        if(temp->left)
            enqueue(q,temp->left);
        if(temp->right)
            enqueue(q,temp->right);
        temp = dequeue(q);
    }
}

int main(){
    NODE* root = NULL;
    root = createTree();
    printf("\nThe inorder traversal:\n");
    inorder(root);

    printf("\nThe preorder traversal:\n");
    preorder(root);

    printf("\nThe postorder traversal:\n");
    preorder(root);

    printf("\nThe level order traversal:\n");
    levelOrder(root);

    return 0;
}
</code>```

Body:
I wrote a C program that performs iterative inorder, preorder, postorder, and level order traversal using a stack and queue. But my levelorder() function just prints the root element but does not print anything else and postorder(), preorder() function displays the same output. I double-checked the algorithms for each function but I do not understand why I'm getting this output. I'm unsure why I'm getting logical errors.

#include<stdio.h>
#include<stdlib.h>
#define MAX 20
typedef struct node{
    int data;
    struct node *left,*right;
} NODE;

typedef struct{
    NODE* arr[MAX];
    int top;
} STACK;

typedef struct{
    NODE* arr[MAX];
    int front,rear;
} QUEUE;

NODE* createNode(int ele){
    NODE* newnode = (NODE*)malloc(sizeof(NODE));
    newnode->data = ele;
    newnode->right = newnode->left = NULL;
    return newnode;
}

NODE* createTree(){
    int ele;
    printf("Enter root data(-1 to exit):\n");
    scanf("%d",&ele);
    NODE* newnode;
    if(ele == -1){
        return NULL;
    }
    newnode = createNode(ele);
    printf("\nEnter the data for the left child of %d(-1 to stop):\n",ele);
    newnode->left = createTree();
    printf("\nEnter the data for the right child of %d(-1 to stop):\n",ele);
    newnode->right = createTree();
    return newnode;
}

STACK* init(){
    STACK* s = (STACK*)malloc(sizeof(STACK));
    s->top = -1;
    return s;
}

int isEmpty(STACK* s){
    return s->top == -1;
}

int isFull(STACK* s){
    return s->top - 1 == MAX;
}

void push(STACK* s, NODE* ele){
    if(s->top == MAX - 1){
        printf("Stack is full\n");
    }
    else{
        s->arr[(++s->top)] = ele;
    }
}

NODE* pop(STACK* s){
    if(s->top == -1){
        return NULL;
    }
    else
        return s->arr[s->top--];
}

NODE* peek(STACK* s){
    if(isEmpty(s)){
        return NULL;
    }
    else
        return s->arr[s->top];
}

void inorder(NODE* root){
    STACK* s = init();
    NODE* curr = root;
    while(curr != NULL || !isEmpty(s)){
        if(curr != NULL){
            push(s,curr);
            curr = curr->left;
        }
        else{
            curr = pop(s);
            printf(" %d ",curr->data);
            curr = curr->right;
        }
    }
}

void preorder(NODE* root){
    if(root == NULL)
        return;
    STACK* s = init();
    push(s,root);
    while (!isEmpty(s)){
        NODE* current = pop(s);
        printf(" %d ",current->data);
        if(current->right)
            push(s,current->right);
        if (current->left)
            push(s,current->left);
    }
}

void postorder(NODE* root){

    if(root == NULL){
        return;
    }
    STACK* s = init();
    do
    {
        while(root){
            if(root->right)
                push(s,root->right);
            push(s,root);
            root = root->left;
        }
        root = pop(s);
        if(root->right && peek(s) == root->right){
            pop(s);
            push(s,root);
            root = root->right;
        }
        else{
            printf(" %d ",root->data);
            root = NULL;
        }

    } while (!isEmpty(s));
}

QUEUE* initq(){
    QUEUE* q = (QUEUE*)malloc(sizeof(QUEUE));
    q->front = 0;
    q->rear = 0;
    return q;
}

void enqueue(QUEUE* q, NODE* ele){
    if(q->rear == (q->rear % MAX) + 1){
        q->arr[q->rear] = ele;
    }
}

NODE* dequeue(QUEUE* q){
    if(q->front == q->rear){
        return NULL;
    }
    else{
        q->front = (q->front % MAX) + 1;
        return q->arr[q->front];
    }
}

int qisEmpty(QUEUE* q){
    if(q->front == q->rear){
        return 1;
    }
    return 0;
}

int qisFull(QUEUE* q){
    if(q->rear == (q->rear % MAX) + 1)
        return 1;
    else
        return 0;
}

void levelOrder(NODE* root){
    QUEUE* q = initq();
    NODE* temp = root;
    while(temp){
        printf(" %d ", temp->data);

        if(temp->left)
            enqueue(q,temp->left);
        if(temp->right)
            enqueue(q,temp->right);
        temp = dequeue(q);
    }
}

int main(){
    NODE* root = NULL;
    root = createTree();
    printf("\nThe inorder traversal:\n");
    inorder(root);

    printf("\nThe preorder traversal:\n");
    preorder(root);

    printf("\nThe postorder traversal:\n");
    preorder(root);

    printf("\nThe level order traversal:\n");
    levelOrder(root);

    return 0;
}


问:
Cropped graph when using log scale in matplotlib
I'm using matplotlib to plot a pandas dataframe. I want to use log scale on the Y axis, the problem is that when I do so, the graph is cropped (values in Y axis range from 0 to 1). I'm already using log scale on the X axis without problems.

This is the graph with linear scale:

```<code>ax = df2.plot(kind = 'line', x = 'priceUSD', y = 'cumulative_probability')

ax.set_xscale('log')
ax.set_xlabel("Precio medio de los activos")
ax.set_ylabel("Probabilidad")
plt.legend(["Todos los activos"])
</code>```

If I use log scale on the Y axis 0 values are not shown:

```<code>ax = df2.plot(kind = 'line', x = 'priceUSD', y = 'cumulative_probability')

ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel("Precio medio de los activos")
ax.set_ylabel("Probabilidad")
plt.legend(["Todos los activos"])
</code>```

df2 looks like this:

I want the plot to look similar to the following image:

I've been experimenting with set_yticks and set_major_formatter but no luck so far.

Body:
I'm using matplotlib to plot a pandas dataframe. I want to use log scale on the Y axis, the problem is that when I do so, the graph is cropped (values in Y axis range from 0 to 1). I'm already using log scale on the X axis without problems.

This is the graph with linear scale:

ax = df2.plot(kind = 'line', x = 'priceUSD', y = 'cumulative_probability')

ax.set_xscale('log')
ax.set_xlabel("Precio medio de los activos")
ax.set_ylabel("Probabilidad")
plt.legend(["Todos los activos"])

If I use log scale on the Y axis 0 values are not shown:

ax = df2.plot(kind = 'line', x = 'priceUSD', y = 'cumulative_probability')

ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel("Precio medio de los activos")
ax.set_ylabel("Probabilidad")
plt.legend(["Todos los activos"])

df2 looks like this:

I want the plot to look similar to the following image:

I've been experimenting with set_yticks and set_major_formatter but no luck so far.


问:
react-native iOS 16 Xcode 14 This method should not be called on the main thread as it may lead to UI unresponsiveness
After updating to Xcode 14 and iOS 16 I Got  this purple warning on build time and its about 30 to 40 warnings. is there any solutions for this.</p>
```<code>/Users/apple/repos/ssd/iOS/xxxxxxx/main.m:8 This method should not be called on the main thread as it may lead to UI unresponsiveness.
</code>```

Body:
After updating to Xcode 14 and iOS 16 I Got  this purple warning on build time and its about 30 to 40 warnings. is there any solutions for this.

/Users/apple/repos/ssd/iOS/xxxxxxx/main.m:8 This method should not be called on the main thread as it may lead to UI unresponsiveness.


问:
How should pyenv interface with Conda environments?
I saw on the Internet that we should use pyenv to avoid affecting the system Python. I know we can use pyenv-virtualenv to create a virtual environment. However, Conda can also be used to create virtual environments. I'm confused up to this point. Should I install pyenv and Miniconda separately, or should I install Miniconda under pyenv?

Currently, I have installed pyenv and miniforge on my Mac with Homebrew. I mainly use Conda to create my virtual environments, but this makes pyenv seems kinda useless.

Edit:

So in the beginning, I also saw this post: What is the difference between pyenv, virtualenv, anaconda?, comparing the differences. I thought these two different things shoudl be used separately until I saw the github page of pyenv-virtualenv: https://github.com/pyenv/pyenv-virtualenv. In the last section, it says something like

You can manage conda environments by conda create as same manner as standard Anaconda/Miniconda installations. To use those environments, you can use pyenv activate and pyenv deactivate

People also mentioned conflicts between conda and pyenv. How can I install Anaconda aside an existing pyenv installation on OSX?. So I'm confused that if I should install conda under pyenv or install them separately.


问:
Dynamic mapping for nested array values in Elasticsearch
I want to create dynamic mapping for objects like:

```<code>{
  "id": 1,
  "name": "item1",
  "inventory": {
    "newyork": {
      "total_sales_count": 10000,
      "rank": 10,
      "average_sales_count": 100,
      "discount": 10,
      "store_info": [
        {
          "discounted_price": 250,
          "catalog_price": 300,
          "store_id": 101,
          "rank": 10,
          "status": "active"
        },
        {
          "discounted_price": 150,
          "catalog_price": 200,
          "store_id": 102,
          "rank": 11,
          "status": "active"
        }
      ],
    },
    "boston": {
      ...
      "store_info": [
        {
          "discounted_price": 250,
          "catalog_price": 300,
          "store_id": 103,
          "rank": 21,
          "status": "active"
        },
        ...
      ],

    }
  }
}
</code>```

I would like all the objects inside store_info array to be indexed as nested so that i can query by attributes like store_id and rank. I could directly define mapping in index to treat this store_info data as nested but it is inside dynamic field which will be a city name like "newyork", "boston".

I had applied mapping to define inventory field as nested but the same is not working.

Is there any way to achieve the same using dynamic mapping or any other method in Elasticsearch?

Body:
I want to create dynamic mapping for objects like:

{
  "id": 1,
  "name": "item1",
  "inventory": {
    "newyork": {
      "total_sales_count": 10000,
      "rank": 10,
      "average_sales_count": 100,
      "discount": 10,
      "store_info": [
        {
          "discounted_price": 250,
          "catalog_price": 300,
          "store_id": 101,
          "rank": 10,
          "status": "active"
        },
        {
          "discounted_price": 150,
          "catalog_price": 200,
          "store_id": 102,
          "rank": 11,
          "status": "active"
        }
      ],
    },
    "boston": {
      ...
      "store_info": [
        {
          "discounted_price": 250,
          "catalog_price": 300,
          "store_id": 103,
          "rank": 21,
          "status": "active"
        },
        ...
      ],

    }
  }
}

I would like all the objects inside store_info array to be indexed as nested so that i can query by attributes like store_id and rank. I could directly define mapping in index to treat this store_info data as nested but it is inside dynamic field which will be a city name like "newyork", "boston".

I had applied mapping to define inventory field as nested but the same is not working.

Is there any way to achieve the same using dynamic mapping or any other method in Elasticsearch?


问:
Reading pixels from a bmp file in RISC-V assembly [RARS]
I'm trying to access a bmp file using RARS and I have a problem with accessing pixels of it.

I'm trying to find a black pixel in my bitmap image but the way I did it gives me address out of range error when loading a byte from t3 to t5. Therefore I am pretty sure that I did something wrong with accessing data.

```<code>.data

FileName: .space 64
width: .space 320
height: .space 240
buf: .space 54

.text

#reading what is the file name
ReadingFileName:

    li a7, 8
    la a0, FileName
    li a1, 64
    ecall

    la t0, FileName
    li t1, '\n'

FindEndOfString:
    lbu t2, (t0)
    beq t1, t2, RemoveN
    addi t0, t0, 1
    j FindEndOfString

RemoveN:
    li t1, '\0'
    sb t1, (t0)

#Reading data from file
ReadingData:
    #open the file
    li a7, 1024
    la a0, FileName
    li a1, 0
    ecall

    #file descriptor
    mv s0, a0

    #check if file was opened correctly
    bltz s0, OpeningError

    #read data from file
    li a7, 63
    mv a0, s0
    la a1, buf
    li a2, 54
    ecall

    beq zero, a0, FileClose

    lw s1, buf
    addi s1, s1, 54 #start of pixels

FileClose:
    li a7, 57
    mv a0, s0
    ecall

Main:
    li t1, 0 #first column of black pixels
    li t2, 0 #last column of black pixels
    mv t3, s1 #start of pixels

LookForBlackPixel:
    lbu t5, (t3)
    beqz t5, BlackPixelFound
    addi t3, t3, 1
    j LookForBlackPixel

BlackPixelFound:

OpeningError:

</code>```

The error:
Runtime exception at 0x00400094: address out of range 0x84364d78

Body:
I'm trying to access a bmp file using RARS and I have a problem with accessing pixels of it.

I'm trying to find a black pixel in my bitmap image but the way I did it gives me address out of range error when loading a byte from t3 to t5. Therefore I am pretty sure that I did something wrong with accessing data.

.data

FileName: .space 64
width: .space 320
height: .space 240
buf: .space 54

.text

#reading what is the file name
ReadingFileName:

    li a7, 8
    la a0, FileName
    li a1, 64
    ecall

    la t0, FileName
    li t1, '\n'

FindEndOfString:
    lbu t2, (t0)
    beq t1, t2, RemoveN
    addi t0, t0, 1
    j FindEndOfString

RemoveN:
    li t1, '\0'
    sb t1, (t0)

#Reading data from file
ReadingData:
    #open the file
    li a7, 1024
    la a0, FileName
    li a1, 0
    ecall

    #file descriptor
    mv s0, a0

    #check if file was opened correctly
    bltz s0, OpeningError

    #read data from file
    li a7, 63
    mv a0, s0
    la a1, buf
    li a2, 54
    ecall

    beq zero, a0, FileClose

    lw s1, buf
    addi s1, s1, 54 #start of pixels

FileClose:
    li a7, 57
    mv a0, s0
    ecall

Main:
    li t1, 0 #first column of black pixels
    li t2, 0 #last column of black pixels
    mv t3, s1 #start of pixels

LookForBlackPixel:
    lbu t5, (t3)
    beqz t5, BlackPixelFound
    addi t3, t3, 1
    j LookForBlackPixel

BlackPixelFound:

OpeningError:

The error:
Runtime exception at 0x00400094: address out of range 0x84364d78


问:
Git- Make project size small like after clone
I have a clone of the project from another team then I run it a few times. I checked, the size of this project increased significantly. From 2MB as when the new clone until now is 190MB.

I checked and found that this increase was caused by the .git/objects folder.

I tried something like git gc --prune=now --aggressive but nothing changed.

I can delete the project and clone again but I think there is a way for the project to keep the same size as when I first cloned.
So is there a way to refresh my project to the way it was when I cloned?

===================================================================

EDIT 2: I follow the steps in Remove large .pack file created by git but the pack file (.git/objects/xxxxxxxxx.pack) keeps 200 MB. It's ridiculous but what I want is just to make my project as small as when I first cloned. But it seems that git is not capable of providing this.

My workaround was to delete all files and try to clone the project again.