问:
QuartzDeadlineManager (Scheduler) inadvertently replaces configured TransactionManager
Axon documentation is somewhat faulty at describing the nuances between EventScheduler and DeadlineManager, and in which scenario you have to use each one. In a trial by fire, I attempted to use EventScheduler in one of few Sagas implemented. I realized it does not trigger @EventSourcingHandler on Aggregate, so I was forced to change to a DeadlineManager. (Hint: this could be better described in documentation)

Now first challenge was to configure the DeadlineManager without any insight. Here is the final code I ended doing:

```<code>@Configuration
public class AxonConfiguration {
    @Bean
    public DeadlineManager deadlineManager(
        final Scheduler scheduler,
        // Disregard "Could not autowire. No beans of 'AxonConfiguration' type found." complain from IntelliJ.
        // This class is an @Configuration, which is a @Component by itself.
        final org.axonframework.spring.config.AxonConfiguration configuration,
        final TransactionManager transactionManager,
        final Serializer serializer
    ) {
        return QuartzDeadlineManager.builder()
            .scheduler(scheduler)
            .serializer(serializer)
            .scopeAwareProvider(new ConfigurationScopeAwareProvider(configuration))
            .transactionManager(transactionManager)
            .build();
    }
}
</code>```

As you may see, when using a reputable IDE, it complains that AxonConfiguration is not a Bean, so you have to live with the warning forever.

When I injected the DeadlineManager in my Saga, I've done this:

```<code>@Slf4j
@Saga
public class MySaga {
    static final Long DELAY_INITIALIZE = 60L;
    static final String INITIALIZE_DEADLINE_NAME = "MyInitialize";

    @Autowired
    private transient DeadlineManager deadlineManager;

    @Autowired
    private transient CommandGateway commandGateway;

    private String scheduleName;
    private String scheduleId;

    @StartSaga
    @SagaEventHandler(associationProperty = "correlationId")
    protected void on(final ScheduleEvent event, @Timestamp final Instant eventInstant) {
        final Instant timerInitialize = eventInstant.plus(Duration.ofSeconds(DELAY_INITIALIZE));

        this.scheduleName = INITIALIZE_DEADLINE_NAME;
        this.scheduleId = this.deadlineManager.schedule(
            timerInitialize,
            INITIALIZE_DEADLINE_NAME,
            InitializeEvent.builder()
                .id(event.getId())
                .build()
        );
    }

    @DeadlineHandler(deadlineName = INITIALIZE_DEADLINE_NAME)
    protected void onDeadline(final InitializeEvent command) {
        this.commandGateway.send(command);
    }

    // ...
}
</code>```

I've abstracted away the non-relevant code. Keep in mind that nowhere else in the codebase we modify the StdScheduler instance injected as a Bean dependency for DeadlineManager.

However, when executing my code, I keep getting the following Exception:

```<code>2020-05-28 03:26:13.001 ERROR 1 --- [eduler_Worker-1] o.a.deadline.quartz.DeadlineJob          : Exception occurred during processing a deadline job which will be retried [com.eblock.simulcast.bidding_engine_axon.auction_event.command.InitializeAuctionEvent]

javax.persistence.TransactionRequiredException: Executing an update/delete query
    at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:413) ~[hibernate-core-5.4.15.Final.jar!/:5.4.15.Final]
    at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1608) ~[hibernate-core-5.4.15.Final.jar!/:5.4.15.Final]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:409) ~[spring-orm-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at com.sun.proxy.$Proxy175.executeUpdate(Unknown Source) ~[na:na]
    at org.axonframework.modelling.saga.repository.jpa.JpaSagaStore.updateSaga(JpaSagaStore.java:272) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.updateSaga(AnnotatedSagaRepository.java:208) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.commit(AnnotatedSagaRepository.java:174) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.lambda$doLoad$2(AnnotatedSagaRepository.java:121) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.MessageProcessingContext.notifyHandlers(MessageProcessingContext.java:71) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.DefaultUnitOfWork.notifyHandlers(DefaultUnitOfWork.java:106) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.changePhase(AbstractUnitOfWork.java:222) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.commitAsRoot(AbstractUnitOfWork.java:83) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.commit(AbstractUnitOfWork.java:71) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.DefaultUnitOfWork.executeWithResult(DefaultUnitOfWork.java:92) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.UnitOfWork.executeWithResult(UnitOfWork.java:328) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.deadline.quartz.DeadlineJob.execute(DeadlineJob.java:134) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.2.jar!/:na]
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) ~[quartz-2.3.2.jar!/:na]

2020-05-28 03:26:13.001  INFO 1 --- [eduler_Worker-1] org.quartz.core.JobRunShell              : Job InitializeAuctionEvent.deadline-7e5d9eec-2c7d-4312-9dde-acb9a56abc6b threw a JobExecutionException:

org.quartz.JobExecutionException: javax.persistence.TransactionRequiredException: Executing an update/delete query
    at org.axonframework.deadline.quartz.DeadlineJob.execute(DeadlineJob.java:143) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.2.jar!/:na]
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) ~[quartz-2.3.2.jar!/:na]
Caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query
    at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:413) ~[hibernate-core-5.4.15.Final.jar!/:5.4.15.Final]
    at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1608) ~[hibernate-core-5.4.15.Final.jar!/:5.4.15.Final]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:409) ~[spring-orm-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at com.sun.proxy.$Proxy175.executeUpdate(Unknown Source) ~[na:na]
    at org.axonframework.modelling.saga.repository.jpa.JpaSagaStore.updateSaga(JpaSagaStore.java:272) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.updateSaga(AnnotatedSagaRepository.java:208) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.commit(AnnotatedSagaRepository.java:174) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.lambda$doLoad$2(AnnotatedSagaRepository.java:121) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.MessageProcessingContext.notifyHandlers(MessageProcessingContext.java:71) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.DefaultUnitOfWork.notifyHandlers(DefaultUnitOfWork.java:106) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.changePhase(AbstractUnitOfWork.java:222) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.commitAsRoot(AbstractUnitOfWork.java:83) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.commit(AbstractUnitOfWork.java:71) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.DefaultUnitOfWork.executeWithResult(DefaultUnitOfWork.java:92) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.UnitOfWork.executeWithResult(UnitOfWork.java:328) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.deadline.quartz.DeadlineJob.execute(DeadlineJob.java:134) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    ... 2 common frames omitted
</code>```

I decided to debug and spend a few hours trying to narrow down the issue. I realized that somehow outside of my codebase (likely Axon magic), the StdScheduler.getContext().get(DeadlineJob.TRANSACTION_MANAGER_KEY) gets overridden.

Here are 2 screenshots that highlight the issue:

As you can see, the instance number of StdScheduler 13137 contains the SpringTransactionManager during initialize().

When I add the breakpoint straight on my scheduling line, here is the screenshot:

Instance of StdScheduler is still 13137, and the QuartzDeadlineManager.transactionManager still contains an instance of SpringTransactionManager. But the StdScheduler.getContext().get(DeadlineJob.TRANSACTION_MANAGER_KEY) now contains a NoTransactionManager instance, which then causes my execution to break due to a TransactionRequiredException.

Did anyone experience this scenario? How was it mitigated? Right now I'm traversing through all Axon code in an attempt to understand where the instance gets swapped.

Thanks,

答:
I ended up figuring it out the issue.
In my AxonConfiguration class, the method for EventScheduler was left there in case we had to revert or use that scheduler in a near future.
The EventScheduler was defined as this:

```<code>    @Bean
    public QuartzEventSchedulerFactoryBean eventScheduler() {
        return new QuartzEventSchedulerFactoryBean();
    }
</code>```

As the QuartzEventScheduler was created by the FactoryBean, it was pulling the StdScheduler from the ApplicationContext, and assigning the relevant variables all over again. Since I had no customized TransactionManager, the default (NoTransactionManager) was being assigned to the QuartzEventScheduler, which then changes the QuartzScheduler context, causing the issue.

To fix that, I expanded my Bean to the following:

```<code>    @Bean
    public QuartzEventSchedulerFactoryBean eventScheduler(
        final ApplicationContext applicationContext,
        @Qualifier("eventStore") final EventBus eventBus,
        final Scheduler scheduler,
        final PlatformTransactionManager transactionManager
    ) {
        final QuartzEventSchedulerFactoryBean factoryBean = new QuartzEventSchedulerFactoryBean();

        factoryBean.setApplicationContext(applicationContext);
        factoryBean.setEventBus(eventBus);
        factoryBean.setScheduler(scheduler);
        factoryBean.setTransactionManager(transactionManager);
        factoryBean.setTransactionDefinition(new DefaultTransactionDefinition());

        return factoryBean;
    }
</code>```

Here is my ask for the Axon team:

The QuartzEventScheduler(FactoryBean) requires the underlying PlatformTransactionManager, and creates a new SpringTransactionManager to assign. It would be much easier if they kept the same approach as QuartzDeadlineManager, using directly an autowired TransactionManager, instead of handling the instantiation internally (and replacing the axon-spring-autoconfigure created one).

Body:
Axon documentation is somewhat faulty at describing the nuances between EventScheduler and DeadlineManager, and in which scenario you have to use each one. In a trial by fire, I attempted to use EventScheduler in one of few Sagas implemented. I realized it does not trigger @EventSourcingHandler on Aggregate, so I was forced to change to a DeadlineManager. (Hint: this could be better described in documentation)

Now first challenge was to configure the DeadlineManager without any insight. Here is the final code I ended doing:

@Configuration
public class AxonConfiguration {
    @Bean
    public DeadlineManager deadlineManager(
        final Scheduler scheduler,
        // Disregard "Could not autowire. No beans of 'AxonConfiguration' type found." complain from IntelliJ.
        // This class is an @Configuration, which is a @Component by itself.
        final org.axonframework.spring.config.AxonConfiguration configuration,
        final TransactionManager transactionManager,
        final Serializer serializer
    ) {
        return QuartzDeadlineManager.builder()
            .scheduler(scheduler)
            .serializer(serializer)
            .scopeAwareProvider(new ConfigurationScopeAwareProvider(configuration))
            .transactionManager(transactionManager)
            .build();
    }
}

As you may see, when using a reputable IDE, it complains that AxonConfiguration is not a Bean, so you have to live with the warning forever.

When I injected the DeadlineManager in my Saga, I've done this:

@Slf4j
@Saga
public class MySaga {
    static final Long DELAY_INITIALIZE = 60L;
    static final String INITIALIZE_DEADLINE_NAME = "MyInitialize";

    @Autowired
    private transient DeadlineManager deadlineManager;

    @Autowired
    private transient CommandGateway commandGateway;

    private String scheduleName;
    private String scheduleId;

    @StartSaga
    @SagaEventHandler(associationProperty = "correlationId")
    protected void on(final ScheduleEvent event, @Timestamp final Instant eventInstant) {
        final Instant timerInitialize = eventInstant.plus(Duration.ofSeconds(DELAY_INITIALIZE));

        this.scheduleName = INITIALIZE_DEADLINE_NAME;
        this.scheduleId = this.deadlineManager.schedule(
            timerInitialize,
            INITIALIZE_DEADLINE_NAME,
            InitializeEvent.builder()
                .id(event.getId())
                .build()
        );
    }

    @DeadlineHandler(deadlineName = INITIALIZE_DEADLINE_NAME)
    protected void onDeadline(final InitializeEvent command) {
        this.commandGateway.send(command);
    }

    // ...
}

I've abstracted away the non-relevant code. Keep in mind that nowhere else in the codebase we modify the StdScheduler instance injected as a Bean dependency for DeadlineManager.

However, when executing my code, I keep getting the following Exception:

2020-05-28 03:26:13.001 ERROR 1 --- [eduler_Worker-1] o.a.deadline.quartz.DeadlineJob          : Exception occurred during processing a deadline job which will be retried [com.eblock.simulcast.bidding_engine_axon.auction_event.command.InitializeAuctionEvent]

javax.persistence.TransactionRequiredException: Executing an update/delete query
    at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:413) ~[hibernate-core-5.4.15.Final.jar!/:5.4.15.Final]
    at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1608) ~[hibernate-core-5.4.15.Final.jar!/:5.4.15.Final]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:409) ~[spring-orm-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at com.sun.proxy.$Proxy175.executeUpdate(Unknown Source) ~[na:na]
    at org.axonframework.modelling.saga.repository.jpa.JpaSagaStore.updateSaga(JpaSagaStore.java:272) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.updateSaga(AnnotatedSagaRepository.java:208) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.commit(AnnotatedSagaRepository.java:174) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.lambda$doLoad$2(AnnotatedSagaRepository.java:121) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.MessageProcessingContext.notifyHandlers(MessageProcessingContext.java:71) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.DefaultUnitOfWork.notifyHandlers(DefaultUnitOfWork.java:106) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.changePhase(AbstractUnitOfWork.java:222) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.commitAsRoot(AbstractUnitOfWork.java:83) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.commit(AbstractUnitOfWork.java:71) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.DefaultUnitOfWork.executeWithResult(DefaultUnitOfWork.java:92) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.UnitOfWork.executeWithResult(UnitOfWork.java:328) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.deadline.quartz.DeadlineJob.execute(DeadlineJob.java:134) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.2.jar!/:na]
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) ~[quartz-2.3.2.jar!/:na]

2020-05-28 03:26:13.001  INFO 1 --- [eduler_Worker-1] org.quartz.core.JobRunShell              : Job InitializeAuctionEvent.deadline-7e5d9eec-2c7d-4312-9dde-acb9a56abc6b threw a JobExecutionException:

org.quartz.JobExecutionException: javax.persistence.TransactionRequiredException: Executing an update/delete query
    at org.axonframework.deadline.quartz.DeadlineJob.execute(DeadlineJob.java:143) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.2.jar!/:na]
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) ~[quartz-2.3.2.jar!/:na]
Caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query
    at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:413) ~[hibernate-core-5.4.15.Final.jar!/:5.4.15.Final]
    at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1608) ~[hibernate-core-5.4.15.Final.jar!/:5.4.15.Final]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:409) ~[spring-orm-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at com.sun.proxy.$Proxy175.executeUpdate(Unknown Source) ~[na:na]
    at org.axonframework.modelling.saga.repository.jpa.JpaSagaStore.updateSaga(JpaSagaStore.java:272) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.updateSaga(AnnotatedSagaRepository.java:208) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.commit(AnnotatedSagaRepository.java:174) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.modelling.saga.repository.AnnotatedSagaRepository.lambda$doLoad$2(AnnotatedSagaRepository.java:121) ~[axon-modelling-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.MessageProcessingContext.notifyHandlers(MessageProcessingContext.java:71) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.DefaultUnitOfWork.notifyHandlers(DefaultUnitOfWork.java:106) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.changePhase(AbstractUnitOfWork.java:222) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.commitAsRoot(AbstractUnitOfWork.java:83) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.AbstractUnitOfWork.commit(AbstractUnitOfWork.java:71) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.DefaultUnitOfWork.executeWithResult(DefaultUnitOfWork.java:92) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.messaging.unitofwork.UnitOfWork.executeWithResult(UnitOfWork.java:328) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    at org.axonframework.deadline.quartz.DeadlineJob.execute(DeadlineJob.java:134) ~[axon-messaging-4.3.3.jar!/:4.3.3]
    ... 2 common frames omitted

I decided to debug and spend a few hours trying to narrow down the issue. I realized that somehow outside of my codebase (likely Axon magic), the StdScheduler.getContext().get(DeadlineJob.TRANSACTION_MANAGER_KEY) gets overridden.

Here are 2 screenshots that highlight the issue:

As you can see, the instance number of StdScheduler 13137 contains the SpringTransactionManager during initialize().

When I add the breakpoint straight on my scheduling line, here is the screenshot:

Instance of StdScheduler is still 13137, and the QuartzDeadlineManager.transactionManager still contains an instance of SpringTransactionManager. But the StdScheduler.getContext().get(DeadlineJob.TRANSACTION_MANAGER_KEY) now contains a NoTransactionManager instance, which then causes my execution to break due to a TransactionRequiredException.

Did anyone experience this scenario? How was it mitigated? Right now I'm traversing through all Axon code in an attempt to understand where the instance gets swapped.

Thanks,

Body:
I ended up figuring it out the issue.
In my AxonConfiguration class, the method for EventScheduler was left there in case we had to revert or use that scheduler in a near future.
The EventScheduler was defined as this:

    @Bean
    public QuartzEventSchedulerFactoryBean eventScheduler() {
        return new QuartzEventSchedulerFactoryBean();
    }

As the QuartzEventScheduler was created by the FactoryBean, it was pulling the StdScheduler from the ApplicationContext, and assigning the relevant variables all over again. Since I had no customized TransactionManager, the default (NoTransactionManager) was being assigned to the QuartzEventScheduler, which then changes the QuartzScheduler context, causing the issue.

To fix that, I expanded my Bean to the following:

    @Bean
    public QuartzEventSchedulerFactoryBean eventScheduler(
        final ApplicationContext applicationContext,
        @Qualifier("eventStore") final EventBus eventBus,
        final Scheduler scheduler,
        final PlatformTransactionManager transactionManager
    ) {
        final QuartzEventSchedulerFactoryBean factoryBean = new QuartzEventSchedulerFactoryBean();

        factoryBean.setApplicationContext(applicationContext);
        factoryBean.setEventBus(eventBus);
        factoryBean.setScheduler(scheduler);
        factoryBean.setTransactionManager(transactionManager);
        factoryBean.setTransactionDefinition(new DefaultTransactionDefinition());

        return factoryBean;
    }

Here is my ask for the Axon team:

The QuartzEventScheduler(FactoryBean) requires the underlying PlatformTransactionManager, and creates a new SpringTransactionManager to assign. It would be much easier if they kept the same approach as QuartzDeadlineManager, using directly an autowired TransactionManager, instead of handling the instantiation internally (and replacing the axon-spring-autoconfigure created one).


来源: stackexchange

问:
z3 extracting Seq Int as std::vector<int>
I'm trying to extract a Seq Int from a model to a std::vector<int>.
I can print it with << but how can I do the extraction?

```<code>void oren_example()
{
    // context + solver
    context ctx;
    solver solver(ctx);

    // sorts
    sort int_sort     = ctx.int_sort();
    sort seq_int_sort = ctx.seq_sort(int_sort);
    sort bool_sort    = ctx.bool_sort();

    // constants
    expr two   = ctx.int_val(2);
    expr five  = ctx.int_val(5);
    expr four  = ctx.int_val(4);
    expr three = ctx.int_val(3);

    // define State sort
    const char *names[4]={"x","A","b","n"};
    sort sorts[4]={int_sort,seq_int_sort,bool_sort,int_sort};
    func_decl_vector projs(ctx);
    sort state_sort = ctx.tuple_sort("State",4,names,sorts,projs).range();

    // define an arbitrary state sigma
    expr sigma = ctx.constant("sigma",state_sort);

    // define some predicate on the state
    func_decl init = function("init",state_sort,bool_sort);
    solver.add(forall(sigma,
        init(sigma) == (
            ((projs[0](sigma))          == two  ) &&
            ((projs[1](sigma).length()) == three) &&
            ((projs[1](sigma).nth(two)) == five ) &&
            ((projs[3](sigma))          == five ))));

    // find an initial state
    solver.add(init(sigma));

    // check sat + get model
    if (solver.check() == sat)
    {
        model m = solver.get_model();
        std::cout << "x = " << m.eval(projs[0](sigma)) << "\n";
        std::cout << "A = " << m.eval(projs[1](sigma)) << "\n";
        std::cout << "b = " << m.eval(projs[2](sigma)) << "\n";
        std::cout << "n = " << m.eval(projs[3](sigma)) << "\n";
    }
}
</code>```

Everything is printed out as expected:

```<code>x = 2
A = (seq.++ (seq.unit 6) (seq.unit 7) (seq.unit 5))
b = false
n = 5
</code>```

答:
Try:

```<code>        std::vector<int> output;
        int size = m.eval(projs[1](sigma).length()).get_numeral_int();
        std::cout << "size = " << size << std::endl;
        for(int i = 0; i < size; ++i)
            output.push_back(m.eval(projs[1](sigma).nth(ctx.int_val(i))).get_numeral_int());
        for(int i = 0; i < size; ++i)
            std::cout << "output[" << i << "] = " << output[i] << std::endl;
</code>```

When I add this to your program and I run it, I get:

```<code>x = 2
A = (seq.++ (seq.unit 4) (seq.unit 6) (seq.unit 5))
b = false
n = 5
size = 3
output[0] = 4
output[1] = 6
output[2] = 5
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to extract a Seq Int from a model to a std::vector<int>.
I can print it with << but how can I do the extraction?

void oren_example()
{
    // context + solver
    context ctx;
    solver solver(ctx);

    // sorts
    sort int_sort     = ctx.int_sort();
    sort seq_int_sort = ctx.seq_sort(int_sort);
    sort bool_sort    = ctx.bool_sort();

    // constants
    expr two   = ctx.int_val(2);
    expr five  = ctx.int_val(5);
    expr four  = ctx.int_val(4);
    expr three = ctx.int_val(3);

    // define State sort
    const char *names[4]={"x","A","b","n"};
    sort sorts[4]={int_sort,seq_int_sort,bool_sort,int_sort};
    func_decl_vector projs(ctx);
    sort state_sort = ctx.tuple_sort("State",4,names,sorts,projs).range();

    // define an arbitrary state sigma
    expr sigma = ctx.constant("sigma",state_sort);

    // define some predicate on the state
    func_decl init = function("init",state_sort,bool_sort);
    solver.add(forall(sigma,
        init(sigma) == (
            ((projs[0](sigma))          == two  ) &&
            ((projs[1](sigma).length()) == three) &&
            ((projs[1](sigma).nth(two)) == five ) &&
            ((projs[3](sigma))          == five ))));

    // find an initial state
    solver.add(init(sigma));

    // check sat + get model
    if (solver.check() == sat)
    {
        model m = solver.get_model();
        std::cout << "x = " << m.eval(projs[0](sigma)) << "\n";
        std::cout << "A = " << m.eval(projs[1](sigma)) << "\n";
        std::cout << "b = " << m.eval(projs[2](sigma)) << "\n";
        std::cout << "n = " << m.eval(projs[3](sigma)) << "\n";
    }
}

Everything is printed out as expected:

x = 2
A = (seq.++ (seq.unit 6) (seq.unit 7) (seq.unit 5))
b = false
n = 5

Body:
Try:

        std::vector<int> output;
        int size = m.eval(projs[1](sigma).length()).get_numeral_int();
        std::cout << "size = " << size << std::endl;
        for(int i = 0; i < size; ++i)
            output.push_back(m.eval(projs[1](sigma).nth(ctx.int_val(i))).get_numeral_int());
        for(int i = 0; i < size; ++i)
            std::cout << "output[" << i << "] = " << output[i] << std::endl;

When I add this to your program and I run it, I get:

x = 2
A = (seq.++ (seq.unit 4) (seq.unit 6) (seq.unit 5))
b = false
n = 5
size = 3
output[0] = 4
output[1] = 6
output[2] = 5


问:
filtering a dataframe, present rows depending on the value of certain columns
I have the following type of dataframe and I want to leave only rows where columns that are named 'Model' are equal to 'BUY' or 'SELL'

Input:

```<code>          Date Ticker IssuerTier     Action  ... ModelG1 ModelG2  ModelG3  ModelG4
0   2020-05-28   AAPL       gold       None  ...   STAND   STAND    STAND    STAND
1   2020-05-28   ABBV       gold  reiterate  ...   STAND   STAND    STAND    STAND
2   2020-05-28   ABMD   standard       None  ...   STAND   STAND    SELL     STAND
3   2020-05-28   ACAD       gold       None  ...   BUY     STAND    STAND    STAND
4   2020-05-28   ADSK   standard       None  ...   STAND   STAND    STAND    STAND
..         ...    ...        ...        ...  ...     ...     ...      ...      ...
130 2020-05-28    WEX       gold       None  ...   STAND   STAND    STAND    STAND
131 2020-05-28   WYNN       gold       None  ...   STAND   STAND    STAND    STAND
132 2020-05-28    ZEN       gold       None  ...   BUY     STAND    STAND    STAND
133 2020-05-28    ZEN       gold  reiterate  ...   STAND   STAND    STAND    STAND
134 2020-05-28    ZEN     silver       None  ...   STAND   STAND    STAND    STAND

[135 rows x 58 columns]
</code>```

Output:

```<code>          Date Ticker IssuerTier     Action  ... ModelG1 ModelG2  ModelG3  ModelG4

2   2020-05-28   ABMD   standard       None  ...   STAND   STAND    SELL     STAND
3   2020-05-28   ACAD       gold       None  ...   BUY     STAND    STAND    STAND
132 2020-05-28    ZEN       gold       None  ...   BUY     STAND    STAND    STAND
</code>```

I tried using the following masks but I've gotten NaNs on all my dataframe for some reason:

```<code>mask1 = signals.loc[:, 'ModelA1':] == 'BUY'
mask2 = signals.loc[:, 'ModelA1':] == 'SELL'
signals = signals[mask1 & mask2]
</code>```

The model columns go from A1, A2, A3, A4... to G1, G2, G3, G4.

Thanks for the help!

答:
Could you give this a shot?

cols_to_check = list(filter(lambda col : col.startswith('Model'), df.columns))

def should_allow(row):
    return all(map(lambda col : row[col] in ('BUY', 'SELL'), cols_to_check))

df = df[df.apply(should_allow, axis=1)]
print(df)
```

Body:
I have the following type of dataframe and I want to leave only rows where columns that are named 'Model' are equal to 'BUY' or 'SELL'

Input:

          Date Ticker IssuerTier     Action  ... ModelG1 ModelG2  ModelG3  ModelG4
0   2020-05-28   AAPL       gold       None  ...   STAND   STAND    STAND    STAND
1   2020-05-28   ABBV       gold  reiterate  ...   STAND   STAND    STAND    STAND
2   2020-05-28   ABMD   standard       None  ...   STAND   STAND    SELL     STAND
3   2020-05-28   ACAD       gold       None  ...   BUY     STAND    STAND    STAND
4   2020-05-28   ADSK   standard       None  ...   STAND   STAND    STAND    STAND
..         ...    ...        ...        ...  ...     ...     ...      ...      ...
130 2020-05-28    WEX       gold       None  ...   STAND   STAND    STAND    STAND
131 2020-05-28   WYNN       gold       None  ...   STAND   STAND    STAND    STAND
132 2020-05-28    ZEN       gold       None  ...   BUY     STAND    STAND    STAND
133 2020-05-28    ZEN       gold  reiterate  ...   STAND   STAND    STAND    STAND
134 2020-05-28    ZEN     silver       None  ...   STAND   STAND    STAND    STAND

[135 rows x 58 columns]

Output:

          Date Ticker IssuerTier     Action  ... ModelG1 ModelG2  ModelG3  ModelG4

2   2020-05-28   ABMD   standard       None  ...   STAND   STAND    SELL     STAND
3   2020-05-28   ACAD       gold       None  ...   BUY     STAND    STAND    STAND
132 2020-05-28    ZEN       gold       None  ...   BUY     STAND    STAND    STAND

I tried using the following masks but I've gotten NaNs on all my dataframe for some reason:

mask1 = signals.loc[:, 'ModelA1':] == 'BUY'
mask2 = signals.loc[:, 'ModelA1':] == 'SELL'
signals = signals[mask1 & mask2]

The model columns go from A1, A2, A3, A4... to G1, G2, G3, G4.

Thanks for the help!


问:
Execution time of very short function
I am required to display the execution time of some searching algorithms. However, when I use start/end_t = clock(), it always displays 0.00000 due to low precision (even with double-type)

Please tell me how to display those running times.

```<code>int LinearSearch (int M[], int target, int size)
{
int k = 0;
for (k=0; k<size; k++)
{
    if(M[k]==target)
    {
        return k;
    }
    //else return -1;
}
}

 int LinearSentinelSearch (int M[],int target, int size)
{
int k = 0;
M[size]=target;
while (M[k] != target)
    k++;
return k;
}

int binSearch(int List[], int Target, int Size)
{
int Mid;
int low = 0;
int high = Size -1;
int count=0;
int a;

while( low <= high)
{
    Mid = (low + high) / 2;

    if(List[Mid] == Target) return Mid;

    else if( Target < List[Mid] )
        high = Mid - 1;
    else
        low = Mid + 1;
}
return -1;

}
</code>```

答:
You can calculate the mean execution time by simply executing the algorithm multiple times N and then divide the total time by N. Using your binSearch as an example:

```<code>int i;
clock_t start, end;

start = clock();
for (i = 0 ; i < 1000 ; i++) {
    binSearch(/* your actual parameters here */);
}
end = clock();

printf("Mean ticks to execute binSearch: %f\n", (end - start) / 1000.0);
</code>```

Title: Execution time of very short function

Body:
I am required to display the execution time of some searching algorithms. However, when I use start/end_t = clock(), it always displays 0.00000 due to low precision (even with double-type)

Please tell me how to display those running times.

int LinearSearch (int M[], int target, int size)
{
int k = 0;
for (k=0; k<size; k++)
{
    if(M[k]==target)
    {
        return k;
    }
    //else return -1;
}
}

 int LinearSentinelSearch (int M[],int target, int size)
{
int k = 0;
M[size]=target;
while (M[k] != target)
    k++;
return k;
}

int binSearch(int List[], int Target, int Size)
{
int Mid;
int low = 0;
int high = Size -1;
int count=0;
int a;

while( low <= high)
{
    Mid = (low + high) / 2;

    if(List[Mid] == Target) return Mid;

    else if( Target < List[Mid] )
        high = Mid - 1;
    else
        low = Mid + 1;
}
return -1;

}

Body:
You can calculate the mean execution time by simply executing the algorithm multiple times N and then divide the total time by N. Using your binSearch as an example:

int i;
clock_t start, end;

start = clock();
for (i = 0 ; i < 1000 ; i++) {
    binSearch(/* your actual parameters here */);
}
end = clock();

printf("Mean ticks to execute binSearch: %f\n", (end - start) / 1000.0);


问:
Why am I not able to import TFLearn?
I'm trying to import TFLearn with this simple code:

```<code>import tflearn
</code>```

But I'm getting the following error:

```<code>AttributeError: module 'tensorflow.python.framework.ops' has no attribute 'RegisterShape'
</code>```

I've got installed the following versions of programs:

Python 3.7.6 64 bit
Tensorflow 2.1.0
TFlearn 0.3.2

答:
This question is answered here:
AttributeError: module 'tensorflow.python.framework.ops' has no attribute 'RegisterShape'

Maybe you can find help there.

Title: Why am I not able to import TFLearn?

Body:
I'm trying to import TFLearn with this simple code:

import tflearn

But I'm getting the following error:

AttributeError: module 'tensorflow.python.framework.ops' has no attribute 'RegisterShape'

I've got installed the following versions of programs:

Python 3.7.6 64 bit
Tensorflow 2.1.0
TFlearn 0.3.2


问:
How to apply a single style to the selected element within an *ngFor?
within my angular application, I'm going through the following array of objects to display my elements on the screen

```<code>[{
  "name": "Equipment",
  "functional_id": "furniture",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "White bags",
      "description": "Reusable",
      "id": 11,
      "path": "",
      "items": [
        {
          "name": "Small model",
          "description": "25",
          "price": 0,
          "functional_id": "white_bags_small_model_by_25"
        },
        {
          "name": "Medium model",
          "description": "20",
          "price": 0,
          "functional_id": "white_bags_medium_model_by_20"
        },
        {
          "name": "Large model",
          "description": "10",
          "price": 0,
          "functional_id": "white_bags_large_model_by_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Burgundy bags",
      "description": "Reusable",
      "id": 12,
      "path": "",
      "items": [
        {
          "name": "Small model",
          "description": "25",
          "price": 0,
          "functional_id": "bags_burgundy_bags_small_model_by_10"
        },
        {
          "name": "Large model",
          "description": "Par 10",
          "price": 0,
          "functional_id": "bags_burgundy_bags_large_model_by_10"
        }
      ]
    }
  ],
  "sorting": 2300"
},
{
  "name": "Documents",
  "functional_id": "docs",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Book of conventions",
      "id": 17,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "agreement_book"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Procedure posters",
      "description": "Procedure",
      "id": 18,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "posters_procedure_of_taking_in_charge"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Services Brochures",
      "description": "Brochures",
      "id": 19,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "services_brochures"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue"
        }
      ]
    }
  ],
  "sorting": 2400
},
{
  "name": "Products",
  "functional_id": "prods",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Articles",
      "id": 19,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "book_1"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Procedure_b",
      "description": "Procedure",
      "id": 24,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "book_charge"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Book Services",
      "description": "Book Services",
      "id": 26,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "book_services"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue",
      "id": 32,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue"
        }
      ]
    }
  ],
  "sorting": 4400
}
]
</code>```

I get to the next point where I paint the following button for each type of product and I want to apply a class to only the one selected. I set the following in my html:

```<code>            <div class='child'>
              <div>
                <ul class='p-0 m-0'>
                  <li *ngFor='let item of product.items; let i = index'>
                    <button class='cart' [ngClass]="{'in-row': i === product.items.length - 1}" (click)='this.updateCart()'><i class='icon-addcart'></i></button>
                  </li>
                </ul>
              </div>
            </div>

</code>```

according to this code the class 'in-row' is being applied to all buttons, when it should only be applied to the selected ones

I'm kind of new at using an angle and I don't really understand what I'm doing wrong. Someone who can give me an idea of what I'm doing wrong?
Thank you in advance.

答:
You need to applay css to the product with a current id:

https://stackblitz.com/edit/stackoverflow-active-product-button

```

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',,
      styles: ['.in-row {    background: red;  }   ']
    })

    export class AppComponent {
      title = 'final';

      products = [
        { id: 1, name: 'product1' },
        { id: 2, name: 'product2' },
        { id: 3, name: 'product3' },
      ]

      selectedItem: any;
      updateCart(id: number) {
        this.selectedItem = id;
      }
    }

```

  <button class='cart' [ngClass]="{'in-row': selectedItem == item.id}" (click)='updateCart(item.id)'>button {{ i }}</button>

```

Body:
within my angular application, I'm going through the following array of objects to display my elements on the screen

[{
  "name": "Equipment",
  "functional_id": "furniture",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "White bags",
      "description": "Reusable",
      "id": 11,
      "path": "",
      "items": [
        {
          "name": "Small model",
          "description": "25",
          "price": 0,
          "functional_id": "white_bags_small_model_by_25"
        },
        {
          "name": "Medium model",
          "description": "20",
          "price": 0,
          "functional_id": "white_bags_medium_model_by_20"
        },
        {
          "name": "Large model",
          "description": "10",
          "price": 0,
          "functional_id": "white_bags_large_model_by_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Burgundy bags",
      "description": "Reusable",
      "id": 12,
      "path": "",
      "items": [
        {
          "name": "Small model",
          "description": "25",
          "price": 0,
          "functional_id": "bags_burgundy_bags_small_model_by_10"
        },
        {
          "name": "Large model",
          "description": "Par 10",
          "price": 0,
          "functional_id": "bags_burgundy_bags_large_model_by_10"
        }
      ]
    }
  ],
  "sorting": 2300"
},
{
  "name": "Documents",
  "functional_id": "docs",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Book of conventions",
      "id": 17,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "agreement_book"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Procedure posters",
      "description": "Procedure",
      "id": 18,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "posters_procedure_of_taking_in_charge"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Services Brochures",
      "description": "Brochures",
      "id": 19,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "services_brochures"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue"
        }
      ]
    }
  ],
  "sorting": 2400
},
{
  "name": "Products",
  "functional_id": "prods",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Articles",
      "id": 19,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "book_1"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Procedure_b",
      "description": "Procedure",
      "id": 24,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "book_charge"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Book Services",
      "description": "Book Services",
      "id": 26,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "book_services"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue",
      "id": 32,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue"
        }
      ]
    }
  ],
  "sorting": 4400
}
]

I get to the next point where I paint the following button for each type of product and I want to apply a class to only the one selected. I set the following in my html:

                    <button class='cart' [ngClass]="{'in-row': i === product.items.length - 1}" (click)='this.updateCart()'></button>

according to this code the class 'in-row' is being applied to all buttons, when it should only be applied to the selected ones

I'm kind of new at using an angle and I don't really understand what I'm doing wrong. Someone who can give me an idea of what I'm doing wrong?
Thank you in advance.

Body:
You need to applay css to the product with a current id:

https://stackblitz.com/edit/stackoverflow-active-product-button

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',,
      styles: ['.in-row {    background: red;  }   ']
    })

    export class AppComponent {
      title = 'final';

      products = [
        { id: 1, name: 'product1' },
        { id: 2, name: 'product2' },
        { id: 3, name: 'product3' },
      ]

      selectedItem: any;
      updateCart(id: number) {
        this.selectedItem = id;
      }
    }

<li *ngFor='let item of products; let i = index'>
  <button class='cart' [ngClass]="{'in-row': selectedItem == item.id}" (click)='updateCart(item.id)'><i
          class='icon-addcart'></i>button {{ i }}</button>
</li>


问:
Unity clamped UI Image is shaking
I am using the followng script to clamp the UI Image to the player in 2D game, but when the player is moving, the image is shaking a little. What am I doing wrong?</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthBarClamp : MonoBehaviour
{

    public Transform targetToFollow;
    Transform thisTransform;

    void Start()
    {
        thisTransform = transform;
    }

    void Update()
    {
        thisTransform.position = new Vector3(targetToFollow.position.x,
            targetToFollow.position.y + 1.5f, thisTransform.position.z);
    }
}
</code>```

答:
If you're moving the target object around using physics or in FixedUpdate, then you'll need to move the camera around in FixedUpdate as well. Update happens every frame, fast or slow, whereas FixedUpdate is simulated to happen at consistent intervals to help keep physics calculations from going nuts. If you move the camera in Update and the target in FixedUpdate, then you'll end up with tiny differences that look like shaking.

(Or you can follow the advice given in the comments. It works perfectly fine to make a UI element a child of the moving object, although I personally prefer to do it the way you had it originally because it makes things like "smooth" camera movement easier.)

Title: Unity clamped UI Image is shaking

Body:
I am using the followng script to clamp the UI Image to the player in 2D game, but when the player is moving, the image is shaking a little. What am I doing wrong?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthBarClamp : MonoBehaviour
{

    public Transform targetToFollow;
    Transform thisTransform;

    void Start()
    {
        thisTransform = transform;
    }

    void Update()
    {
        thisTransform.position = new Vector3(targetToFollow.position.x,
            targetToFollow.position.y + 1.5f, thisTransform.position.z);
    }
}


问:
Kubernetes kubeadm reset error - unable to reset
I initialized k8 using kubeadm and now when I try to reset using kubeadm reset , am getting the following error. I searched for several forums but couldn't find any answers

```<code>> "level":"warn","ts":"2020-05-28T11:57:52.940+0200","caller":"clientv3/retry_interceptor.go:61","msg":"retrying
> o
> f unary invoker
> failed","target":"endpoint://client-e6d5f25b-0ed2-400f-b4d7-2ccabb09a838/192.168.178.200:2379","a
> ttempt":0,"error":"rpc error: code = Unknown desc = etcdserver:
> re-configuration failed due to not enough started
> members"}
</code>```

The master node status is showing as not ready and I have not been able to reset the network plugin (weave)

```<code>  ubuntu@ubuntu-nuc-masternode:~$ kubectl get nodes
NAME         STATUS                        ROLES    AGE   VERSION
ubuntu-nuc   NotReady,SchedulingDisabled   master   20h   v1.18.3
</code>```

I tried forcing reset but hasn't worked. Any help is much appreciated

答:
This seems to be reported issue kubeadm reset takes more than 50 seconds to retry deleting the last etcd member which was moved here.

Fix was committed kubeadm: skip removing last etcd member in reset phase on May 28th.

What type of PR is this?

  /kind bug

What this PR does / why we need it:

  If this is the last etcd member of the cluster, it cannot be removed due to "not enough started members". Skip it as the cluster will be destroyed in the next phase, otherwise the retries with exponential backoff will take more than 50 seconds to proceed.

Which issue(s) this PR fixes:

Fixes  kubernetes/kubeadm#2144

Special notes for your reviewer:

Does this PR introduce a user-facing change?:

```<code>kubeadm: during "reset" do not remove the only remaining stacked etcd member from the cluster and just proceed with the cleanup of the local etcd storage.
</code>```

Body:
I initialized k8 using kubeadm and now when I try to reset using kubeadm reset , am getting the following error. I searched for several forums but couldn't find any answers

> "level":"warn","ts":"2020-05-28T11:57:52.940+0200","caller":"clientv3/retry_interceptor.go:61","msg":"retrying
> o
> f unary invoker
> failed","target":"endpoint://client-e6d5f25b-0ed2-400f-b4d7-2ccabb09a838/192.168.178.200:2379","a
> ttempt":0,"error":"rpc error: code = Unknown desc = etcdserver:
> re-configuration failed due to not enough started
> members"}

The master node status is showing as not ready and I have not been able to reset the network plugin (weave)

  ubuntu@ubuntu-nuc-masternode:~$ kubectl get nodes
NAME         STATUS                        ROLES    AGE   VERSION
ubuntu-nuc   NotReady,SchedulingDisabled   master   20h   v1.18.3

I tried forcing reset but hasn't worked. Any help is much appreciated

Body:
This seems to be reported issue kubeadm reset takes more than 50 seconds to retry deleting the last etcd member which was moved here.

Fix was committed kubeadm: skip removing last etcd member in reset phase on May 28th.

What type of PR is this?

  /kind bug

What this PR does / why we need it:

  If this is the last etcd member of the cluster, it cannot be removed due to "not enough started members". Skip it as the cluster will be destroyed in the next phase, otherwise the retries with exponential backoff will take more than 50 seconds to proceed.

Which issue(s) this PR fixes:

Fixes  kubernetes/kubeadm#2144

Special notes for your reviewer:

Does this PR introduce a user-facing change?:

kubeadm: during "reset" do not remove the only remaining stacked etcd member from the cluster and just proceed with the cleanup of the local etcd storage.


问:
How can I find() a resource passed to a sidekiq worker?
Basically, I have a block of code that needs to be executed inside a sidekiq worker, which will interact over a resource passed as argument (maybe). This resource is a Rails model.

Differently from other questions on SO related to passing arguments to a worker, here I don't know if it will be a User or a House model. So I can't simply use MyWorker.perform(user_id), since I don't know which model id I'll be passing as argument.

Also, I read that I can't simply expect to pass my model object to a sidekiq worker and receive it on the other side, once it'll transform it to json.

So what I had in mind, was something like this:

```<code># somewhere_in_my_code.rb

MyWorker.perform(resource.id, resource_model) # still don't know what this resource_model would be

# my_worker.rb

def perform(resource_id, resource_model)
  model = some_magic_method_to_return_a_model(resource_model)
  resource = model.find(resource_id)

  # do what I have to do with the resource found
end
</code>```

But I really don't know if this some_magic_method_to_return_a_model exists. Or if that's even possible. Anyway, any help will be appreciated, thanks!

NOTE: I'm using Ruby 2.4.8, Rails 4.1.10, Sidekiq 4.1.0

答:
It does. Let's assume you have a User model:

```<code>> user = User.last
> id = user.id
> model_name = user.model_name.name
> model_name.safe_constantize.find(id)
> model_name.safe_constantize.find(id) == user
=> true
</code>```

This is basically how polymorphic associations work in Rails.

Body:
Basically, I have a block of code that needs to be executed inside a sidekiq worker, which will interact over a resource passed as argument (maybe). This resource is a Rails model.

Differently from other questions on SO related to passing arguments to a worker, here I don't know if it will be a User or a House model. So I can't simply use MyWorker.perform(user_id), since I don't know which model id I'll be passing as argument.

Also, I read that I can't simply expect to pass my model object to a sidekiq worker and receive it on the other side, once it'll transform it to json.

So what I had in mind, was something like this:

# somewhere_in_my_code.rb

MyWorker.perform(resource.id, resource_model) # still don't know what this resource_model would be

# my_worker.rb

def perform(resource_id, resource_model)
  model = some_magic_method_to_return_a_model(resource_model)
  resource = model.find(resource_id)

  # do what I have to do with the resource found
end

But I really don't know if this some_magic_method_to_return_a_model exists. Or if that's even possible. Anyway, any help will be appreciated, thanks!

NOTE: I'm using Ruby 2.4.8, Rails 4.1.10, Sidekiq 4.1.0

Body:
It does. Let's assume you have a User model:

> user = User.last
> id = user.id
> model_name = user.model_name.name
> model_name.safe_constantize.find(id)
> model_name.safe_constantize.find(id) == user
=> true

This is basically how polymorphic associations work in Rails.


问:
Difference between memcache, memcached and redis
We are currently using memcache for storing session data. I have heard that memcached or redis are better. I need to understand what is the difference between them? in order to understand which one is the best choice

答:
For your own use case I'd say Redis is better. Since you're using it to store user session data you probably have the need to perform operations on a single field of the session and for that the Redis hash data type is perfect.
You can find a very detailed comparison between them in this article: Redis VS Memcached: Which one to choose?</p>

ContentLicense: CC BY-SA 3.0


问:
Is there a tool to capture an objects state to disk?
What I would like to do is capture an object that's in memory to disk for testing purposes. Since it takes many steps to get to this state, I would like to capture it once and skip the steps.

I realize that I could mock these objects up manually but I'd rather "record" and "replay" real objects because I think this would be faster.

Edit: The question is regarding this entire process, not just the serialization of the object (also file operations) and my hope that a tool exists to do this process on standard objects.

I am interested in Actionscript specifically for this is application but...

Are there examples of this in other
programming languages?

What is this process commonly called?

How would this be done in
Actionscript?

Edit:

Are there tools that make serialization and file operations automatic (i.e. no special interfaces)?

Would anybody else find the proposed tool useful (if it doesn't exist)?

Use case of what I am thinking of:

```<code>ObjectSaver.save(objZombie,"zombie"); //save the object
var zombieClone:Zombie = ObjectSaver.get("zombie"); // get the object
</code>```

and the disk location being configurable somewhere.

答:
Check out the flash.utils.IExternalizable interface. It can be used to serialize ActionScript objects into a ByteArray. The resulting data could easily be written to disk or used to clone objects.

Note that this is not "automatic". You have to manually implement the interface and write the readExternal() and writeExternal() functions for each class you want to serialize. You'll be hard pressed to find a way to serialize custom classes "automatically" because private members are only accessible within the class itself. You'll need to make everything that you need serialized public if you want to create an external serialization method.

OwnerDisplayName: Brandon

ContentLicense: CC BY-SA 2.5

Body:
What I would like to do is capture an object that's in memory to disk for testing purposes. Since it takes many steps to get to this state, I would like to capture it once and skip the steps.

I realize that I could mock these objects up manually but I'd rather "record" and "replay" real objects because I think this would be faster.

Edit: The question is regarding this entire process, not just the serialization of the object (also file operations) and my hope that a tool exists to do this process on standard objects.

I am interested in Actionscript specifically for this is application but...

Are there examples of this in other
programming languages?

What is this process commonly called?

How would this be done in
Actionscript?

Edit:

Are there tools that make serialization and file operations automatic (i.e. no special interfaces)?

Would anybody else find the proposed tool useful (if it doesn't exist)?

Use case of what I am thinking of:

ObjectSaver.save(objZombie,"zombie"); //save the object
var zombieClone:Zombie = ObjectSaver.get("zombie"); // get the object

and the disk location being configurable somewhere.

LastEditorDisplayName: Brandon

OwnerDisplayName: joshtynjala


问:
IOS Core Audio - MP3 to WAV working only when 1 channel, how to get stereo?
Currently taking in an MP3 file spitting out a WAV. My code has worked fine for a while, but I now want to change it where the exported WAV is a 2-channel stereo file.

The problem lies here somewhere. This describes the desired output format.

This code below is what worked fine beforehand (mono):

```<code>AudioStreamBasicDescription outputFormat = new AudioStreamBasicDescription();
outputFormat.setFormat(AudioFormat.LinearPCM);
outputFormat.setFormatFlags(AudioFormatFlags.Canonical);
outputFormat.setBitsPerChannel(16);
outputFormat.setChannelsPerFrame(1);
outputFormat.setFramesPerPacket(1);
outputFormat.setBytesPerFrame(2);
outputFormat.setBytesPerPacket(2);
outputFormat.setSampleRate(pitch);
</code>```

Changing it to setChannelsPerFrame(2); didn't work. Not sure what else needs changing?

The error is:

```<code>Launcher[318:12909] 224: SetDataFormat failed
Launcher[318:12909] 367: EXCEPTION (1718449215): "create audio file"

org.robovm.apple.corefoundation.OSStatusException: 1718449215
at org.robovm.apple.corefoundation.OSStatusException.throwIfNecessary(OSStatusException.java:53)
at org.robovm.apple.audiotoolbox.ExtAudioFile.create(ExtAudioFile.java:80)
at package.Launcher.mp3ToPCM(Launcher.java:1108)
...
</code>```

Where the line in question is

outputFileExtAudio = ExtAudioFile.create(outputFileURL, AudioFileType.WAVE, outputFormat, null, AudioFileFlags.EraseFile);

But the problem must be stemming from my AudioStreamBasicDescription of the outputFormat, as that is the only thing changing to "2 channels" and suddenly it no longer works.

(This is Java code, utilizing RoboVM to convert to native IOS code.)

答:
You also need to update the sizes.

In Core Audio a sample is one single value and a frame is one sample across all channels. For PCM audio, a single frame is also a single packet.

For 16-bit mono audio, a frame and sample are synonymous and take up 2 bytes. For 16-bit stereo audio, a frame consists of two samples (left and right), with each sample taking up 2 bytes and each frame taking up 4 bytes.

The values of AudioStreamBasicDescription vary slightly on whether the format being described is interleaved or not.

You can generally think of non-interleaved PCM AudioStreamBasicDescriptions like this:

```<code>asbd.mBytesPerFrame     = asbd.mBitsPerChannel / 8;
</code>```

and interleaved like this:

```<code>asbd.mBytesPerFrame     = (asbd.mBitsPerChannel / 8) * asbd.mChannelsPerFrame;
</code>```

with both having

```<code>asbd.mFramesPerPacket   = 1;
asbd.mBytesPerPacket    = asbd.mBytesPerFrame;
</code>```

AudioFormatFlags.Canonical is deprecated but I assume here it equates to interleaved packed native-endian signed integers.

So for your case, interleaved 16-bit stereo is:

```<code>AudioStreamBasicDescription outputFormat = new AudioStreamBasicDescription();
outputFormat.setFormat(AudioFormat.LinearPCM);
outputFormat.setFormatFlags(AudioFormatFlags.Canonical);

outputFormat.setSampleRate(pitch);
outputFormat.setChannelsPerFrame(2);
outputFormat.setBitsPerChannel(16);

outputFormat.setBytesPerFrame(4);
outputFormat.setFramesPerPacket(1);
outputFormat.setBytesPerPacket(4);
</code>```

Here are two helper functions (in C++) showing the relationships:

```<code>static AudioFormatFlags CalculateLPCMFlags(UInt32 validBitsPerChannel, UInt32 totalBitsPerChannel, bool isFloat, bool isBigEndian, bool isNonInterleaved)
{
    return (isFloat ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger) | (isBigEndian ? ((UInt32)kAudioFormatFlagIsBigEndian) : 0) | ((validBitsPerChannel == totalBitsPerChannel) ? kAudioFormatFlagIsPacked : kAudioFormatFlagIsAlignedHigh) | (isNonInterleaved ? ((UInt32)kAudioFormatFlagIsNonInterleaved) : 0);
}

static void FillOutASBDForLPCM(AudioStreamBasicDescription *asbd, Float64 sampleRate, UInt32 channelsPerFrame, UInt32 validBitsPerChannel, UInt32 totalBitsPerChannel, bool isFloat, bool isBigEndian, bool isNonInterleaved)
{
    asbd->mFormatID = kAudioFormatLinearPCM;
    asbd->mFormatFlags = CalculateLPCMFlags(validBitsPerChannel, totalBitsPerChannel, isFloat, isBigEndian, isNonInterleaved);

    asbd->mSampleRate = sampleRate;
    asbd->mChannelsPerFrame = channelsPerFrame;
    asbd->mBitsPerChannel = validBitsPerChannel;

    asbd->mBytesPerPacket = (isNonInterleaved ? 1 : channelsPerFrame) * (totalBitsPerChannel / 8);
    asbd->mFramesPerPacket = 1;
    asbd->mBytesPerFrame = (isNonInterleaved ? 1 : channelsPerFrame) * (totalBitsPerChannel / 8);
}
</code>```

Body:
Currently taking in an MP3 file spitting out a WAV. My code has worked fine for a while, but I now want to change it where the exported WAV is a 2-channel stereo file.

The problem lies here somewhere. This describes the desired output format.

This code below is what worked fine beforehand (mono):

AudioStreamBasicDescription outputFormat = new AudioStreamBasicDescription();
outputFormat.setFormat(AudioFormat.LinearPCM);
outputFormat.setFormatFlags(AudioFormatFlags.Canonical);
outputFormat.setBitsPerChannel(16);
outputFormat.setChannelsPerFrame(1);
outputFormat.setFramesPerPacket(1);
outputFormat.setBytesPerFrame(2);
outputFormat.setBytesPerPacket(2);
outputFormat.setSampleRate(pitch);

Changing it to setChannelsPerFrame(2); didn't work. Not sure what else needs changing?

The error is:

Launcher[318:12909] 224: SetDataFormat failed
Launcher[318:12909] 367: EXCEPTION (1718449215): "create audio file"

org.robovm.apple.corefoundation.OSStatusException: 1718449215
at org.robovm.apple.corefoundation.OSStatusException.throwIfNecessary(OSStatusException.java:53)
at org.robovm.apple.audiotoolbox.ExtAudioFile.create(ExtAudioFile.java:80)
at package.Launcher.mp3ToPCM(Launcher.java:1108)
...

Where the line in question is

outputFileExtAudio = ExtAudioFile.create(outputFileURL, AudioFileType.WAVE, outputFormat, null, AudioFileFlags.EraseFile);

But the problem must be stemming from my AudioStreamBasicDescription of the outputFormat, as that is the only thing changing to "2 channels" and suddenly it no longer works.

(This is Java code, utilizing RoboVM to convert to native IOS code.)

Body:
You also need to update the sizes.

In Core Audio a sample is one single value and a frame is one sample across all channels. For PCM audio, a single frame is also a single packet.

For 16-bit mono audio, a frame and sample are synonymous and take up 2 bytes. For 16-bit stereo audio, a frame consists of two samples (left and right), with each sample taking up 2 bytes and each frame taking up 4 bytes.

The values of AudioStreamBasicDescription vary slightly on whether the format being described is interleaved or not.

You can generally think of non-interleaved PCM AudioStreamBasicDescriptions like this:

asbd.mBytesPerFrame     = asbd.mBitsPerChannel / 8;

and interleaved like this:

asbd.mBytesPerFrame     = (asbd.mBitsPerChannel / 8) * asbd.mChannelsPerFrame;

with both having

asbd.mFramesPerPacket   = 1;
asbd.mBytesPerPacket    = asbd.mBytesPerFrame;

AudioFormatFlags.Canonical is deprecated but I assume here it equates to interleaved packed native-endian signed integers.

So for your case, interleaved 16-bit stereo is:

AudioStreamBasicDescription outputFormat = new AudioStreamBasicDescription();
outputFormat.setFormat(AudioFormat.LinearPCM);
outputFormat.setFormatFlags(AudioFormatFlags.Canonical);

outputFormat.setSampleRate(pitch);
outputFormat.setChannelsPerFrame(2);
outputFormat.setBitsPerChannel(16);

outputFormat.setBytesPerFrame(4);
outputFormat.setFramesPerPacket(1);
outputFormat.setBytesPerPacket(4);

Here are two helper functions (in C++) showing the relationships:

static AudioFormatFlags CalculateLPCMFlags(UInt32 validBitsPerChannel, UInt32 totalBitsPerChannel, bool isFloat, bool isBigEndian, bool isNonInterleaved)
{
    return (isFloat ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger) | (isBigEndian ? ((UInt32)kAudioFormatFlagIsBigEndian) : 0) | ((validBitsPerChannel == totalBitsPerChannel) ? kAudioFormatFlagIsPacked : kAudioFormatFlagIsAlignedHigh) | (isNonInterleaved ? ((UInt32)kAudioFormatFlagIsNonInterleaved) : 0);
}

static void FillOutASBDForLPCM(AudioStreamBasicDescription *asbd, Float64 sampleRate, UInt32 channelsPerFrame, UInt32 validBitsPerChannel, UInt32 totalBitsPerChannel, bool isFloat, bool isBigEndian, bool isNonInterleaved)
{
    asbd->mFormatID = kAudioFormatLinearPCM;
    asbd->mFormatFlags = CalculateLPCMFlags(validBitsPerChannel, totalBitsPerChannel, isFloat, isBigEndian, isNonInterleaved);

    asbd->mSampleRate = sampleRate;
    asbd->mChannelsPerFrame = channelsPerFrame;
    asbd->mBitsPerChannel = validBitsPerChannel;

    asbd->mBytesPerPacket = (isNonInterleaved ? 1 : channelsPerFrame) * (totalBitsPerChannel / 8);
    asbd->mFramesPerPacket = 1;
    asbd->mBytesPerFrame = (isNonInterleaved ? 1 : channelsPerFrame) * (totalBitsPerChannel / 8);
}


问:
Xcode 11.1 SwiftUI Preview failing
I receive this error whenever I try to preview a freshly created swiftui view.

messageRepliedWithError("Connecting to launched interactive agent 9297", Optional(Error Domain=com.apple.dt.ultraviolet.service Code=17 "connectToPreviewHost: Failed to connect to 9297: Error Domain=com.apple.dt.ProcessAttachUtilities Code=3 "Target process 9297 exited prematurely, likely crashed" UserInfo={NSLocalizedDescription=Target process 9297 exited prematurely, likely crashed}" UserInfo={NSLocalizedDescription=connectToPreviewHost: Failed to connect to 9297: Error Domain=com.apple.dt.ProcessAttachUtilities Code=3 "Target process 9297 exited prematurely, likely crashed" UserInfo={NSLocalizedDescription=Target process 9297 exited prematurely, likely crashed}}))

I have no idea how to fix this so I can see previews again.  I am on the latest Catalina 10.15.1

答: Turning off the thread sanitizer worked for me (I was just playing around with settings against another project that worked), so there's one more thing to try...</p>

Title: Xcode 11.1 SwiftUI Preview failing


问:
aspNetCore 2.2.0 - AspNetCoreModuleV2 error
After updating my project to "Microsoft.AspNetCore.All" 2.2.0, I get an error when running in IIS, but not when running in Visual Studio.

HTTP-Fehler 500.21 - Internal Server Error
Der Handler "aspNetCore" weist das ungültige Modul "AspNetCoreModuleV2" in der Modulliste auf.

I don't know what is causing this and the www does not seem to have an answer.
Maybe someone facing the same thing and has a solution

答: Not an answer, but an important and critical component of all the answers here. MAKE SURE YOU RESTART IIS after installing the modules needed.</p>


问:
How to use local docker images with Minikube?
I have several docker images that I want to use with minikube. I don't want to first have to upload and then download the same image instead of just using the local image directly. How do I do this?

Stuff I tried:

1. I tried running these commands (separately, deleting the instances of minikube both times and starting fresh)

```<code>kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989
kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989 imagePullPolicy=Never
</code>```

Output:

```<code>NAME                    READY     STATUS              RESTARTS   AGE
hdfs-2425930030-q0sdl   0/1       ContainerCreating   0          10m
</code>```

It just gets stuck on some status but never reaches the ready state.

2. I tried creating a registry and then putting images into it but that didn't work either. I might've done that incorrectly but I can't find proper instructions to do this task.

Please provide instructions to use local docker images in local kubernetes instance.

OS: ubuntu 16.04

Docker : Docker version 1.13.1, build 092cba3

Kubernetes :

```<code>Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.3", GitCommit:"029c3a408176b55c30846f0faedf56aae5992e9b", GitTreeState:"clean", BuildDate:"2017-02-15T06:40:50Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"08e099554f3c31f6e6f07b448ab3ed78d0520507", GitTreeState:"clean", BuildDate:"1970-01-01T00:00:00Z", GoVersion:"go1.7.1", Compiler:"gc", Platform:"linux/amd64"}
</code>```

If someone could help me get a solution that uses docker-compose to do this, that'd be awesome.

Edit:

Images loaded in eval $(minikube docker-env):

```<code>REPOSITORY                                            TAG                 IMAGE ID            CREATED             SIZE
fluxcapacitor/jupyterhub                              latest              e5175fb26522        4 weeks ago         9.59 GB
fluxcapacitor/zeppelin                                latest              fe4bc823e57d        4 weeks ago         4.12 GB
fluxcapacitor/prediction-pmml                         latest              cae5b2d9835b        4 weeks ago         973 MB
fluxcapacitor/scheduler-airflow                       latest              95adfd56f656        4 weeks ago         8.89 GB
fluxcapacitor/loadtest                                latest              6a777ab6167c        5 weeks ago         899 MB
fluxcapacitor/hdfs                                    latest              00fa0ed0064b        6 weeks ago         1.16 GB
fluxcapacitor/sql-mysql                               latest              804137671a8c        7 weeks ago         679 MB
fluxcapacitor/metastore-1.2.1                         latest              ea7ce8c5048f        7 weeks ago         1.35 GB
fluxcapacitor/cassandra                               latest              3cb5ff117283        7 weeks ago         953 MB
fluxcapacitor/apachespark-worker-2.0.1                latest              14ee3e4e337c        7 weeks ago         3.74 GB
fluxcapacitor/apachespark-master-2.0.1                latest              fe60b42d54e5        7 weeks ago         3.72 GB
fluxcapacitor/package-java-openjdk-1.8                latest              1db08965289d        7 weeks ago         841 MB
gcr.io/google_containers/kubernetes-dashboard-amd64   v1.5.1              1180413103fd        7 weeks ago         104 MB
fluxcapacitor/stream-kafka-0.10                       latest              f67750239f4d        2 months ago        1.14 GB
fluxcapacitor/pipeline                                latest              f6afd6c5745b        2 months ago        11.2 GB
gcr.io/google-containers/kube-addon-manager           v6.1                59e1315aa5ff        3 months ago        59.4 MB
gcr.io/google_containers/kubedns-amd64                1.9                 26cf1ed9b144        3 months ago        47 MB
gcr.io/google_containers/kube-dnsmasq-amd64           1.4                 3ec65756a89b        5 months ago        5.13 MB
gcr.io/google_containers/exechealthz-amd64            1.2                 93a43bfb39bf        5 months ago        8.37 MB
gcr.io/google_containers/pause-amd64
</code>```

答:
setup minikube docker-env

again build the same docker image (using minikube docker-env)

change imagePullPolicy to Never in your deployment

actually what happens here , your Minikube can't recognise your docker daemon as it is independent service.You have to first set your minikube-docker environment use below command to check

```<code> "eval $(minikube docker-env)"
</code>```

If you run below command it will show where your minikube looks for docker.

```<code>~$ minikube docker-env
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.37.192:2376"
export DOCKER_CERT_PATH="/home/ubuntu/.minikube/certs"
export MINIKUBE_ACTIVE_DOCKERD="minikube"

**# To point your shell to minikube's docker-daemon, run:**
# eval $(minikube -p minikube docker-env)
</code>```

You have to again build images once you setup minikube docker-env else it will fail.

Body:
I have several docker images that I want to use with minikube. I don't want to first have to upload and then download the same image instead of just using the local image directly. How do I do this?

Stuff I tried:

1. I tried running these commands (separately, deleting the instances of minikube both times and starting fresh)

kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989
kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989 imagePullPolicy=Never

Output:

NAME                    READY     STATUS              RESTARTS   AGE
hdfs-2425930030-q0sdl   0/1       ContainerCreating   0          10m

It just gets stuck on some status but never reaches the ready state.

2. I tried creating a registry and then putting images into it but that didn't work either. I might've done that incorrectly but I can't find proper instructions to do this task.

Please provide instructions to use local docker images in local kubernetes instance.

OS: ubuntu 16.04

Docker : Docker version 1.13.1, build 092cba3

Kubernetes :

Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.3", GitCommit:"029c3a408176b55c30846f0faedf56aae5992e9b", GitTreeState:"clean", BuildDate:"2017-02-15T06:40:50Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"08e099554f3c31f6e6f07b448ab3ed78d0520507", GitTreeState:"clean", BuildDate:"1970-01-01T00:00:00Z", GoVersion:"go1.7.1", Compiler:"gc", Platform:"linux/amd64"}

If someone could help me get a solution that uses docker-compose to do this, that'd be awesome.

Edit:

Images loaded in eval $(minikube docker-env):

REPOSITORY                                            TAG                 IMAGE ID            CREATED             SIZE
fluxcapacitor/jupyterhub                              latest              e5175fb26522        4 weeks ago         9.59 GB
fluxcapacitor/zeppelin                                latest              fe4bc823e57d        4 weeks ago         4.12 GB
fluxcapacitor/prediction-pmml                         latest              cae5b2d9835b        4 weeks ago         973 MB
fluxcapacitor/scheduler-airflow                       latest              95adfd56f656        4 weeks ago         8.89 GB
fluxcapacitor/loadtest                                latest              6a777ab6167c        5 weeks ago         899 MB
fluxcapacitor/hdfs                                    latest              00fa0ed0064b        6 weeks ago         1.16 GB
fluxcapacitor/sql-mysql                               latest              804137671a8c        7 weeks ago         679 MB
fluxcapacitor/metastore-1.2.1                         latest              ea7ce8c5048f        7 weeks ago         1.35 GB
fluxcapacitor/cassandra                               latest              3cb5ff117283        7 weeks ago         953 MB
fluxcapacitor/apachespark-worker-2.0.1                latest              14ee3e4e337c        7 weeks ago         3.74 GB
fluxcapacitor/apachespark-master-2.0.1                latest              fe60b42d54e5        7 weeks ago         3.72 GB
fluxcapacitor/package-java-openjdk-1.8                latest              1db08965289d        7 weeks ago         841 MB
gcr.io/google_containers/kubernetes-dashboard-amd64   v1.5.1              1180413103fd        7 weeks ago         104 MB
fluxcapacitor/stream-kafka-0.10                       latest              f67750239f4d        2 months ago        1.14 GB
fluxcapacitor/pipeline                                latest              f6afd6c5745b        2 months ago        11.2 GB
gcr.io/google-containers/kube-addon-manager           v6.1                59e1315aa5ff        3 months ago        59.4 MB
gcr.io/google_containers/kubedns-amd64                1.9                 26cf1ed9b144        3 months ago        47 MB
gcr.io/google_containers/kube-dnsmasq-amd64           1.4                 3ec65756a89b        5 months ago        5.13 MB
gcr.io/google_containers/exechealthz-amd64            1.2                 93a43bfb39bf        5 months ago        8.37 MB
gcr.io/google_containers/pause-amd64

Body:
setup minikube docker-env

again build the same docker image (using minikube docker-env)

change imagePullPolicy to Never in your deployment

actually what happens here , your Minikube can't recognise your docker daemon as it is independent service.You have to first set your minikube-docker environment use below command to check

 "eval $(minikube docker-env)"

If you run below command it will show where your minikube looks for docker.

~$ minikube docker-env
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.37.192:2376"
export DOCKER_CERT_PATH="/home/ubuntu/.minikube/certs"
export MINIKUBE_ACTIVE_DOCKERD="minikube"

**# To point your shell to minikube's docker-daemon, run:**
# eval $(minikube -p minikube docker-env)

You have to again build images once you setup minikube docker-env else it will fail.


问:
JQuery - is there a way to make less calls to the dom
i have this jquery function

```<code>    function update_prices(that, current_id, quantity) {
         //that == $(this)
        var wrapper = that.parents(".wrapper");
        var standard = wrapper.find(".prettyCheckbox small:eq(0)").parents("span").parents("label").prev("input").val();
        var professional = wrapper.find(".prettyCheckbox small:eq(1)").parents("span").parents("label").prev("input").val();
        var premium = wrapper.find(".prettyCheckbox small:eq(2)").parents("span").parents("label").prev("input").val();
        $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&standard_id=" + standard + "&professional_id" + professional + "&premium_id" + premium + "&quantity" + quantity;
            function(data) {
                var standard_price = data[0];
                var professional_price = data[0];
                var premium_price = data[0];
        });
        wrapper.find(".prettyCheckbox small:eq(0)").text(standard_price);
        wrapper.find(".prettyCheckbox small:eq(1)").text(professional_price);
        wrapper.find(".prettyCheckbox small:eq(2)").text(premium_price);
        return true;
    }
</code>```

and i feel like i am calling the same elements on the dom  more then i should ....is there anyone that can think of a better way to achieve what i want without making all these calls

答:
You could cache the prettyCheckBox items:

```<code>function update_prices(that, current_id, quantity) {

    //that == $(this)

    var $wrapper = that.parents(".wrapper"),
        $prettyCheckBox0 = $wrapper.find(".prettyCheckbox small:eq(0)"),
        $prettyCheckBox1 = $wrapper.find(".prettyCheckbox small:eq(1)"),
        $prettyCheckBox2 = $wrapper.find(".prettyCheckbox small:eq(2)"),
        standard = $prettyCheckBox0.parents("span").parents("label").prev("input").val(),
        professional = $prettyCheckBox1.parents("span").parents("label").prev("input").val(),
        premium = $prettyCheckBox2.parents("span").parents("label").prev("input").val();

    $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&standard_id=" + standard + "&professional_id" + professional + "&premium_id" + premium + "&quantity" + quantity,
        function(data) {
            var standard_price = data[0];
            var professional_price = data[0];
            var premium_price = data[0];
    });

    $prettyCheckBox0.text(standard_price);
    $prettyCheckBox1.text(professional_price);
    $prettyCheckBox2.text(premium_price);

    return true;
}
</code>```

Also, I fixed an error.  You had quantity; and it should be quantity,.

Body:
i have this jquery function

    function update_prices(that, current_id, quantity) {
         //that == $(this)
        var wrapper = that.parents(".wrapper");
        var standard = wrapper.find(".prettyCheckbox small:eq(0)").parents("span").parents("label").prev("input").val();
        var professional = wrapper.find(".prettyCheckbox small:eq(1)").parents("span").parents("label").prev("input").val();
        var premium = wrapper.find(".prettyCheckbox small:eq(2)").parents("span").parents("label").prev("input").val();
        $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&standard_id=" + standard + "&professional_id" + professional + "&premium_id" + premium + "&quantity" + quantity;
            function(data) {
                var standard_price = data[0];
                var professional_price = data[0];
                var premium_price = data[0];
        });
        wrapper.find(".prettyCheckbox small:eq(0)").text(standard_price);
        wrapper.find(".prettyCheckbox small:eq(1)").text(professional_price);
        wrapper.find(".prettyCheckbox small:eq(2)").text(premium_price);
        return true;
    }

and i feel like i am calling the same elements on the dom  more then i should ....is there anyone that can think of a better way to achieve what i want without making all these calls

Body:
You could cache the prettyCheckBox items:

function update_prices(that, current_id, quantity) {

    //that == $(this)

    var $wrapper = that.parents(".wrapper"),
        $prettyCheckBox0 = $wrapper.find(".prettyCheckbox small:eq(0)"),
        $prettyCheckBox1 = $wrapper.find(".prettyCheckbox small:eq(1)"),
        $prettyCheckBox2 = $wrapper.find(".prettyCheckbox small:eq(2)"),
        standard = $prettyCheckBox0.parents("span").parents("label").prev("input").val(),
        professional = $prettyCheckBox1.parents("span").parents("label").prev("input").val(),
        premium = $prettyCheckBox2.parents("span").parents("label").prev("input").val();

    $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&standard_id=" + standard + "&professional_id" + professional + "&premium_id" + premium + "&quantity" + quantity,
        function(data) {
            var standard_price = data[0];
            var professional_price = data[0];
            var premium_price = data[0];
    });

    $prettyCheckBox0.text(standard_price);
    $prettyCheckBox1.text(professional_price);
    $prettyCheckBox2.text(premium_price);

    return true;
}

Also, I fixed an error.  You had quantity; and it should be quantity,.


问:
SwiftUI - Struct Binding doesn't update UI as expected
I have a SwiftUI question which doesn't look like it's answered or a duplicate of another issue, and SwiftUI is rather new.

The following code, with my understanding, show toggle the background of the Button control. The number of likes increments as expected, but the state changes don't seem to pass through to the Book struct.

Everything I have read is that in the preview, you need to use:
.constant(x) within the view of the PreviewProvider.

However, it doesn't work and the Button with likes does not the foreground, nor the background color.

When debugging the app, the result of the book isLiked does change. But the foreground/background colors do not.

Here is the code for the view.

```<code>import SwiftUI

struct BookDetailView: View {

  @Binding var book: Book
    @State var likes: Int = 0
  var body: some View {
    VStack {

      Text(book.title)
      Image(book.imageName)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .scaledToFit()

        Button(action: {
            self.book.isLiked.toggle()
            self.likes = self.likes + 1
        }) {
            Text(" Like \(likes)")
                .padding()
                .foregroundColor(self.book.isLiked ? .secondary : .primary)
                .background(self.book.isLiked ? Color.rayWenderlichGreen : Color.white)
                .cornerRadius(10)
        }
    }
  }
}

struct BookDetailView_Previews: PreviewProvider {

  static var previews: some View {
    BookDetailView(book: .constant(Book.demoBooks.randomElement()!))
  }
}
</code>```

Here is the actual book model

```<code>import SwiftUI

struct Book: Identifiable {
  var id = UUID()
  var title: String
  var imageName: String
  var isLiked = false
}

extension Book: Equatable {
  static func == (lhs: Book, rhs: Book) -> Bool {
    return lhs.id == rhs.id
  }
}
</code>```

I have invested some time in trying to understand why this is happening, and it seems like it could just be a bug with SwiftUI.

Any thoughts or suggestions?

答:
I cannot test because there is no Book type provided, but if it is a struct, the following should work (note: .constant binding is constant, it does not modify wrapped value, you need alive one)

```<code>struct BookDetailView_Previews: PreviewProvider {
  struct TestView: View {
     @State private var book = Book.demoBooks.randomElement()!
     var body: some View {
       BookDetailView(book: $book)
     }
  }
  static var previews: some View {
    TestView()
  }
}
</code>```

Update: now with fix - the reason is that made equatable book does not take into account changed isLiked state, so view does not detect that anything changed and does not update.

The solution is either remove that extension or make it take into account all fields that should indicate modified value, as below

```<code>extension Book: Equatable {
  static func == (lhs: Book, rhs: Book) -> Bool {
    lhs.id == rhs.id && lhs.isLiked == rhs.isLiked
  }
}
</code>```

Tested & works with Xcode 11.4 / iOS 13.4

Body:
I have a SwiftUI question which doesn't look like it's answered or a duplicate of another issue, and SwiftUI is rather new.

The following code, with my understanding, show toggle the background of the Button control. The number of likes increments as expected, but the state changes don't seem to pass through to the Book struct.

Everything I have read is that in the preview, you need to use:
.constant(x) within the view of the PreviewProvider.

However, it doesn't work and the Button with likes does not the foreground, nor the background color.

When debugging the app, the result of the book isLiked does change. But the foreground/background colors do not.

Here is the code for the view.

import SwiftUI

struct BookDetailView: View {

  @Binding var book: Book
    @State var likes: Int = 0
  var body: some View {
    VStack {

      Text(book.title)
      Image(book.imageName)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .scaledToFit()

        Button(action: {
            self.book.isLiked.toggle()
            self.likes = self.likes + 1
        }) {
            Text(" Like \(likes)")
                .padding()
                .foregroundColor(self.book.isLiked ? .secondary : .primary)
                .background(self.book.isLiked ? Color.rayWenderlichGreen : Color.white)
                .cornerRadius(10)
        }
    }
  }
}

struct BookDetailView_Previews: PreviewProvider {

  static var previews: some View {
    BookDetailView(book: .constant(Book.demoBooks.randomElement()!))
  }
}

Here is the actual book model

import SwiftUI

struct Book: Identifiable {
  var id = UUID()
  var title: String
  var imageName: String
  var isLiked = false
}

extension Book: Equatable {
  static func == (lhs: Book, rhs: Book) -> Bool {
    return lhs.id == rhs.id
  }
}

I have invested some time in trying to understand why this is happening, and it seems like it could just be a bug with SwiftUI.

Any thoughts or suggestions?

Body:
I cannot test because there is no Book type provided, but if it is a struct, the following should work (note: .constant binding is constant, it does not modify wrapped value, you need alive one)

struct BookDetailView_Previews: PreviewProvider {
  struct TestView: View {
     @State private var book = Book.demoBooks.randomElement()!
     var body: some View {
       BookDetailView(book: $book)
     }
  }
  static var previews: some View {
    TestView()
  }
}

Update: now with fix - the reason is that made equatable book does not take into account changed isLiked state, so view does not detect that anything changed and does not update.

The solution is either remove that extension or make it take into account all fields that should indicate modified value, as below

extension Book: Equatable {
  static func == (lhs: Book, rhs: Book) -> Bool {
    lhs.id == rhs.id && lhs.isLiked == rhs.isLiked
  }
}

Tested & works with Xcode 11.4 / iOS 13.4


问:
Django Showing Error while running manage.py file
while running my .....python manage.py

Traceback (most recent call last):   File "manage.py", line 10, in

      execute_from_command_line(sys.argv)   File "/home/devbase/env/local/lib/python2.7/site-packages/django/core/management/init.py",
  line 364, in execute_from_command_line
      utility.execute()   File "/home/devbase/env/local/lib/python2.7/site-packages/django/core/management/init.py",
  line 338, in execute
      django.setup()   File "/home/devbase/env/local/lib/python2.7/site-packages/django/init.py",
  line 27, in setup
      apps.populate(settings.INSTALLED_APPS)   File "/home/devbase/env/local/lib/python2.7/site-packages/django/apps/registry.py",
  line 85, in populate
      app_config = AppConfig.create(entry)   File "/home/devbase/env/local/lib/python2.7/site-packages/django/apps/config.py",
  line 94, in create
      module = import_module(entry)   File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module
      import(name) ImportError: No module named djorm_pgtrgm

答: First check for clear installation of django. And fire correct query at correct path. Open your cmd , go to the path were you placed your manage.py file is. And then fire query python manage.py runserver.