问:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pictureResource'
Im working on a school project and decided to work with spring. I set it up myself for the first time myself and cant run it propperly now.

Im following this tutorial https://www.youtube.com/watch?v=Gx4iBLKLVHk and I did everything exactly the same. Atleast I think so. If someone needs more Information about the Project please contact me.

Thank you very much for your time.

My Model:

```<code>package ch.M306_LB.gallery.model;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class Picture {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, updatable = false)
    private Long id;
    private String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
</code>```

My Service

```<code>package ch.M306_LB.gallery.service;

import ch.M306_LB.gallery.exception.UserNotFoundException;
import ch.M306_LB.gallery.model.Picture;
import ch.M306_LB.gallery.repo.PictureRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PictureService {
    private final PictureRepo pictureRepo;

    @Autowired
    public PictureService(PictureRepo pictureRepo) {
        this.pictureRepo = pictureRepo;
    }

    public Picture addPicture(Picture picture){
        return pictureRepo.save(picture);
    }

    public List<Picture> findAllPictures(){
        return pictureRepo.findAll();
    }

    public Picture updatePicture(Picture picture){
        return pictureRepo.save(picture);
    }

    public Picture findPictureById(Long id){
        return pictureRepo.findPictureById(id)
                .orElseThrow(() -> new UserNotFoundException("User by id " + id + " was not found"));
    }

    public void deletePicture(Long id){
        pictureRepo.deletePictureById(id);
    }
}
</code>```

My Repo:

```<code>package ch.M306_LB.gallery.repo;

import ch.M306_LB.gallery.model.Picture;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface PictureRepo extends JpaRepository<Picture, Long> {
    void deletePictureById(Long id);

    Optional<Picture> findPictureById(Long id);
}
</code>```

My Resource:

```<code>    package ch.M306_LB.gallery;

import ch.M306_LB.gallery.model.Picture;
import ch.M306_LB.gallery.service.PictureService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/picture")
public class PictureResource {
    private final PictureService pictureService;

    public PictureResource(PictureService pictureService) {
        this.pictureService = pictureService;
    }

    @GetMapping("/all")
    public ResponseEntity<List<Picture>> getAllPictures(){
        List<Picture> pictures = pictureService.findAllPictures();
        return new ResponseEntity<>(pictures, HttpStatus.OK);
    }

    @GetMapping("/find{id}")
    public ResponseEntity<Picture> getPictureById(@PathVariable("id") Long id){
        Picture picture = pictureService.findPictureById(id);
        return new ResponseEntity<>(picture, HttpStatus.OK);
    }

    @PostMapping("/add")
    public ResponseEntity<Picture> addPicture(@RequestBody Picture picture){
        Picture newPicture = pictureService.addPicture(picture);
        return new ResponseEntity<>(newPicture, HttpStatus.CREATED);
    }

    @PutMapping("/update")
    public ResponseEntity<Picture> updatePicture(@RequestBody Picture picture){
        Picture updatePicture = pictureService.updatePicture(picture);
        return new ResponseEntity<>(updatePicture, HttpStatus.OK);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deletePicture(@PathVariable("id") Long id){
        pictureService.deletePicture(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
</code>```

Error Log:

```<code>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-02-13 23:48:27.596 ERROR 11656 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pictureResource' defined in file [C:\Users\david\Desktop\BZZ\Workspace\Modul 152\LB\gallery\target\classes\ch\M306_LB\gallery\PictureResource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pictureService' defined in file [C:\Users\david\Desktop\BZZ\Workspace\Modul 152\LB\gallery\target\classes\ch\M306_LB\gallery\service\PictureService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pictureRepo' defined in ch.M306_LB.gallery.repo.PictureRepo defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class ch.M306_LB.gallery.model.Picture
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar:2.6.3]
    at ch.M306_LB.gallery.GalleryApplication.main(GalleryApplication.java:10) ~[classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pictureService' defined in file [C:\Users\david\Desktop\BZZ\Workspace\Modul 152\LB\gallery\target\classes\ch\M306_LB\gallery\service\PictureService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pictureRepo' defined in ch.M306_LB.gallery.repo.PictureRepo defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class ch.M306_LB.gallery.model.Picture
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 19 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pictureRepo' defined in ch.M306_LB.gallery.repo.PictureRepo defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class ch.M306_LB.gallery.model.Picture
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 33 common frames omitted
Caused by: java.lang.IllegalArgumentException: Not a managed type: class ch.M306_LB.gallery.model.Picture
    at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:582) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:85) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:75) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:232) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:181) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:164) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:75) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:324) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:322) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:230) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:328) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 44 common frames omitted

Process finished with exit code 1
</code>```

答:
It failing as the Spring JPA not able to scan the model public class Picture. Adding @Entity on model will solve the problem.

```<code>@Entity
public class Picture
</code>```

Body:
Im working on a school project and decided to work with spring. I set it up myself for the first time myself and cant run it propperly now.

Im following this tutorial https://www.youtube.com/watch?v=Gx4iBLKLVHk and I did everything exactly the same. Atleast I think so. If someone needs more Information about the Project please contact me.

Thank you very much for your time.

My Model:

package ch.M306_LB.gallery.model;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class Picture {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, updatable = false)
    private Long id;
    private String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

My Service

package ch.M306_LB.gallery.service;

import ch.M306_LB.gallery.exception.UserNotFoundException;
import ch.M306_LB.gallery.model.Picture;
import ch.M306_LB.gallery.repo.PictureRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PictureService {
    private final PictureRepo pictureRepo;

    @Autowired
    public PictureService(PictureRepo pictureRepo) {
        this.pictureRepo = pictureRepo;
    }

    public Picture addPicture(Picture picture){
        return pictureRepo.save(picture);
    }

    public List<Picture> findAllPictures(){
        return pictureRepo.findAll();
    }

    public Picture updatePicture(Picture picture){
        return pictureRepo.save(picture);
    }

    public Picture findPictureById(Long id){
        return pictureRepo.findPictureById(id)
                .orElseThrow(() -> new UserNotFoundException("User by id " + id + " was not found"));
    }

    public void deletePicture(Long id){
        pictureRepo.deletePictureById(id);
    }
}

My Repo:

package ch.M306_LB.gallery.repo;

import ch.M306_LB.gallery.model.Picture;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface PictureRepo extends JpaRepository<Picture, Long> {
    void deletePictureById(Long id);

    Optional<Picture> findPictureById(Long id);
}

My Resource:

    package ch.M306_LB.gallery;

import ch.M306_LB.gallery.model.Picture;
import ch.M306_LB.gallery.service.PictureService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/picture")
public class PictureResource {
    private final PictureService pictureService;

    public PictureResource(PictureService pictureService) {
        this.pictureService = pictureService;
    }

    @GetMapping("/all")
    public ResponseEntity<List<Picture>> getAllPictures(){
        List<Picture> pictures = pictureService.findAllPictures();
        return new ResponseEntity<>(pictures, HttpStatus.OK);
    }

    @GetMapping("/find{id}")
    public ResponseEntity<Picture> getPictureById(@PathVariable("id") Long id){
        Picture picture = pictureService.findPictureById(id);
        return new ResponseEntity<>(picture, HttpStatus.OK);
    }

    @PostMapping("/add")
    public ResponseEntity<Picture> addPicture(@RequestBody Picture picture){
        Picture newPicture = pictureService.addPicture(picture);
        return new ResponseEntity<>(newPicture, HttpStatus.CREATED);
    }

    @PutMapping("/update")
    public ResponseEntity<Picture> updatePicture(@RequestBody Picture picture){
        Picture updatePicture = pictureService.updatePicture(picture);
        return new ResponseEntity<>(updatePicture, HttpStatus.OK);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deletePicture(@PathVariable("id") Long id){
        pictureService.deletePicture(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

Error Log:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-02-13 23:48:27.596 ERROR 11656 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pictureResource' defined in file [C:\Users\david\Desktop\BZZ\Workspace\Modul 152\LB\gallery\target\classes\ch\M306_LB\gallery\PictureResource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pictureService' defined in file [C:\Users\david\Desktop\BZZ\Workspace\Modul 152\LB\gallery\target\classes\ch\M306_LB\gallery\service\PictureService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pictureRepo' defined in ch.M306_LB.gallery.repo.PictureRepo defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class ch.M306_LB.gallery.model.Picture
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar:2.6.3]
    at ch.M306_LB.gallery.GalleryApplication.main(GalleryApplication.java:10) ~[classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pictureService' defined in file [C:\Users\david\Desktop\BZZ\Workspace\Modul 152\LB\gallery\target\classes\ch\M306_LB\gallery\service\PictureService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pictureRepo' defined in ch.M306_LB.gallery.repo.PictureRepo defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class ch.M306_LB.gallery.model.Picture
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 19 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pictureRepo' defined in ch.M306_LB.gallery.repo.PictureRepo defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class ch.M306_LB.gallery.model.Picture
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 33 common frames omitted
Caused by: java.lang.IllegalArgumentException: Not a managed type: class ch.M306_LB.gallery.model.Picture
    at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:582) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:85) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:75) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:232) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:181) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:164) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:75) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:324) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:322) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:230) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:328) ~[spring-data-commons-2.6.1.jar:2.6.1]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.6.1.jar:2.6.1]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 44 common frames omitted

Process finished with exit code 1

Body:
It failing as the Spring JPA not able to scan the model public class Picture. Adding @Entity on model will solve the problem.

@Entity
public class Picture


来源: stackexchange

问:
Why is my WPF binding not working in state change?
I have some items in a WrapPanel.  I want to be able to click on an item and have it expand to the full width of the wrap panel.  I tried doing this by creating two states, Expanded and Colapsed, in the control that is used for each item.  For the Expanded state, I bound the Width of the control to be equal to the ActualWidth of the WrapPanel.

When I didn't get the result I expected, I tried setting Expanded value to a specific number (instead of the the binding).  That is working.  The items toggle between the two Colapsed and Exapanded widths.  I still want to have the Expanded state be equal to the width of the WrapPanel though, not an arbitrary fixed width.  I know my binding works because if I just bind the Width property directly (not via visual states), the items in the WrapPanel match its width.

Expanded state with Binding - Doesn't work:

```<code><VisualState x:Name="Expanded">
<Storyboard>
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="JobMaster">
        <EasingDoubleKeyFrame KeyTime="0">
            <EasingDoubleKeyFrame.Value>
                 <Binding
                   Path="ActualWidth"
                   RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type WrapPanel}}" />
            </EasingDoubleKeyFrame.Value>
        </EasingDoubleKeyFrame>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>
</code>```

Expanded State with hard coded value - Works

```<code><VisualState x:Name="Expanded">
<Storyboard>
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="JobMaster">
        <EasingDoubleKeyFrame KeyTime="0" Value="800" />
    </DoubleAnimationUsingKeyFrames>
</Storyboard>
</code>```

Bind the control Width property directly works

```<code><UserControl.Width>
       <Binding
       Path="ActualWidth"
       RelativeSource="{RelativeSource AncestorType={x:Type WrapPanel}}" />
</UserControl.Width>
</code>```

So why doesn't the Binding in the state work or is there another way to do this?

答:
I was never able to get this working using visual states.  Instead I wrote a behavoir.</p>

```<code>public class TileExpandColapseBehavoir : Behavior<Control>
{
    private ITile _data;

    #region Properties

    public static readonly DependencyProperty TileControlProperty = DependencyProperty.Register("TileControl", typeof(object), typeof(TileExpandColapseBehavoir), new PropertyMetadata(null));
    public static readonly DependencyProperty DefaultWidthProperty = DependencyProperty.Register("DefaultWidth", typeof(Double), typeof(TileExpandColapseBehavoir), new PropertyMetadata(null));

    public object TileControl
    {
        get { return (object)this.GetValue(TileControlProperty); }
        set { this.SetValue(TileControlProperty, value); }
    }

    public double DefaultWidth
    {
        get { return (double)this.GetValue(DefaultWidthProperty); }
        set { this.SetValue(DefaultWidthProperty, value); }
    }

    #endregion

    public TileExpandColapseBehavoir()
    {
    }

    protected override void OnAttached()
    {
        this.AssociatedObject.PreviewMouseDown +=new MouseButtonEventHandler(AssociatedObject_MouseUp);
    }

    private void AssociatedObject_MouseUp(object sender, MouseButtonEventArgs e)
    {
        UIElement child = (UIElement)sender;
        WrapPanel parentWrap = FindAncestorUtil.TryFindAcestor<WrapPanel>(child);
        if (parentWrap != null && TileControl is UserControl)
        {
            GetData();
            if (_data.IsExpanded == false)
            {
                Binding newBinding = new Binding();
                newBinding.Source = parentWrap;
                newBinding.Path = new PropertyPath("ActualWidth");

                UserControl thisTile = (UserControl)TileControl;
                BindingOperations.SetBinding(thisTile, UserControl.WidthProperty, newBinding);
                _data.IsExpanded = true;
            }
            else
            {
                UserControl thisTile = (UserControl)TileControl;

                BindingOperations.ClearBinding(thisTile, UserControl.WidthProperty);
                thisTile.Width = DefaultWidth;
                _data.IsExpanded = false;
            }
        }
    }

    private void GetData()
    {
        if (_data == null && AssociatedObject.DataContext is ITile)
        {
             _data = (ITile)AssociatedObject.DataContext;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some items in a WrapPanel.  I want to be able to click on an item and have it expand to the full width of the wrap panel.  I tried doing this by creating two states, Expanded and Colapsed, in the control that is used for each item.  For the Expanded state, I bound the Width of the control to be equal to the ActualWidth of the WrapPanel.

When I didn't get the result I expected, I tried setting Expanded value to a specific number (instead of the the binding).  That is working.  The items toggle between the two Colapsed and Exapanded widths.  I still want to have the Expanded state be equal to the width of the WrapPanel though, not an arbitrary fixed width.  I know my binding works because if I just bind the Width property directly (not via visual states), the items in the WrapPanel match its width.

Expanded state with Binding - Doesn't work:

<VisualState x:Name="Expanded">
<Storyboard>
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="JobMaster">
        <EasingDoubleKeyFrame KeyTime="0">
            <EasingDoubleKeyFrame.Value>
                 <Binding
                   Path="ActualWidth"
                   RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type WrapPanel}}" />
            </EasingDoubleKeyFrame.Value>
        </EasingDoubleKeyFrame>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

Expanded State with hard coded value - Works

<VisualState x:Name="Expanded">
<Storyboard>
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="JobMaster">
        <EasingDoubleKeyFrame KeyTime="0" Value="800" />
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

Bind the control Width property directly works

<UserControl.Width>
       <Binding
       Path="ActualWidth"
       RelativeSource="{RelativeSource AncestorType={x:Type WrapPanel}}" />
</UserControl.Width>

So why doesn't the Binding in the state work or is there another way to do this?

Body:
I was never able to get this working using visual states.  Instead I wrote a behavoir.

public class TileExpandColapseBehavoir : Behavior<Control>
{
    private ITile _data;

    #region Properties

    public static readonly DependencyProperty TileControlProperty = DependencyProperty.Register("TileControl", typeof(object), typeof(TileExpandColapseBehavoir), new PropertyMetadata(null));
    public static readonly DependencyProperty DefaultWidthProperty = DependencyProperty.Register("DefaultWidth", typeof(Double), typeof(TileExpandColapseBehavoir), new PropertyMetadata(null));

    public object TileControl
    {
        get { return (object)this.GetValue(TileControlProperty); }
        set { this.SetValue(TileControlProperty, value); }
    }

    public double DefaultWidth
    {
        get { return (double)this.GetValue(DefaultWidthProperty); }
        set { this.SetValue(DefaultWidthProperty, value); }
    }

    #endregion

    public TileExpandColapseBehavoir()
    {
    }

    protected override void OnAttached()
    {
        this.AssociatedObject.PreviewMouseDown +=new MouseButtonEventHandler(AssociatedObject_MouseUp);
    }

    private void AssociatedObject_MouseUp(object sender, MouseButtonEventArgs e)
    {
        UIElement child = (UIElement)sender;
        WrapPanel parentWrap = FindAncestorUtil.TryFindAcestor<WrapPanel>(child);
        if (parentWrap != null && TileControl is UserControl)
        {
            GetData();
            if (_data.IsExpanded == false)
            {
                Binding newBinding = new Binding();
                newBinding.Source = parentWrap;
                newBinding.Path = new PropertyPath("ActualWidth");

                UserControl thisTile = (UserControl)TileControl;
                BindingOperations.SetBinding(thisTile, UserControl.WidthProperty, newBinding);
                _data.IsExpanded = true;
            }
            else
            {
                UserControl thisTile = (UserControl)TileControl;

                BindingOperations.ClearBinding(thisTile, UserControl.WidthProperty);
                thisTile.Width = DefaultWidth;
                _data.IsExpanded = false;
            }
        }
    }

    private void GetData()
    {
        if (_data == null && AssociatedObject.DataContext is ITile)
        {
             _data = (ITile)AssociatedObject.DataContext;
        }
    }
}


问:
Tailwind css footer position not to the bottom
I am new to the tailwind css. I was making my new webpage where I am putting a footer. But the problem is the footer position is relative to the content. That is, if the content is less than the page size, it goes up. I tried googling the problem and found some solutions and none of them worked.

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

            Sachchidanand Prasad
            <button class="md:hidden rounded-lg focus:outline-none focus:shadow-outline" @click="open = !open">
                <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6">
                <path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path>
                <path x-show="open" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                </svg>
            </button>

            Home

            Research

            CV

                    Useful Links

                        MathSciNet

                        AMS open Math Notes

                        MTTS

                        ATM School

                    Useful Links

                        NBHM

                        About Us

                        Blogs

                        Contact Us

                    Social Networks

                        Facebook

                        Twitter

                        Instagram

                        Github

            All rights reserved by @ Sachchidanand 2022

```

The output:

答:
You can set a mt-auto to the footer. See Full Page:

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

            Sachchidanand Prasad
            <button class="md:hidden rounded-lg focus:outline-none focus:shadow-outline" @click="open = !open">
                <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6">
                <path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path>
                <path x-show="open" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                </svg>
            </button>

            Home

            Research

            CV

                    Useful Links

                        MathSciNet

                        AMS open Math Notes

                        MTTS

                        ATM School

                    Useful Links

                        NBHM

                        About Us

                        Blogs

                        Contact Us

                    Social Networks

                        Facebook

                        Twitter

                        Instagram

                        Github

            All rights reserved by @ Sachchidanand 2022

```

ContentLicense: CC BY-SA 4.0

Body:
I am new to the tailwind css. I was making my new webpage where I am putting a footer. But the problem is the footer position is relative to the content. That is, if the content is less than the page size, it goes up. I tried googling the problem and found some solutions and none of them worked.

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

            Sachchidanand Prasad
            <button class="md:hidden rounded-lg focus:outline-none focus:shadow-outline" @click="open = !open">
                <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6">
                <path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path>
                <path x-show="open" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                </svg>
            </button>

            Home

            Research

            CV

                    Useful Links

                        MathSciNet

                        AMS open Math Notes

                        MTTS

                        ATM School

                    Useful Links

                        NBHM

                        About Us

                        Blogs

                        Contact Us

                    Social Networks

                        Facebook

                        Twitter

                        Instagram

                        Github

            All rights reserved by @ Sachchidanand 2022

The output:

Body:
You can set a mt-auto to the footer. See Full Page:

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>
<div class="flex flex-col h-screen">
<!-- navbar -->
<div class="w-full text-gray-700 bg-white dark-mode:text-gray-200 dark-mode:bg-gray-800">
        <div x-data="{ open: false }" class="flex flex-col max-w-screen-xl px-4 mx-auto   md:items-center md:justify-between md:flex-row md:px-6 lg:px-8">
        <div class="p-4 flex flex-row items-center justify-between">
            <a href="#" class="text-lg font-semibold tracking-widest text-gray-900 uppercase rounded-lg dark-mode:text-white focus:outline-none focus:shadow-outline">Sachchidanand Prasad</a>
            <button class="md:hidden rounded-lg focus:outline-none focus:shadow-outline" @click="open = !open">
                <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6">
                <path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path>
                <path x-show="open" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                </svg>
            </button>
        </div>

        <nav :class="{'flex': open, 'hidden': !open}" class="flex-col flex-grow pb-4 md:pb-0 hidden md:flex md:justify-end md:flex-row">
            <a class="px-4 py-2 mt-2 text-sm font-semibold bg-transparent rounded-lg dark-mode:bg-gray-700 dark-mode:hover:bg-gray-600 dark-mode:focus:bg-gray-600 dark-mode:focus:text-white dark-mode:hover:text-white dark-mode:text-gray-200 md:mt-0 hover:text-gray-900 focus:text-gray-900 hover:bg-gray-200 focus:bg-gray-200 focus:outline-none focus:shadow-outline" href="index.html">Home</a>

            <a class="px-4 py-2 mt-2 text-sm font-semibold bg-transparent rounded-lg dark-mode:bg-transparent dark-mode:hover:bg-gray-600 dark-mode:focus:bg-gray-600 dark-mode:focus:text-white dark-mode:hover:text-white dark-mode:text-gray-200 md:mt-0 md:ml-4 hover:text-gray-900 focus:text-gray-900 hover:bg-gray-200 focus:bg-gray-200 focus:outline-none focus:shadow-outline" href="research.html">Research</a>

            <a class="px-4 py-2 mt-2 text-sm font-semibold bg-gray-200 text-gray-900 rounded-lg dark-mode:bg-transparent dark-mode:hover:bg-gray-600 dark-mode:focus:bg-gray-600 dark-mode:focus:text-white dark-mode:hover:text-white dark-mode:text-gray-200 md:mt-0 md:ml-4 hover:text-gray-900 focus:text-gray-900 hover:bg-gray-200 focus:bg-gray-200 focus:outline-none focus:shadow-outline" href="cv.html">CV</a>
        </nav>
    </div>
</div>

<!-- footer -->
<footer class="mt-auto border-t border-gray-200">
    <div class=" container flex flex-col flex-wrap px-4 py-16 mx-auto md:items-center lg:items-start md:flex-row md:flex-nowrap">

        <div class="justify-between w-full mt-4 text-center lg:flex">
            <div class="w-full px-4 lg:w-1/3 md:w-1/2">
                <h2 class="mb-2 font-bold tracking-widest text-gray-900">
                    Useful Links
                </h2>
                <ul class="mb-8 space-y-2 text-sm list-none">
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="https://mathscinet.ams.org/mathscinet/" target="_blank">MathSciNet</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="https://www.ams.org/open-math-notes" target="_blank">AMS open Math Notes</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="https://mtts.org.in/" target="_blank">MTTS</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="https://www.atmschools.org/" target="_blank">ATM School</a>
                    </li>
                </ul>
            </div>
            <div class="w-full px-4 lg:w-1/3 md:w-1/2">
                <h2 class="mb-2 font-bold tracking-widest text-gray-900">
                    Useful Links
                </h2>
                <ul class="mb-8 space-y-2 text-sm list-none">
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="http://www.nbhm.dae.gov.in/" target="_blank">NBHM</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800">About Us</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800">Blogs</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800">Contact Us</a>
                    </li>
                </ul>
            </div>
            <div class="w-full px-4 lg:w-1/3 md:w-1/2">
                <h2 class="mb-2 font-bold tracking-widest text-gray-900">
                    Social Networks
                </h2>
                <ul class="mb-8 space-y-2 text-sm list-none">
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="">Facebook</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="">Twitter</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="">Instagram</a>
                    </li>
                    <li>
                        <a class="text-gray-600 hover:text-gray-800" href="">Github</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="flex justify-center">
        <p class="text-base text-gray-400">
            All rights reserved by @ <a class="text-gray-400 hover:text-gray-800" href="index.html">Sachchidanand</a> 2022
        </p>
    </div>
</footer>
</div>


问:
Converting multi digit char to int in C++
While I know that you can convert single digits that are characters to integers by doing, for example:

```<code>int main()
{
    char var = '5';
    int num_var = var - 48;
}
</code>```

I know you can't do the same thing for a character with a value which is say, '148'. Is there an easy way to convert this character value to an integer value of 148?

答:
Case 1

First you should not use magic number like 48 etc because they make the program less portable. You should instead subtract '0' as shown below:

```<code>char var = '5';
int num_var = var - '0'; ////the result of var - '0' is guaranteed to be the integer 5
</code>```

Here both var and '0' will be promoted to int. And the final result that is used to initialize variable num_var on the left hand side will be the result of subtraction of those two promoted int values on the right hand side. Moreover, the result is guaranteed to be the integer 5 since from C++ Standard (2.3 Character sets):

...In both the source and execution basic character sets, the value of
each character after 0 in the above list of decimal digits shall be
one greater than the value of the previous.

Case 2

Suppose we have more than one characters, then one way would be to use std::string and std::istringstream as shown below:

```<code>std::string var = "148";
int num_var;
std::istringstream ss(var);
ss >> num_var; //now num_var is the integer 148
</code>```

Body:
While I know that you can convert single digits that are characters to integers by doing, for example:

int main()
{
    char var = '5';
    int num_var = var - 48;
}

I know you can't do the same thing for a character with a value which is say, '148'. Is there an easy way to convert this character value to an integer value of 148?

Body:
Case 1

First you should not use magic number like 48 etc because they make the program less portable. You should instead subtract '0' as shown below:

char var = '5';
int num_var = var - '0'; ////the result of var - '0' is guaranteed to be the integer 5

Here both var and '0' will be promoted to int. And the final result that is used to initialize variable num_var on the left hand side will be the result of subtraction of those two promoted int values on the right hand side. Moreover, the result is guaranteed to be the integer 5 since from C++ Standard (2.3 Character sets):

...In both the source and execution basic character sets, the value of
each character after 0 in the above list of decimal digits shall be
one greater than the value of the previous.

Case 2

Suppose we have more than one characters, then one way would be to use std::string and std::istringstream as shown below:

std::string var = "148";
int num_var;
std::istringstream ss(var);
ss >> num_var; //now num_var is the integer 148


问:
White space outside html on mobile Safari when keyboard is open
I have a very weird bug in my JavaScript library on mobile Safari, that I've tried to reproduce with a simple example:

I have basic css and html:

html,
body {
    margin: 0;
    padding: 0;
    font-family: monospace;
}
body {
  min-height: 100vh;
  /* mobile viewport bug fix */
  min-height: -webkit-fill-available;
}
html {
  height: -webkit-fill-available;
}
#term {
    background: black;
    color: #ccc;
    height: 100%;
}
h1 {
    margin: 0;
    font-weight: normal;
}
```
<p><em>html</em>:</p>
<pre class="lang-html prettyprint-override"><code>    ...
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
  <div id="term" contenteditable>
    <h1>HELLO Mobile</h1>
    ...
</code>```

and when I open the website on mobile Safari and open the virtual keyboard, I can scroll down outside of the content.

Here is the screenshot from BrowserStack when I hover over body, I'm not able to hover over html to highlight it.

Does anybody know how to fix this issue? It looks like a basic page.

Here is the link to the website: https://terminal.jcubic.pl/mobile.html

As you can see from the code I've tried to fix the issue by adding:

```<code>-webkit-fill-available
</code>```

Found in an article: CSS fix for 100vh in mobile WebKit by Chris Coyier. But it doesn't make any change.

Is there a way to get rid of that white space, it seems that even CodePen has this issue. Is it a bug in Mobile Safari, is there a hack to fix it?

EDIT:

I think that this is a long-standing issue and Apple doesn't care how miserable users and developers are. Safari on iOS scrolls beyond  element when virtual keyboard is opened

答:
Try this:

JS File:

```<code>const appHeight = () => {
 const doc = document.documentElement
 doc.style.setProperty('--app-height', `${window.innerHeight}px`)
}
window.addEventListener('resize', appHeight)
appHeight()
</code>```

CSS File:

```<code>:root {
 --app-height: 100%;
}
html,
body {
 padding: 0;
 margin: 0;
 overflow: hidden;
 width: 100vw;
 height: 100vh;
 height: var(--app-height);
}
</code>```

It may help

Body:
I have a very weird bug in my JavaScript library on mobile Safari, that I've tried to reproduce with a simple example:

I have basic css and html:

html,
body {
    margin: 0;
    padding: 0;
    font-family: monospace;
}
body {
  min-height: 100vh;
  /* mobile viewport bug fix */
  min-height: -webkit-fill-available;
}
html {
  height: -webkit-fill-available;
}
#term {
    background: black;
    color: #ccc;
    height: 100%;
}
h1 {
    margin: 0;
    font-weight: normal;
}

html:

    ...
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

HELLO Mobile

    ...

and when I open the website on mobile Safari and open the virtual keyboard, I can scroll down outside of the content.

Here is the screenshot from BrowserStack when I hover over body, I'm not able to hover over html to highlight it.

Does anybody know how to fix this issue? It looks like a basic page.

Here is the link to the website: https://terminal.jcubic.pl/mobile.html

As you can see from the code I've tried to fix the issue by adding:

-webkit-fill-available

Found in an article: CSS fix for 100vh in mobile WebKit by Chris Coyier. But it doesn't make any change.

Is there a way to get rid of that white space, it seems that even CodePen has this issue. Is it a bug in Mobile Safari, is there a hack to fix it?

EDIT:

I think that this is a long-standing issue and Apple doesn't care how miserable users and developers are. Safari on iOS scrolls beyond  element when virtual keyboard is opened

Body:
Try this:

JS File:

const appHeight = () => {
 const doc = document.documentElement
 doc.style.setProperty('--app-height', `${window.innerHeight}px`)
}
window.addEventListener('resize', appHeight)
appHeight()

CSS File:

:root {
 --app-height: 100%;
}
html,
body {
 padding: 0;
 margin: 0;
 overflow: hidden;
 width: 100vw;
 height: 100vh;
 height: var(--app-height);
}

It may help


问:
Convert array in JSON file to string
Here's a snippet of my JSON object (EDITED) -

```<code>[{
    "traditional": "%",
    "simplified": "%",
    "referencedTraditional": [],
    "referencedSimplified": [],
    "pinyinNumeric": "pa1",
    "pinyinDiacritic": "pā",
    "definitions": [
        "percent (Tw)"
    ],
    "definitionsDiacritic": [
        "percent (Tw)"
    ]
},
{
"traditional":"龠","simplified":"龠","referencedTraditional":[{"cp":"9fa0","c":"龠"}],"referencedSimplified":[{"cp":"9fa0","c":"龠"}],"pinyinNumeric":"yue4","pinyinDiacritic":"yuè","definitions":["ancient unit of volume (half a 合[ge3], equivalent to 50ml)","ancient flute"],"definitionsDiacritic":["ancient unit of volume (half a 合[gě], equivalent to 50ml)","ancient flute"]},
    {"traditional":"龡","simplified":"龡","referencedTraditional":[{"cp":"9fa1","c":"龡"}],"referencedSimplified":[{"cp":"9fa1","c":"龡"}],"pinyinNumeric":"chui4","pinyinDiacritic":"chuì","definitions":["to blow (a flute)","archaic version of 吹"],"definitionsDiacritic":["to blow (a flute)","archaic version of 吹"]},
]
</code>```

I want to convert every key called definitions from an array into a string.

E.g. From ["percent (Tw)"] to "percent (Tw)". Basically, I don't want the array brackets.

So far, I've tried looping through the file and converting every "definitions" key with JSON.stringify() or toString() -

```<code>translations.forEach(key => JSON.stringify((key.definitions)))
</code>```

However, nothing changes in the outputted file.

答:
I think what may be happening for you is that you aren't saving the resulting array anywhere. The approach could be to create a new object.

```<code>const obj = {
    traditional: '%',
    simplified: '%',
    referencedTraditional: [],
    referencedSimplified: [],
    pinyinNumeric: 'pa1',
    pinyinDiacritic: 'pā',
    definitions: ['percent (Tw)'],
    definitionsDiacritic: ['percent (Tw)'],
};

const output = Object.keys(obj).reduce((accumulator, currentKey) => {
    const currentValue = obj[currentKey];
    if (currentKey === 'definitions' && Array.isArray(currentValue)) {
            accumulator[currentKey] = currentValue.join('');
    } else {
        accumulator[currentKey] = currentValue;
    }
    return accumulator;
}, {})

console.log(output);
</code>```

This solution checks if it is an array, and also just joins everything in the array just in case there are multiple things in the array, but how this is handled is really up to you :)

Title: Convert array in JSON file to string

Body:
Here's a snippet of my JSON object (EDITED) -

[{
    "traditional": "%",
    "simplified": "%",
    "referencedTraditional": [],
    "referencedSimplified": [],
    "pinyinNumeric": "pa1",
    "pinyinDiacritic": "pā",
    "definitions": [
        "percent (Tw)"
    ],
    "definitionsDiacritic": [
        "percent (Tw)"
    ]
},
{
"traditional":"龠","simplified":"龠","referencedTraditional":[{"cp":"9fa0","c":"龠"}],"referencedSimplified":[{"cp":"9fa0","c":"龠"}],"pinyinNumeric":"yue4","pinyinDiacritic":"yuè","definitions":["ancient unit of volume (half a 合[ge3], equivalent to 50ml)","ancient flute"],"definitionsDiacritic":["ancient unit of volume (half a 合[gě], equivalent to 50ml)","ancient flute"]},
    {"traditional":"龡","simplified":"龡","referencedTraditional":[{"cp":"9fa1","c":"龡"}],"referencedSimplified":[{"cp":"9fa1","c":"龡"}],"pinyinNumeric":"chui4","pinyinDiacritic":"chuì","definitions":["to blow (a flute)","archaic version of 吹"],"definitionsDiacritic":["to blow (a flute)","archaic version of 吹"]},
]

I want to convert every key called definitions from an array into a string.

E.g. From ["percent (Tw)"] to "percent (Tw)". Basically, I don't want the array brackets.

So far, I've tried looping through the file and converting every "definitions" key with JSON.stringify() or toString() -

translations.forEach(key => JSON.stringify((key.definitions)))

However, nothing changes in the outputted file.

Body:
I think what may be happening for you is that you aren't saving the resulting array anywhere. The approach could be to create a new object.

const obj = {
    traditional: '%',
    simplified: '%',
    referencedTraditional: [],
    referencedSimplified: [],
    pinyinNumeric: 'pa1',
    pinyinDiacritic: 'pā',
    definitions: ['percent (Tw)'],
    definitionsDiacritic: ['percent (Tw)'],
};

const output = Object.keys(obj).reduce((accumulator, currentKey) => {
    const currentValue = obj[currentKey];
    if (currentKey === 'definitions' && Array.isArray(currentValue)) {
            accumulator[currentKey] = currentValue.join('');
    } else {
        accumulator[currentKey] = currentValue;
    }
    return accumulator;
}, {})

console.log(output);

This solution checks if it is an array, and also just joins everything in the array just in case there are multiple things in the array, but how this is handled is really up to you :)


问:
setiting repeated task in AlarmManager problem
I trying to set a repeating task using the AlarmManager

the task is to send a broadcast to my BroadcastReciever that runs a service (if it isn't already).

this is the code which sets the repeating task:

```<code>alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 10000 , 60 * 1000 , pendingIntent);
</code>```

now the repeating task works fine, but if my application is still running, and I stop it, I don't get the broadcast anymore.

what am I doing wrong here?

edit:

the manifest: (only the relevant part)

```<code><service android:name=".TQService"/>
<receiver android:name=".TQServiceManager"
            android:process=":remote">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
    <intent-filter>
        <action android:name="com.xxxxx.tq.TQServiceManager"></action>
    </intent-filter>
</receiver>
</code>```

the code:

```<code>PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.xxxxx.tq.TQServiceManager"), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 , 30 * 1000 , pendingIntent);
</code>```

答: How is your BroadcastReceiver registered? It must be in your AndroidManifest.xml file, and not manually registered. The fact that it works when your app is running and doesn't when your app is not running sounds like it isn't in the manifest.</p>

Body:
I trying to set a repeating task using the AlarmManager

the task is to send a broadcast to my BroadcastReciever that runs a service (if it isn't already).

this is the code which sets the repeating task:

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 10000 , 60 * 1000 , pendingIntent);

now the repeating task works fine, but if my application is still running, and I stop it, I don't get the broadcast anymore.

what am I doing wrong here?

edit:

the manifest: (only the relevant part)

<service android:name=".TQService"/>
<receiver android:name=".TQServiceManager"
            android:process=":remote">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
    <intent-filter>
        <action android:name="com.xxxxx.tq.TQServiceManager"></action>
    </intent-filter>
</receiver>

the code:

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.xxxxx.tq.TQServiceManager"), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 , 30 * 1000 , pendingIntent);


问:
how to set superset SQLALCHEMY URI to connect HiveServer2 with custom auth
Superset want to connect HiveServer2 datasource with custom auth (that is specify username and password), python code as below is ok

```<code>from pyhive import hive

host_name = "192.168.0.38"
port = 10000
user = "admin"
password = "password"
database="test_db"

def hiveconnection(host_name, port, user,password, database):
    conn = hive.Connection(host=host_name, port=port, username=user, password=password,
                           database=database, auth='CUSTOM')
    cur = conn.cursor()
    cur.execute('select item_sk,reason_sk, account_credit from returns limit 5')
    result = cur.fetchall()

    return result
</code>```

but how to set Superset SQLALCHEMY URI ?

```<code>hive://hive@{hostname}:{port}/{database}
</code>```

Body:
Superset want to connect HiveServer2 datasource with custom auth (that is specify username and password), python code as below is ok

from pyhive import hive

host_name = "192.168.0.38"
port = 10000
user = "admin"
password = "password"
database="test_db"

def hiveconnection(host_name, port, user,password, database):
    conn = hive.Connection(host=host_name, port=port, username=user, password=password,
                           database=database, auth='CUSTOM')
    cur = conn.cursor()
    cur.execute('select item_sk,reason_sk, account_credit from returns limit 5')
    result = cur.fetchall()

    return result

but how to set Superset SQLALCHEMY URI ?

hive://hive@{hostname}:{port}/{database}

Body:
please see:
https://github.com/apache/superset/discussions/18699#discussioncomment-2170334

hive://username:password@hostname:port/database?auth=CUSTOM


问:
Google Cloud Shell Editor Not Resuming From Last Closed Session
I have tinkered with settings, preferences and also save workspace before exiting yet I am unable to make Google Cloud Shell Editor (IDE), launch with my last session's files, even if I open the Workspace file I had saved last.
If this works, I can avoid opening last session's (open) files one by one.</p>

答:
Google Cloud Shell Editor (gGSE) still does not resume sessions from the last one. It's been more then a month now that I have been working on it.
I found a work around: I now call edit in cloudshell CLI to open batches of files when I begin.
Cumbersome, but continuing with gGSE for ReactJS projects while using AWS Cloud9 (aC9) for Python, since aC9 IDE doesn't yet support ReactJS intellisense.
But for this issue, full marks to gGSE for the smooth IDE and terminal experience.


问:
dbOpenDynaset vs dbOpenTable with index
I just did a split of an Access database and I've got a couple of linked tables that use a line similar to VL2.Index = "ReportKey" after being opened via VL2.Index = db.OpenRecordset("VolunteerDetail", dbOpenTable), which no longer works because they're now linked tables.

So what do I do instead? I can open the recordset by omitting the dbOpenTable part, but it's the index that I don't know how to handle, because the dynaset piece doesn't have an index in the same way. I understand that VL2.Index = "ReportKey" is assigning the name to the index, but what is the equivalent of that with dbOpenDynaset? I've seen references to things like FindFirst, but those don't make sense to me.

What do I replace VL2.Index = "ReportKey"` with, when using a dynaset?

答:
Ok

VL2.Index = "ReportKey" after being opened via VL2.Index = db.OpenRecordset("VolunteerDetail", dbOpenTable), which no longer works because they're now linked tables.

correct. So this suggests you are using seek() code in your applcation.

There are two solutions here:

So, in place of this:

```<code>Dim rstHotels       As DAO.Recordset

Set rstHotels = CurrentDb.OpenRecordset("tblhotels", dbOpenTable)

rstHotels.Index = "PrimaryKey"
rstHotels.Seek "=", 17

If rstHotels.NoMatch Then
   Debug.Print "not found"
Else
   Debug.Print "found it"
End If

rstHotels.Close
</code>```

Change your code to use .FindFirst:

You would use say:

```<code>Dim rstHotels  As DAO.Recordset

Set rstHotels = CurrentDb.OpenRecordset("tblHotels1")

rstHotels.FindFirst "ID = 17"

If rstHotels.NoMatch Then
   Debug.Print "not found"
Else
   Debug.Print "fount it"
End If
</code>```

So, you can use .FindFirst, and you do NOT need to use the .index setting. I suspect the above could be used with "much less" changes to your existing code.

but, you can also consider writing out the sql, say like this:

```<code>Dim rstHotels  As DAO.Recordset
Dim strSQL     As String

strSQL = "SELECT * from tblHotels WHERE ID = 17"

Set rstHotels = CurrentDb.OpenRecordset(strSQL)

If rstHotels.RecordCount > 0 Then
   Debug.Print "found it"
End If
</code>```

So, one approach is to dump seek, but still use .FindFirst and .nomatch.

However, seek() MAY WELL be desired.

VERY important is HOW are you using seek?
(or are you even using seek????).

I ask, since seek() is  SUPER DUPER high speed performance option. This goes back to the early days of desktop database systems. seek() does NOT even use SQL, and it is VERY fast - I mean blistering fast.

So, it really depends on how you were using the .index setting. If you were just using .FindFirst, then in fact you don't need to set .index. You ONLY need to set the index WHEN using .seek().

Now, if you ARE using .seek() and you ARE hitting a whole bunch of PK or index values for special processing? If you can build a single query, no problem.

However, if the .seek() is to be used over and over - say in a processing loop?

then you can consider a 3rd alternative, use the data engine object, and DIRECLTY open the back end database, and your existing code and .seek() can still be used.

You would use this:

```<code>Public Function OpenForSeek(TableName As String) As Recordset
' Assume MS-ACCESS table
Set OpenForSeek = DBEngine.Workspaces(0).OpenDatabase _
                (Mid(CurrentDb().TableDefs(TableName).Connect, _
                11), False, False, "").OpenRecordset(TableName, _
                dbOpenTable)
End Function
</code>```

Then, you can go:

```<code>dim rstHotels   as DAO.RecordSet

set rstHotels = OpenForSeek("tblHotels")
</code>```

So, the above means you open the back end table directly in a round about way. I only suggest this last option if you REALLY do need .seek(), and you really need super duper performance to pull values.

Title: dbOpenDynaset vs dbOpenTable with index

Body:
Ok

VL2.Index = "ReportKey" after being opened via VL2.Index = db.OpenRecordset("VolunteerDetail", dbOpenTable), which no longer works because they're now linked tables.

correct. So this suggests you are using seek() code in your applcation.

There are two solutions here:

So, in place of this:

Dim rstHotels       As DAO.Recordset

Set rstHotels = CurrentDb.OpenRecordset("tblhotels", dbOpenTable)

rstHotels.Index = "PrimaryKey"
rstHotels.Seek "=", 17

If rstHotels.NoMatch Then
   Debug.Print "not found"
Else
   Debug.Print "found it"
End If

rstHotels.Close

Change your code to use .FindFirst:

You would use say:

Dim rstHotels  As DAO.Recordset

Set rstHotels = CurrentDb.OpenRecordset("tblHotels1")

rstHotels.FindFirst "ID = 17"

If rstHotels.NoMatch Then
   Debug.Print "not found"
Else
   Debug.Print "fount it"
End If

So, you can use .FindFirst, and you do NOT need to use the .index setting. I suspect the above could be used with "much less" changes to your existing code.

but, you can also consider writing out the sql, say like this:

Dim rstHotels  As DAO.Recordset
Dim strSQL     As String

strSQL = "SELECT * from tblHotels WHERE ID = 17"

Set rstHotels = CurrentDb.OpenRecordset(strSQL)

If rstHotels.RecordCount > 0 Then
   Debug.Print "found it"
End If

So, one approach is to dump seek, but still use .FindFirst and .nomatch.

However, seek() MAY WELL be desired.

VERY important is HOW are you using seek?
(or are you even using seek????).

I ask, since seek() is  SUPER DUPER high speed performance option. This goes back to the early days of desktop database systems. seek() does NOT even use SQL, and it is VERY fast - I mean blistering fast.

So, it really depends on how you were using the .index setting. If you were just using .FindFirst, then in fact you don't need to set .index. You ONLY need to set the index WHEN using .seek().

Now, if you ARE using .seek() and you ARE hitting a whole bunch of PK or index values for special processing? If you can build a single query, no problem.

However, if the .seek() is to be used over and over - say in a processing loop?

then you can consider a 3rd alternative, use the data engine object, and DIRECLTY open the back end database, and your existing code and .seek() can still be used.

You would use this:

Public Function OpenForSeek(TableName As String) As Recordset
' Assume MS-ACCESS table
Set OpenForSeek = DBEngine.Workspaces(0).OpenDatabase _
                (Mid(CurrentDb().TableDefs(TableName).Connect, _
                11), False, False, "").OpenRecordset(TableName, _
                dbOpenTable)
End Function

Then, you can go:

dim rstHotels   as DAO.RecordSet

set rstHotels = OpenForSeek("tblHotels")

So, the above means you open the back end table directly in a round about way. I only suggest this last option if you REALLY do need .seek(), and you really need super duper performance to pull values.


问:
Election Polls Query
I have SQL tables below.

```<code>Candidates
ID Name Position
1 Pacquio President
2 Leni    President
3 Herbert Senator
4 Tulfo   Senator
5 Marcoleta Senator

Voters
ID  Name Candidates
1  Noel 1,3,4
2 Mar   2,4,5
3 Dan.  2,4,3
</code>```

The result should be below

```<code>Results
Position Name Votes
President Leni 2
President Pacquio 1
Senator Tulfo 2
Senator Herbert 1
Senator Marcoleta 1
</code>```

What should be my SQL Query

Thanks very much
Noel

答:
```<code>;WITH CastedVotes(VoterID,CandidateID) as --using CTE
(
SELECT ID, value
FROM Voters
CROSS APPLY STRING_SPLIT(Candidates, ',')
)
SELECT DISTINCT C.NAME
, Position
, COUNT (C.ID) OVER (PARTITION BY C.ID) AS VotesCount
FROM CastedVotes CV
INNER JOIN Voters V ON VoterID=V.ID
INNER JOIN Candidates C ON CandidateID=C.ID
ORDER BY Position, VotesCount DESC
</code>```

Here is the answer, I want the field position first. Any Idea maybe group by

Title: Election Polls Query

Body:
I have SQL tables below.

Candidates
ID Name Position
1 Pacquio President
2 Leni    President
3 Herbert Senator
4 Tulfo   Senator
5 Marcoleta Senator

Voters
ID  Name Candidates
1  Noel 1,3,4
2 Mar   2,4,5
3 Dan.  2,4,3

The result should be below

Results
Position Name Votes
President Leni 2
President Pacquio 1
Senator Tulfo 2
Senator Herbert 1
Senator Marcoleta 1

What should be my SQL Query

Thanks very much
Noel

Body:
;WITH CastedVotes(VoterID,CandidateID) as --using CTE
(
SELECT ID, value
FROM Voters
CROSS APPLY STRING_SPLIT(Candidates, ',')
)
SELECT DISTINCT C.NAME
, Position
, COUNT (C.ID) OVER (PARTITION BY C.ID) AS VotesCount
FROM CastedVotes CV
INNER JOIN Voters V ON VoterID=V.ID
INNER JOIN Candidates C ON CandidateID=C.ID
ORDER BY Position, VotesCount DESC

Here is the answer, I want the field position first. Any Idea maybe group by


问:
Http to Https redirect not working for ASPNET Core3.1 app on GCP App Engine Flex
I have deployed an ASPNET Core 3.1 app on Google's App Engine in a flex environment. The app is still accessible on both HTTP and HTTPS. I want to redirect all HTTP requests to HTTPS. Read in many places that apps on GCP App Engine should be configured on application level to handle http redirection I have tried Microsoft.AspNetCore.Rewrite but it would return too many redirects once the app is deployed on App Engine. When not using the rewriter it will have the app accessible on both protocols. I have even tried a custom middleware as instructed here but again it would return too many redirects. Please tell me where I am wrong and how can I get it resolved. Thanks a lot.

Startup.cs

```<code>public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //app.UseHttpsEnforcement();
                //var options = new RewriteOptions().AddRedirectToHttps(301, 443);
                //app.UseRewriter(options);
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
</code>```

Custom middleware

```<code>public static class AppBuilderExtensions
    {
        public static IApplicationBuilder UseHttpsEnforcement(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            return app.UseMiddleware<EnforceHttpsMiddleware>();
        }
    }
</code>```
```<code> public class EnforceHttpsMiddleware
    {
        private readonly RequestDelegate _next;

        public EnforceHttpsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            HttpRequest req = context.Request;
            if (req.IsHttps == false)
            {
                string url = "https://" + req.Host + req.Path + req.QueryString;
                context.Response.Redirect(url, permanent: true);
            }
            else
            {
                await _next(context);
            }
        }
    }
</code>```

app.yaml

```<code>runtime: aspnetcore
env: flex

manual_scaling:
  instances: 1

resources:
  cpu: 1
  memory_gb: 1
  disk_size_gb: 10

</code>```

答: So fortunately I was able to resolve it. The app needed some configuration in order properly able to understand the request. See Natthapol Vanasrivilai's answer here. The solution was targeted at NET Core 2.1 but it turns out to be working in NET Core 3.1 as well.</p>

Body:
I have deployed an ASPNET Core 3.1 app on Google's App Engine in a flex environment. The app is still accessible on both HTTP and HTTPS. I want to redirect all HTTP requests to HTTPS. Read in many places that apps on GCP App Engine should be configured on application level to handle http redirection I have tried Microsoft.AspNetCore.Rewrite but it would return too many redirects once the app is deployed on App Engine. When not using the rewriter it will have the app accessible on both protocols. I have even tried a custom middleware as instructed here but again it would return too many redirects. Please tell me where I am wrong and how can I get it resolved. Thanks a lot.

Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //app.UseHttpsEnforcement();
                //var options = new RewriteOptions().AddRedirectToHttps(301, 443);
                //app.UseRewriter(options);
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }

Custom middleware

public static class AppBuilderExtensions
    {
        public static IApplicationBuilder UseHttpsEnforcement(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            return app.UseMiddleware<EnforceHttpsMiddleware>();
        }
    }

 public class EnforceHttpsMiddleware
    {
        private readonly RequestDelegate _next;

        public EnforceHttpsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            HttpRequest req = context.Request;
            if (req.IsHttps == false)
            {
                string url = "https://" + req.Host + req.Path + req.QueryString;
                context.Response.Redirect(url, permanent: true);
            }
            else
            {
                await _next(context);
            }
        }
    }

app.yaml

runtime: aspnetcore
env: flex

manual_scaling:
  instances: 1

resources:
  cpu: 1
  memory_gb: 1
  disk_size_gb: 10


问:
Keras - Trying to get 'logits' - one layer before the softmax activation function
I'm trying to get the 'logits' out of my Keras CNN classifier.
I have tried the suggested method here: link.

First I created two models to check the implementation :

create_CNN_MNIST CNN classifier that returns the softmax probabilities.

create_CNN_MNIST_logits CNN with the same layers as in (1) with a little twist in the last layer - changed the activation function to linear to return logits.

Both models were fed with the same Train and Test data of MNIST. Then I applied softmax on the logits, I got a different output from the softmax CNN.

I couldn't find a problem in my code. Maybe you could help advise another method to extract 'logits' from the model?

the code:

```<code>def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=0)

def create_CNN_MNIST_logits() :
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))
    model.add(MaxPooling2D((2, 2)))
    model.add(Flatten())
    model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))
    model.add(Dense(10, activation='linear'))
    # compile model
    opt = SGD(learning_rate=0.01, momentum=0.9)

    def my_sparse_categorical_crossentropy(y_true, y_pred):
        return keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=True)

    model.compile(optimizer=opt, loss=my_sparse_categorical_crossentropy, metrics=['accuracy'])
    return model

def create_CNN_MNIST() :
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))
    model.add(MaxPooling2D((2, 2)))
    model.add(Flatten())
    model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))
    model.add(Dense(10, activation='softmax'))
    # compile model
    opt = SGD(learning_rate=0.01, momentum=0.9)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# load data
X_train = np.load('./data/X_train.npy')
X_test = np.load('./data/X_test.npy')
y_train = np.load('./data/y_train.npy')
y_test = np.load('./data/y_test.npy')

#create models
model_softmax = create_CNN_MNIST()
model_logits = create_CNN_MNIST_logits()

pixels = 28
channels = 1
num_labels = 10

# Reshaping to format which CNN expects (batch, height, width, channels)
trainX_cnn = X_train.reshape(X_train.shape[0], pixels, pixels, channels).astype('float32')
testX_cnn = X_test.reshape(X_test.shape[0], pixels, pixels, channels).astype('float32')

# Normalize images from 0-255 to 0-1
trainX_cnn /= 255
testX_cnn /= 255

train_y_cnn = utils.to_categorical(y_train, num_labels)
test_y_cnn = utils.to_categorical(y_test, num_labels)

#train the models:
model_logits.fit(trainX_cnn, train_y_cnn, validation_split=0.2, epochs=10,
                          batch_size=32)
model_softmax.fit(trainX_cnn, train_y_cnn, validation_split=0.2, epochs=10,
                          batch_size=32)

</code>```

On the evaluation stage, I'll do softmax on the logits to check if its the same as the regular model:

```<code>#predict
y_pred_softmax = model_softmax.predict(testX_cnn)
y_pred_logits = model_logits.predict(testX_cnn)

#apply softmax on the logits to get the same result of regular CNN
y_pred_logits_activated = softmax(y_pred_logits)

</code>```

Now I get different values in both y_pred_logits_activated and y_pred_softmax that lead to different accuracy on the test set.

答:
Your models are probably being trained differently, make sure to set the seed prior to both fit commands so that they're initialised the same weights and have the same train/val split. Also, is the softmax might be incorrect:

```<code>def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x)
    return e_x / e_x.sum(axis=1)
</code>```

This is numerically equivalent to subtracting the max (https://stackoverflow.com/a/34969389/10475762), and the axis should be 1 if your matrix is of shape [batch, outputs].

Body:
I'm trying to get the 'logits' out of my Keras CNN classifier.
I have tried the suggested method here: link.

First I created two models to check the implementation :

create_CNN_MNIST CNN classifier that returns the softmax probabilities.

create_CNN_MNIST_logits CNN with the same layers as in (1) with a little twist in the last layer - changed the activation function to linear to return logits.

Both models were fed with the same Train and Test data of MNIST. Then I applied softmax on the logits, I got a different output from the softmax CNN.

I couldn't find a problem in my code. Maybe you could help advise another method to extract 'logits' from the model?

the code:

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=0)

def create_CNN_MNIST_logits() :
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))
    model.add(MaxPooling2D((2, 2)))
    model.add(Flatten())
    model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))
    model.add(Dense(10, activation='linear'))
    # compile model
    opt = SGD(learning_rate=0.01, momentum=0.9)

    def my_sparse_categorical_crossentropy(y_true, y_pred):
        return keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=True)

    model.compile(optimizer=opt, loss=my_sparse_categorical_crossentropy, metrics=['accuracy'])
    return model

def create_CNN_MNIST() :
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))
    model.add(MaxPooling2D((2, 2)))
    model.add(Flatten())
    model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))
    model.add(Dense(10, activation='softmax'))
    # compile model
    opt = SGD(learning_rate=0.01, momentum=0.9)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# load data
X_train = np.load('./data/X_train.npy')
X_test = np.load('./data/X_test.npy')
y_train = np.load('./data/y_train.npy')
y_test = np.load('./data/y_test.npy')

#create models
model_softmax = create_CNN_MNIST()
model_logits = create_CNN_MNIST_logits()

pixels = 28
channels = 1
num_labels = 10

# Reshaping to format which CNN expects (batch, height, width, channels)
trainX_cnn = X_train.reshape(X_train.shape[0], pixels, pixels, channels).astype('float32')
testX_cnn = X_test.reshape(X_test.shape[0], pixels, pixels, channels).astype('float32')

# Normalize images from 0-255 to 0-1
trainX_cnn /= 255
testX_cnn /= 255

train_y_cnn = utils.to_categorical(y_train, num_labels)
test_y_cnn = utils.to_categorical(y_test, num_labels)

#train the models:
model_logits.fit(trainX_cnn, train_y_cnn, validation_split=0.2, epochs=10,
                          batch_size=32)
model_softmax.fit(trainX_cnn, train_y_cnn, validation_split=0.2, epochs=10,
                          batch_size=32)

On the evaluation stage, I'll do softmax on the logits to check if its the same as the regular model:

#predict
y_pred_softmax = model_softmax.predict(testX_cnn)
y_pred_logits = model_logits.predict(testX_cnn)

#apply softmax on the logits to get the same result of regular CNN
y_pred_logits_activated = softmax(y_pred_logits)

Now I get different values in both y_pred_logits_activated and y_pred_softmax that lead to different accuracy on the test set.

Body:
Your models are probably being trained differently, make sure to set the seed prior to both fit commands so that they're initialised the same weights and have the same train/val split. Also, is the softmax might be incorrect:

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x)
    return e_x / e_x.sum(axis=1)

This is numerically equivalent to subtracting the max (https://stackoverflow.com/a/34969389/10475762), and the axis should be 1 if your matrix is of shape [batch, outputs].