问:
Why Hibernate error when get data @Many to many in hibernate, JPA
I create 2 entities (Student, Subject) with @ManyToMany relationship, I use mysql database. Why does it fail when i send an api localhost:8080/admin2/student (case 1) from postman

```<code>Thank all of you for all your assistance
</code>```

Source: https://github.com/nguyenvantuyen6789/supeo-forum

In Student.java

```<code>@Fetch(value = FetchMode.SUBSELECT)
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "tbl_student_subject", schema = "supeo_forum",
        joinColumns = {@JoinColumn(name = "student_id")},
        inverseJoinColumns = {@JoinColumn(name = "subject_id")})
private Set<Subject> subjects = new HashSet<>(0);
</code>```

and in Subject.java

```<code>@ManyToMany(fetch = FetchType.EAGER, mappedBy = "subjects")
private Set<Student> students = new HashSet<>(0);
</code>```

Case 1: Use database in the file resources/supeo_forum.sql
When I run api from postman, It causes error

```<code>DELETE FROM `tbl_student_subject`;
DELETE FROM `tbl_student`;
DELETE FROM `tbl_subject`;

INSERT INTO `tbl_subject` (`subject_id`, `subject_name`) VALUES
(1, 'Math'),
(2, 'English');

INSERT INTO `tbl_student` (`student_id`, `student_name`) VALUES
(1, 'Jay'),
(2, 'Anna');

INSERT INTO `tbl_student_subject` (`student_id`, `subject_id`) VALUES
(1, 1),
(1, 2),
(2, 2);
</code>```

Result:

{
"timestamp": "2022-02-11T06:56:48.483+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "java.lang.StackOverflowError\n\tat com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1565)\n\tat com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:337)\n\tat com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java)\n\tat org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:149)\n\tat org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:176)\n\tat org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:151)\n\tat org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:2122)\n\tat org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2059)\n\tat org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2037)\n\tat org.hibernate.loader.Loader.doQuery(Loader.java:956)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:357)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:327)\n\tat org.hibernate.loader.Loader.loadCollectionSubselect(Loader.java:2645)\n\tat org.hibernate.loader.collection.SubselectCollectionLoader.initialize(SubselectCollectionLoader.java:64)\n\tat org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:705)\n\tat org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\n\tat org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2203)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:595)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\n\tat org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)\n\tat com.tuyennguyen.supeo.forum.entity.Student.hashCode(Student.java:13)\n\tat java.base/java.util.HashMap.hash(HashMap.java:340)\n\tat java.base/java.util.HashMap.put(HashMap.java:608)\n\tat java.base/java.util.HashSet.add(HashSet.java:220)\n\tat java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352)\n\tat org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198)\n\tat org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154)\n\tat org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:232)\n\tat org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:190)\n\tat org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:96)\n\tat org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:105)\n\tat org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87)\n\tat org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:705)\n\tat org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\n\tat org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2203)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:595)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\n\tat org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)\n\tat com.tuyennguyen.supeo.forum.entity.Subject.hashCode(Subject.java:11)\n\tat java.base/java.util.HashMap.hash(HashMap.java:340)\n\tat java.base/java.util.HashMap.put(HashMap.java:608)\n\tat java.base/java.util.HashSet.add(HashSet.java:220)\n\tat java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352)\n\tat org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198)\n\tat org.hibernate.loader.Loader.endCollectionLoad(Loader.java:1257)\n\tat org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1214)\n\tat org.hibernate.loader.Loader.processResultSet(Loader.java:1009)\n\tat org.hibernate.loader.Loader.doQuery(Loader.java:967)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:357)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:327)\n\tat org.hibernate.loader.Loader.loadCollectionSubselect(Loader.java:2645)\n\tat org.hibernate.loader.collection.SubselectCollectionLoader.initialize(SubselectCollectionLoader.java:64)\n\tat org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:705)\n\tat org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\n\tat org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2203)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:595)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\n\tat org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)\n\tat com.tuyennguyen.supeo.forum.entity.Student.hashCode(Student.java:13)\n\tat java.base/java.util.HashMap.hash(HashMap.java:340)\n\tat java.base/java.util.HashMap.put(HashMap.java:608)\n\tat java.base/java.util.HashSet.add(HashSet.java:220)\n\tat java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352)\n\tat org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198)\n\tat org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154)\n\tat org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:232)\n\tat org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:190)\n\tat org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:96)\n\tat org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:105)\n\tat org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87)\n\tat org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:705)\n\tat org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\n\tat org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2203)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:595)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\n\tat org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)\n\tat com.tuyennguyen.supeo.forum.entity.Subject.hashCode(Subject.java:11)\n\tat java.base/java.util.HashMap.hash(HashMap.java:340)\n\tat java.base/java.util.HashMap.put(HashMap.java:608)\n\tat java.base/java.util.HashSet.add(HashSet.java:220)\n\tat java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352)\n\tat org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198)\n\tat org.hibernate.loader.Loader.endCollectionLoad(Loader.java:1257)\n\tat org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1214)\n\tat org.hibernate.loader.Loader.processResultSet(Loader.java:1009)\n\tat org.hibernate.loader.Loader.doQuery(Loader.java:967)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:357)\n\tat
...

Case 2: Use database in the file resources/supeo_forum2.sql
When I run api from postman, It causes error

```<code>DELETE FROM `tbl_student_subject`;

DELETE FROM `tbl_student`;
INSERT INTO `tbl_student` (`student_id`, `student_name`) VALUES
(1, 'Jay'),
(2, 'Anna');

DELETE FROM `tbl_subject`;
INSERT INTO `tbl_subject` (`subject_id`, `subject_name`) VALUES
(1, 'Math'),
(2, 'English');
</code>```

Result:

```<code>[
    {
        "studentId": 1,
        "studentName": "Jay",
        "subjects": []
    },
    {
        "studentId": 2,
        "studentName": "Anna",
        "subjects": []
    }
]
</code>```

答:
java.lang.StackOverflowError is because recursive calls between your Subject and Student. Try adding @EqualsAndHashCode.Exclude and @ToString.Exclude to one side of the relationship or both.

@Fetch(value = FetchMode.SUBSELECT)
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "tbl_student_subject", schema = "supeo_forum",
        joinColumns = {@JoinColumn(name = "student_id")},
        inverseJoinColumns = {@JoinColumn(name = "subject_id")})
@EqualsAndHashCode.Exclude // <<<<<<<<<<
@ToString.Exclude // <<<<<<<
private Set<Subject> subjects = new HashSet<>(0);
```
<pre class="lang-java prettyprint-override"><code>@ManyToMany(fetch = FetchType.EAGER, mappedBy = "subjects")
@EqualsAndHashCode.Exclude // <<<<<<<<<<
@ToString.Exclude // <<<<<<<
private Set<Student> students = new HashSet<>(0);
</code>```

Body:
I create 2 entities (Student, Subject) with @ManyToMany relationship, I use mysql database. Why does it fail when i send an api localhost:8080/admin2/student (case 1) from postman

Thank all of you for all your assistance

Source: https://github.com/nguyenvantuyen6789/supeo-forum

In Student.java

@Fetch(value = FetchMode.SUBSELECT)
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "tbl_student_subject", schema = "supeo_forum",
        joinColumns = {@JoinColumn(name = "student_id")},
        inverseJoinColumns = {@JoinColumn(name = "subject_id")})
private Set<Subject> subjects = new HashSet<>(0);

and in Subject.java

@ManyToMany(fetch = FetchType.EAGER, mappedBy = "subjects")
private Set<Student> students = new HashSet<>(0);

Case 1: Use database in the file resources/supeo_forum.sql
When I run api from postman, It causes error

DELETE FROM `tbl_student_subject`;
DELETE FROM `tbl_student`;
DELETE FROM `tbl_subject`;

INSERT INTO `tbl_subject` (`subject_id`, `subject_name`) VALUES
(1, 'Math'),
(2, 'English');

INSERT INTO `tbl_student` (`student_id`, `student_name`) VALUES
(1, 'Jay'),
(2, 'Anna');

INSERT INTO `tbl_student_subject` (`student_id`, `subject_id`) VALUES
(1, 1),
(1, 2),
(2, 2);

Result:

{
"timestamp": "2022-02-11T06:56:48.483+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "java.lang.StackOverflowError\n\tat com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1565)\n\tat com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:337)\n\tat com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java)\n\tat org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:149)\n\tat org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:176)\n\tat org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:151)\n\tat org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:2122)\n\tat org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2059)\n\tat org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2037)\n\tat org.hibernate.loader.Loader.doQuery(Loader.java:956)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:357)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:327)\n\tat org.hibernate.loader.Loader.loadCollectionSubselect(Loader.java:2645)\n\tat org.hibernate.loader.collection.SubselectCollectionLoader.initialize(SubselectCollectionLoader.java:64)\n\tat org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:705)\n\tat org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\n\tat org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2203)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:595)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\n\tat org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)\n\tat com.tuyennguyen.supeo.forum.entity.Student.hashCode(Student.java:13)\n\tat java.base/java.util.HashMap.hash(HashMap.java:340)\n\tat java.base/java.util.HashMap.put(HashMap.java:608)\n\tat java.base/java.util.HashSet.add(HashSet.java:220)\n\tat java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352)\n\tat org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198)\n\tat org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154)\n\tat org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:232)\n\tat org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:190)\n\tat org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:96)\n\tat org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:105)\n\tat org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87)\n\tat org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:705)\n\tat org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\n\tat org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2203)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:595)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\n\tat org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)\n\tat com.tuyennguyen.supeo.forum.entity.Subject.hashCode(Subject.java:11)\n\tat java.base/java.util.HashMap.hash(HashMap.java:340)\n\tat java.base/java.util.HashMap.put(HashMap.java:608)\n\tat java.base/java.util.HashSet.add(HashSet.java:220)\n\tat java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352)\n\tat org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198)\n\tat org.hibernate.loader.Loader.endCollectionLoad(Loader.java:1257)\n\tat org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1214)\n\tat org.hibernate.loader.Loader.processResultSet(Loader.java:1009)\n\tat org.hibernate.loader.Loader.doQuery(Loader.java:967)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:357)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:327)\n\tat org.hibernate.loader.Loader.loadCollectionSubselect(Loader.java:2645)\n\tat org.hibernate.loader.collection.SubselectCollectionLoader.initialize(SubselectCollectionLoader.java:64)\n\tat org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:705)\n\tat org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\n\tat org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2203)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:595)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\n\tat org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)\n\tat com.tuyennguyen.supeo.forum.entity.Student.hashCode(Student.java:13)\n\tat java.base/java.util.HashMap.hash(HashMap.java:340)\n\tat java.base/java.util.HashMap.put(HashMap.java:608)\n\tat java.base/java.util.HashSet.add(HashSet.java:220)\n\tat java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352)\n\tat org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198)\n\tat org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154)\n\tat org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:232)\n\tat org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:190)\n\tat org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:96)\n\tat org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:105)\n\tat org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87)\n\tat org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:705)\n\tat org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76)\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\n\tat org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2203)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:595)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\n\tat org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458)\n\tat com.tuyennguyen.supeo.forum.entity.Subject.hashCode(Subject.java:11)\n\tat java.base/java.util.HashMap.hash(HashMap.java:340)\n\tat java.base/java.util.HashMap.put(HashMap.java:608)\n\tat java.base/java.util.HashSet.add(HashSet.java:220)\n\tat java.base/java.util.AbstractCollection.addAll(AbstractCollection.java:352)\n\tat org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224)\n\tat org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198)\n\tat org.hibernate.loader.Loader.endCollectionLoad(Loader.java:1257)\n\tat org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1214)\n\tat org.hibernate.loader.Loader.processResultSet(Loader.java:1009)\n\tat org.hibernate.loader.Loader.doQuery(Loader.java:967)\n\tat org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:357)\n\tat
...

Case 2: Use database in the file resources/supeo_forum2.sql
When I run api from postman, It causes error

DELETE FROM `tbl_student_subject`;

DELETE FROM `tbl_student`;
INSERT INTO `tbl_student` (`student_id`, `student_name`) VALUES
(1, 'Jay'),
(2, 'Anna');

DELETE FROM `tbl_subject`;
INSERT INTO `tbl_subject` (`subject_id`, `subject_name`) VALUES
(1, 'Math'),
(2, 'English');

Result:

[
    {
        "studentId": 1,
        "studentName": "Jay",
        "subjects": []
    },
    {
        "studentId": 2,
        "studentName": "Anna",
        "subjects": []
    }
]

Body:
java.lang.StackOverflowError is because recursive calls between your Subject and Student. Try adding @EqualsAndHashCode.Exclude and @ToString.Exclude to one side of the relationship or both.

@Fetch(value = FetchMode.SUBSELECT)
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "tbl_student_subject", schema = "supeo_forum",
        joinColumns = {@JoinColumn(name = "student_id")},
        inverseJoinColumns = {@JoinColumn(name = "subject_id")})
@EqualsAndHashCode.Exclude // <<<<<<<<<<
@ToString.Exclude // <<<<<<<
private Set<Subject> subjects = new HashSet<>(0);

@ManyToMany(fetch = FetchType.EAGER, mappedBy = "subjects")
@EqualsAndHashCode.Exclude // <<<<<<<<<<
@ToString.Exclude // <<<<<<<
private Set<Student> students = new HashSet<>(0);


来源: stackexchange

问:
How to size a SingleChildScrollView dynamically inside a Column?
I'm having a bit of a problem with Flutter's widget placement. Here's the code:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              controller: _scrollController,
              child: DataTable(
                //Rows and columns filled with random data
                columns: const <DataColumn>[
                  DataColumn(
                    label: Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Age',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Role',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Age',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Role',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                ],
                rows: const <DataRow>[
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Janine')),
                      DataCell(Text('43')),
                      DataCell(Text('Professor')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('William')),
                      DataCell(Text('27')),
                      DataCell(Text('Associate Professor')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                ],
              ),
            ),
            //How to make this widget be at the bottom?
            const Text('This widget should be at the bottom'),
          ],
        ),
      ),
    );
  }
}
</code>```

I have a DataTable and a Text widget, wrapped with a Column and two SingleChilScrollViews in order to have bidirectional scrolling (the table is larger than the screen). I want to place the Text widget on the bottom of the screen. Tinkering with the code, I can do it pretty easily by giving the Column widget a parent Container, and fixing its size to my screen. However, how would I go about sizing it dynamically? I've tried using MediaQuery but the result was not that accurate. This "fix" can be found below:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                controller: _scrollController,
                child: DataTable(
                  //Rows and columns filled with random data
                  columns: const <DataColumn>[
                    DataColumn(
                      label: Text(
                        'Name',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Age',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Role',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Name',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Age',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Role',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                  ],
                  rows: const <DataRow>[
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('Janine')),
                        DataCell(Text('43')),
                        DataCell(Text('Professor')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('William')),
                        DataCell(Text('27')),
                        DataCell(Text('Associate Professor')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                  ],
                ),
              ),
              //How to make this widget be at the bottom?
              const Text('This widget should be at the bottom'),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Any ideas or suggestions on how to tackle this issue? Thanks.

EDIT

Using the text in the bottomNavigationBar of the Scaffold works as well, however it doens't seem an appropriate solution.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: ListView(
        children: [
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              //Rows and columns filled with random data
              columns: const <DataColumn>[
                DataColumn(
                  label: Text(
                    'Name',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Age',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Role',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Name',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Age',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Role',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
              ],
              rows: const <DataRow>[
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('Janine')),
                    DataCell(Text('43')),
                    DataCell(Text('Professor')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('William')),
                    DataCell(Text('27')),
                    DataCell(Text('Associate Professor')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: const Text('Is at the bottom - doesnt seem right'),
    );
  }
}
</code>```

答:
You can use a SingleChildScrollView inside a Listview to achive that.</p>
```<code>ListView(
 children: [
  SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    child: Column(
     children: [
       //Your table goes here
     ],
    ),
   ),
   Text(
    //Your bottom text goes here,
   ),
  ],
 ),
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having a bit of a problem with Flutter's widget placement. Here's the code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              controller: _scrollController,
              child: DataTable(
                //Rows and columns filled with random data
                columns: const <DataColumn>[
                  DataColumn(
                    label: Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Age',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Role',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Name',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Age',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Role',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                ],
                rows: const <DataRow>[
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('Janine')),
                      DataCell(Text('43')),
                      DataCell(Text('Professor')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                  DataRow(
                    cells: <DataCell>[
                      DataCell(Text('William')),
                      DataCell(Text('27')),
                      DataCell(Text('Associate Professor')),
                      DataCell(Text('Sarah')),
                      DataCell(Text('19')),
                      DataCell(Text('Student')),
                    ],
                  ),
                ],
              ),
            ),
            //How to make this widget be at the bottom?
            const Text('This widget should be at the bottom'),
          ],
        ),
      ),
    );
  }
}

I have a DataTable and a Text widget, wrapped with a Column and two SingleChilScrollViews in order to have bidirectional scrolling (the table is larger than the screen). I want to place the Text widget on the bottom of the screen. Tinkering with the code, I can do it pretty easily by giving the Column widget a parent Container, and fixing its size to my screen. However, how would I go about sizing it dynamically? I've tried using MediaQuery but the result was not that accurate. This "fix" can be found below:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                controller: _scrollController,
                child: DataTable(
                  //Rows and columns filled with random data
                  columns: const <DataColumn>[
                    DataColumn(
                      label: Text(
                        'Name',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Age',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Role',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Name',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Age',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Role',
                        style: TextStyle(fontStyle: FontStyle.italic),
                      ),
                    ),
                  ],
                  rows: const <DataRow>[
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('Janine')),
                        DataCell(Text('43')),
                        DataCell(Text('Professor')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text('William')),
                        DataCell(Text('27')),
                        DataCell(Text('Associate Professor')),
                        DataCell(Text('Sarah')),
                        DataCell(Text('19')),
                        DataCell(Text('Student')),
                      ],
                    ),
                  ],
                ),
              ),
              //How to make this widget be at the bottom?
              const Text('This widget should be at the bottom'),
            ],
          ),
        ),
      ),
    );
  }
}

Any ideas or suggestions on how to tackle this issue? Thanks.

EDIT

Using the text in the bottomNavigationBar of the Scaffold works as well, however it doens't seem an appropriate solution.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: ListView(
        children: [
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              //Rows and columns filled with random data
              columns: const <DataColumn>[
                DataColumn(
                  label: Text(
                    'Name',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Age',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Role',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Name',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Age',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
                DataColumn(
                  label: Text(
                    'Role',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
              ],
              rows: const <DataRow>[
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('Janine')),
                    DataCell(Text('43')),
                    DataCell(Text('Professor')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
                DataRow(
                  cells: <DataCell>[
                    DataCell(Text('William')),
                    DataCell(Text('27')),
                    DataCell(Text('Associate Professor')),
                    DataCell(Text('Sarah')),
                    DataCell(Text('19')),
                    DataCell(Text('Student')),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: const Text('Is at the bottom - doesnt seem right'),
    );
  }
}

Body:
You can use a SingleChildScrollView inside a Listview to achive that.

ListView(
 children: [
  SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    child: Column(
     children: [
       //Your table goes here
     ],
    ),
   ),
   Text(
    //Your bottom text goes here,
   ),
  ],
 ),


问:
This version of selection sort I tried to make doesnot work properly, but it works surprisingly for larger arrays
I was doing selection sort yesterday. I wondered if I could replace the min and max values to begining and end of the unsorted array every time I iterated. I am just a beginner at programming, so its obvious that this wouldn't work. However, suprisingly, the code below does sort a larger array (~ 30k - 40k) in size. I experimented by generating random values from rand()%2000 and the function sorted the array successfully 28 times in 30 experiments.

But it can't sort something as simple as {4,2,3}
I think there's a bug somewhere, I couldn't figure it out so I've come here.

I'm also curious about the fact that it sorted such large arrays successfully. How?

```<code>int *zigzag_sort(int arr[])
{
    // loop through array
    // find min and max
    // replace min at begining and max at end
    // keep doing until sorted

    int f_idx = 0, l_idx = n-1;
    int min_pos, max_pos;

    while( f_idx < l_idx ) {
        min_pos = f_idx;
        max_pos = l_idx;

        for(int i = f_idx+1; i <= l_idx; i++)
        {
            if(arr[i] < arr[min_pos])
                min_pos = i;
            else if(arr[i] > arr[max_pos])
                max_pos = i;
        }
        swap(&arr[f_idx], &arr[min_pos]);
        swap(&arr[l_idx], &arr[max_pos]);

        f_idx++;
        l_idx--;
        }

    return arr;
}

</code>```
```<code>void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
</code>```

Body:
I was doing selection sort yesterday. I wondered if I could replace the min and max values to begining and end of the unsorted array every time I iterated. I am just a beginner at programming, so its obvious that this wouldn't work. However, suprisingly, the code below does sort a larger array (~ 30k - 40k) in size. I experimented by generating random values from rand()%2000 and the function sorted the array successfully 28 times in 30 experiments.

But it can't sort something as simple as {4,2,3}
I think there's a bug somewhere, I couldn't figure it out so I've come here.

I'm also curious about the fact that it sorted such large arrays successfully. How?

int *zigzag_sort(int arr[])
{
    // loop through array
    // find min and max
    // replace min at begining and max at end
    // keep doing until sorted

    int f_idx = 0, l_idx = n-1;
    int min_pos, max_pos;

    while( f_idx < l_idx ) {
        min_pos = f_idx;
        max_pos = l_idx;

        for(int i = f_idx+1; i <= l_idx; i++)
        {
            if(arr[i] < arr[min_pos])
                min_pos = i;
            else if(arr[i] > arr[max_pos])
                max_pos = i;
        }
        swap(&arr[f_idx], &arr[min_pos]);
        swap(&arr[l_idx], &arr[max_pos]);

        f_idx++;
        l_idx--;
        }

    return arr;
}

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

Body:
Why doesn't it work for { 4, 2, 3 }?

    ... // f_idx = 0; l_idx = 2; min_pos = 1; max_pos = 0;
    swap(&arr[f_idx], &arr[min_pos]); // swap(&arr[0], &arr[1]) ==> { 2, 4, 3 }
    // ===> max_pos is "wrong" now <===
    swap(&arr[l_idx], &arr[max_pos]); // swap(&arr[2], &arr[0]) ==> { 3, 4, 2 }


问:
Speed up solving time of this function
This function is working fine but it takes too much time to solve. Please suggest me how to improve the solving time.

```<code>from sympy.solvers import solve
from sympy import Symbol

QD = 25.45
CDI = 0.65
AIN = 33.6
GTL = 10
GTSELV = 2300.1
CDGT = 1.9

def fun(HWE):
    TWE = Symbol('TWE')
    expression = (CDI*AIN*(2*9.81*(HWE-TWE))**0.5) - (CDGT*GTL*(TWE-GTSELV)**1.5)-QD
    solution = solve(expression)
    return solution
</code>```

Function fun(2303) gives [2302.23386564786] which is correct but solving time is about 30 seconds. I need to run this for many arguments.

答:
Use solve when you want a solution in terms of symbols. Use nsolve when you want a numerical solution. In your case, replace solve with nsolve and add the argument HWE to the call statement (i.e. nsolve(expression, HWE)). That 2nd argument is a guess at where the solution is near. Alternatively, give fun a 2nd arg guess and use that as the 2nd arg for nsolve. If you slowly change some parameter, using the last solution as the guess for the next solution will speed up the process (which is already quite fast).

If you know that the solution is real then you might want to take the real part of it with re(solution) since the solution comes back with a small imaginary component.

Title: Speed up solving time of this function

Body:
This function is working fine but it takes too much time to solve. Please suggest me how to improve the solving time.

from sympy.solvers import solve
from sympy import Symbol

QD = 25.45
CDI = 0.65
AIN = 33.6
GTL = 10
GTSELV = 2300.1
CDGT = 1.9

def fun(HWE):
    TWE = Symbol('TWE')
    expression = (CDI*AIN*(2*9.81*(HWE-TWE))**0.5) - (CDGT*GTL*(TWE-GTSELV)**1.5)-QD
    solution = solve(expression)
    return solution

Function fun(2303) gives [2302.23386564786] which is correct but solving time is about 30 seconds. I need to run this for many arguments.


问:
How to disable night mode in my application even if night mode is enable in android 9.0 (pie)?
I created my application before the android pie has been released, in every layout I put android: background = "white" it works fine in every device, but when my brother installed the application and enabled night mode my application becomes a disaster with one single move, everything turns into back and white movie.

```<code><style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/COLOR_PRIMARY</item>
    <item name="colorPrimaryDark">@color/COLOR_PRIMARY</item>
    <item name="colorAccent">@color/COLOR_PRIMARY</item>
    <item name="cardViewStyle">@style/CardView</item>
    <item name="android:fontFamily">@font/helvetica</item>
</style>
</code>```

my color primary is red.

答:
Change both Light and Dark themes to the same colours.
That will not affect output even if the device is in dark mode.

Inside both value/theme.xml and night/theme.xml

Change the following line

```<code><style name="Theme.Labmuffles" parent="Theme.MaterialComponents.DayNight.NoActionBar">
</code>```

to

```<code><style name="Theme.Labmuffles" parent="Theme.MaterialComponents.Light.NoActionBar">
</code>```

The app will be in dark mode but even in the dark mode it will display colours of the light mode and it will stay always light.

Body:
I created my application before the android pie has been released, in every layout I put android: background = "white" it works fine in every device, but when my brother installed the application and enabled night mode my application becomes a disaster with one single move, everything turns into back and white movie.

my color primary is red.

Body:
Change both Light and Dark themes to the same colours.
That will not affect output even if the device is in dark mode.

Inside both value/theme.xml and night/theme.xml

Change the following line

<style name="Theme.Labmuffles" parent="Theme.MaterialComponents.DayNight.NoActionBar">

to

<style name="Theme.Labmuffles" parent="Theme.MaterialComponents.Light.NoActionBar">

The app will be in dark mode but even in the dark mode it will display colours of the light mode and it will stay always light.


问:
ContainsKey Thread Safe
In the following code:

```<code>public class StringCache
{
    private readonly object lockobj = new object();

    private readonly Dictionary<int, string> cache = new Dictionary<int, string>();

    public string GetMemberInfo(int key)
    {
        if (cache.ContainsKey(key))
            return cache[key];
        lock (lockobj)
        {
            if (!cache.ContainsKey(key))
                cache[key] = GetString(key);
        }
        return cache[key];
    }

    private static string GetString(int key)
    {
        return "Not Important";
    }
}
</code>```

1) Is ContainsKey thread safe?  IOW, what happens if that method is executing when another thread is adding something to the dictionary?
2) For the first return cache[key], is there any chance that it could return a garbled value?

TIA,

MB

答:
Dictionary is not Thread-Safe.

If you say that

what happens if that method is
  executing when another thread is
  adding something to the dictionary?

then I suppose other functions access the cache as well. You need to synchronize  accesses(reading and writing) to the cache. Use your lock object in all of these operations.

OwnerDisplayName: MBeckius

ContentLicense: CC BY-SA 2.5

Title: ContainsKey Thread Safe

Body:
In the following code:

public class StringCache
{
    private readonly object lockobj = new object();

    private readonly Dictionary<int, string> cache = new Dictionary<int, string>();

    public string GetMemberInfo(int key)
    {
        if (cache.ContainsKey(key))
            return cache[key];
        lock (lockobj)
        {
            if (!cache.ContainsKey(key))
                cache[key] = GetString(key);
        }
        return cache[key];
    }

    private static string GetString(int key)
    {
        return "Not Important";
    }
}

1) Is ContainsKey thread safe?  IOW, what happens if that method is executing when another thread is adding something to the dictionary?
2) For the first return cache[key], is there any chance that it could return a garbled value?

TIA,

MB

OwnerDisplayName: bruno conde


问:
override component mui v5 react
I'm using mui v5 and I'm trying to override the Container component to be have a padding of 4rem.
here is a simple code example:

```<code>import * as React from "react";
import { Container } from "@mui/material";
import Navbar from "./components/Navbar";
import { styled } from "@mui/system";
import CssBaseline from "@mui/material/CssBaseline";
import { ThemeProvider, StyledEngineProvider } from "@mui/material/styles";
import theme from "./theme";

const MyContainer = styled(Container, {})`
  padding-left: 4rem;
  background-color: aqua;
`;

export default function App() {
   return (
    <ThemeProvider theme={theme}>
       <StyledEngineProvider injectFirst>
         <CssBaseline />
         <MyContainer maxWidth="xl">
            <div>test</div>
         </MyContainer>
      </StyledEngineProvider>
    </ThemeProvider>,
   );
}
</code>```

But this yields no results.
here is a sandbox:
https://codesandbox.io/s/wizardly-leakey-xumyd

答:
You can use make use of shouldForwardProp of mui v5.

```<code>const MyContainer = styled(Container, {
  shouldForwardProp: (prop) => prop
})(({ padding }) => ({
  padding: padding,
  backgroundColor: "aqua"
}));
</code>```

You can check forked codesandbox here
open this

Title: override component mui v5 react

Body:
I'm using mui v5 and I'm trying to override the Container component to be have a padding of 4rem.
here is a simple code example:

import * as React from "react";
import { Container } from "@mui/material";
import Navbar from "./components/Navbar";
import { styled } from "@mui/system";
import CssBaseline from "@mui/material/CssBaseline";
import { ThemeProvider, StyledEngineProvider } from "@mui/material/styles";
import theme from "./theme";

const MyContainer = styled(Container, {})`
  padding-left: 4rem;
  background-color: aqua;
`;

export default function App() {
   return (
    <ThemeProvider theme={theme}>

    </ThemeProvider>,
   );
}

But this yields no results.
here is a sandbox:
https://codesandbox.io/s/wizardly-leakey-xumyd

Body:
You can use make use of shouldForwardProp of mui v5.

const MyContainer = styled(Container, {
  shouldForwardProp: (prop) => prop
})(({ padding }) => ({
  padding: padding,
  backgroundColor: "aqua"
}));

You can check forked codesandbox here
open this


问:
Django how to set a class based view queryset with function return
im trying to make endless pagination with filtered data and im geting the data with get request.

views.py:

```<code>class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        renkler = Renk.objects.all()
        beden = Varyasyon.objects.all()
        katagori = Grub.objects.all()
        order = self.request.GET.get('order')
        filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
        checked_var = self.request.GET.getlist('varyasyon_id__in')
        checked_renk = self.request.GET.getlist('renk_id__in')
        checked_kat = self.request.GET.getlist('grub_id__in')
        if self.request.GET.getlist("varyasyon_id__in"):
            filtered = filtered.filter(
                Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
            )
        if self.request.GET.getlist("renk_id__in"):
            filtered = filtered.filter(
                Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
            )
        if self.request.GET.getlist("grub_id__in"):
            filtered = filtered.filter(
                Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
            )

        if order == "date":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )
        elif order == "sale":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
        )
        elif order == "tesettur":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
        )
        else:
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )

        context = {"renkler":renkler,"bedenler":beden,"katagoriler":katagori,'filtered':filters,'checkedvar':checked_var,'checkedrenk':checked_renk,'checkedkat':checked_kat}
        self.queryset = context
        return context
    queryset = get_context_data()
</code>```

i want to set the queryset from get_context_data's return but it asks for self argument.

error

```<code>TypeError: ProductsView.get_context_data() missing 1 required positional argument: 'self'
</code>```

when i define queryset on the top it says that get_context_data is not defined.

答:
First - why your code fails. You override get_context_data, then make invalid call to it (you don't pass self to it at all), and finally all this happens during class creation, not instantiation, so get_context_data isn't aware about request when you call it on last line. And context_data is not same thing as queryset. Here's what you can do instead to get paginated content of filtered queryset:

class ProductsView(ListView):
    paginate_by = 20
    context_object_name = 'filtered'
    template_name = 'urunler.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'renkler': Renk.objects.all(),
            'bedenler': Varyasyon.objects.all(),
            'katagoriler': Grub.objects.all(),
            'checkedvar':  self.request.GET.getlist('varyasyon_id__in'),
            'checkedrenk': self.request.GET.getlist('renk_id__in'),
            'checkedkat': self.request.GET.getlist('grub_id__in'),
        })
        return context

    def get_queryset(self):
        filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')

        checked_var = self.request.GET.getlist('varyasyon_id__in')
        checked_renk = self.request.GET.getlist('renk_id__in')
        checked_kat = self.request.GET.getlist('grub_id__in')
        if checked_var:
            filtered = filtered.filter(varyasyon_id__in=checked_var)
        if checked_renk:
            filtered = filtered.filter(renk_id__in=checked_renk)
        if checked_cat:
            filtered = filtered.filter(grub_id__in=checked_cat)

        filtered = filtered.filter(urun_id__yayin=True, stok_adet__gt=0)
        order = self.request.GET.get('order')
        if order == "sale":
            filtered = filtered.filter(indirim=True)
        elif order == "tesettur":
            filtered = filtered.filter(urun_id__tesettur=True)

        return filtered
```

Body:
im trying to make endless pagination with filtered data and im geting the data with get request.

views.py:

class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        renkler = Renk.objects.all()
        beden = Varyasyon.objects.all()
        katagori = Grub.objects.all()
        order = self.request.GET.get('order')
        filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
        checked_var = self.request.GET.getlist('varyasyon_id__in')
        checked_renk = self.request.GET.getlist('renk_id__in')
        checked_kat = self.request.GET.getlist('grub_id__in')
        if self.request.GET.getlist("varyasyon_id__in"):
            filtered = filtered.filter(
                Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
            )
        if self.request.GET.getlist("renk_id__in"):
            filtered = filtered.filter(
                Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
            )
        if self.request.GET.getlist("grub_id__in"):
            filtered = filtered.filter(
                Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
            )

        if order == "date":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )
        elif order == "sale":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
        )
        elif order == "tesettur":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
        )
        else:
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )

        context = {"renkler":renkler,"bedenler":beden,"katagoriler":katagori,'filtered':filters,'checkedvar':checked_var,'checkedrenk':checked_renk,'checkedkat':checked_kat}
        self.queryset = context
        return context
    queryset = get_context_data()

i want to set the queryset from get_context_data's return but it asks for self argument.

error

TypeError: ProductsView.get_context_data() missing 1 required positional argument: 'self'

when i define queryset on the top it says that get_context_data is not defined.


问:
'>' not supported between instances of 'dict' and 'dict' in Django 3.0
I am using Django 3.0 and Python 3.7

here is my views.py

```<code>@login_required
def updated_status(request, pk):
    s1 = []
    purchase_quantity = Item.objects.filter(order_id=pk)
    data = set()
    a = [x.id for x in purchase_quantity if x.id not in data and not data.add(x.id)]
    stock_quantity = Stock.objects.filter(other_id=pk)
    data1 = set()
    b = [x.other_item.id for x in stock_quantity if
         x.other_item.id not in data1 and not data1.add(x.other_item.id)]
    if data == data1:
        for j in data1:
            stock_quantity = Stock.objects.filter(other_order_id=pk,
                                                           other_item_id=j).aggregate(Sum('quantity'))
            purchase_quantity = Item.objects.filter(
                    other_id=pk, id=j).aggregate(Sum('quantity'))
            if stock_quantity > purchase_quantity:
                Order.objects.filter(id=pk).update(flag=1)
            if stock_quantity >= purchase_quantity:
                s1.append('true')
            else:
                s1.append('false')
            if 'false' in s1:
                Order.objects.filter(id=pk).update(status=3)
            else:
                Order.objects.filter(id=pk).update(status=2)
    else:
        pass
    return redirect(reverse('get_list_data'))
</code>```

How could i solve this issue " TypeError: '>' not supported between instances of 'dict' and 'dict' "

答:
Both stock_quantity and purchase_quantity are dictionaries here: you need to unwrap the item from the dictionary, so:

```<code>stock_quantity = StockMovements.objects.filter(
    other_order_id=pk, other_order_item_id=j
).aggregate(Sum('quantity'))<strong>['quantity__sum']</strong>
purchase_item_quantity = OtherOrderItem.objects.filter(
    other_order_id=pk, id=j
).aggregate(Sum('quantity'))<strong>['quantity__sum']</strong></code>```

Body:
I am using Django 3.0 and Python 3.7

here is my views.py

@login_required
def updated_status(request, pk):
    s1 = []
    purchase_quantity = Item.objects.filter(order_id=pk)
    data = set()
    a = [x.id for x in purchase_quantity if x.id not in data and not data.add(x.id)]
    stock_quantity = Stock.objects.filter(other_id=pk)
    data1 = set()
    b = [x.other_item.id for x in stock_quantity if
         x.other_item.id not in data1 and not data1.add(x.other_item.id)]
    if data == data1:
        for j in data1:
            stock_quantity = Stock.objects.filter(other_order_id=pk,
                                                           other_item_id=j).aggregate(Sum('quantity'))
            purchase_quantity = Item.objects.filter(
                    other_id=pk, id=j).aggregate(Sum('quantity'))
            if stock_quantity > purchase_quantity:
                Order.objects.filter(id=pk).update(flag=1)
            if stock_quantity >= purchase_quantity:
                s1.append('true')
            else:
                s1.append('false')
            if 'false' in s1:
                Order.objects.filter(id=pk).update(status=3)
            else:
                Order.objects.filter(id=pk).update(status=2)
    else:
        pass
    return redirect(reverse('get_list_data'))

How could i solve this issue " TypeError: '>' not supported between instances of 'dict' and 'dict' "

Body:
Both stock_quantity and purchase_quantity are dictionaries here: you need to unwrap the item from the dictionary, so:

stock_quantity = StockMovements.objects.filter(
    other_order_id=pk, other_order_item_id=j
).aggregate(Sum('quantity'))['quantity__sum']
purchase_item_quantity = OtherOrderItem.objects.filter(
    other_order_id=pk, id=j
).aggregate(Sum('quantity'))['quantity__sum']


问:
Bigquery - Column name name is ambiguous at [2:3]
I am new to this -  The below query is showing an error - employees and departments are tables and departmnet_id is the column name.

SELECT
name,
department_id,
role
FROM
employee_data.employees
INNER JOIN
employee_data.departments
ON
'august-emitter-173906.employee_data.employees.department_id' = 'august-emitter-173906.employee_data.departments.department_id'

答:
This is because your department_id in your select could refer to either department id from departments or employees.

Try using an alias like:

```<code>SELECT
emp.name, emp.department_id, emp.role
FROM employee_data.employees emp
INNER JOIN employee_data.departments  dep
ON emp.department_id = dep.department_id
</code>```

Note: not sure which one is the correct table to use in your case but simply swap the alias as needed.

Example error:
As you can see here, I am not using an alias, similar to your question, and there is an ambiguity error:

Example solution:
With alias the ambiguity error is resolved

Body:
This is because your department_id in your select could refer to either department id from departments or employees.

Try using an alias like:

SELECT
emp.name, emp.department_id, emp.role
FROM employee_data.employees emp
INNER JOIN employee_data.departments  dep
ON emp.department_id = dep.department_id

Note: not sure which one is the correct table to use in your case but simply swap the alias as needed.

Example error:
As you can see here, I am not using an alias, similar to your question, and there is an ambiguity error:

Example solution:
With alias the ambiguity error is resolved


问:
Vanilla Javascript use of bind() with REST parameter
Why bind() passes even the type of event with rest parameters. How to avoid passing the event 'click'?

```<code>function say(...numbers) {
  for (const number of numbers) {
    console.log(number);
  }
}

window.addEventListener('DOMContentLoaded', () => {
  const el = document.getElementById('input_10_5');
  el.addEventListener('click', say.bind(null, 1, 2, 3));
});
</code>```

Console.log result:

```<code>1
2
3
click { target: input#input_10_5.medium, buttons: 0, clientX: 1062, clientY: 732, layerX: 96, layerY: 24
</code>```

}

答:
This behavior doesn't have to do with rest parameters .... It is more to do with the behavior of .bind(). When you bind a function with arguments (in this case you've used 1, 2, 3), calling that bound function causes those bound arguments to be passed to the function first, then followed by any additional arguments you call the bound function with, eg:

function foo(one, two, three, evt) {
  console.log(one, two, three, evt);
}

const bar = foo.bind(null, 1, 2, 3);
bar({type: "click"}); // becomes the 4th argument (after 1, 2, 3)```
</div>
</div>
</p>
<p>Under the hood, JavaScript is calling your bound function that you pass to <code>.addEventListener()</code> with the event object, which ends up becoming the fourth argument to your <code>say</code> function. This is then included as part of the <code>numbers</code> array. You can instead create a wrapper function that gets passed <code>event</code> (which you ignore), and then use <code>.call()</code> to call your function (using <code>.call()</code> here instead of just <code>()</code> allows you to explicitly define the <code>this</code> value like you're doing with <code>.bind()</code>):</p>
<pre class="lang-js prettyprint-override"><code>window.addEventListener('DOMContentLoaded', () => {
  const el = document.getElementById('input_10_5');
  el.addEventListener('click', () => say.call(null, 1, 2, 3));
});
</code>```

Body:
Why bind() passes even the type of event with rest parameters. How to avoid passing the event 'click'?

function say(...numbers) {
  for (const number of numbers) {
    console.log(number);
  }
}

window.addEventListener('DOMContentLoaded', () => {
  const el = document.getElementById('input_10_5');
  el.addEventListener('click', say.bind(null, 1, 2, 3));
});

Console.log result:

1
2
3
click { target: input#input_10_5.medium, buttons: 0, clientX: 1062, clientY: 732, layerX: 96, layerY: 24

}

Body:
This behavior doesn't have to do with rest parameters .... It is more to do with the behavior of .bind(). When you bind a function with arguments (in this case you've used 1, 2, 3), calling that bound function causes those bound arguments to be passed to the function first, then followed by any additional arguments you call the bound function with, eg:

function foo(one, two, three, evt) {
  console.log(one, two, three, evt);
}

const bar = foo.bind(null, 1, 2, 3);
bar({type: "click"}); // becomes the 4th argument (after 1, 2, 3)

Under the hood, JavaScript is calling your bound function that you pass to .addEventListener() with the event object, which ends up becoming the fourth argument to your say function. This is then included as part of the numbers array. You can instead create a wrapper function that gets passed event (which you ignore), and then use .call() to call your function (using .call() here instead of just () allows you to explicitly define the this value like you're doing with .bind()):

window.addEventListener('DOMContentLoaded', () => {
  const el = document.getElementById('input_10_5');
  el.addEventListener('click', () => say.call(null, 1, 2, 3));
});


问:
Accidentally entered git stash pop instead of git stash--how to undo it?
I know there are similar questions but I am very much new to the whole 'git' scene. So I wanted to ask this question with my own contextual situation.

So I use git for work, where I use SmartGit to stage and commit files, gitbash to push/pull, and polygerrit to submit those commits into my work's repo.

My usual steps are:

open smartgit and select files in working tree to be staged

select all staged files and commit

enter description and click commit (I don't push from SmartGit because it's caused problems before)

go to PolyGerrit, +1 the commit myself, then submit

open gitbash and change directory

do "git push"

do "git stash"

do "git pull" then "git push"

do "git stash pop"

then, I'm usually all good to go.

I'm sure there's something unnecessary I'm doing, or an easier way, but after many a merge conflict and other issues, these exact steps have worked fine for a while now. But today I accidentally typed "git stash pop" before using "git stash". PolyGerrit doesn't show any mergeconflicts, but gitbash does? Is there any way at all to undo the "git stash pop"?

The files are either .png, .md, .ai, or .svg (if it helps at all?)

Any help is much appreciated. Thanks!

答: A general suggestion is to use git stash apply instead of git stash pop as the former is more forgiving as it keeps the stashed diff in the stash-list whereas the latter removes it after applying.


答:
Look at the documentation:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

You can't prevent bind from doing that.

If you don't want that, don't use bind.

Just create a new function the traditional way instead.

```<code>el.addEventListener('click', function () { say(1, 2, 3) });
</code>```

Title: Vanilla Javascript use of bind() with REST parameter

Body:
Look at the documentation:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

You can't prevent bind from doing that.

If you don't want that, don't use bind.

Just create a new function the traditional way instead.

el.addEventListener('click', function () { say(1, 2, 3) });


问:
Apple isn't accepting applications built with this version of SDK (10.7.1)
I updated to OS X 10.7.1 yesterday. After that, Xcode has been saying, whenever I try to upload a Mac app to the App Store, that Apple isn't accepting applications built with this version of the SDK.

I am 100% sure I have the lastest Xcode (4.1, build 4B110), as I have even completely uninstalled Xcode and reinstalled again from the Mac App Store. This happens with all 3 projects I tried to upload.

Architectures are set to 32/64-bit Intel, and Base SDK is Latest Mac OS X (10.7).

Hope any of you can help me,

Thanks.

答: Turns out it was a temporary issue, just like Brad said.</p>

ContentLicense: CC BY-SA 3.0


问:
Sum the nth value for every key in a python dictionary
EDIT

I have the following dictionary:

```<code>dictionary = {'abc': [20, 'john'], 'def': [25, 'jim'], 'ghi': [30, 'jack']}
</code>```

I would like to sum all of the first values for each key and define it as a variable

Expected answer:

```<code>20 + 25 + 30

total_score = 75
</code>```

答:
You have a dict() having set() assigned to each key. You can not index sets. So considering that the first value in the set will always be the value you want is meaningless.

A workaround is to use list comprehension to build a list() from the set(), that list containing only integer elements. Since you only have one integer per set, then the first index of the list will be the value of interest.

```<code>dct = {'abc': {20, 'john'}, 'def': {25, 'jim'}, 'ghi': {30, 'jack'}}

var = 0

for v in dct.values():
    v = [x for x in v if isinstance(x, int)][0]
    var += v

print(var)
</code>```

Output:

```<code>75
</code>```

Edit:

Since the OP edited his question, the new code would be:

```<code>dct = {'abc': [20, 'john'], 'def': [25, 'jim'], 'ghi': [30, 'jack']}

var = 0

for v in dct.values():
    var += v[0]

print(var)
</code>```

Or:

```<code>var = sum(v[0] for v in dct.values())
</code>```

Body:
EDIT

I have the following dictionary:

dictionary = {'abc': [20, 'john'], 'def': [25, 'jim'], 'ghi': [30, 'jack']}

I would like to sum all of the first values for each key and define it as a variable

Expected answer:

20 + 25 + 30

total_score = 75

Body:
You have a dict() having set() assigned to each key. You can not index sets. So considering that the first value in the set will always be the value you want is meaningless.

A workaround is to use list comprehension to build a list() from the set(), that list containing only integer elements. Since you only have one integer per set, then the first index of the list will be the value of interest.

dct = {'abc': {20, 'john'}, 'def': {25, 'jim'}, 'ghi': {30, 'jack'}}

var = 0

for v in dct.values():
    v = [x for x in v if isinstance(x, int)][0]
    var += v

print(var)

Output:

75

Edit:

Since the OP edited his question, the new code would be:

dct = {'abc': [20, 'john'], 'def': [25, 'jim'], 'ghi': [30, 'jack']}

var = 0

for v in dct.values():
    var += v[0]

print(var)

Or:

var = sum(v[0] for v in dct.values())


问:
add text and button in a background image flutter
I'm a student new to flutter. I want to add a Text and a button on this background image. how should I do that  using flutter. appreciate your help on this.

text -"Hello there"

button - Get Started

image description

```<code>    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';

    class GetStarted extends StatelessWidget {
      const GetStarted({Key? key}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            color: Colors.black,
            child: Stack(
              children: [
                Positioned.fill(
                  child: Opacity(
                    opacity: 0.4,
                    child:
                        Image.asset('assets/images/person1.png', fit: BoxFit.cover),
                  ),
                )
              ],
            ),
          ),
        );
      }

}
</code>```

答:
You can just add the other widgets to the Stack and wrap them in an Align to put them where you want them.

Stack(
  children: [
    Positioned.fill(
      child: Opacity(
        opacity: 0.4,
        child: Image.asset('assets/images/person1.png', fit: BoxFit.cover),
      ),
    ),
    Align(
      alignment: Alignment.bottomCenter,
      child: ElevatedButton(child: Text('Button'), onPressed: () {})
    ),
    Text('ABC'),
  ],
),
```

https://api.flutter.dev/flutter/widgets/Align-class.html

https://api.flutter.dev/flutter/widgets/Stack-class.html

Body:
I'm a student new to flutter. I want to add a Text and a button on this background image. how should I do that  using flutter. appreciate your help on this.

text -"Hello there"

button - Get Started

image description

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';

    class GetStarted extends StatelessWidget {
      const GetStarted({Key? key}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            color: Colors.black,
            child: Stack(
              children: [
                Positioned.fill(
                  child: Opacity(
                    opacity: 0.4,
                    child:
                        Image.asset('assets/images/person1.png', fit: BoxFit.cover),
                  ),
                )
              ],
            ),
          ),
        );
      }

}

Body:
You can just add the other widgets to the Stack and wrap them in an Align to put them where you want them.

Stack(
  children: [
    Positioned.fill(
      child: Opacity(
        opacity: 0.4,
        child: Image.asset('assets/images/person1.png', fit: BoxFit.cover),
      ),
    ),
    Align(
      alignment: Alignment.bottomCenter,
      child: ElevatedButton(child: Text('Button'), onPressed: () {})
    ),
    Text('ABC'),
  ],
),

https://api.flutter.dev/flutter/widgets/Align-class.html

https://api.flutter.dev/flutter/widgets/Stack-class.html


问:
how to test if a postgres partition has been populated or not
How can I (quickly) test if a postgres partition has any rows in it?

I have a partitioned postgres table 'TABLE_A', partitioned by date-range. The name of each individual partition indicates the date-range i.e. TABLE_A_20220101 (1st Jan this year) TABLE_A_20220102 (2nd Jan 2022)

The table includes many years of data, so it includes several thousand individual partitions, each partition contains many millions of rows.

Is there a quick way of testing if a partition has any data in it? There are several solutions I've found, but they all involve count(*) and all take ages.

Please note - I'm NOT trying to accurately determine the row-count, just determine if each partition has any rows in it.

答:
You can use an exists condition:

```<code>select exists (select * from partition_name limit 1)
</code>```

That will return true if partition_name contains at least one row

Body:
You can use an exists condition:

select exists (select * from partition_name limit 1)

That will return true if partition_name contains at least one row


问:
De-aggregate a data frame
There have been many similar questions (e.g. Repeat each row of data.frame the number of times specified in a column, De-aggregate / reverse-summarise / expand a dataset in R, Repeating rows of data.frame in dplyr), but my data set is of a different structure than the answers to these questions assume.

I have a data frame with the frequencies of measurements within each group and the total number of observations for each outcome per group total_N:

```<code>tibble(group=c("A", "B"), total_N=c(4,5), measure_A=c(1,4), measure_B=c(2,3))
# A tibble: 2 x 4
  group total_N outcome_A outcome_B
  <chr>   <dbl>     <dbl>     <dbl>
1 A           4         1         2
2 B           5         4         3
</code>```

I want to de-aggregate the data, so that the data frame has as many rows as total observations and each outcome has a 1 for all observations with the outcome and a 0 for all observations without the outcome. Thus the final result should be a data frame like this:

```<code># A tibble: 9 x 3
  group outcome_A outcome_B
  <chr>     <dbl>     <dbl>
1 A             1         1
2 A             0         1
3 A             0         0
4 A             0         0
5 B             1         1
6 B             1         1
7 B             1         1
8 B             1         0
9 B             0         0
</code>```

As the aggregated data does not contain any information about the frequency of combinations (i.e., the correlation) of outcome_A and outcome_B, this can be ignored.

答:
Here's a tidyverse solution.

As you say, it's easy to repeat a row an arbitrary number of times.  If you know that row_number() counts rows within groups when a data frame is grouped, then it's easy to convert grouped counts to presence/absence flags.  across gives you a way to succinctly convert multiple count columns.

```<code>library(tidyverse)

tibble(group=c("A", "B"), total_N=c(4,5), measure_A=c(1,4), measure_B=c(2,3)) %>%
  uncount(total_N) %>%
  group_by(group) %>%
  mutate(
    across(
      starts_with("measure"),
      function(x) as.numeric(row_number() <= x)
    )
  ) %>%
  ungroup()
# A tibble: 9 × 3
  group measure_A measure_B
  <chr>     <dbl>     <dbl>
1 A             1         1
2 A             0         1
3 A             0         0
4 A             0         0
5 B             1         1
6 B             1         1
7 B             1         1
8 B             1         0
9 B             0         0
</code>```

As you say, this approach takes no account of correlations between the outcome columns, as this cannot be deduced from the grouped data.

Title: De-aggregate a data frame

Body:
There have been many similar questions (e.g. Repeat each row of data.frame the number of times specified in a column, De-aggregate / reverse-summarise / expand a dataset in R, Repeating rows of data.frame in dplyr), but my data set is of a different structure than the answers to these questions assume.

I have a data frame with the frequencies of measurements within each group and the total number of observations for each outcome per group total_N:

tibble(group=c("A", "B"), total_N=c(4,5), measure_A=c(1,4), measure_B=c(2,3))
# A tibble: 2 x 4
  group total_N outcome_A outcome_B
  <chr>   <dbl>     <dbl>     <dbl>
1 A           4         1         2
2 B           5         4         3

I want to de-aggregate the data, so that the data frame has as many rows as total observations and each outcome has a 1 for all observations with the outcome and a 0 for all observations without the outcome. Thus the final result should be a data frame like this:

# A tibble: 9 x 3
  group outcome_A outcome_B
  <chr>     <dbl>     <dbl>
1 A             1         1
2 A             0         1
3 A             0         0
4 A             0         0
5 B             1         1
6 B             1         1
7 B             1         1
8 B             1         0
9 B             0         0

As the aggregated data does not contain any information about the frequency of combinations (i.e., the correlation) of outcome_A and outcome_B, this can be ignored.

Body:
Here's a tidyverse solution.

As you say, it's easy to repeat a row an arbitrary number of times.  If you know that row_number() counts rows within groups when a data frame is grouped, then it's easy to convert grouped counts to presence/absence flags.  across gives you a way to succinctly convert multiple count columns.

library(tidyverse)

tibble(group=c("A", "B"), total_N=c(4,5), measure_A=c(1,4), measure_B=c(2,3)) %>%
  uncount(total_N) %>%
  group_by(group) %>%
  mutate(
    across(
      starts_with("measure"),
      function(x) as.numeric(row_number() <= x)
    )
  ) %>%
  ungroup()
# A tibble: 9 × 3
  group measure_A measure_B
  <chr>     <dbl>     <dbl>
1 A             1         1
2 A             0         1
3 A             0         0
4 A             0         0
5 B             1         1
6 B             1         1
7 B             1         1
8 B             1         0
9 B             0         0

As you say, this approach takes no account of correlations between the outcome columns, as this cannot be deduced from the grouped data.


问:
How center the new location of Google Map on React?
I use google-map-react to display a Google Map with Custom Marker to show a location.

Can i change the location succesfully, its mean, passing lat and lng to the map component and put the marker on the new location, butthe view of the map its still on the older location.

How can i center on the new location?

Main Component

Lat and Lng starts with a coordinates, whit setState put a new

Don't put the entire component but it's the way I call the map

```<code>return (
    <div className="main">
        <div className="main__map">
            <TheMap center={[this.state.lat, this.state.lng]} />
        </div>
    </div>
)
</code>```

TheMap Component

```<code>import React,{useState , useEffect} from 'react';
import GoogleMapReact from 'google-map-react';

function TheMap(props){
    const [cordinates , setCordinates] = useState(props);
    const MyCustomMarker = () => <span class="material-icons">place</span>;

    useEffect(() => {
       setCordinates(props);
    }, [props])

    return(
        <GoogleMapReact
            yesIWantToUseGoogleMapApiInternals={true}
            bootstrapURLKeys={{key:'THE KEY'}}
            defaultZoom={16}
            center={cordinates.center}
        >
            <MyCustomMarker
                lat={cordinates.center[0]}
                lng={cordinates.center[1]}
            />
        </GoogleMapReact>
    )
}

export default TheMap
</code>```

答:
You need to ensure that in
center={coordinates}
coordinates is a new object and not only the same object with just changed values of lat and lng. Otherwise react will not recognize it as changed.
If it doesn't work in the above then the same object was passed already to props.center.</p>

Body:
I use google-map-react to display a Google Map with Custom Marker to show a location.

Can i change the location succesfully, its mean, passing lat and lng to the map component and put the marker on the new location, butthe view of the map its still on the older location.

How can i center on the new location?

Main Component

Lat and Lng starts with a coordinates, whit setState put a new

Don't put the entire component but it's the way I call the map

return (

            <TheMap center={[this.state.lat, this.state.lng]} />

)

TheMap Component

import React,{useState , useEffect} from 'react';
import GoogleMapReact from 'google-map-react';

function TheMap(props){
    const [cordinates , setCordinates] = useState(props);
    const MyCustomMarker = () => place;

    useEffect(() => {
       setCordinates(props);
    }, [props])

    return(
        <GoogleMapReact
            yesIWantToUseGoogleMapApiInternals={true}
            bootstrapURLKeys={{key:'THE KEY'}}
            defaultZoom={16}
            center={cordinates.center}
        >
            <MyCustomMarker
                lat={cordinates.center[0]}
                lng={cordinates.center[1]}
            />
        </GoogleMapReact>
    )
}

export default TheMap