问:
getter is targetting wrong column, unable to map the corrrect one
extra info : legacy database with two problematic columns codeArticle and code_article in the same table.
My problem is that i need to retreive the data from codeArticle and not from code_article but my getter method seems to want to target code_article regardless how i map it...
I have also tried to rename the code_article field so that it wouldnt interfere with codeArticle but not only the same error pops up, but it also recreates the code_article field back in the table.

My entity:

```<code>@Entity
@Table(name = "produits", schema = "t_orvif_web_dev")
public class Produits {

    private int idProduits;
    private int cleSystem;
    private String codeOrvif;
    private String refFournisseur;
    private String libelle;
    private String descriptif;
    private String avantages;
    private float ppht;
    private float ppttc;
    private Double ecoPart;
    private Double ecoMobilier;
    private float pphtPublic;
    private float ppttcPublic;
    private boolean visible;
    private int codeArticle; // <----------- this guy...
    private String libelleUrl;
    private Marques marquesByIdMarques;
    private Familles famillesByIdFamilles;
    private Categories categoriesByIdCategories;
    private Gammes gammesByIdGammes;
    private int idMarques;
    private int idUv;
    private int idUf;
    private int idFamilles;
    private int idSsfamilles;
    private int idCategories;
    private int idSscategories;
    private boolean obligatoire;
    private Integer idGammes;
    private Collection<Groupe> groupesByIdProduits;
    private Collection<LignePanier> lignePaniersByIdProduits;
    private UnitesVente unitesVenteByIdUv;
    private UnitesFacturation unitesFacturationByIdUf;
    private SsFamilles ssFamillesByIdSsfamilles;
    private SsCategories ssCategoriesByIdSscategories;

    @Basic
    @Column(name = "codeArticle", nullable = false)
    public int getCodeArticle() {
        return codeArticle;
    }

    public void setCodeArticle(int codeArticle) {
        this.codeArticle = codeArticle;
    }
...
</code>```

Im my query, i selected all the columns that i need and not selected the problematic unwanted column.
when i test the query in mysqlworkbench , the result is good.
My  JPA repository:

```<code>public interface ProduitsRepository extends JpaRepository<Produits, Integer> {

    @Query(value = "SELECT id_produits, cle_system, code_orvif, ref_fournisseur, libelle, descriptif, avantages, ppht, eco_part, eco_mobilier," +
            " id_marques, id_uv, id_uf, id_familles, id_ssfamilles, id_categories, id_sscategories, id_gammes, visible, codeArticle, available, " +
            "defi, destockage, libelle_url, obligatoire, ppht_public, ppttc, ppttc_public " +
            "FROM PRODUITS WHERE codeArticle IN (SELECT * FROM (SELECT DISTINCT(codeArticle) FROM PRODUITS LIMIT 5, :number )as t) ORDER BY codeArticle;", nativeQuery = true)
    List<Produits> getRandomGroups2( @Param("number") int number);

</code>```

But when i call the query in a method that my controller uses, my getter method seems to want to fetch the data from the unwanted column (code_article) instead of codeArticle.

The method where i call the query:

```<code>   @Autowired
    private ProduitsRepository pr;

...

public List<Groupe>randGrp(int number, String cleClient) {
        try {
        List<Produits> tempList = pr.getRandomGroups2(number);
        List<Groupe> groupes = new ArrayList<>();
        Groupe currentGroupe = null;
        for (Produits p : tempList) {
            System.out.println(p.getCodeArticle() ); //// test

            if (currentGroupe == null || currentGroupe.getId() != p.getCodeArticle()) {
                if (currentGroupe != null) {
                    groupes.add(currentGroupe);
                }
                currentGroupe = new Groupe();
                currentGroupe.setId(p.getCodeArticle());
                List<com.orvif.website3.Entity.Document> documents = new ArrayList<>();
                documents.add(dr.getFirstImageByProduct(p.getIdProduits()));
                p.setImageCollection(documents);
            }
            currentGroupe.getProducts().add(p);
        }
        if (currentGroupe != null) {
            groupes.add(currentGroupe);
        }
        getProductsInfoFromNxGroup(groupes, cleClient);
        return groupes;
    } catch (DAOException e) {
        throw e;
        } catch (Exception e) {
        e.printStackTrace();
        throw new DAOException(e.getClass().getName() + " exception while fetching random groups.");
        }
</code>```

When i launch the app i get the following error:

```<code>2020-02-19 16:59:26.309 ERROR 10532 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'code_article' not found.
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT id_produits, cle_system, code_orvif, ref_fournisseur, libelle, descriptif, avantages, ppht, eco_part, eco_mobilier, id_marques, id_uv, id_uf, id_familles, id_ssfamilles, id_categories, id_sscategories, id_gammes, visible, codeArticle, available, defi, destockage, libelle_url, obligatoire, ppht_public, ppttc, ppttc_public FROM PRODUITS WHERE codeArticle IN (SELECT * FROM (SELECT DISTINCT(codeArticle) FROM PRODUITS LIMIT 5, ? )as t) ORDER BY codeArticle;]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy104.getRandomGroups2(Unknown Source)
    at com.orvif.website3.Controller.AccueilController.randGrp(AccueilController.java:102)
    at com.orvif.website3.Controller.AccueilController.showAccueil(AccueilController.java:86)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.loader.Loader.doList(Loader.java:2818)
    at org.hibernate.loader.Loader.doList(Loader.java:2797)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2629)
    at org.hibernate.loader.Loader.list(Loader.java:2624)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2123)
    at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1134)
    at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:173)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1526)
    at org.hibernate.query.Query.getResultList(Query.java:165)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:126)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:154)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:142)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:618)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 59 more
Caused by: java.sql.SQLException: Column 'code_article' not found.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.result.ResultSetImpl.findColumn(ResultSetImpl.java:548)
    at com.mysql.cj.jdbc.result.ResultSetImpl.getInt(ResultSetImpl.java:807)
    at com.zaxxer.hikari.pool.HikariProxyResultSet.getInt(HikariProxyResultSet.java)
    at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$2.doExtract(IntegerTypeDescriptor.java:62)
    at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
    at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3059)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1866)
    at org.hibernate.loader.Loader.hydrateEntityState(Loader.java:1794)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1767)
    at org.hibernate.loader.Loader.getRow(Loader.java:1615)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:745)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:1008)
    at org.hibernate.loader.Loader.doQuery(Loader.java:964)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
    at org.hibernate.loader.Loader.doList(Loader.java:2815)
    ... 81 more
2020-02-19 16:59:26.345 ERROR 10532 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.orvif.website3.Repository.DAOException: org.springframework.dao.InvalidDataAccessResourceUsageException exception while fetching random groups.] with root cause

com.orvif.website3.Repository.DAOException: org.springframework.dao.InvalidDataAccessResourceUsageException exception while fetching random groups.
    at com.orvif.website3.Controller.AccueilController.randGrp(AccueilController.java:134) ~[classes/:na]
    at com.orvif.website3.Controller.AccueilController.showAccueil(AccueilController.java:86) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) [na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) [na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at java.base/java.lang.Thread.run(Thread.java:844) [na:na]

</code>```

If i change my query to select * in order to include the unwanted feild, then the app runs but my getter will be linked to the wrong feild.

Any idea how to get my getter method to chose the correct feild?
Let me know if you need any additional info/code.
Thanks in advance!

答:
problem fixed.
i ended up deleting code_article column from the database, renaming codeArticle column to code_article and renaming all occurences of codeArticle to code_article across the app.</p>

Body:
extra info : legacy database with two problematic columns codeArticle and code_article in the same table.
My problem is that i need to retreive the data from codeArticle and not from code_article but my getter method seems to want to target code_article regardless how i map it...
I have also tried to rename the code_article field so that it wouldnt interfere with codeArticle but not only the same error pops up, but it also recreates the code_article field back in the table.

My entity:

@Entity
@Table(name = "produits", schema = "t_orvif_web_dev")
public class Produits {

    private int idProduits;
    private int cleSystem;
    private String codeOrvif;
    private String refFournisseur;
    private String libelle;
    private String descriptif;
    private String avantages;
    private float ppht;
    private float ppttc;
    private Double ecoPart;
    private Double ecoMobilier;
    private float pphtPublic;
    private float ppttcPublic;
    private boolean visible;
    private int codeArticle; // <----------- this guy...
    private String libelleUrl;
    private Marques marquesByIdMarques;
    private Familles famillesByIdFamilles;
    private Categories categoriesByIdCategories;
    private Gammes gammesByIdGammes;
    private int idMarques;
    private int idUv;
    private int idUf;
    private int idFamilles;
    private int idSsfamilles;
    private int idCategories;
    private int idSscategories;
    private boolean obligatoire;
    private Integer idGammes;
    private Collection<Groupe> groupesByIdProduits;
    private Collection<LignePanier> lignePaniersByIdProduits;
    private UnitesVente unitesVenteByIdUv;
    private UnitesFacturation unitesFacturationByIdUf;
    private SsFamilles ssFamillesByIdSsfamilles;
    private SsCategories ssCategoriesByIdSscategories;

    @Basic
    @Column(name = "codeArticle", nullable = false)
    public int getCodeArticle() {
        return codeArticle;
    }

    public void setCodeArticle(int codeArticle) {
        this.codeArticle = codeArticle;
    }
...

Im my query, i selected all the columns that i need and not selected the problematic unwanted column.
when i test the query in mysqlworkbench , the result is good.
My  JPA repository:

public interface ProduitsRepository extends JpaRepository<Produits, Integer> {

    @Query(value = "SELECT id_produits, cle_system, code_orvif, ref_fournisseur, libelle, descriptif, avantages, ppht, eco_part, eco_mobilier," +
            " id_marques, id_uv, id_uf, id_familles, id_ssfamilles, id_categories, id_sscategories, id_gammes, visible, codeArticle, available, " +
            "defi, destockage, libelle_url, obligatoire, ppht_public, ppttc, ppttc_public " +
            "FROM PRODUITS WHERE codeArticle IN (SELECT * FROM (SELECT DISTINCT(codeArticle) FROM PRODUITS LIMIT 5, :number )as t) ORDER BY codeArticle;", nativeQuery = true)
    List<Produits> getRandomGroups2( @Param("number") int number);

But when i call the query in a method that my controller uses, my getter method seems to want to fetch the data from the unwanted column (code_article) instead of codeArticle.

The method where i call the query:

   @Autowired
    private ProduitsRepository pr;

...

public List<Groupe>randGrp(int number, String cleClient) {
        try {
        List<Produits> tempList = pr.getRandomGroups2(number);
        List<Groupe> groupes = new ArrayList<>();
        Groupe currentGroupe = null;
        for (Produits p : tempList) {
            System.out.println(p.getCodeArticle() ); //// test

            if (currentGroupe == null || currentGroupe.getId() != p.getCodeArticle()) {
                if (currentGroupe != null) {
                    groupes.add(currentGroupe);
                }
                currentGroupe = new Groupe();
                currentGroupe.setId(p.getCodeArticle());
                List<com.orvif.website3.Entity.Document> documents = new ArrayList<>();
                documents.add(dr.getFirstImageByProduct(p.getIdProduits()));
                p.setImageCollection(documents);
            }
            currentGroupe.getProducts().add(p);
        }
        if (currentGroupe != null) {
            groupes.add(currentGroupe);
        }
        getProductsInfoFromNxGroup(groupes, cleClient);
        return groupes;
    } catch (DAOException e) {
        throw e;
        } catch (Exception e) {
        e.printStackTrace();
        throw new DAOException(e.getClass().getName() + " exception while fetching random groups.");
        }

When i launch the app i get the following error:

2020-02-19 16:59:26.309 ERROR 10532 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'code_article' not found.
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT id_produits, cle_system, code_orvif, ref_fournisseur, libelle, descriptif, avantages, ppht, eco_part, eco_mobilier, id_marques, id_uv, id_uf, id_familles, id_ssfamilles, id_categories, id_sscategories, id_gammes, visible, codeArticle, available, defi, destockage, libelle_url, obligatoire, ppht_public, ppttc, ppttc_public FROM PRODUITS WHERE codeArticle IN (SELECT * FROM (SELECT DISTINCT(codeArticle) FROM PRODUITS LIMIT 5, ? )as t) ORDER BY codeArticle;]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy104.getRandomGroups2(Unknown Source)
    at com.orvif.website3.Controller.AccueilController.randGrp(AccueilController.java:102)
    at com.orvif.website3.Controller.AccueilController.showAccueil(AccueilController.java:86)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.loader.Loader.doList(Loader.java:2818)
    at org.hibernate.loader.Loader.doList(Loader.java:2797)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2629)
    at org.hibernate.loader.Loader.list(Loader.java:2624)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2123)
    at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1134)
    at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:173)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1526)
    at org.hibernate.query.Query.getResultList(Query.java:165)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:126)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:154)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:142)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:618)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 59 more
Caused by: java.sql.SQLException: Column 'code_article' not found.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.result.ResultSetImpl.findColumn(ResultSetImpl.java:548)
    at com.mysql.cj.jdbc.result.ResultSetImpl.getInt(ResultSetImpl.java:807)
    at com.zaxxer.hikari.pool.HikariProxyResultSet.getInt(HikariProxyResultSet.java)
    at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$2.doExtract(IntegerTypeDescriptor.java:62)
    at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
    at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3059)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1866)
    at org.hibernate.loader.Loader.hydrateEntityState(Loader.java:1794)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1767)
    at org.hibernate.loader.Loader.getRow(Loader.java:1615)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:745)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:1008)
    at org.hibernate.loader.Loader.doQuery(Loader.java:964)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
    at org.hibernate.loader.Loader.doList(Loader.java:2815)
    ... 81 more
2020-02-19 16:59:26.345 ERROR 10532 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.orvif.website3.Repository.DAOException: org.springframework.dao.InvalidDataAccessResourceUsageException exception while fetching random groups.] with root cause

com.orvif.website3.Repository.DAOException: org.springframework.dao.InvalidDataAccessResourceUsageException exception while fetching random groups.
    at com.orvif.website3.Controller.AccueilController.randGrp(AccueilController.java:134) ~[classes/:na]
    at com.orvif.website3.Controller.AccueilController.showAccueil(AccueilController.java:86) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) [na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) [na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.30.jar:9.0.30]
    at java.base/java.lang.Thread.run(Thread.java:844) [na:na]

If i change my query to select * in order to include the unwanted feild, then the app runs but my getter will be linked to the wrong feild.

Any idea how to get my getter method to chose the correct feild?
Let me know if you need any additional info/code.
Thanks in advance!


来源: stackexchange

问:
How to avoid casting to a specific interface

Background info

I have a set of interfaces/classes as follows. For the sake of simplicity imagine more properties, collections etc.

interface IMaster
{
//Some properties
}

interface IB : IMaster
{
    string PropOnA { get; set }
}
interface IC : IMaster
{
    string PropOnB { get; set }
}

class B : IB
class C : IC
...
```

<p>These contracts were designed to store data(which is held in a slightly different format in each case). There is a lot of code that uses these contracts to get the data, format it, process it, write etc.
We have developed an entire library that does not see the concrete implementations(B,C) of any of these contracts by inverting control and allow the user to use our 'default implementations' for each contract or just loading in their own. We have registry where the user can register a different implementation.</p>

<p>To this end I have implemented a kind of strategy pattern where there exists a strategy for each contract type based on the task at hand. For the sake of simplicity lets say the task is <strong>writing</strong>, in reality it is much more complicated.</p>

```interface IWriteStrategy
{
    public Write(IMaster thing);
}

class WriterA : IWriteStrategy

class WriterB : IWriteStrategy

etc
```

<p>The above concrete strategies are also never 'seen' in our library, the client must register their own implementation or our default version. </p>

<h3>Design flaw??</h3>

<p>I am not liking the cast in every strategy that is now necessary.</p>

```public classWriterA : IWriteStrategy
{
    public void Write(IMaster thing)
    {
        if(thing is IA thingA)
        //do some work
    }
}

public classWriterB : IWriteStrategy
{
    public void Write(IMaster thing)
    {
        if(thing is IB thingB)
        //do some work
    }
}
```

<p>What we want to do is be able to loop through a list of <code>IMaster</code> objects and run some operations.</p>

```foreach(var thing in Things)
{
    var strategy = GetStrategy(thing.GetType());  //this gets the strategy object from our `registry` if one exists
    strategy.Execute(thing);
}
```

The above design allows this but there seems to be a flaw which I cant for the life of me spot a solution to. We have to cast to the specific interface within each strategy implementation.

I have tried with generics, but just cant seem to nail it.

Question

What would be a better way of designing this to avoid the cast but still be able to loop through a list of IMaster things and treat them the same? Or is the cast absolutely necessary here?

I am trying to follow a SOLID design but feel the cast is messing with this as the client implementing the strategies will have to do the cast in order to get anything to work within the Write method.

[Edit]
I have updated the classes implementing the IWriteStrategy.

答:
Maybe it is appropriate to use Strategy pattern and just give an implementation and execute it. Let me show an example.

```<code>interface IMaster
{
    void ExecuteMaster();
}

class MasterOne : IMaster
{
    public void ExecuteMaster()
    {
        Console.WriteLine("Master One");
    }
}

class MasterTwo : IMaster
{
    public void ExecuteMaster()
    {
        Console.WriteLine("Master Two");
    }
}
</code>```

and

```<code>interface IWriteStrategy
{
    void Write(IMaster thing);
}

class WriterA : IWriteStrategy
{
    public void Write(IMaster thing)
    {
        Console.WriteLine("Writer A");
        thing.ExecuteMaster();
    }
}

class WriterB : IWriteStrategy
{
    public void Write(IMaster thing)
    {
        Console.WriteLine("Writer B");
        thing.ExecuteMaster();
    }
}
</code>```

and code to execute:

```<code>static void Main(string[] args)
{
    List<IWriteStrategy> writeStrategies = new List<IWriteStrategy>()
    {
        new WriterA(),
        new WriterB()
    };
    List<IMaster> executes = new List<IMaster>()
    {
         new MasterOne(),
         new MasterTwo()
    };

    for (int i = 0; i < writeStrategies.Count(); i++)
    {
         writeStrategies[i].Write(executes[i]);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Background info

I have a set of interfaces/classes as follows. For the sake of simplicity imagine more properties, collections etc.

interface IMaster
{
//Some properties
}

interface IB : IMaster
{
    string PropOnA { get; set }
}
interface IC : IMaster
{
    string PropOnB { get; set }
}

class B : IB
class C : IC
...

These contracts were designed to store data(which is held in a slightly different format in each case). There is a lot of code that uses these contracts to get the data, format it, process it, write etc.
We have developed an entire library that does not see the concrete implementations(B,C) of any of these contracts by inverting control and allow the user to use our 'default implementations' for each contract or just loading in their own. We have registry where the user can register a different implementation.

To this end I have implemented a kind of strategy pattern where there exists a strategy for each contract type based on the task at hand. For the sake of simplicity lets say the task is writing, in reality it is much more complicated.

interface IWriteStrategy
{
    public Write(IMaster thing);
}

class WriterA : IWriteStrategy

class WriterB : IWriteStrategy

etc

The above concrete strategies are also never 'seen' in our library, the client must register their own implementation or our default version.

Design flaw??

I am not liking the cast in every strategy that is now necessary.

public classWriterA : IWriteStrategy
{
    public void Write(IMaster thing)
    {
        if(thing is IA thingA)
        //do some work
    }
}

public classWriterB : IWriteStrategy
{
    public void Write(IMaster thing)
    {
        if(thing is IB thingB)
        //do some work
    }
}

What we want to do is be able to loop through a list of IMaster objects and run some operations.

foreach(var thing in Things)
{
    var strategy = GetStrategy(thing.GetType());  //this gets the strategy object from our `registry` if one exists
    strategy.Execute(thing);
}

The above design allows this but there seems to be a flaw which I cant for the life of me spot a solution to. We have to cast to the specific interface within each strategy implementation.

I have tried with generics, but just cant seem to nail it.

Question

What would be a better way of designing this to avoid the cast but still be able to loop through a list of IMaster things and treat them the same? Or is the cast absolutely necessary here?

I am trying to follow a SOLID design but feel the cast is messing with this as the client implementing the strategies will have to do the cast in order to get anything to work within the Write method.

[Edit]
I have updated the classes implementing the IWriteStrategy.

Body:
Maybe it is appropriate to use Strategy pattern and just give an implementation and execute it. Let me show an example.

interface IMaster
{
    void ExecuteMaster();
}

class MasterOne : IMaster
{
    public void ExecuteMaster()
    {
        Console.WriteLine("Master One");
    }
}

class MasterTwo : IMaster
{
    public void ExecuteMaster()
    {
        Console.WriteLine("Master Two");
    }
}

and

interface IWriteStrategy
{
    void Write(IMaster thing);
}

class WriterA : IWriteStrategy
{
    public void Write(IMaster thing)
    {
        Console.WriteLine("Writer A");
        thing.ExecuteMaster();
    }
}

class WriterB : IWriteStrategy
{
    public void Write(IMaster thing)
    {
        Console.WriteLine("Writer B");
        thing.ExecuteMaster();
    }
}

and code to execute:

static void Main(string[] args)
{
    List<IWriteStrategy> writeStrategies = new List<IWriteStrategy>()
    {
        new WriterA(),
        new WriterB()
    };
    List<IMaster> executes = new List<IMaster>()
    {
         new MasterOne(),
         new MasterTwo()
    };

    for (int i = 0; i < writeStrategies.Count(); i++)
    {
         writeStrategies[i].Write(executes[i]);
    }
}


问:
Functional, Declarative, and Imperative Programming
What do the terms functional, declarative, and imperative programming mean?</p>

答:
In a nutshell:

An imperative language specfies a series of instructions that the computer executes in sequence (do this, then do that).

A declarative language declares a set of rules about what outputs should result from which inputs (eg. if you have A, then the result is B).  An engine will apply these rules to inputs, and give an output.

A functional language declares a set of mathematical/logical functions which define how input is translated to output.  eg. f(y) = y * y.  it is a type of declarative language.

OwnerDisplayName: curiouskitty

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: mdja


问:
Where can I download a sample Django template?
I just started working at a place as a front end developer where I need to build Django templates. I never worked with these before, does anyone know where I can download a sample template so I can look through the code structure?

I won't be doing any application development using the Django framework, only taking the variables the developer gives me and incorporating the in the html/css templates I build.

答:
There are lots of Open Source django apps that you could look at for inspiration. One example is Zinnia which is a blogging application - there are dozens of templates in this project, see this directory. There are many other open source django projects on http://github.com and http://bitbucket.org

You should also take a look at the official template documentation, there are lots of snippets there that are very useful.


问:
What interface type is suited for implementing strategy with different signature?
consider the following game code:

public class Player : MonoBehaviour {
    public void UseItem(Item item) {
        item.Use(this);
    }
    public void GetDrunk() {}
}

public class Item {
    public WhatInterface[] itemUsages;

    public void Use(Player player) {
        foreach(var usage in itemUsages) {
            usage.Execute(new ItemUsageArgs {itemUser = player, itemUsed = this})
        }
    }
}

public class GameManager : MonoBehaviour {

    public Player mainCharacter;
    public Item beer = new Item {itemUsages = new [] {
        new TestConsole(),
        new DamageFromItem (),
        new DrunkFromITem ()
    }}

    private void Start() {
        mainCharacter.Use(beer);
    }
}

public class TestConsole : WhatInterface {
    public void Execute(BaseArgs args) {
        Debug.Log("function call executed");
    }
}

public class DamageFromItem : WhatInterface {
    public void Execute(ItemUsageArgs args) {
        Debug.Log(args.itemUser + " take damage from " + args.itemUsed);
    }
}

public class DrunkFromITem : WhatInterface {
    public void Execute(ItemUsageArgs args) {
        args.itemUser.GetDrunk();
    }
}

public class BaseArgs {}

public class ItemUsageArgs : BaseArgs {
   public Player itemUser;
   public Item itemUsed;
}
```

<p>so how to create interface type code that is suited for itemUsages?</p>

<p>Or do I wrongly create the design for this context?</p>

<p>Basically I'm trying strategy pattern so that item usages could be vary for every kind of item.</p>

<p>Things I tried, creating IItemUsage interface:</p>

```public interface IItemUsage {
    void Execute(ItemUsageArgs args);
    // but then anything that needs to implement this interface must use this method, even though it only needs BaseArgs.
    // TestConsole class must conform to Execute(ItemUsageArgs) signature..
}

public class TestConsole : IItemUsage {
    public void Execute(BaseArgs args) {
        Debug.Log("function call executed");
    }
    // this won't compile
}
```

答:
Assuming this is all of your code, you can make IItemUsage generic, and contravairant on the generic parameter.

```<code>public interface IItemUsage<in T> where T: BaseArgs {
    void Execute(T args);
}
</code>```

Have TestConsole implement IItemUsage<BaseArgs> and the other two classes implement IItemUsage<ItemUsageArgs>.

Now you can put instances of all three classes into an IItemUsage<ItemUsageArgs>[]:

```<code>IItemUsage<ItemUsageArgs>[] arr = new IItemUsage<ItemUsageArgs>[] {
    new TestConsole(), new DamageFromItem(), new DrunkFromITem()
};
</code>```

Body:
consider the following game code:

public class Player : MonoBehaviour {
    public void UseItem(Item item) {
        item.Use(this);
    }
    public void GetDrunk() {}
}

public class Item {
    public WhatInterface[] itemUsages;

    public void Use(Player player) {
        foreach(var usage in itemUsages) {
            usage.Execute(new ItemUsageArgs {itemUser = player, itemUsed = this})
        }
    }
}

public class GameManager : MonoBehaviour {

    public Player mainCharacter;
    public Item beer = new Item {itemUsages = new [] {
        new TestConsole(),
        new DamageFromItem (),
        new DrunkFromITem ()
    }}

    private void Start() {
        mainCharacter.Use(beer);
    }
}

public class TestConsole : WhatInterface {
    public void Execute(BaseArgs args) {
        Debug.Log("function call executed");
    }
}

public class DamageFromItem : WhatInterface {
    public void Execute(ItemUsageArgs args) {
        Debug.Log(args.itemUser + " take damage from " + args.itemUsed);
    }
}

public class DrunkFromITem : WhatInterface {
    public void Execute(ItemUsageArgs args) {
        args.itemUser.GetDrunk();
    }
}

public class BaseArgs {}

public class ItemUsageArgs : BaseArgs {
   public Player itemUser;
   public Item itemUsed;
}

so how to create interface type code that is suited for itemUsages?

Or do I wrongly create the design for this context?

Basically I'm trying strategy pattern so that item usages could be vary for every kind of item.

Things I tried, creating IItemUsage interface:

public interface IItemUsage {
    void Execute(ItemUsageArgs args);
    // but then anything that needs to implement this interface must use this method, even though it only needs BaseArgs.
    // TestConsole class must conform to Execute(ItemUsageArgs) signature..
}

public class TestConsole : IItemUsage {
    public void Execute(BaseArgs args) {
        Debug.Log("function call executed");
    }
    // this won't compile
}

Body:
Assuming this is all of your code, you can make IItemUsage generic, and contravairant on the generic parameter.

public interface IItemUsage<in T> where T: BaseArgs {
    void Execute(T args);
}

Have TestConsole implement IItemUsage<BaseArgs> and the other two classes implement IItemUsage<ItemUsageArgs>.

Now you can put instances of all three classes into an IItemUsage<ItemUsageArgs>[]:

IItemUsage<ItemUsageArgs>[] arr = new IItemUsage<ItemUsageArgs>[] {
    new TestConsole(), new DamageFromItem(), new DrunkFromITem()
};


问:
Date of birth restriction
I want to restrict my date picker dialog to select a minimum of 18 years of age</p>

```<code>    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)

    val abc = findViewById<Button>(R.id.birth)

    abc.setOnClickListener {
        DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, mMonth, mDay ->
            date.setText("" + mDay +"/" + mMonth +"/" + mYear)
        }, year, month, day).show()
   }
}
</code>```

答:
You can try it this way</p>

```<code>val calendarMaxDate = Calendar.getInstance()
calendarMaxDate.add(Calendar.YEAR, -18)

val datePickerDialog = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, mMonth, mDay ->
                        date.setText("" + mDay +"/" + mMonth +"/" + mYear)
                    }, year, month, day)
    datePickerDialog.datePicker.maxDate = calendarMaxDate.timeInMillis
    datePickerDialog.show()
</code>```

Title: Date of birth restriction

Body:
I want to restrict my date picker dialog to select a minimum of 18 years of age

    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)

    val abc = findViewById<Button>(R.id.birth)

    abc.setOnClickListener {
        DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, mMonth, mDay ->
            date.setText("" + mDay +"/" + mMonth +"/" + mYear)
        }, year, month, day).show()
   }
}

Body:
You can try it this way

val calendarMaxDate = Calendar.getInstance()
calendarMaxDate.add(Calendar.YEAR, -18)

val datePickerDialog = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, mMonth, mDay ->
                        date.setText("" + mDay +"/" + mMonth +"/" + mYear)
                    }, year, month, day)
    datePickerDialog.datePicker.maxDate = calendarMaxDate.timeInMillis
    datePickerDialog.show()


问:
How to combine and get data from multiple tables for a single id
table A :

```<code>................
id   name  age |
................
1    G     29  |
2    A     30  |
................
</code>```

table B : (table b have the foreign key of table A in tableA_id field which comes multiple)

```<code>id   phone     rank   tableA_id
1    98989     A      1
2    98989     C      1
3    98989     D      2
</code>```

table C : (table C have the foreign key of table A in tableA_id field which comes multiple)

```<code>id   notes     email            tableA_id
1    98989     A@gmail.com      1
2    98989     C@gmail.com      1
</code>```

In my case i am want to get all the data from all the tables and want to display in a single page . the what i want is i want one single query to get the all data from all of
    three table with one query set.
    And id what i am sending is Table_id = 1
    so how can i get the data for table 1 from all the tables can anyone have idea please  let me now i am a new be here

答:
Well, probably you can't do it in single query. But using prefetch_related you can load all the related tables, so that DB hits will be reduced. For example:

```<code># if the models are defined like this:

class TableA(models.Model):
    name = models.CharField(...)
    age = models.IntegerField(...)

class TableB(models.Model):
    table_a = models.ForeignKey(TableA)

class TableC(models.Model):
    table_a = models.ForeignKey(TableA)

# then the query will be like this

table_data = TableA.objects.filter(pk=1).prefetch_related('tableb', 'tablec')
for data in table_data:
    print(data.name)
    print(data.tableb.all().values())
    print(data.tablec.all().values())
</code>```

Body:
table A :

................
id   name  age |
................
1    G     29  |
2    A     30  |
................

table B : (table b have the foreign key of table A in tableA_id field which comes multiple)

id   phone     rank   tableA_id
1    98989     A      1
2    98989     C      1
3    98989     D      2

table C : (table C have the foreign key of table A in tableA_id field which comes multiple)

id   notes     email            tableA_id
1    98989     A@gmail.com      1
2    98989     C@gmail.com      1

In my case i am want to get all the data from all the tables and want to display in a single page . the what i want is i want one single query to get the all data from all of
    three table with one query set.
    And id what i am sending is Table_id = 1
    so how can i get the data for table 1 from all the tables can anyone have idea please  let me now i am a new be here

Body:
Well, probably you can't do it in single query. But using prefetch_related you can load all the related tables, so that DB hits will be reduced. For example:

# if the models are defined like this:

class TableA(models.Model):
    name = models.CharField(...)
    age = models.IntegerField(...)

class TableB(models.Model):
    table_a = models.ForeignKey(TableA)

class TableC(models.Model):
    table_a = models.ForeignKey(TableA)

# then the query will be like this

table_data = TableA.objects.filter(pk=1).prefetch_related('tableb', 'tablec')
for data in table_data:
    print(data.name)
    print(data.tableb.all().values())
    print(data.tablec.all().values())


问:
Python - Count Numbers of Different Digits in String
I'm very new to Python, please help.

I can only use if else statements, no loops or anything special like that.

This program asks the user for one string.
It counts the number of different digits in the string.  for
example a11111a1a1 contains a single digit, while a1s2d1d2d1d2d1
contains 2 digits.

Examples:

```<code>% python3 countNumbers.py
enter string: qwerty
there are no digits in string: "qwerty"

% python3 countNumbers.py
enter string: asdf1sdfg
there is one digit in string: "asdf1sdfg"

% python3 countNumbers.py
enter string: as1as2as333333
there are 3 different digits in string: "as1as2as333333"

% python3 countNumbers.py
enter string: a0123456789x
there are 10 different digits in string: "a0123456789x"
</code>```

```<code>num = input("enter string: ")
count = 0

if "0" in num:
    count = count + 1
if "1" in num:
    count = count + 1
if "2" in num:
    count = count + 1
if "3" in num:
    count = count + 1
if "4" in num:
    count = count + 1
if "5" in num:
    count = count + 1
if "6" in num:
    count = count + 1
if "7" in num:
    count = count + 1
if "8" in num:
    count = count + 1
if "9" in num:
    count = count + 1

if count >= 1:
    print("there is one digit in string: ", num)
elif count >= 2:
    print("there are two digits in string: ", num)
else:
    print("there are no digits in string: ", num)

</code>```

答:
This is using regex, so import the regex library:

```<code>import re
</code>```

Use the following Python to find individual digits:

```<code>a = re.findall('\d', string)
</code>```

If you want more than one digit together use:

```<code>a = re.findall('\d+', string)
</code>```

Then use the following to count (len) the set (which makes it unique):

```<code>len(set(a))
</code>```

Body:
I'm very new to Python, please help.

I can only use if else statements, no loops or anything special like that.

This program asks the user for one string.
It counts the number of different digits in the string.  for
example a11111a1a1 contains a single digit, while a1s2d1d2d1d2d1
contains 2 digits.

Examples:

% python3 countNumbers.py
enter string: qwerty
there are no digits in string: "qwerty"

% python3 countNumbers.py
enter string: asdf1sdfg
there is one digit in string: "asdf1sdfg"

% python3 countNumbers.py
enter string: as1as2as333333
there are 3 different digits in string: "as1as2as333333"

% python3 countNumbers.py
enter string: a0123456789x
there are 10 different digits in string: "a0123456789x"

num = input("enter string: ")
count = 0

if "0" in num:
    count = count + 1
if "1" in num:
    count = count + 1
if "2" in num:
    count = count + 1
if "3" in num:
    count = count + 1
if "4" in num:
    count = count + 1
if "5" in num:
    count = count + 1
if "6" in num:
    count = count + 1
if "7" in num:
    count = count + 1
if "8" in num:
    count = count + 1
if "9" in num:
    count = count + 1

if count >= 1:
    print("there is one digit in string: ", num)
elif count >= 2:
    print("there are two digits in string: ", num)
else:
    print("there are no digits in string: ", num)

Body:
This is using regex, so import the regex library:

import re

Use the following Python to find individual digits:

a = re.findall('\d', string)

If you want more than one digit together use:

a = re.findall('\d+', string)

Then use the following to count (len) the set (which makes it unique):

len(set(a))


问:
Error in calculating weighted means: 'x' and 'w' must have the same length
Im trying to calculate weighted confidence intervals and need to use the a weighted mean to do so. But I keep running into the same failure that I cant figure out how to solve. The data is based on the European Social Survey and I have loaded the following libraries:

```<code>library(tidyverse)
library(haven)
library(essurvey)
library(radiant.data)
</code>```

The following code should output, among others, confidence intervals:

```<code>ESS %>% # Use the ESS, then
  transmute( # Create new variables and only keep these new ones
    # Make the following variables factors:
    cntry = as_factor(cntry),
    # Make the following variables numeric:
    pspwght = zap_labels(pspwght),
    hmsacld = max(zap_labels(hmsacld), na.rm = TRUE) - zap_labels(hmsacld), #Turning scale around
  ) %>%
  group_by(cntry) %>% # Group data by country, then
  summarize(
    n = sum(pspwght, na.rm = TRUE),
    mean_hmsacld = weighted.mean(hmsacld, pspwght, na.rm = TRUE),
    sd_hmsacld = weighted.sd(hmsacld, pspwght),
    se_hmsacld = sd_hmsacld / sqrt(n),
    min95 = mean_hmsacld - se_hmsacld * qt(p = 0.975, df = n),
    max95 = mean_hmsacld + se_hmsacld * qt(p = 0.975, df = n)
  )
</code>```

Instead, I get the following error:

```<code>Error in weighted.mean.default(x, wt) :
  'x' and 'w' must have the same length
</code>```

Any idea how to fix this?

Thanks

答:
You have NA in hmsacld column, which causes the error you observe.
If you want weighted.mean, you need to provide weights for each pspwght. A simple experiment -let's drop all rows with NA inside ESS:

```<code>library(tidyverse)
library(haven)
library(essurvey)
library(radiant.data)

ESS <- structure(list(cntry = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("AT",
"BE", "CH", "CZ", "DE", "EE", "ES", "FI", "FR", "GB", "HU", "IE",
"IL", "IS", "IT", "LT", "NL", "NO", "PL", "PT", "RU", "SE", "SI"
), class = "factor"), pspwght = c(1.17849552631378, 0.899471521377563,
0.31575334072113, 0.472467392683029, 2.24670553207397, 1.01137900352478,
1.83802974224091, 1.20280182361603, 0.320830971002579, 0.99757444858551,
0.550059616565704, 0.691191911697388, 0.411176264286041, 0.673080623149872,
1.28033947944641, 0.647780179977417, 2.93387079238892, 0.374067783355713,
0.696788847446442, 0.699867308139801), hmsacld = c(4, 4, 2, 3,
4, 1, NA, 2, 2, 1, 4, 2, 3, 3, 0, 4, 3, 1, 3, 4)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -20L))

ESS %>% # Use the ESS, then
  transmute( # Create new variables and only keep these new ones
    # Make the following variables factors:
    cntry = as_factor(cntry),
    # Make the following variables numeric:
    pspwght = zap_labels(pspwght),
    hmsacld = max(zap_labels(hmsacld), na.rm = TRUE) - zap_labels(hmsacld), #Turning scale around
  ) %>%
  drop_na() %>%
  group_by(cntry) %>% # Group data by country, then
  summarize(
    n = sum(pspwght, na.rm = TRUE),
    mean_hmsacld = weighted.mean(hmsacld, pspwght, na.rm = TRUE),
    sd_hmsacld = weighted.sd(hmsacld, pspwght),
    se_hmsacld = sd_hmsacld / sqrt(n),
    min95 = mean_hmsacld - se_hmsacld * qt(p = 0.975, df = n),
    max95 = mean_hmsacld + se_hmsacld * qt(p = 0.975, df = n)
  )
</code>```

Regards
Paweł

Body:
Im trying to calculate weighted confidence intervals and need to use the a weighted mean to do so. But I keep running into the same failure that I cant figure out how to solve. The data is based on the European Social Survey and I have loaded the following libraries:

library(tidyverse)
library(haven)
library(essurvey)
library(radiant.data)

The following code should output, among others, confidence intervals:

ESS %>% # Use the ESS, then
  transmute( # Create new variables and only keep these new ones
    # Make the following variables factors:
    cntry = as_factor(cntry),
    # Make the following variables numeric:
    pspwght = zap_labels(pspwght),
    hmsacld = max(zap_labels(hmsacld), na.rm = TRUE) - zap_labels(hmsacld), #Turning scale around
  ) %>%
  group_by(cntry) %>% # Group data by country, then
  summarize(
    n = sum(pspwght, na.rm = TRUE),
    mean_hmsacld = weighted.mean(hmsacld, pspwght, na.rm = TRUE),
    sd_hmsacld = weighted.sd(hmsacld, pspwght),
    se_hmsacld = sd_hmsacld / sqrt(n),
    min95 = mean_hmsacld - se_hmsacld * qt(p = 0.975, df = n),
    max95 = mean_hmsacld + se_hmsacld * qt(p = 0.975, df = n)
  )

Instead, I get the following error:

Error in weighted.mean.default(x, wt) :
  'x' and 'w' must have the same length

Any idea how to fix this?

Thanks

Body:
You have NA in hmsacld column, which causes the error you observe.
If you want weighted.mean, you need to provide weights for each pspwght. A simple experiment -let's drop all rows with NA inside ESS:

library(tidyverse)
library(haven)
library(essurvey)
library(radiant.data)

ESS <- structure(list(cntry = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("AT",
"BE", "CH", "CZ", "DE", "EE", "ES", "FI", "FR", "GB", "HU", "IE",
"IL", "IS", "IT", "LT", "NL", "NO", "PL", "PT", "RU", "SE", "SI"
), class = "factor"), pspwght = c(1.17849552631378, 0.899471521377563,
0.31575334072113, 0.472467392683029, 2.24670553207397, 1.01137900352478,
1.83802974224091, 1.20280182361603, 0.320830971002579, 0.99757444858551,
0.550059616565704, 0.691191911697388, 0.411176264286041, 0.673080623149872,
1.28033947944641, 0.647780179977417, 2.93387079238892, 0.374067783355713,
0.696788847446442, 0.699867308139801), hmsacld = c(4, 4, 2, 3,
4, 1, NA, 2, 2, 1, 4, 2, 3, 3, 0, 4, 3, 1, 3, 4)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -20L))

ESS %>% # Use the ESS, then
  transmute( # Create new variables and only keep these new ones
    # Make the following variables factors:
    cntry = as_factor(cntry),
    # Make the following variables numeric:
    pspwght = zap_labels(pspwght),
    hmsacld = max(zap_labels(hmsacld), na.rm = TRUE) - zap_labels(hmsacld), #Turning scale around
  ) %>%
  drop_na() %>%
  group_by(cntry) %>% # Group data by country, then
  summarize(
    n = sum(pspwght, na.rm = TRUE),
    mean_hmsacld = weighted.mean(hmsacld, pspwght, na.rm = TRUE),
    sd_hmsacld = weighted.sd(hmsacld, pspwght),
    se_hmsacld = sd_hmsacld / sqrt(n),
    min95 = mean_hmsacld - se_hmsacld * qt(p = 0.975, df = n),
    max95 = mean_hmsacld + se_hmsacld * qt(p = 0.975, df = n)
  )

Regards
Paweł


问:
Can I use part of a Shell Object parsing name in the windows portable device (WPD) api to get a file stream?
Is it always valid to use the first part of the last guid from a windows api codepack ShellObject parsing name representing a path to a USB-connected android or iphone device when transferring a file to local storage in the windows portable device (WPD) api?

Eg. an example parsing name from a ShellObject get parsing name call:

```<code>::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\?\usb#vid_22b8&pid_2e82#zy322kldjb#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\{00000009-0001-0001-0000-000000000000}\{00000009-0001-0001-0000-000000000000}\{00005461-0001-0001-0000-000000000000}
</code>```

As far as I can tell, this represents:

```<code>- My Computer    ::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\
- USB device     \\?\usb#vid_22b8&pid_2e82#zy322kldjb#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\
- Root folder    SID-{10001,,26401026048}\
- Folder 1       {00000009-0001-0001-0000-000000000000}\
- Folder 2       {00000075-0001-0001-0000-000000000000}\
- File           {00005461-0001-0001-0000-000000000000}
</code>```

Enumerating the contents of Folder 2 on the device using the WPD api, I can see the same file has a file id like o5461 - this looks like part of the File part above.

Is this assumption always correct - can I always use it like in the following code, to copy one file from an android phone to local storage on the c-drive? Or is there sometimes a mismatch? Also, what does the "o" mean in the file id?

This seems to work, but I'm hesitant to use it in production-ready code.

```<code>using System.IO;
using PortableDeviceApiLib;

public class Copier
{
  public void PerformCopy()
  {
    var deviceId = @"\\?\usb#vid_22b8&pid_2e82#zy322kldjb#{6ac27878-a6fa-4155-ba85-f98f491d4f33}";
    var sourceItemGuidString = "{00005461-0001-0001-0000-000000000000}";
    var destinationPath = @"C:\Test\";
    var fileName = "Testing.jpg";
    var size = 3738545;

    // get "o5461" from the parsing path from the Shell libraries
    var fileId = "o" + sourceItemGuidString.Replace("{", string.Empty).Replace("}", string.Empty).Split('-')[0].TrimStart('0');

    this.TransferContentFromDevice(deviceId, fileId, size, destinationPath, fileName);
  }

  private void TransferContentFromDevice(string deviceId, string fileId, long length, string saveToPath, string fileName)
  {
    PortableDeviceClass device;

    try
    {
      device = SomehowGetOnePortableDeviceAndConnectToIt(deviceId);

      // Make sure that the target dir exists.
      Directory.CreateDirectory(saveToPath);

      device.Content(out var content);
      content.Transfer(out var resources);

      var property = new _tagpropertykey
      {
        fmtid = new Guid(0xE81E79BE, 0x34F0, 0x41BF, 0xB5, 0x3F, 0xF1, 0xA0, 0x6A, 0xE8, 0x78, 0x42),
        pid = 0
      };

      uint optimalTransferSize = 0;
      resources.GetStream(fileId, ref property, 0, ref optimalTransferSize, out IStream wpdStream);

      var sourceStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;
      using (var targetStream = new FileStream(Path.Combine(saveToPath, fileName), FileMode.Create, FileAccess.Write))
      {
        // Get the total size.
        long written = 0;
        long lPCt = 0;
        unsafe
        {
          var buffer = new byte[1024];
          int bytesRead;
          do
          {
            sourceStream.Read(buffer, 1024, new IntPtr(&bytesRead));
            targetStream.Write(buffer, 0, bytesRead);

            written += 1024;
            long PCt = length > 0 ? (100 * written) / length : 100;
            if (PCt != lPCt)
            {
              lPCt = PCt;
              Console.WriteLine("Progress: " + lPCt);
            }
          } while (bytesRead > 0);
        }
      }
    }
    finally
    {
      Disconnect(device);
    }
  }
}
</code>```

答:
If item has a parsing name like below, I was after the 5461 part from the final guid:

```<code>::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\?\usb#vid_22b8&pid_2e82#zy322kldjb#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\SID-{10001,,26401026048}\{00000009-0001-0001-0000-000000000000}\{00000075-0001-0001-0000-000000000000}\{00005461-0001-0001-0000-000000000000}
</code>```

We can use the following code which will get the WPD_OBJECT_ID property from a ShellObject. More info on this and related properties here:

```<code>string GetFileId(ShellObject item)
{
  const int WPD_OBJECT_ID = 2;
  var property = item.Properties.GetProperty(new PropertyKey(new Guid("{ef6b490d-5cd8-437a-affc-da8b60ee4a3c}"), WPD_OBJECT_ID));
  return property.ValueAsObject as string;
}
</code>```

This returns the file id o5641, which can then be used in my TransferContentFromDevice method directly.

Thanks to @SimonMourier for pointing me in the right direction.

Body:
Is it always valid to use the first part of the last guid from a windows api codepack ShellObject parsing name representing a path to a USB-connected android or iphone device when transferring a file to local storage in the windows portable device (WPD) api?

Eg. an example parsing name from a ShellObject get parsing name call:

::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\?\usb#vid_22b8&pid_2e82#zy322kldjb#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\{00000009-0001-0001-0000-000000000000}\{00000009-0001-0001-0000-000000000000}\{00005461-0001-0001-0000-000000000000}

As far as I can tell, this represents:

- My Computer    ::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\
- USB device     \\?\usb#vid_22b8&pid_2e82#zy322kldjb#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\
- Root folder    SID-{10001,,26401026048}\
- Folder 1       {00000009-0001-0001-0000-000000000000}\
- Folder 2       {00000075-0001-0001-0000-000000000000}\
- File           {00005461-0001-0001-0000-000000000000}

Enumerating the contents of Folder 2 on the device using the WPD api, I can see the same file has a file id like o5461 - this looks like part of the File part above.

Is this assumption always correct - can I always use it like in the following code, to copy one file from an android phone to local storage on the c-drive? Or is there sometimes a mismatch? Also, what does the "o" mean in the file id?

This seems to work, but I'm hesitant to use it in production-ready code.

using System.IO;
using PortableDeviceApiLib;

public class Copier
{
  public void PerformCopy()
  {
    var deviceId = @"\\?\usb#vid_22b8&pid_2e82#zy322kldjb#{6ac27878-a6fa-4155-ba85-f98f491d4f33}";
    var sourceItemGuidString = "{00005461-0001-0001-0000-000000000000}";
    var destinationPath = @"C:\Test\";
    var fileName = "Testing.jpg";
    var size = 3738545;

    // get "o5461" from the parsing path from the Shell libraries
    var fileId = "o" + sourceItemGuidString.Replace("{", string.Empty).Replace("}", string.Empty).Split('-')[0].TrimStart('0');

    this.TransferContentFromDevice(deviceId, fileId, size, destinationPath, fileName);
  }

  private void TransferContentFromDevice(string deviceId, string fileId, long length, string saveToPath, string fileName)
  {
    PortableDeviceClass device;

    try
    {
      device = SomehowGetOnePortableDeviceAndConnectToIt(deviceId);

      // Make sure that the target dir exists.
      Directory.CreateDirectory(saveToPath);

      device.Content(out var content);
      content.Transfer(out var resources);

      var property = new _tagpropertykey
      {
        fmtid = new Guid(0xE81E79BE, 0x34F0, 0x41BF, 0xB5, 0x3F, 0xF1, 0xA0, 0x6A, 0xE8, 0x78, 0x42),
        pid = 0
      };

      uint optimalTransferSize = 0;
      resources.GetStream(fileId, ref property, 0, ref optimalTransferSize, out IStream wpdStream);

      var sourceStream = (System.Runtime.InteropServices.ComTypes.IStream)wpdStream;
      using (var targetStream = new FileStream(Path.Combine(saveToPath, fileName), FileMode.Create, FileAccess.Write))
      {
        // Get the total size.
        long written = 0;
        long lPCt = 0;
        unsafe
        {
          var buffer = new byte[1024];
          int bytesRead;
          do
          {
            sourceStream.Read(buffer, 1024, new IntPtr(&bytesRead));
            targetStream.Write(buffer, 0, bytesRead);

            written += 1024;
            long PCt = length > 0 ? (100 * written) / length : 100;
            if (PCt != lPCt)
            {
              lPCt = PCt;
              Console.WriteLine("Progress: " + lPCt);
            }
          } while (bytesRead > 0);
        }
      }
    }
    finally
    {
      Disconnect(device);
    }
  }
}

Body:
If item has a parsing name like below, I was after the 5461 part from the final guid:

::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\?\usb#vid_22b8&pid_2e82#zy322kldjb#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\SID-{10001,,26401026048}\{00000009-0001-0001-0000-000000000000}\{00000075-0001-0001-0000-000000000000}\{00005461-0001-0001-0000-000000000000}

We can use the following code which will get the WPD_OBJECT_ID property from a ShellObject. More info on this and related properties here:

string GetFileId(ShellObject item)
{
  const int WPD_OBJECT_ID = 2;
  var property = item.Properties.GetProperty(new PropertyKey(new Guid("{ef6b490d-5cd8-437a-affc-da8b60ee4a3c}"), WPD_OBJECT_ID));
  return property.ValueAsObject as string;
}

This returns the file id o5641, which can then be used in my TransferContentFromDevice method directly.

Thanks to @SimonMourier for pointing me in the right direction.


问:
Logging GPS locations to file in Android
I have an Android application that periodically gets GPS updates. If I wanted to store the lat, lon, speed, altitude etc. in a file, what is the best practice for doing this?</p>

答: I'd suggest you use a database - they were made for tasks like this. Here is an Android database tutorial: http://www.vogella.de/articles/AndroidSQLite/article.html</p>


答:
You can do it this way:

len(set(a).intersection(map(str, range(10))))
```

Title: Python - Count Numbers of Different Digits in String


问:
Finding the "fairest" meeting point in an undirected weighted graph
Given an undirected weighted graph, a start node and an end node, is there a way to (without using brute force) find a meeting point in between the start and end nodes such that:

the difference between 1) the distance from start to meeting point and 2) the distance from end to meeting point

is minimized?

I cant seem to think of any way to do this without using brute force.

Thank you

答: Just launch Dijkstra's algorithm to find distances to all nodes from the start node, then from the end node. Then find a node for which a difference between calculated distances is minimized.</p>


问:
Logger configuration in Alfresco
Is there  a specific onfiguration for logger to print log.info() message  ?   I have action classes extended quatz class as shown below .  but the log is not printing out in log file - alfresco.log . I can see system.out.println in tomcat log .

please let me know if there are any configuration changes reuired in log4j.properties  ? I have kept all the config default didnt make any changes in log4j

following is screen shot of  java class

答:
first, please follow the rules how to ask in SO - otherwise your questions may be closed unresponded. Make sure you spent a minimum in research and learning from available how to's and explain what you found and tried so far. Don't expect busy people do your job ...

Alfresco's documentation is well indexed by Goolge: log4j.properties file

You need to overwriter the root loogging config
log4j.rootLogger=error
by enable the required log level for your package / class by
log4j.com.mycompany.mypackage.myclass=info

Title: Logger configuration in Alfresco


问:
How can I append div on click?
Lets say I have this div

```<code>        <div class="row deliver-to forms">
            <div class="col-4">
                <label>Region</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">
            </div>
            <div class="col-4">
                <label>District</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">
            </div>
            <div class="col-4">
                <label>Town</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">
            </div>
        </div>
</code>```

and this button

```<code><button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button" id="add_place">
    <i class="fa fa-plus"></i>
</button>
</code>```

How can I actually append this entire div after itself by clicking on this button?

Entire structure of my code looks like:

```<code>        <div class="row deliver-to forms">
            <div class="col-4">
                <label>Region</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">
            </div>
            <div class="col-4">
                <label>District</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">
            </div>
            <div class="col-4">
                <label>Town</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">
            </div>
        </div>
        <button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button"
                id="add_place">
            <i class="fa fa-plus"></i>
        </button>
</code>```

答:
$("button").click(function(){
        $(".next").append("
\n" +
            "
\n" +
            "                Region\n" +
            "                <input class=\"w-50 mt-2 form-control\" type=\"text\" data-id=\"region-to\" id=\"region-to\">\n" +
            "
\n" +
            "
\n" +
            "                District\n" +
            "                <input class=\"w-50 mt-2 form-control\" type=\"text\" data-id=\"district-to\" id=\"district-to\">\n" +
            "
\n" +
            "
\n" +
            "                Town\n" +
            "                <input class=\"w-50 mt-2 form-control\" type=\"text\" data-id=\"town-to\" id=\"town-to\">\n" +
            "
\n" +
            "
")});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row deliver-to forms">
            <div class="col-4">
                <label>Region</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">
            </div>
            <div class="col-4">
                <label>District</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">
            </div>
            <div class="col-4">
                <label>Town</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">
            </div>
        </div>
        <button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button"
                id="add_place">
            <i class="fa fa-plus">click</i>
        </button>
        <div class="next"></div></code>```

Title: How can I append div on click?

Body:
Lets say I have this div

                Region
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">

                District
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">

                Town
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">

and this button

<button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button" id="add_place">

</button>

How can I actually append this entire div after itself by clicking on this button?

Entire structure of my code looks like:

                Region
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">

                District
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">

                Town
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">

        <button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button"
                id="add_place">

        </button>

Body:
$("button").click(function(){
        $(".next").append("<div class=\"row deliver-to forms\">\n" +
            "            <div class=\"col-4\">\n" +
            "                <label>Region</label>\n" +
            "                <input class=\"w-50 mt-2 form-control\" type=\"text\" data-id=\"region-to\" id=\"region-to\">\n" +
            "            </div>\n" +
            "            <div class=\"col-4\">\n" +
            "                <label>District</label>\n" +
            "                <input class=\"w-50 mt-2 form-control\" type=\"text\" data-id=\"district-to\" id=\"district-to\">\n" +
            "            </div>\n" +
            "            <div class=\"col-4\">\n" +
            "                <label>Town</label>\n" +
            "                <input class=\"w-50 mt-2 form-control\" type=\"text\" data-id=\"town-to\" id=\"town-to\">\n" +
            "            </div>\n" +
            "        </div>")});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row deliver-to forms">
            <div class="col-4">
                <label>Region</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="region-to" id="region-to">
            </div>
            <div class="col-4">
                <label>District</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="district-to" id="district-to">
            </div>
            <div class="col-4">
                <label>Town</label>
                <input class="w-50 mt-2 form-control" type="text" data-id="town-to" id="town-to">
            </div>
        </div>
        <button class="btn btn-primary btn-flat mt-3 offset-10 add_place" type="button"
                id="add_place">
            <i class="fa fa-plus">click</i>
        </button>
        <div class="next"></div>