问:
spring-boo/neo4j Concurrent Save leads to deadlock

General Problem

I have a Node that has a Parent/Child relationship to itself (Same Label/Class). I can add a new Relathiship to a new Child node by adding the Parent Node to Parents-Relationship list (see code below).
This works for saving one entity, when trying to Save the relationship for different Children of the same Parent I receive a deadlock-error (TransientDataAccessResourceException).

Setup

Maven Project

Spring-Boot (spring-boot-starter-parent 2.6.13)

Neo4J: spring-boot-starter-data-neo4j

Project Lombok

Java 11

Database: Docker-Container

```<code>docker run --name eval.neo4j -d -v eval.neo4j-data:/data -p 7474:7474 -p 7687:7687 neo4j
</code>```

Config

```<code>spring:
  neo4j:
    uri: bolt://localhost:7687
    authentication:
      username: neo4j
      password: admin
</code>```

Java Code

Node

@Getter
@Setter
@Node("Example")
@NoArgsConstructor
public class ExampleNode {

    private static final String CHILD_OF = "CHILD_OF";

    @Id
    @GeneratedValue
    private Long id;

    @Version
    private Long version;

    @Property
    private String name;

    @Relationship(type= CHILD_OF, direction = Relationship.Direction.OUTGOING)
    private Set<ExampleNode> parents;

    @Relationship(type= CHILD_OF, direction = Relationship.Direction.INCOMING)
    private Set<ExampleNode> children;

    public ExampleNode(String name) {
        this.name = name;
    }

    public void addParent(ExampleNode parent) {
        if (parents == null) {
            parents = new HashSet<>();
        }
        parents.add(parent);
    }

    @Override
    public String toString() {
        return "ExampleNode{" +
                "id=" + id +
                ", version=" + version +
                ", name='" + name + '\'' +
                ", parents=" + (parents == null ? 0: parents.size()) +
                ", children=" + (children == null ? 0 : children.size()) +
                '}';
    }
}

```
<p>Repository:</p>
<pre class="lang-java prettyprint-override"><code>
@Transactional
public interface ExampleRepository extends CrudRepository<ExampleNode, Long> {
}

</code>```

CRUD Service

@Slf4j
@Service
@RequiredArgsConstructor
public class ExampleService {

    private final ExampleRepository repository;

    @Transactional
    public Long create(String name, Long parentId) {
        ExampleNode entity = new ExampleNode(name);
        if (parentId != null) {
            entity.addParent(repository.findById(parentId).orElseThrow());
        }
        ExampleNode response = repository.save(entity);
        log.info("Created {}", response);
        return response.getId();
    }

    @Async
    public Future<Long> createAsync(String name, Long parentId) {
        return new AsyncResult<>(create(name, parentId));
    }

    public ExampleNode read(Long id) {
        return repository.findById(id).orElse(null);
    }

}

```
<p>App with CommandLineRunner (for simplicity - the actual implementation uses RestController with spring-mvc</p>
<pre class="lang-java prettyprint-override"><code>@Slf4j
@EnableAsync
@SpringBootApplication
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(ExampleService service) {
        return (args) -> {
            Long p1 = service.create("Parent-1", null);
            Long p2 = service.create("Parent-2", null);

            // works for synchronous calls or when synchronizing
            // before the first call. async is used to simulate
            // concurrent executions i.E. via rest-calls
            final Future<Long> one = service.createAsync("one", p1);
            final Future<Long> two = service.createAsync("two", p1);

            Long id1 = one.get(2, TimeUnit.SECONDS);
            Long id2 = two.get(2, TimeUnit.SECONDS);
            log.info("load parents {} {}", service.read(p1), service.read(p2));
            log.info("load children {}: {}, {}:{}", id1, service.read(id1), id2, service.read(id2));
        };
    }
}

</code>```

Log

```2022-12-07 08:42:07.537 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Getting transaction for [de.example.graph.service.ExampleService.create]
2022-12-07 08:42:07.550 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:07.804 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:07.805  INFO 27776 --- [           main] de.example.graph.service.ExampleService  : Created ProblemEntity{id=35, version=0, name='Parent-1', parents=0, children=0}
2022-12-07 08:42:07.807 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Completing transaction for [de.example.graph.service.ExampleService.create]
2022-12-07 08:42:07.835 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Getting transaction for [de.example.graph.service.ExampleService.create]
2022-12-07 08:42:07.836 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:07.854 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:07.854  INFO 27776 --- [           main] de.example.graph.service.ExampleService  : Created ProblemEntity{id=36, version=0, name='Parent-2', parents=0, children=0}
2022-12-07 08:42:07.854 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Completing transaction for [de.example.graph.service.ExampleService.create]
2022-12-07 08:42:07.882 TRACE 27776 --- [         task-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findById]
2022-12-07 08:42:07.895 TRACE 27776 --- [         task-2] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findById]
2022-12-07 08:42:08.211 TRACE 27776 --- [         task-2] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findById]
2022-12-07 08:42:08.211 TRACE 27776 --- [         task-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findById]
2022-12-07 08:42:08.223 TRACE 27776 --- [         task-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:08.223 TRACE 27776 --- [         task-2] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:08.418 TRACE 27776 --- [         task-2] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save] after exception: org.springframework.dao.TransientDataAccessResourceException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]; Error code 'Neo.TransientError.Transaction.DeadlockDetected'; nested exception is org.neo4j.driver.exceptions.TransientException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]
2022-12-07 08:42:08.480 TRACE 27776 --- [         task-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:08.495  INFO 27776 --- [         task-1] de.example.graph.service.ExampleService  : Created ProblemEntity{id=37, version=0, name='one', parents=1, children=0}
2022-12-07 08:42:08.498  INFO 27776 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-12-07 08:42:08.537 ERROR 27776 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:785) ~[spring-boot-2.6.13.jar:2.6.13]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:766) ~[spring-boot-2.6.13.jar:2.6.13]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-2.6.13.jar:2.6.13]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1317) ~[spring-boot-2.6.13.jar:2.6.13]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.6.13.jar:2.6.13]
    at de.example.graph.ExampleApplication.main(ExampleApplication.java:20) ~[classes/:na]
Caused by: java.util.concurrent.ExecutionException: org.springframework.dao.TransientDataAccessResourceException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]; Error code 'Neo.TransientError.Transaction.DeadlockDetected'; nested exception is org.neo4j.driver.exceptions.TransientException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]
    at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:na]
    at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:205) ~[na:na]
    at de.example.graph.ExampleApplication.lambda$runner$0(ExampleApplication.java:33) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:782) ~[spring-boot-2.6.13.jar:2.6.13]
    ... 5 common frames omitted
Caused by: org.springframework.dao.TransientDataAccessResourceException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]; Error code 'Neo.TransientError.Transaction.DeadlockDetected'; nested exception is org.neo4j.driver.exceptions.TransientException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]
    at org.springframework.data.neo4j.core.Neo4jPersistenceExceptionTranslator.translateImpl(Neo4jPersistenceExceptionTranslator.java:107) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jPersistenceExceptionTranslator.translateExceptionIfPossible(Neo4jPersistenceExceptionTranslator.java:79) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.DefaultNeo4jClient.potentiallyConvertRuntimeException(DefaultNeo4jClient.java:233) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.DefaultNeo4jClient.access$600(DefaultNeo4jClient.java:62) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.DefaultNeo4jClient$DefaultRecordFetchSpec.one(DefaultNeo4jClient.java:461) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.lambda$processNestedRelations$25(Neo4jTemplate.java:865) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:388) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.processNestedRelations(Neo4jTemplate.java:729) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.processRelations(Neo4jTemplate.java:714) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.saveImpl(Neo4jTemplate.java:433) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.save(Neo4jTemplate.java:345) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save(SimpleNeo4jRepository.java:119) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    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.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:530) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:286) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:640) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.23.jar:5.3.23]
    at com.sun.proxy.$Proxy64.save(Unknown Source) ~[na:na]
    at de.example.graph.service.ExampleService.create(ExampleService.java:27) ~[classes/:na]
    at de.example.graph.service.ExampleService.createAsync(ExampleService.java:34) ~[classes/:na]
    at de.example.graph.service.ExampleService$$FastClassBySpringCGLIB$$91503e55.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115) ~[spring-aop-5.3.23.jar:5.3.23]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:839) ~[na:na]
Caused by: org.neo4j.driver.exceptions.TransientException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]
    at org.neo4j.driver.internal.util.Futures.blockingGet(Futures.java:111) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
    at org.neo4j.driver.internal.InternalResult.blockingGet(InternalResult.java:107) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
    at org.neo4j.driver.internal.InternalResult.hasNext(InternalResult.java:53) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
    at org.springframework.data.neo4j.core.DefaultNeo4jClient$DefaultRecordFetchSpec.one(DefaultNeo4jClient.java:455) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    ... 43 common frames omitted
    Suppressed: org.neo4j.driver.internal.util.ErrorUtil$InternalExceptionCause: null
        at org.neo4j.driver.internal.util.ErrorUtil.newNeo4jError(ErrorUtil.java:80) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.async.inbound.InboundMessageDispatcher.handleFailureMessage(InboundMessageDispatcher.java:107) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.messaging.common.CommonMessageReader.unpackFailureMessage(CommonMessageReader.java:75) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.messaging.common.CommonMessageReader.read(CommonMessageReader.java:53) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.async.inbound.InboundMessageHandler.channelRead0(InboundMessageHandler.java:81) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.async.inbound.InboundMessageHandler.channelRead0(InboundMessageHandler.java:37) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:327) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:299) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.async.inbound.MessageDecoder.channelRead(MessageDecoder.java:42) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:327) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:299) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:286) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        ... 1 common frames omitted

2022-12-07 08:42:08.543  INFO 27776 --- [           main] o.neo4j.driver.internal.InternalDriver   : Closing driver instance -634758184
2022-12-07 08:42:08.548  INFO 27776 --- [           main] o.n.d.i.async.pool.ConnectionPoolImpl    : Closing connection pool towards localhost:7687

Process finished with exit code 1
```

Problem

Saving the second Child node seems to be locked by the first (or the other way around). I thought this would be resolved by the transaction annotation. I am also worried about NODE_RELATIONSHIP_GROUP_DELETE in the log-output - this seems to indicate that the first child will be removed when saving the second.
I was unable to find a simple spring-like solution for only saving the node and the relationship without touching the parent-node, since the parent node properties are unchanged.

Thank you for your Help :)

Body:
General Problem

I have a Node that has a Parent/Child relationship to itself (Same Label/Class). I can add a new Relathiship to a new Child node by adding the Parent Node to Parents-Relationship list (see code below).
This works for saving one entity, when trying to Save the relationship for different Children of the same Parent I receive a deadlock-error (TransientDataAccessResourceException).

Setup

Maven Project

Spring-Boot (spring-boot-starter-parent 2.6.13)

Neo4J: spring-boot-starter-data-neo4j

Project Lombok

Java 11

Database: Docker-Container

docker run --name eval.neo4j -d -v eval.neo4j-data:/data -p 7474:7474 -p 7687:7687 neo4j

Config

spring:
  neo4j:
    uri: bolt://localhost:7687
    authentication:
      username: neo4j
      password: admin

Java Code

Node

@Getter
@Setter
@Node("Example")
@NoArgsConstructor
public class ExampleNode {

    private static final String CHILD_OF = "CHILD_OF";

    @Id
    @GeneratedValue
    private Long id;

    @Version
    private Long version;

    @Property
    private String name;

    @Relationship(type= CHILD_OF, direction = Relationship.Direction.OUTGOING)
    private Set<ExampleNode> parents;

    @Relationship(type= CHILD_OF, direction = Relationship.Direction.INCOMING)
    private Set<ExampleNode> children;

    public ExampleNode(String name) {
        this.name = name;
    }

    public void addParent(ExampleNode parent) {
        if (parents == null) {
            parents = new HashSet<>();
        }
        parents.add(parent);
    }

    @Override
    public String toString() {
        return "ExampleNode{" +
                "id=" + id +
                ", version=" + version +
                ", name='" + name + '\'' +
                ", parents=" + (parents == null ? 0: parents.size()) +
                ", children=" + (children == null ? 0 : children.size()) +
                '}';
    }
}

Repository:

@Transactional
public interface ExampleRepository extends CrudRepository<ExampleNode, Long> {
}

CRUD Service

@Slf4j
@Service
@RequiredArgsConstructor
public class ExampleService {

    private final ExampleRepository repository;

    @Transactional
    public Long create(String name, Long parentId) {
        ExampleNode entity = new ExampleNode(name);
        if (parentId != null) {
            entity.addParent(repository.findById(parentId).orElseThrow());
        }
        ExampleNode response = repository.save(entity);
        log.info("Created {}", response);
        return response.getId();
    }

    @Async
    public Future<Long> createAsync(String name, Long parentId) {
        return new AsyncResult<>(create(name, parentId));
    }

    public ExampleNode read(Long id) {
        return repository.findById(id).orElse(null);
    }

}

App with CommandLineRunner (for simplicity - the actual implementation uses RestController with spring-mvc

@Slf4j
@EnableAsync
@SpringBootApplication
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(ExampleService service) {
        return (args) -> {
            Long p1 = service.create("Parent-1", null);
            Long p2 = service.create("Parent-2", null);

            // works for synchronous calls or when synchronizing
            // before the first call. async is used to simulate
            // concurrent executions i.E. via rest-calls
            final Future<Long> one = service.createAsync("one", p1);
            final Future<Long> two = service.createAsync("two", p1);

            Long id1 = one.get(2, TimeUnit.SECONDS);
            Long id2 = two.get(2, TimeUnit.SECONDS);
            log.info("load parents {} {}", service.read(p1), service.read(p2));
            log.info("load children {}: {}, {}:{}", id1, service.read(id1), id2, service.read(id2));
        };
    }
}

Log

2022-12-07 08:42:07.537 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Getting transaction for [de.example.graph.service.ExampleService.create]
2022-12-07 08:42:07.550 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:07.804 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:07.805  INFO 27776 --- [           main] de.example.graph.service.ExampleService  : Created ProblemEntity{id=35, version=0, name='Parent-1', parents=0, children=0}
2022-12-07 08:42:07.807 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Completing transaction for [de.example.graph.service.ExampleService.create]
2022-12-07 08:42:07.835 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Getting transaction for [de.example.graph.service.ExampleService.create]
2022-12-07 08:42:07.836 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:07.854 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:07.854  INFO 27776 --- [           main] de.example.graph.service.ExampleService  : Created ProblemEntity{id=36, version=0, name='Parent-2', parents=0, children=0}
2022-12-07 08:42:07.854 TRACE 27776 --- [           main] o.s.t.i.TransactionInterceptor           : Completing transaction for [de.example.graph.service.ExampleService.create]
2022-12-07 08:42:07.882 TRACE 27776 --- [         task-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findById]
2022-12-07 08:42:07.895 TRACE 27776 --- [         task-2] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findById]
2022-12-07 08:42:08.211 TRACE 27776 --- [         task-2] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findById]
2022-12-07 08:42:08.211 TRACE 27776 --- [         task-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findById]
2022-12-07 08:42:08.223 TRACE 27776 --- [         task-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:08.223 TRACE 27776 --- [         task-2] o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:08.418 TRACE 27776 --- [         task-2] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save] after exception: org.springframework.dao.TransientDataAccessResourceException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]; Error code 'Neo.TransientError.Transaction.DeadlockDetected'; nested exception is org.neo4j.driver.exceptions.TransientException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]
2022-12-07 08:42:08.480 TRACE 27776 --- [         task-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save]
2022-12-07 08:42:08.495  INFO 27776 --- [         task-1] de.example.graph.service.ExampleService  : Created ProblemEntity{id=37, version=0, name='one', parents=1, children=0}
2022-12-07 08:42:08.498  INFO 27776 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-12-07 08:42:08.537 ERROR 27776 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:785) ~[spring-boot-2.6.13.jar:2.6.13]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:766) ~[spring-boot-2.6.13.jar:2.6.13]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-2.6.13.jar:2.6.13]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1317) ~[spring-boot-2.6.13.jar:2.6.13]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.6.13.jar:2.6.13]
    at de.example.graph.ExampleApplication.main(ExampleApplication.java:20) ~[classes/:na]
Caused by: java.util.concurrent.ExecutionException: org.springframework.dao.TransientDataAccessResourceException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]; Error code 'Neo.TransientError.Transaction.DeadlockDetected'; nested exception is org.neo4j.driver.exceptions.TransientException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]
    at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:na]
    at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:205) ~[na:na]
    at de.example.graph.ExampleApplication.lambda$runner$0(ExampleApplication.java:33) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:782) ~[spring-boot-2.6.13.jar:2.6.13]
    ... 5 common frames omitted
Caused by: org.springframework.dao.TransientDataAccessResourceException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]; Error code 'Neo.TransientError.Transaction.DeadlockDetected'; nested exception is org.neo4j.driver.exceptions.TransientException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]
    at org.springframework.data.neo4j.core.Neo4jPersistenceExceptionTranslator.translateImpl(Neo4jPersistenceExceptionTranslator.java:107) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jPersistenceExceptionTranslator.translateExceptionIfPossible(Neo4jPersistenceExceptionTranslator.java:79) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.DefaultNeo4jClient.potentiallyConvertRuntimeException(DefaultNeo4jClient.java:233) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.DefaultNeo4jClient.access$600(DefaultNeo4jClient.java:62) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.DefaultNeo4jClient$DefaultRecordFetchSpec.one(DefaultNeo4jClient.java:461) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.lambda$processNestedRelations$25(Neo4jTemplate.java:865) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:388) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.processNestedRelations(Neo4jTemplate.java:729) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.processRelations(Neo4jTemplate.java:714) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.saveImpl(Neo4jTemplate.java:433) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.core.Neo4jTemplate.save(Neo4jTemplate.java:345) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    at org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save(SimpleNeo4jRepository.java:119) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    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.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:530) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:286) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:640) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139) ~[spring-data-commons-2.6.9.jar:2.6.9]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.23.jar:5.3.23]
    at com.sun.proxy.$Proxy64.save(Unknown Source) ~[na:na]
    at de.example.graph.service.ExampleService.create(ExampleService.java:27) ~[classes/:na]
    at de.example.graph.service.ExampleService.createAsync(ExampleService.java:34) ~[classes/:na]
    at de.example.graph.service.ExampleService$$FastClassBySpringCGLIB$$91503e55.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115) ~[spring-aop-5.3.23.jar:5.3.23]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:839) ~[na:na]
Caused by: org.neo4j.driver.exceptions.TransientException: ForsetiClient[transactionId=94, clientId=2] can't acquire ExclusiveLock{owner=ForsetiClient[transactionId=93, clientId=1]} on NODE_RELATIONSHIP_GROUP_DELETE(35), because holders of that lock are waiting for ForsetiClient[transactionId=94, clientId=2].
 Wait list:ExclusiveLock[
Client[93] waits for [ForsetiClient[transactionId=94, clientId=2]]]
    at org.neo4j.driver.internal.util.Futures.blockingGet(Futures.java:111) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
    at org.neo4j.driver.internal.InternalResult.blockingGet(InternalResult.java:107) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
    at org.neo4j.driver.internal.InternalResult.hasNext(InternalResult.java:53) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
    at org.springframework.data.neo4j.core.DefaultNeo4jClient$DefaultRecordFetchSpec.one(DefaultNeo4jClient.java:455) ~[spring-data-neo4j-6.2.9.jar:6.2.9]
    ... 43 common frames omitted
    Suppressed: org.neo4j.driver.internal.util.ErrorUtil$InternalExceptionCause: null
        at org.neo4j.driver.internal.util.ErrorUtil.newNeo4jError(ErrorUtil.java:80) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.async.inbound.InboundMessageDispatcher.handleFailureMessage(InboundMessageDispatcher.java:107) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.messaging.common.CommonMessageReader.unpackFailureMessage(CommonMessageReader.java:75) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.messaging.common.CommonMessageReader.read(CommonMessageReader.java:53) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.async.inbound.InboundMessageHandler.channelRead0(InboundMessageHandler.java:81) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.async.inbound.InboundMessageHandler.channelRead0(InboundMessageHandler.java:37) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:327) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:299) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.async.inbound.MessageDecoder.channelRead(MessageDecoder.java:42) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:327) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:299) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:286) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        at org.neo4j.driver.internal.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[neo4j-java-driver-4.4.9.jar:4.4.9-e855bcc800deff6ddcf064c822314bb5c8d08c53]
        ... 1 common frames omitted

2022-12-07 08:42:08.543  INFO 27776 --- [           main] o.neo4j.driver.internal.InternalDriver   : Closing driver instance -634758184
2022-12-07 08:42:08.548  INFO 27776 --- [           main] o.n.d.i.async.pool.ConnectionPoolImpl    : Closing connection pool towards localhost:7687

Process finished with exit code 1

Problem

Saving the second Child node seems to be locked by the first (or the other way around). I thought this would be resolved by the transaction annotation. I am also worried about NODE_RELATIONSHIP_GROUP_DELETE in the log-output - this seems to indicate that the first child will be removed when saving the second.
I was unable to find a simple spring-like solution for only saving the node and the relationship without touching the parent-node, since the parent node properties are unchanged.

Thank you for your Help :)


来源: stackexchange

问:
how can I provide Role based access to Blog app?
I am confused in how can I develop user roles to the Blog application?

I have tried to give roles in user model itself [Admin, user, author]

But now I am getting confuse, how can user have aceess of all blogs to READ.

If my user wants to create a blog, then his role is changing at that point of time form "user" to "author" of a prticular blog.

And "admin" have only accees to delete blogs. So can I give DELETE access to my "user" or "author"?

ContentLicense: CC BY-SA 4.0


问:
Python-Gitlab: Wait until deleting a branch is completed
I'm having an issue with Gitlab when deleting branches in Python. The problem is that Gitlab seems to be taking too long to complete the deletion, and I'm not sure why. I've created a brute-force code to try to reproduce the issue, it sometimes gets stuck in an endless loop, at least on my end.

If anyone has experienced this issue before or has any ideas on how to fix it, I'd really appreciate some help.

Thanks in advance!

for i in range(100):
    # (1) Start creating a new branch
    project.branches.create({'branch': 'head_branch','ref': 'main'})
    # (2) Wait until the new branch is created to move on.
    j = 0
    while 'head_branch' not in [branch.name for branch in project.branches.list(get_all=True)]:
        print(j)
        j +=1
    # (3) Delete the recently created branch
    deleted_branch = project.branches.delete('head_branch')
    # (4) Wait until the branch is deleted to move on.
    j = 0
    while 'head_branch' in [branch.name for branch in project.branches.list(get_all=True)]:
        print(j)
        j +=1
```


问:
Symfony ~ SULU - Property from "route" to "resource_locator"
In the exemple i made in the pictures, i change the property "url" of "Mathématique" page type from "route" type to "resource_locator" but this one is skipped in the hierarchy usage.

Do you have any idea about how to refresh URLs ?

```<code><property name="url" type="resource_locator" mandatory="true">
    <meta>
        <title lang="en">Resourcelocator</title>
        <title lang="de">Adresse</title>
    </meta>

    <tag name="sulu.rlp"/>
</property>
</code>```

Body:
In the exemple i made in the pictures, i change the property "url" of "Mathématique" page type from "route" type to "resource_locator" but this one is skipped in the hierarchy usage.

Do you have any idea about how to refresh URLs ?

<property name="url" type="resource_locator" mandatory="true">
    <meta>
        <title lang="en">Resourcelocator</title>
        <title lang="de">Adresse</title>
    </meta>

    <tag name="sulu.rlp"/>
</property>


问:
Modify class instances inside a context mananger and keep track of them
I'm designing a small workflow manager similar to Apache Airflow where I want to build a directed computational graph. Every Node will inherit from Node and the graph is build inside a contextmanager dag. I'd like to

keep track of all instances of Node that are created inside the dag.

want the Nodes to know if there inside with dag() or not.

There would be two approaches to this:

I create a DAG instance and pass it to my Nodes upon creation. This would be very simple but the __init__ would have to accept the dag as kwargs.

dag = DAG()
Node(dag, **kwargs)
```
<ol start="2">
<li>In the style of Apache Airflow using a context manager:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>with dag():
    Node()
</code>```

where I define a global list of all Nodes dags = [] as well as the parent Node and the context manager as follows:

import contextlib

class Node:
    _dag_ = None
    def __init__(self):
        if self._dag_ is not None:
            self._dag_.append(self)
            print("Inside DAG manager")
        else:
            print("Not inside DAG manager")

dags = []

@contextlib.contextmanager
def dag():
    Node._dag_ = dags
    try:
        yield
    finally:
        Node._dag_ = None
```

This works but looks a little bit scary to me.
There would be issues with multithreading but I have no plans in supporting that.
Is there a better solution to what I'm trying to do? Could there be any issues I'm missing?
I tried to read through the Airflow code but couldn't understand how they do it. Does anyone know / understand?

Body:
I'm designing a small workflow manager similar to Apache Airflow where I want to build a directed computational graph. Every Node will inherit from Node and the graph is build inside a contextmanager dag. I'd like to

keep track of all instances of Node that are created inside the dag.

want the Nodes to know if there inside with dag() or not.

There would be two approaches to this:

I create a DAG instance and pass it to my Nodes upon creation. This would be very simple but the __init__ would have to accept the dag as kwargs.

dag = DAG()
Node(dag, **kwargs)

In the style of Apache Airflow using a context manager:

with dag():
    Node()

where I define a global list of all Nodes dags = [] as well as the parent Node and the context manager as follows:

import contextlib

class Node:
    _dag_ = None
    def __init__(self):
        if self._dag_ is not None:
            self._dag_.append(self)
            print("Inside DAG manager")
        else:
            print("Not inside DAG manager")

dags = []

@contextlib.contextmanager
def dag():
    Node._dag_ = dags
    try:
        yield
    finally:
        Node._dag_ = None

This works but looks a little bit scary to me.
There would be issues with multithreading but I have no plans in supporting that.
Is there a better solution to what I'm trying to do? Could there be any issues I'm missing?
I tried to read through the Airflow code but couldn't understand how they do it. Does anyone know / understand?


问:
Why does minikube cluster goes away from kind cluster gets deleted?
So I first start a minikube cluster (1.25.2) using minikube start.  Then I bring up a kind cluster using some kind-Calico-conf.yml file:

```<code>$ kind create cluster --name=calico --config=./kind-Calico-conf.yml
</code>```

When I later delete this Calico cluster (kind delete cluster --name=calico), I can see that the minikube cluster is gone too.  Why is this happening?

Body:
So I first start a minikube cluster (1.25.2) using minikube start.  Then I bring up a kind cluster using some kind-Calico-conf.yml file:

$ kind create cluster --name=calico --config=./kind-Calico-conf.yml

When I later delete this Calico cluster (kind delete cluster --name=calico), I can see that the minikube cluster is gone too.  Why is this happening?


问:
Adding items to a nosql objects with minimum time complexity
In a nosql database multiple items are stored with the category and subcategory in the format given below.

```<code>    Category: [
        {id: "c2", subCategories: [ {id: "s2", items: [ {id: i3}, {id: i4} ] } ] }
        {id: "c1", subCategories: [ {id: "s1", items: [ {id: i1}, {id: i2} ] } ] }
    ]

</code>```

Problem is to add new items with optimised time complexity, we get the same structure to add new items and we have to find and update the subcategories with the new items.

Let's say we get this

```<code>    Category: [
        {id: "c2", subCategories: [ {id: "s2", items: [ {id: i5} ] } ] }
        {id: "c1", subCategories: [ {id: "s1", items: [ {id: i6}, {id: i7} ] } ] }
    ]

</code>```

then the result should be

```<code>Category: [
        {id: "c2", subCategories: [ {id: "s2", items: [ {id: i3}, {id: i4}, {id: i5} ] } ] } ]
        {id: "c1", subCategories: [ {id: "s1", items: [ {id: i1}, {id: i2},{id: i6}, {id: i7} ] }]
    ],
</code>```

currently the approach I can think of, is to iterate over the data with multiple categories and subcategories the time complexity goes to n3 and then after getting the item which is to be added we have to find out where we need to add that item it further increases, is there a way we could reduce this complexity ?

Body:
In a nosql database multiple items are stored with the category and subcategory in the format given below.

    Category: [
        {id: "c2", subCategories: [ {id: "s2", items: [ {id: i3}, {id: i4} ] } ] }
        {id: "c1", subCategories: [ {id: "s1", items: [ {id: i1}, {id: i2} ] } ] }
    ]

Problem is to add new items with optimised time complexity, we get the same structure to add new items and we have to find and update the subcategories with the new items.

Let's say we get this

    Category: [
        {id: "c2", subCategories: [ {id: "s2", items: [ {id: i5} ] } ] }
        {id: "c1", subCategories: [ {id: "s1", items: [ {id: i6}, {id: i7} ] } ] }
    ]

then the result should be

Category: [
        {id: "c2", subCategories: [ {id: "s2", items: [ {id: i3}, {id: i4}, {id: i5} ] } ] } ]
        {id: "c1", subCategories: [ {id: "s1", items: [ {id: i1}, {id: i2},{id: i6}, {id: i7} ] }]
    ],

currently the approach I can think of, is to iterate over the data with multiple categories and subcategories the time complexity goes to n3 and then after getting the item which is to be added we have to find out where we need to add that item it further increases, is there a way we could reduce this complexity ?


问:
Missing "content-type". I'm using busboy and jest for testing purposes
```<code>import { uploadFile } from "../../src/handler";
import { APIGatewayRequest } from "../eventGenerator";
import FormData from "form-data";
import fs from "fs";

export const uploadfile = () => {
  it("Upload File", async () => {
    const filePath = fs.createReadStream("../image/hulk.PNG");
    const formData = new FormData();

    formData.append("file", filePath);
    formData.append("Title", "Jesting");
    formData.append("Description", "JestingJest");
    formData.append("Editor", "Jester");

    console.log(formData);

    const event = APIGatewayRequest({
      body: formData,
      method: "",
      path: "",
      queryStringObject: "",
      pathParametersObject: "",
      stageVariables: null,
    });

    const test = await uploadFile(event);
    expect(test.statusCode).toBe(201);
  }, 50000);
};

</code>```

//////////////////////////////////////////////////////////////////////

```<code>  ...const request: APIGatewayProxyEvent = {
    body: body ? JSON.stringify(body) : null,
    headers: {
      "for-coop-id": "test",
      "content-type": "multipart/form-data",
      // "Access-Control-Allow-Origin": "*",
    },...

</code>```

I did change content-type from all-caps it did not change a thing. I tried putting boundaries and removing content-type. Hope you could help.

Body:
import { uploadFile } from "../../src/handler";
import { APIGatewayRequest } from "../eventGenerator";
import FormData from "form-data";
import fs from "fs";

export const uploadfile = () => {
  it("Upload File", async () => {
    const filePath = fs.createReadStream("../image/hulk.PNG");
    const formData = new FormData();

    formData.append("file", filePath);
    formData.append("Title", "Jesting");
    formData.append("Description", "JestingJest");
    formData.append("Editor", "Jester");

    console.log(formData);

    const event = APIGatewayRequest({
      body: formData,
      method: "",
      path: "",
      queryStringObject: "",
      pathParametersObject: "",
      stageVariables: null,
    });

    const test = await uploadFile(event);
    expect(test.statusCode).toBe(201);
  }, 50000);
};

//////////////////////////////////////////////////////////////////////

  ...const request: APIGatewayProxyEvent = {
    body: body ? JSON.stringify(body) : null,
    headers: {
      "for-coop-id": "test",
      "content-type": "multipart/form-data",
      // "Access-Control-Allow-Origin": "*",
    },...

I did change content-type from all-caps it did not change a thing. I tried putting boundaries and removing content-type. Hope you could help.


问:
Approaches/models to generate 3d talking human head from a 2d image
I am looking for an approach to transform a 2D human head into 3D model and then animate its speech based on an audio file.
I tried some approaches such as meshTalks but the approach uses a pre generated 3d human head meshes.
Any help would be appreciated.
Thank you</p>


问:
Connection to server at port 5436 failed running on docker
I am trying to install pgAdmin4 in my windows machine. I am getting error message of connection to server failed.

I found a similar kind of issue here but the solution doesn't work. I have been struggling with the issue and didn't found any working solution. Earlier, I have PostgreSql 15 version installed but the 15 version was not compatible with yii2 project of mine. So, I uninstalled the PostgreSQL 15 version and reinstalled PostgreSQL 13. After reinstalling I start getting this error.

I tried to restart the services of postgresql from Task Manager -> Services but didn't worked.

Can anyone suggest me what I am doing wrong or what can I do get this fixed.

Many Thanks.


问:
the anchor in javascript does not work correctly
Playback Steps:

In the header, click on any of the links with anchors:
##bankaccount
#pack
#platform
#acq
##scorecard
##intrade
#form
Scroll the page to the top
Reload the page
Actual result:

When reloading a page with an anchor in the url, there is no scrolling to the block.

Expected result:

When a page with an anchor in the url is reloaded, a scroll to the block occurs.

The problem is that while the page is not fully loaded, the scroll works, but when the page is fully loaded, the scroll goes back up

```<code>import React from 'react';

const useScrollToLocation = () => {
    React.useEffect(() => {
        const hash = window.location.hash;
        const id = hash.replace('#', '');
        const element = document.getElementById(id);
        window.location.hash = '';
        if (element) {
            window.location.hash = id;
        }
    }, []);
};
export default useScrollToLocation;
</code>```

Body:
Playback Steps:

In the header, click on any of the links with anchors:
##bankaccount
#pack
#platform
#acq
##scorecard
##intrade
#form
Scroll the page to the top
Reload the page
Actual result:

When reloading a page with an anchor in the url, there is no scrolling to the block.

Expected result:

When a page with an anchor in the url is reloaded, a scroll to the block occurs.

The problem is that while the page is not fully loaded, the scroll works, but when the page is fully loaded, the scroll goes back up

import React from 'react';

const useScrollToLocation = () => {
    React.useEffect(() => {
        const hash = window.location.hash;
        const id = hash.replace('#', '');
        const element = document.getElementById(id);
        window.location.hash = '';
        if (element) {
            window.location.hash = id;
        }
    }, []);
};
export default useScrollToLocation;


问:
Generate blob data from json object in node/express
How can I create blob data from json object ?

I tried few approaches as shown below but front-end always receives empty blob.

Approach: 1

```<code>const buffer = require("buffer");

const myJsonFileData = { "id": 1, "name":"abc"};

const str = JSON.stringify(myJsonFileData );

const bytes = new TextEncoder().encode(str);

const blobForJsonFile = new buffer.Blob([bytes], {
    type: "application/json;charset=utf-8"
});

return res.send({filename:'xxx.json', blob: blobForJsonFile });
</code>```

But front-end always receives

```<code>blob: {}
filename: "xxx.json"
</code>```

If I get proper blob data, at FE, I want create xxx.json file.

Approach: 2

```<code>const Blob = require("buffer").Blob;

const myJsonFileData = { "id": 1, "name":"abc"};

const blob1 = new Blob([JSON.stringify(myJsonFileData , null, 2)], {
                        type: 'application/json',
              });

return res.send({filename:'xxx.json', blob: blobForJsonFile });
</code>```

But it does give same empty result.

Body:
How can I create blob data from json object ?

I tried few approaches as shown below but front-end always receives empty blob.

Approach: 1

const buffer = require("buffer");

const myJsonFileData = { "id": 1, "name":"abc"};

const str = JSON.stringify(myJsonFileData );

const bytes = new TextEncoder().encode(str);

const blobForJsonFile = new buffer.Blob([bytes], {
    type: "application/json;charset=utf-8"
});

return res.send({filename:'xxx.json', blob: blobForJsonFile });

But front-end always receives

blob: {}
filename: "xxx.json"

If I get proper blob data, at FE, I want create xxx.json file.

Approach: 2

const Blob = require("buffer").Blob;

const myJsonFileData = { "id": 1, "name":"abc"};

const blob1 = new Blob([JSON.stringify(myJsonFileData , null, 2)], {
                        type: 'application/json',
              });

return res.send({filename:'xxx.json', blob: blobForJsonFile });

But it does give same empty result.


问:
How to prevent user from dragging a control added to a user control container at design time
We want to create a usercontrol as container for maintain button status and arrange button location called ucSwitchButtonList.

This usercontrol added only one FlowLayoutControl.

After compiling, you can add ucSwitchButtonList on the form and successfully add buttons from CollectionEditor.

We can modify button objects added in ucSwitchButtonList and set properties at design time.

But, when we drag any button at design time, Visual Studio throws a NullReferenceException exception.

How to prevent user from dragging buttons in ucSwitchButtonList at design time? Or how to handle drag event at design time?

I want to achieve the effect of TabPage in TabControl, which can be selected but not dragged at design time.

ucSwitchButtonList.Designer.cs:

```<code>partial class ucSwitchButtonList
{
    private System.ComponentModel.IContainer components = null;

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        this.flpBtnContainer = new System.Windows.Forms.FlowLayoutPanel();
        this.SuspendLayout();
        //
        // flpBtnContainer
        //
        this.flpBtnContainer.AutoScroll = true;
        this.flpBtnContainer.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
        this.flpBtnContainer.Location = new System.Drawing.Point(1, 1);
        this.flpBtnContainer.Margin = new System.Windows.Forms.Padding(0);
        this.flpBtnContainer.Name = "flpBtnContainer";
        this.flpBtnContainer.Size = new System.Drawing.Size(116, 91);
        this.flpBtnContainer.TabIndex = 0;
        //
        // ucSwitchButtonList
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
        this.Controls.Add(this.flpBtnContainer);
        this.DoubleBuffered = true;
        this.Font = new System.Drawing.Font("新細明體", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
        this.Name = "ucSwitchButtonList";
        this.Padding = new System.Windows.Forms.Padding(1);
        this.Size = new System.Drawing.Size(209, 202);
        this.Load += new System.EventHandler(this.ucSwitchButtonList_Load);
        this.ResumeLayout(false);

    }

    private System.Windows.Forms.Panel flpBtnContainer;
}
</code>```

ucSwitchButtonList.cs:

```<code>public partial class ucSwitchButtonList : UserControl
{
    ObservableCollection<Button> _ButtonList = new System.Collections.ObjectModel.ObservableCollection<Button>();
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    [Browsable(true), EditorBrowsable(EditorBrowsableState.Always),
    Editor(typeof(CollectionEditor), typeof(UITypeEditor))
    ]
    public ObservableCollection<Button> ButtonList
    {
        get => _ButtonList;
    }

    public ucSwitchButtonList()
    {
        InitializeComponent();
        flpBtnContainer.Padding = new Padding(0);
        flpBtnContainer.Size = this.Size;
        flpBtnContainer.Dock = DockStyle.Fill;
        _ButtonList.CollectionChanged += ButtonList_CollectionChanged;
        Size = new Size(80, 160);
    }

    private void ucSwitchButtonList_Load(object sender, EventArgs e)
    {

    }

    private void ButtonList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        flpBtnContainer.SuspendLayout();
        flpBtnContainer.Controls.Clear();
        flpBtnContainer.Controls.AddRange(_ButtonList.ToArray());
        flpBtnContainer.ResumeLayout();

        foreach (Control ctl in flpBtnContainer.Controls)
        {
            if (ctl is Button btn)
            {
                btn.Click += Btn_Click;
                if (e.NewItems.Contains(btn))
                {
                    btn.BackColor = Color.White;
                }
            }
        }

        Invalidate(true);
    }

    private void Btn_Click(object sender, EventArgs e)
    {
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if (DesignMode && BorderStyle == BorderStyle.None)
        {
            var rect = Rectangle.Inflate(ClientRectangle, 0, 0);
            rect.Width--;
            rect.Height--;
            Color lc = ControlPaint.Dark(Parent.BackColor);
            if (lc == Parent.BackColor) lc = ControlPaint.LightLight(Parent.BackColor);

            using (Pen lp = new Pen(lc))
            {
                lp.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                lp.Alignment = System.Drawing.Drawing2D.PenAlignment.Center;
                e.Graphics.DrawRectangle(lp, rect);
            }
        }
    }

}
</code>```

Body:
We want to create a usercontrol as container for maintain button status and arrange button location called ucSwitchButtonList.

This usercontrol added only one FlowLayoutControl.

After compiling, you can add ucSwitchButtonList on the form and successfully add buttons from CollectionEditor.

We can modify button objects added in ucSwitchButtonList and set properties at design time.

But, when we drag any button at design time, Visual Studio throws a NullReferenceException exception.

How to prevent user from dragging buttons in ucSwitchButtonList at design time? Or how to handle drag event at design time?

I want to achieve the effect of TabPage in TabControl, which can be selected but not dragged at design time.

ucSwitchButtonList.Designer.cs:

partial class ucSwitchButtonList
{
    private System.ComponentModel.IContainer components = null;

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        this.flpBtnContainer = new System.Windows.Forms.FlowLayoutPanel();
        this.SuspendLayout();
        //
        // flpBtnContainer
        //
        this.flpBtnContainer.AutoScroll = true;
        this.flpBtnContainer.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
        this.flpBtnContainer.Location = new System.Drawing.Point(1, 1);
        this.flpBtnContainer.Margin = new System.Windows.Forms.Padding(0);
        this.flpBtnContainer.Name = "flpBtnContainer";
        this.flpBtnContainer.Size = new System.Drawing.Size(116, 91);
        this.flpBtnContainer.TabIndex = 0;
        //
        // ucSwitchButtonList
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
        this.Controls.Add(this.flpBtnContainer);
        this.DoubleBuffered = true;
        this.Font = new System.Drawing.Font("新細明體", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
        this.Name = "ucSwitchButtonList";
        this.Padding = new System.Windows.Forms.Padding(1);
        this.Size = new System.Drawing.Size(209, 202);
        this.Load += new System.EventHandler(this.ucSwitchButtonList_Load);
        this.ResumeLayout(false);

    }

    private System.Windows.Forms.Panel flpBtnContainer;
}

ucSwitchButtonList.cs:

public partial class ucSwitchButtonList : UserControl
{
    ObservableCollection<Button> _ButtonList = new System.Collections.ObjectModel.ObservableCollection<Button>();
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    [Browsable(true), EditorBrowsable(EditorBrowsableState.Always),
    Editor(typeof(CollectionEditor), typeof(UITypeEditor))
    ]
    public ObservableCollection<Button> ButtonList
    {
        get => _ButtonList;
    }

    public ucSwitchButtonList()
    {
        InitializeComponent();
        flpBtnContainer.Padding = new Padding(0);
        flpBtnContainer.Size = this.Size;
        flpBtnContainer.Dock = DockStyle.Fill;
        _ButtonList.CollectionChanged += ButtonList_CollectionChanged;
        Size = new Size(80, 160);
    }

    private void ucSwitchButtonList_Load(object sender, EventArgs e)
    {

    }

    private void ButtonList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        flpBtnContainer.SuspendLayout();
        flpBtnContainer.Controls.Clear();
        flpBtnContainer.Controls.AddRange(_ButtonList.ToArray());
        flpBtnContainer.ResumeLayout();

        foreach (Control ctl in flpBtnContainer.Controls)
        {
            if (ctl is Button btn)
            {
                btn.Click += Btn_Click;
                if (e.NewItems.Contains(btn))
                {
                    btn.BackColor = Color.White;
                }
            }
        }

        Invalidate(true);
    }

    private void Btn_Click(object sender, EventArgs e)
    {
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if (DesignMode && BorderStyle == BorderStyle.None)
        {
            var rect = Rectangle.Inflate(ClientRectangle, 0, 0);
            rect.Width--;
            rect.Height--;
            Color lc = ControlPaint.Dark(Parent.BackColor);
            if (lc == Parent.BackColor) lc = ControlPaint.LightLight(Parent.BackColor);

            using (Pen lp = new Pen(lc))
            {
                lp.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                lp.Alignment = System.Drawing.Drawing2D.PenAlignment.Center;
                e.Graphics.DrawRectangle(lp, rect);
            }
        }
    }

}


问:
I want to get the right collision whenever my player touches the box
```<code>import pygame
from sys import exit
import random

pygame.init()

WIDTH, HEIGHT = 800, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My game!")
fps = pygame.time.Clock()
active = True

test_font = pygame.font.Font("letters.ttf", 50)
text_surface = test_font.render("Samad ge mig ett A!", False, (64,64,64))
text_rect = text_surface.get_rect(center = (400,50))

#Box
box_x = random.randint(10, 800)
box = pygame.image.load("box.png").convert_alpha()
box_rect = box.get_rect(midbottom = (box_x,540))

#Background och Ground
background = pygame.image.load("sky.png").convert()
ground = pygame.image.load("ground.png").convert()

#player PNG
player = pygame.image.load("player.png").convert_alpha()
player = pygame.transform.rotozoom(player,0,2.5)
player_rect = player.get_rect(midbottom = (400,325))

#pickaxe PNG
pickaxe = pygame.image.load("pickaxe.png").convert_alpha()
pickaxe = pygame.transform.rotozoom(pickaxe,0,3.5)
pickaxe_rect = pickaxe.get_rect(center = (400,325))

#Gravity
player_gravity = 0
pickaxe_gravity = 0

while True:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      exit()

    if active:
      if event.type == pygame.MOUSEBUTTONDOWN:
        if player_rect.collidepoint(event.pos) and player_rect.bottom >= 325:
          player_gravity = -20
          pickaxe_gravity = -20

      if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT or event.key == pygame.K_a:
          player_rect.x -= 20
          pickaxe_rect.x -= 20

        if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
          player_rect.x += 20
          pickaxe_rect.x += 20

        if (event.key == pygame.K_SPACE or event.key == pygame.K_w or event.key == pygame.K_UP) and player_rect.bottom >= 325:
          player_gravity = -20
          pickaxe_gravity = -20

  if active:
    screen.blit(background,(0,0))
    screen.blit(ground,(0,300))
    screen.blit(box, box_rect)
    screen.blit(pickaxe, pickaxe_rect)
    screen.blit(player,player_rect)
    screen.blit(text_surface, text_rect)

    player_gravity += 1
    pickaxe_gravity += 1
    player_rect.y += player_gravity
    pickaxe_rect.y += pickaxe_gravity
    if pickaxe_rect.bottom >= 325: pickaxe_rect.bottom = 325
    if player_rect.bottom >= 325: player_rect.bottom = 325

    if player_rect.x <= -10 and pickaxe_rect.x <= -10:
      player_rect.x = -10
      pickaxe_rect.x = player_rect.x - 70

    if player_rect.colliderect(box_rect): print("1")

  pygame.display.update()
  fps.tick(60)
</code>```

I was trying to get the player to collide with the box but whenever I try it, it always says that it collided even tho i clearly see that it hasn't. Please tell me how to fix it.

I thought that when the player was on the box (or touching it) then it would print "1" that it touched it but it always says "1" even thought i didnt touch it.

Body:
import pygame
from sys import exit
import random

pygame.init()

WIDTH, HEIGHT = 800, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My game!")
fps = pygame.time.Clock()
active = True

test_font = pygame.font.Font("letters.ttf", 50)
text_surface = test_font.render("Samad ge mig ett A!", False, (64,64,64))
text_rect = text_surface.get_rect(center = (400,50))

#Box
box_x = random.randint(10, 800)
box = pygame.image.load("box.png").convert_alpha()
box_rect = box.get_rect(midbottom = (box_x,540))

#Background och Ground
background = pygame.image.load("sky.png").convert()
ground = pygame.image.load("ground.png").convert()

#player PNG
player = pygame.image.load("player.png").convert_alpha()
player = pygame.transform.rotozoom(player,0,2.5)
player_rect = player.get_rect(midbottom = (400,325))

#pickaxe PNG
pickaxe = pygame.image.load("pickaxe.png").convert_alpha()
pickaxe = pygame.transform.rotozoom(pickaxe,0,3.5)
pickaxe_rect = pickaxe.get_rect(center = (400,325))

#Gravity
player_gravity = 0
pickaxe_gravity = 0

while True:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      exit()

    if active:
      if event.type == pygame.MOUSEBUTTONDOWN:
        if player_rect.collidepoint(event.pos) and player_rect.bottom >= 325:
          player_gravity = -20
          pickaxe_gravity = -20

      if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT or event.key == pygame.K_a:
          player_rect.x -= 20
          pickaxe_rect.x -= 20

        if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
          player_rect.x += 20
          pickaxe_rect.x += 20

        if (event.key == pygame.K_SPACE or event.key == pygame.K_w or event.key == pygame.K_UP) and player_rect.bottom >= 325:
          player_gravity = -20
          pickaxe_gravity = -20

  if active:
    screen.blit(background,(0,0))
    screen.blit(ground,(0,300))
    screen.blit(box, box_rect)
    screen.blit(pickaxe, pickaxe_rect)
    screen.blit(player,player_rect)
    screen.blit(text_surface, text_rect)

    player_gravity += 1
    pickaxe_gravity += 1
    player_rect.y += player_gravity
    pickaxe_rect.y += pickaxe_gravity
    if pickaxe_rect.bottom >= 325: pickaxe_rect.bottom = 325
    if player_rect.bottom >= 325: player_rect.bottom = 325

    if player_rect.x <= -10 and pickaxe_rect.x <= -10:
      player_rect.x = -10
      pickaxe_rect.x = player_rect.x - 70

    if player_rect.colliderect(box_rect): print("1")

  pygame.display.update()
  fps.tick(60)

I was trying to get the player to collide with the box but whenever I try it, it always says that it collided even tho i clearly see that it hasn't. Please tell me how to fix it.

I thought that when the player was on the box (or touching it) then it would print "1" that it touched it but it always says "1" even thought i didnt touch it.


问:
How do I autofocus to text input field in modal? Rails 7, Bootstrap 5
I have a search button in the top navbar. When the user clicks, a modal opens with a text input field. I want the keyboard focus to be automatically inside the text input field when the modal opens.

Here is the search modal code:

```<code><div class="modal" id="searchModal" tabindex="1" aria-labelledby="searchModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="searchModalLabel">Search parks</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <%= search_form_for @q, url: :parks do |f| %>
          <%= f.hidden_field :has_entrance_fee_eq %>
          <%= f.hidden_field :region_eq %>

          <div class="form-group">
            <%= f.text_field :name_en_or_name_he_or_description_en_or_description_he_cont,
                              autofocus: true,
                              placeholder: "Search for a park (English or Hebrew)",
                              class: "form-control" %>
          </div>

          <div class="form-group">
            <%= f.submit 'Search parks', name: "", class: "btn btn-primary" %>
          </div>
        <% end %>
      </div>
    </div>
  </div>
</div>
</code>```

I've already tried simply adding autofocus: true in the rails form, but it doesn't work:

```<code>          <div class="form-group">
            <%= f.text_field :name_en_or_name_he_or_description_en_or_description_he_cont,
                              autofocus: true,
                              placeholder: "Search for a park (English or Hebrew)",
                              class: "form-control" %>
          </div>
</code>```

The Bootstrap documentation says:

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:

```<code>var myModal = document.getElementById('myModal')
var myInput = document.getElementById('myInput')

myModal.addEventListener('shown.bs.modal', function () {
  myInput.focus()
})
</code>```

But I'm not really familiar with Javascript so not sure where/how to use this code, if this is indeed the right direction... In general I'm new to coding so any help would be much appreciated, the more specific the better!

Update:

I tried adding the following code to the search modal but it didn't work:

```<code><script>
  // Get the modal and the input element
  var myModal = document.getElementById('searchModal')
  var myInput = document.querySelector('input')

  // Add a listener for the shown.bs.modal event on the modal
  myModal.addEventListener('shown.bs.modal', function() {
    // When the modal is shown, focus the input element
    myInput.focus()
  })
</script>
</code>```

Body:
I have a search button in the top navbar. When the user clicks, a modal opens with a text input field. I want the keyboard focus to be automatically inside the text input field when the modal opens.

Here is the search modal code:

Search parks

        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

        <%= search_form_for @q, url: :parks do |f| %>
          <%= f.hidden_field :has_entrance_fee_eq %>
          <%= f.hidden_field :region_eq %>

            <%= f.text_field :name_en_or_name_he_or_description_en_or_description_he_cont,
                              autofocus: true,
                              placeholder: "Search for a park (English or Hebrew)",
                              class: "form-control" %>

            <%= f.submit 'Search parks', name: "", class: "btn btn-primary" %>

        <% end %>

I've already tried simply adding autofocus: true in the rails form, but it doesn't work:

            <%= f.text_field :name_en_or_name_he_or_description_en_or_description_he_cont,
                              autofocus: true,
                              placeholder: "Search for a park (English or Hebrew)",
                              class: "form-control" %>

The Bootstrap documentation says:

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:

var myModal = document.getElementById('myModal')
var myInput = document.getElementById('myInput')

myModal.addEventListener('shown.bs.modal', function () {
  myInput.focus()
})

But I'm not really familiar with Javascript so not sure where/how to use this code, if this is indeed the right direction... In general I'm new to coding so any help would be much appreciated, the more specific the better!

Update:

I tried adding the following code to the search modal but it didn't work:


问:
Get the condition caught in a if with multiple or conditions in pandas (python)
I'm iterating the rows of a pandas dataframe. In case the row enters the if, I want to print the index of the condition with which it has entered the if.

```<code>if (row['MCN'] == 2) or (row['ERNF'] == 'T') or (row['EAT1'] == 'T6'):
        print("The condition is", index)
</code>```

Is there any way to get this index?

Body:
I'm iterating the rows of a pandas dataframe. In case the row enters the if, I want to print the index of the condition with which it has entered the if.

if (row['MCN'] == 2) or (row['ERNF'] == 'T') or (row['EAT1'] == 'T6'):
        print("The condition is", index)

Is there any way to get this index?