问:
JSONObject().put using a List Throws recursivelyDefinedObjectException
I have a query that generates a List of Tickets using hibernate like so :

```<code>Query query = session.createQuery(
        "SELECT T.id, T.Objet, T.Details, T.Etat,T.Severity, T.createDateTime, T.user, T.Attachment, U.lastName, L.nomLogiciel, V.nomVersion,T.AssignedTo,T.ClosedBy,T.closedDateTime,T.assignedDateTime, U.firstName, U.username, U.Email, U.Phone  FROM Ticket T, User U, Logiciel L, Version V "
        + "WHERE T.user= :user and T.user=U.user_id AND L.logiciel_id=T.Logiciel AND T.Version=V.version_id AND T.Etat!='fermer' ORDER BY T.createDateTime ")
        .setParameter("user", user);
</code>```

I tried to put the list in a JSONObject :

```<code>    List allTickets = ticketDao.getTicketsByUserDao(user);
    JSONObject jo = new JSONObject();
    jo.put("ticket", allTickets);
</code>```

It throws this exception :

```<code>Hibernate: select ticket0_.ticket_id as col_0_0_, ticket0_.objet as col_1_0_, ticket0_.details as col_2_0_, ticket0_.etat as col_3_0_, ticket0_.severity as col_4_0_, ticket0_.createDateTime as col_5_0_, ticket0_.user_id as col_6_0_, ticket0_.attachment_path as col_7_0_, user1_.last_name as col_8_0_, logiciel2_.nom_logiciel as col_9_0_, version3_.nom_version as col_10_0_, ticket0_.assigned_to as col_11_0_, ticket0_.closed_by as col_12_0_, ticket0_.closedDateTime as col_13_0_, ticket0_.assignedDateTime as col_14_0_, user1_.first_name as col_15_0_, user1_.username as col_16_0_, user1_.email as col_17_0_, user1_.phone as col_18_0_, user4_.user_id as user_id1_9_, user4_.email as email2_9_, user4_.etat as etat3_9_, user4_.phone as phone4_9_, user4_.currentAccessDate as currenta5_9_, user4_.dateExpiration as dateexpi6_9_, user4_.first_name as first_na7_9_, user4_.lastAccessDate as lastacce8_9_, user4_.last_name as last_nam9_9_, user4_.password as passwor10_9_, user4_.structure_id as structu12_9_, user4_.username as usernam11_9_ from tickets ticket0_ cross join users user1_ cross join logiciel logiciel2_ cross join version version3_ inner join users user4_ on ticket0_.user_id=user4_.user_id where ticket0_.user_id=? and ticket0_.user_id=user1_.user_id and logiciel2_.logiciel_id=ticket0_.logiciel_id and ticket0_.version_id=version3_.version_id and ticket0_.etat<>'fermer' order by ticket0_.createDateTime
Hibernate: select tickets0_.user_id as user_id14_8_2_, tickets0_.ticket_id as ticket_i1_8_2_, tickets0_.ticket_id as ticket_i1_8_1_, tickets0_.assigned_to as assigned2_8_1_, tickets0_.attachment_path as attachme3_8_1_, tickets0_.closed_by as closed_b4_8_1_, tickets0_.details as details5_8_1_, tickets0_.etat as etat6_8_1_, tickets0_.logiciel_id as logiciel7_8_1_, tickets0_.objet as objet8_8_1_, tickets0_.severity as severity9_8_1_, tickets0_.version_id as version10_8_1_, tickets0_.assignedDateTime as assigne11_8_1_, tickets0_.closedDateTime as closedd12_8_1_, tickets0_.createDateTime as created13_8_1_, tickets0_.user_id as user_id14_8_1_, planificat1_.planif_id as planif_i1_4_0_, planificat1_.observation as observat2_4_0_, planificat1_.date_debut_planif as date_deb3_4_0_, planificat1_.date_debut_realise as date_deb4_4_0_, planificat1_.date_fin_planif as date_fin5_4_0_, planificat1_.date_fin_realise as date_fin6_4_0_, planificat1_.ticket_id as ticket_i7_4_0_ from tickets tickets0_ left outer join planification planificat1_ on tickets0_.ticket_id=planificat1_.ticket_id where tickets0_.user_id in (select user4_.user_id from tickets ticket0_ cross join users user1_ cross join logiciel logiciel2_ cross join version version3_ inner join users user4_ on ticket0_.user_id=user4_.user_id where ticket0_.user_id=? and ticket0_.user_id=user1_.user_id and logiciel2_.logiciel_id=ticket0_.logiciel_id and ticket0_.version_id=version3_.version_id and ticket0_.etat<>'fermer' )
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select responses0_.user_id as user_id5_5_4_, responses0_.response_id as response1_5_4_, responses0_.response_id as response1_5_3_, responses0_.response as response2_5_3_, responses0_.createDateTime as createda3_5_3_, responses0_.ticket_id as ticket_i4_5_3_, responses0_.user_id as user_id5_5_3_, ticket1_.ticket_id as ticket_i1_8_0_, ticket1_.assigned_to as assigned2_8_0_, ticket1_.attachment_path as attachme3_8_0_, ticket1_.closed_by as closed_b4_8_0_, ticket1_.details as details5_8_0_, ticket1_.etat as etat6_8_0_, ticket1_.logiciel_id as logiciel7_8_0_, ticket1_.objet as objet8_8_0_, ticket1_.severity as severity9_8_0_, ticket1_.version_id as version10_8_0_, ticket1_.assignedDateTime as assigne11_8_0_, ticket1_.closedDateTime as closedd12_8_0_, ticket1_.createDateTime as created13_8_0_, ticket1_.user_id as user_id14_8_0_, user2_.user_id as user_id1_9_1_, user2_.email as email2_9_1_, user2_.etat as etat3_9_1_, user2_.phone as phone4_9_1_, user2_.currentAccessDate as currenta5_9_1_, user2_.dateExpiration as dateexpi6_9_1_, user2_.first_name as first_na7_9_1_, user2_.lastAccessDate as lastacce8_9_1_, user2_.last_name as last_nam9_9_1_, user2_.password as passwor10_9_1_, user2_.structure_id as structu12_9_1_, user2_.username as usernam11_9_1_, planificat3_.planif_id as planif_i1_4_2_, planificat3_.observation as observat2_4_2_, planificat3_.date_debut_planif as date_deb3_4_2_, planificat3_.date_debut_realise as date_deb4_4_2_, planificat3_.date_fin_planif as date_fin5_4_2_, planificat3_.date_fin_realise as date_fin6_4_2_, planificat3_.ticket_id as ticket_i7_4_2_ from responses responses0_ inner join tickets ticket1_ on responses0_.ticket_id=ticket1_.ticket_id left outer join users user2_ on ticket1_.user_id=user2_.user_id left outer join planification planificat3_ on ticket1_.ticket_id=planificat3_.ticket_id where responses0_.user_id in (select user4_.user_id from tickets ticket0_ cross join users user1_ cross join logiciel logiciel2_ cross join version version3_ inner join users user4_ on ticket0_.user_id=user4_.user_id where ticket0_.user_id=? and ticket0_.user_id=user1_.user_id and logiciel2_.logiciel_id=ticket0_.logiciel_id and ticket0_.version_id=version3_.version_id and ticket0_.etat<>'fermer' )
org.json.JSONException: JavaBean object contains recursively defined member variable of key "planification"
    at org.json.JSONObject.recursivelyDefinedObjectException(JSONObject.java:2722)
    at org.json.JSONObject.populateMap(JSONObject.java:1558)
    at org.json.JSONObject.<init>(JSONObject.java:372)
    at org.json.JSONObject.wrap(JSONObject.java:2496)
    at org.json.JSONObject.populateMap(JSONObject.java:1563)
    at org.json.JSONObject.<init>(JSONObject.java:372)
    at org.json.JSONObject.wrap(JSONObject.java:2496)
    at org.json.JSONObject.populateMap(JSONObject.java:1563)
    at org.json.JSONObject.populateMap(JSONObject.java:1530)
    at org.json.JSONObject.<init>(JSONObject.java:367)
    at org.json.JSONObject.wrap(JSONObject.java:2499)
    at org.json.JSONObject.wrap(JSONObject.java:2457)
    at org.json.JSONArray.addAll(JSONArray.java:1609)
    at org.json.JSONArray.<init>(JSONArray.java:176)
    at org.json.JSONObject.wrap(JSONObject.java:2478)
    at org.json.JSONObject.populateMap(JSONObject.java:1563)
    at org.json.JSONObject.populateMap(JSONObject.java:1530)
    at org.json.JSONObject.<init>(JSONObject.java:367)
    at org.json.JSONObject.wrap(JSONObject.java:2499)
    at org.json.JSONObject.wrap(JSONObject.java:2457)
    at org.json.JSONArray.addAll(JSONArray.java:1661)
    at org.json.JSONArray.<init>(JSONArray.java:228)
    at org.json.JSONObject.wrap(JSONObject.java:2481)
    at org.json.JSONObject.wrap(JSONObject.java:2457)
    at org.json.JSONArray.addAll(JSONArray.java:1609)
    at org.json.JSONArray.<init>(JSONArray.java:176)
    at org.json.JSONObject.put(JSONObject.java:1771)
    at com.myproject.helpdesk.controllers.TicketManagement.getTicketsByUser(TicketManagement.java:610)
    at com.myproject.helpdesk.controllers.TicketManagement.doGet(TicketManagement.java:95)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    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:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.myproject.helpdesk.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:33)
    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:196)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:366)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:847)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1680)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

What is a recursivelyDefinedObjectException ? my Google searches always lead to the subject of Recursion &  Functions, not the exception.

When debugging, the allTickets List contains 4 objects like so :

```<code>[
 [Ljava.lang.Object;@10e63606,
 [Ljava.lang.Object;@3c76d000,
 [Ljava.lang.Object;@5f5bfd07,
 [Ljava.lang.Object;@3a14ab96
]
</code>```

He's the content of one first object for example :

```<code>[1455, test ticket, hello world, créé, Critique, 2022-02-03T15:48:41.058086, com.myproject.helpdesk.models.User@6f643c88, null, CTH, dummy, 10.1.1.v, null, null, 2022-02-03T15:48:41.058086, 2022-02-03T15:48:41.058086, CTH, CTH, email@something.com, 00999999999]
</code>```

Environment :

Eclipse : Version: 2021-06 (4.20.0) Build id: 20210612-2011

Java 8

my JSONOject comes from this dependency

Any help appreciated.

EDIT: Adding Entities

Fetching the Tickets list is what's causing the problem so .

Ticket

```<code>@Entity
@Table(name = "tickets")
public class Ticket implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ticket_id")
    private int ticket_id;

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false, insertable = true)
    private User user;

    @OneToMany(fetch = FetchType.EAGER,mappedBy="ticket")
    private List<Response> response;

     @OneToOne(mappedBy = "ticket")
     private Planification planification;
</code>```

Planification

```<code>@Entity
@Table(name = "planification")
public class Planification implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "planif_id")
    private int planifId;

    @OneToOne
    @JoinColumn(name = "ticket_id",unique = true)
    private Ticket ticket;
</code>```

User

```<code>@Entity
@Table(name = "users")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    private int user_id;

    @OneToMany(fetch = FetchType.EAGER ,mappedBy="user")
    @Fetch(value = FetchMode.SUBSELECT)
    private List<Ticket> tickets;

    @OneToMany(fetch = FetchType.EAGER ,mappedBy="user")
    @Fetch(value = FetchMode.SUBSELECT)
    private List<Response> responses;

    @ManyToOne(fetch = FetchType.EAGER ,cascade = CascadeType.ALL)
    @JoinColumn(name = "structure_id")
    private Structure structure;
</code>```

Response

```<code>@Entity
@Table(name = "responses")
public class Response implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "response_id")
    private int responseId;

    @ManyToOne
    @JoinColumn(name = "ticket_id", nullable = false, insertable = true)
    private Ticket ticket;

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false, insertable = true)
    private User user;
</code>```

Structure

```<code>@Entity
@Table(name = "structure")
public class Structure implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "structure_id")
    private int structure_id;

    @OneToMany(mappedBy = "structure")
    private List<User> user;
</code>```

EDIT 2 :

When debugging I noticed that aStructure of User's Ticket has exception stack trace as content for it's PersistentBag,

What the hell is causing this ?! I checked my Entity definitions and they look alright to me.

Side note

My Ticket object contains the User object, which contains a list of the Users's Tickets, and it goes on and on forever, infinite recursion, is this normal ? are my Entity definitions wrong ? how can i fix this ?

答:
You can go with Map.</p>
```<code>Map<String,Object> mapObject = new HashMap<>();
List allTickets = ticketDao.getTicketsByUserDao(user);
mapObject.put("ticket",allTickets);
</code>```

Body:
I have a query that generates a List of Tickets using hibernate like so :

Query query = session.createQuery(
        "SELECT T.id, T.Objet, T.Details, T.Etat,T.Severity, T.createDateTime, T.user, T.Attachment, U.lastName, L.nomLogiciel, V.nomVersion,T.AssignedTo,T.ClosedBy,T.closedDateTime,T.assignedDateTime, U.firstName, U.username, U.Email, U.Phone  FROM Ticket T, User U, Logiciel L, Version V "
        + "WHERE T.user= :user and T.user=U.user_id AND L.logiciel_id=T.Logiciel AND T.Version=V.version_id AND T.Etat!='fermer' ORDER BY T.createDateTime ")
        .setParameter("user", user);

I tried to put the list in a JSONObject :

    List allTickets = ticketDao.getTicketsByUserDao(user);
    JSONObject jo = new JSONObject();
    jo.put("ticket", allTickets);

It throws this exception :

Hibernate: select ticket0_.ticket_id as col_0_0_, ticket0_.objet as col_1_0_, ticket0_.details as col_2_0_, ticket0_.etat as col_3_0_, ticket0_.severity as col_4_0_, ticket0_.createDateTime as col_5_0_, ticket0_.user_id as col_6_0_, ticket0_.attachment_path as col_7_0_, user1_.last_name as col_8_0_, logiciel2_.nom_logiciel as col_9_0_, version3_.nom_version as col_10_0_, ticket0_.assigned_to as col_11_0_, ticket0_.closed_by as col_12_0_, ticket0_.closedDateTime as col_13_0_, ticket0_.assignedDateTime as col_14_0_, user1_.first_name as col_15_0_, user1_.username as col_16_0_, user1_.email as col_17_0_, user1_.phone as col_18_0_, user4_.user_id as user_id1_9_, user4_.email as email2_9_, user4_.etat as etat3_9_, user4_.phone as phone4_9_, user4_.currentAccessDate as currenta5_9_, user4_.dateExpiration as dateexpi6_9_, user4_.first_name as first_na7_9_, user4_.lastAccessDate as lastacce8_9_, user4_.last_name as last_nam9_9_, user4_.password as passwor10_9_, user4_.structure_id as structu12_9_, user4_.username as usernam11_9_ from tickets ticket0_ cross join users user1_ cross join logiciel logiciel2_ cross join version version3_ inner join users user4_ on ticket0_.user_id=user4_.user_id where ticket0_.user_id=? and ticket0_.user_id=user1_.user_id and logiciel2_.logiciel_id=ticket0_.logiciel_id and ticket0_.version_id=version3_.version_id and ticket0_.etat<>'fermer' order by ticket0_.createDateTime
Hibernate: select tickets0_.user_id as user_id14_8_2_, tickets0_.ticket_id as ticket_i1_8_2_, tickets0_.ticket_id as ticket_i1_8_1_, tickets0_.assigned_to as assigned2_8_1_, tickets0_.attachment_path as attachme3_8_1_, tickets0_.closed_by as closed_b4_8_1_, tickets0_.details as details5_8_1_, tickets0_.etat as etat6_8_1_, tickets0_.logiciel_id as logiciel7_8_1_, tickets0_.objet as objet8_8_1_, tickets0_.severity as severity9_8_1_, tickets0_.version_id as version10_8_1_, tickets0_.assignedDateTime as assigne11_8_1_, tickets0_.closedDateTime as closedd12_8_1_, tickets0_.createDateTime as created13_8_1_, tickets0_.user_id as user_id14_8_1_, planificat1_.planif_id as planif_i1_4_0_, planificat1_.observation as observat2_4_0_, planificat1_.date_debut_planif as date_deb3_4_0_, planificat1_.date_debut_realise as date_deb4_4_0_, planificat1_.date_fin_planif as date_fin5_4_0_, planificat1_.date_fin_realise as date_fin6_4_0_, planificat1_.ticket_id as ticket_i7_4_0_ from tickets tickets0_ left outer join planification planificat1_ on tickets0_.ticket_id=planificat1_.ticket_id where tickets0_.user_id in (select user4_.user_id from tickets ticket0_ cross join users user1_ cross join logiciel logiciel2_ cross join version version3_ inner join users user4_ on ticket0_.user_id=user4_.user_id where ticket0_.user_id=? and ticket0_.user_id=user1_.user_id and logiciel2_.logiciel_id=ticket0_.logiciel_id and ticket0_.version_id=version3_.version_id and ticket0_.etat<>'fermer' )
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select response0_.ticket_id as ticket_i4_5_0_, response0_.response_id as response1_5_0_, response0_.response_id as response1_5_1_, response0_.response as response2_5_1_, response0_.createDateTime as createda3_5_1_, response0_.ticket_id as ticket_i4_5_1_, response0_.user_id as user_id5_5_1_, user1_.user_id as user_id1_9_2_, user1_.email as email2_9_2_, user1_.etat as etat3_9_2_, user1_.phone as phone4_9_2_, user1_.currentAccessDate as currenta5_9_2_, user1_.dateExpiration as dateexpi6_9_2_, user1_.first_name as first_na7_9_2_, user1_.lastAccessDate as lastacce8_9_2_, user1_.last_name as last_nam9_9_2_, user1_.password as passwor10_9_2_, user1_.structure_id as structu12_9_2_, user1_.username as usernam11_9_2_, structure2_.structure_id as structur1_6_3_, structure2_.nom_structure as nom_stru2_6_3_ from responses response0_ inner join users user1_ on response0_.user_id=user1_.user_id left outer join structure structure2_ on user1_.structure_id=structure2_.structure_id where response0_.ticket_id=?
Hibernate: select responses0_.user_id as user_id5_5_4_, responses0_.response_id as response1_5_4_, responses0_.response_id as response1_5_3_, responses0_.response as response2_5_3_, responses0_.createDateTime as createda3_5_3_, responses0_.ticket_id as ticket_i4_5_3_, responses0_.user_id as user_id5_5_3_, ticket1_.ticket_id as ticket_i1_8_0_, ticket1_.assigned_to as assigned2_8_0_, ticket1_.attachment_path as attachme3_8_0_, ticket1_.closed_by as closed_b4_8_0_, ticket1_.details as details5_8_0_, ticket1_.etat as etat6_8_0_, ticket1_.logiciel_id as logiciel7_8_0_, ticket1_.objet as objet8_8_0_, ticket1_.severity as severity9_8_0_, ticket1_.version_id as version10_8_0_, ticket1_.assignedDateTime as assigne11_8_0_, ticket1_.closedDateTime as closedd12_8_0_, ticket1_.createDateTime as created13_8_0_, ticket1_.user_id as user_id14_8_0_, user2_.user_id as user_id1_9_1_, user2_.email as email2_9_1_, user2_.etat as etat3_9_1_, user2_.phone as phone4_9_1_, user2_.currentAccessDate as currenta5_9_1_, user2_.dateExpiration as dateexpi6_9_1_, user2_.first_name as first_na7_9_1_, user2_.lastAccessDate as lastacce8_9_1_, user2_.last_name as last_nam9_9_1_, user2_.password as passwor10_9_1_, user2_.structure_id as structu12_9_1_, user2_.username as usernam11_9_1_, planificat3_.planif_id as planif_i1_4_2_, planificat3_.observation as observat2_4_2_, planificat3_.date_debut_planif as date_deb3_4_2_, planificat3_.date_debut_realise as date_deb4_4_2_, planificat3_.date_fin_planif as date_fin5_4_2_, planificat3_.date_fin_realise as date_fin6_4_2_, planificat3_.ticket_id as ticket_i7_4_2_ from responses responses0_ inner join tickets ticket1_ on responses0_.ticket_id=ticket1_.ticket_id left outer join users user2_ on ticket1_.user_id=user2_.user_id left outer join planification planificat3_ on ticket1_.ticket_id=planificat3_.ticket_id where responses0_.user_id in (select user4_.user_id from tickets ticket0_ cross join users user1_ cross join logiciel logiciel2_ cross join version version3_ inner join users user4_ on ticket0_.user_id=user4_.user_id where ticket0_.user_id=? and ticket0_.user_id=user1_.user_id and logiciel2_.logiciel_id=ticket0_.logiciel_id and ticket0_.version_id=version3_.version_id and ticket0_.etat<>'fermer' )
org.json.JSONException: JavaBean object contains recursively defined member variable of key "planification"
    at org.json.JSONObject.recursivelyDefinedObjectException(JSONObject.java:2722)
    at org.json.JSONObject.populateMap(JSONObject.java:1558)
    at org.json.JSONObject.<init>(JSONObject.java:372)
    at org.json.JSONObject.wrap(JSONObject.java:2496)
    at org.json.JSONObject.populateMap(JSONObject.java:1563)
    at org.json.JSONObject.<init>(JSONObject.java:372)
    at org.json.JSONObject.wrap(JSONObject.java:2496)
    at org.json.JSONObject.populateMap(JSONObject.java:1563)
    at org.json.JSONObject.populateMap(JSONObject.java:1530)
    at org.json.JSONObject.<init>(JSONObject.java:367)
    at org.json.JSONObject.wrap(JSONObject.java:2499)
    at org.json.JSONObject.wrap(JSONObject.java:2457)
    at org.json.JSONArray.addAll(JSONArray.java:1609)
    at org.json.JSONArray.<init>(JSONArray.java:176)
    at org.json.JSONObject.wrap(JSONObject.java:2478)
    at org.json.JSONObject.populateMap(JSONObject.java:1563)
    at org.json.JSONObject.populateMap(JSONObject.java:1530)
    at org.json.JSONObject.<init>(JSONObject.java:367)
    at org.json.JSONObject.wrap(JSONObject.java:2499)
    at org.json.JSONObject.wrap(JSONObject.java:2457)
    at org.json.JSONArray.addAll(JSONArray.java:1661)
    at org.json.JSONArray.<init>(JSONArray.java:228)
    at org.json.JSONObject.wrap(JSONObject.java:2481)
    at org.json.JSONObject.wrap(JSONObject.java:2457)
    at org.json.JSONArray.addAll(JSONArray.java:1609)
    at org.json.JSONArray.<init>(JSONArray.java:176)
    at org.json.JSONObject.put(JSONObject.java:1771)
    at com.myproject.helpdesk.controllers.TicketManagement.getTicketsByUser(TicketManagement.java:610)
    at com.myproject.helpdesk.controllers.TicketManagement.doGet(TicketManagement.java:95)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    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:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.myproject.helpdesk.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:33)
    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:196)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:366)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:847)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1680)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

What is a recursivelyDefinedObjectException ? my Google searches always lead to the subject of Recursion &  Functions, not the exception.

When debugging, the allTickets List contains 4 objects like so :

[
 [Ljava.lang.Object;@10e63606,
 [Ljava.lang.Object;@3c76d000,
 [Ljava.lang.Object;@5f5bfd07,
 [Ljava.lang.Object;@3a14ab96
]

He's the content of one first object for example :

[1455, test ticket, hello world, créé, Critique, 2022-02-03T15:48:41.058086, com.myproject.helpdesk.models.User@6f643c88, null, CTH, dummy, 10.1.1.v, null, null, 2022-02-03T15:48:41.058086, 2022-02-03T15:48:41.058086, CTH, CTH, email@something.com, 00999999999]

Environment :

Eclipse : Version: 2021-06 (4.20.0) Build id: 20210612-2011

Java 8

my JSONOject comes from this dependency

Any help appreciated.

EDIT: Adding Entities

Fetching the Tickets list is what's causing the problem so .

Ticket

@Entity
@Table(name = "tickets")
public class Ticket implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ticket_id")
    private int ticket_id;

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false, insertable = true)
    private User user;

    @OneToMany(fetch = FetchType.EAGER,mappedBy="ticket")
    private List<Response> response;

     @OneToOne(mappedBy = "ticket")
     private Planification planification;

Planification

@Entity
@Table(name = "planification")
public class Planification implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "planif_id")
    private int planifId;

    @OneToOne
    @JoinColumn(name = "ticket_id",unique = true)
    private Ticket ticket;

User

@Entity
@Table(name = "users")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    private int user_id;

    @OneToMany(fetch = FetchType.EAGER ,mappedBy="user")
    @Fetch(value = FetchMode.SUBSELECT)
    private List<Ticket> tickets;

    @OneToMany(fetch = FetchType.EAGER ,mappedBy="user")
    @Fetch(value = FetchMode.SUBSELECT)
    private List<Response> responses;

    @ManyToOne(fetch = FetchType.EAGER ,cascade = CascadeType.ALL)
    @JoinColumn(name = "structure_id")
    private Structure structure;

Response

@Entity
@Table(name = "responses")
public class Response implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "response_id")
    private int responseId;

    @ManyToOne
    @JoinColumn(name = "ticket_id", nullable = false, insertable = true)
    private Ticket ticket;

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false, insertable = true)
    private User user;

Structure

@Entity
@Table(name = "structure")
public class Structure implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "structure_id")
    private int structure_id;

    @OneToMany(mappedBy = "structure")
    private List<User> user;

EDIT 2 :

When debugging I noticed that aStructure of User's Ticket has exception stack trace as content for it's PersistentBag,

What the hell is causing this ?! I checked my Entity definitions and they look alright to me.

Side note

My Ticket object contains the User object, which contains a list of the Users's Tickets, and it goes on and on forever, infinite recursion, is this normal ? are my Entity definitions wrong ? how can i fix this ?

Body:
You can go with Map.

Map<String,Object> mapObject = new HashMap<>();
List allTickets = ticketDao.getTicketsByUserDao(user);
mapObject.put("ticket",allTickets);


来源: stackexchange

问:
How to filter for un-empty array in CUBA Platform collection
I need to call a collection consisting of objects that have an un-empty array in the items (array) field, I filter collection like this:

```<code>filter:
conditions:[
{
              property: "items",
              operator: "notEmpty",
              value:null
            }]
</code>```

but this solution doesn't work, 500 error is returned, how to implement it?

答:
CUBA Platform REST API doesn't support filtration by collections (@OneToMany and @ManyToMany relations).

To implement such functionality you need to create and expose predefined JPQL query on back end.

There is similar discussion on CUBA Platform forum.

ContentLicense: CC BY-SA 4.0

Body:
I need to call a collection consisting of objects that have an un-empty array in the items (array) field, I filter collection like this:

filter:
conditions:[
{
              property: "items",
              operator: "notEmpty",
              value:null
            }]

but this solution doesn't work, 500 error is returned, how to implement it?


问:
ERROR: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'name'
I simply can't understand why I get this error:

(models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'name'

```<code>from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=255),
    slug = models.SlugField()

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return f'/{self.slug}'

</code>```

答:
Remove the comma and have it this way:

```<code>class Meta:
    ordering = ('name')
</code>```

Then run the makemigrations && migrate commands.

Body:
I simply can't understand why I get this error:

(models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'name'

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=255),
    slug = models.SlugField()

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return f'/{self.slug}'

Body:
Remove the comma and have it this way:

class Meta:
    ordering = ('name')

Then run the makemigrations && migrate commands.


问:
Sorting heterogeneous elements in arraylist
How to sort heterogeneous elements in a array-list? For example,

```<code>ArrayList l1 = new ArrayList();
l1.add(1);
l1.add("hi");
l1.add(1.0f);
</code>```

Now how to sort this array-list?``

答:
You would have to implement your own Comparator which compares the least upper bound of all involved types. In this case, Object.

Related question (from yesterday):

how to compare on multiple classes in java?

ContentLicense: CC BY-SA 3.0

Body:
How to sort heterogeneous elements in a array-list? For example,

ArrayList l1 = new ArrayList();
l1.add(1);
l1.add("hi");
l1.add(1.0f);

Now how to sort this array-list?``


问:
I am getting "Object reference not set to an instance of an object" on DateTime pass
```<code>if(dates == null)
{
    DateTime tempDate = WorldTimeAPI.instance.GetCurrentDateTime();
    print(tempDate);
    dates.SetDailyWeeklyDate(tempDate);
    SaveSystem.TaskDateSave(dates);
}
</code>```

the error is on third line of the block. The print is printing the date, no issues there.

the SetDailyWeeklyDates() function is below:

```<code>public void SetDailyWeeklyDate(DateTime date)
{
    dailyTaskDate = date;
    weeklyTaskDate = date;
}
</code>```

Thoughts?

答:
"if(dates == null)" - you only get to the code if dates is null

You either want to change the code to "if(dates != null)" or create an instance of whatever class "dates" is before the third line.

Body:
if(dates == null)
{
    DateTime tempDate = WorldTimeAPI.instance.GetCurrentDateTime();
    print(tempDate);
    dates.SetDailyWeeklyDate(tempDate);
    SaveSystem.TaskDateSave(dates);
}

the error is on third line of the block. The print is printing the date, no issues there.

the SetDailyWeeklyDates() function is below:

public void SetDailyWeeklyDate(DateTime date)
{
    dailyTaskDate = date;
    weeklyTaskDate = date;
}

Thoughts?


问:
How to fix this error in IE regarding the from
I'm having this error:

Object doesn't support 'from' property or method

on the following line:

const ids = Array.from(cbs).map(function(cb) {cb.getAttribute("data-item-id")});```

How can I fix it?

答:
Array from is not supported by IE
https://caniuse.com/mdn-javascript_builtins_array_from

https://caniuse.com/ is you best friend in these cases.

Use a following polyfill to make it work.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#polyfill

Body:
I'm having this error:

Object doesn't support 'from' property or method

on the following line:

const ids = Array.from(cbs).map(function(cb) {cb.getAttribute("data-item-id")});

How can I fix it?


问:
Get the full path of file name which is numbers only `highest number` , on main Folder or Subfolders?
I am using database software and export excel files from it and save on my desktop with name like ********.xls

***** means numbers only , for example   08134471.xls

23222578.xls

Those numbers on file name are random on count and length.

The path is constant D:\Users\Waleed\Desktop\    but, file name will change each time incrementally to higher number.

So, I need to open the workbook with highest number on the cited path.

In advance , gratefully for your help.

```<code>Sub Open_Numeric_File()

    Workbooks.Open "D:\Users\Waleed\Desktop\08134471.xls"

End Sub
</code>```

答:
Or something like this:

Uses the VBA Dir() function to loop over all the .xls files (not directories etc) in a folder. It splits out the text in front off the ".", and attempts to convert this into a number, while keeping a track of the maximum number found.

If on a 32-bit system replace LongLong with Long, and CLngLng with CLng.

```<code>Sub ListFiles()
    Dim llFile As LongLong
    Dim llMax As LongLong
    Dim strFileToOpen As String
    Dim strPath As String
    Dim strFile As String

    strPath = Environ("USERPROFILE") & "\Desktop\*.xls"
    strFile = Dir(strPath, vbNormal)

    On Error Resume Next

    While Len(strFile) > 0
        llFile = 0
        llFile = CLngLng(Split(strFile, ".")(0))
        If llFile > 0 And llFile > llMax Then
            llMax = llFile
            strFileToOpen = strFile
        End If

        strFile = Dir()
    Wend

    On Error Goto 0

    If Len(strFileToOpen) > 0 Then Workbooks.Open (strPath & "\" & strFileToOpen)
End Sub
</code>```

Body:
I am using database software and export excel files from it and save on my desktop with name like ********.xls

***** means numbers only , for example   08134471.xls

23222578.xls

Those numbers on file name are random on count and length.

The path is constant D:\Users\Waleed\Desktop\    but, file name will change each time incrementally to higher number.

So, I need to open the workbook with highest number on the cited path.

In advance , gratefully for your help.

Sub Open_Numeric_File()

    Workbooks.Open "D:\Users\Waleed\Desktop\08134471.xls"

End Sub

Body:
Or something like this:

Uses the VBA Dir() function to loop over all the .xls files (not directories etc) in a folder. It splits out the text in front off the ".", and attempts to convert this into a number, while keeping a track of the maximum number found.

If on a 32-bit system replace LongLong with Long, and CLngLng with CLng.

Sub ListFiles()
    Dim llFile As LongLong
    Dim llMax As LongLong
    Dim strFileToOpen As String
    Dim strPath As String
    Dim strFile As String

    strPath = Environ("USERPROFILE") & "\Desktop\*.xls"
    strFile = Dir(strPath, vbNormal)

    On Error Resume Next

    While Len(strFile) > 0
        llFile = 0
        llFile = CLngLng(Split(strFile, ".")(0))
        If llFile > 0 And llFile > llMax Then
            llMax = llFile
            strFileToOpen = strFile
        End If

        strFile = Dir()
    Wend

    On Error Goto 0

    If Len(strFileToOpen) > 0 Then Workbooks.Open (strPath & "\" & strFileToOpen)
End Sub


问:
upload expo camera roll image to server
I'm using expo camera to take a picture. The output I get is a file in format file:///data/user/0/host.exp.exponent/..../Camera/1075d7ef-f88b-4252-ad64-e73238599e94.jpg

I send this file path to the following action and try to upload it to

```<code>export const uploadUserPhoto = (localUri,uid) => async dispatch => {
    let formData = new FormData();
    formData.append('avatar', { uri: localUri, fileName: uid});

    let res = await fetch(`${API_URL}api/uploadPhoto`, {
      method: 'POST',
      body: formData,
      header: {
        'content-type': 'multipart/form-data',
      },
    });
</code>```

Afterward, I get [Unhandled promise rejection: TypeError: Network request failed] and nothing arrives to server. I tried using some string to send in the body and the fetch worked, so I guess it has something to do with my formData configuration.

The formData is:

```<code>{
   "_parts": Array [
            Array [
               "avatar",
                  Object {
                  "fileName": "6eAntcmoEsdBeSD2zfka9Nx9UHJ3",
                  "type": "jpg",
                   "uri": "file:///data/us....2e6e3e8d3223.jpg",
                  },
               ],
            ],
}
</code>```

How I use postman to test my sails controller

Sails controller function:

```<code>uploadPhoto: function (req, res) {
    req.file('avatar').upload({
      adapter: require('skipper-s3'),
      key: 'XXXX',
      secret: 'XXX',
      bucket: 'XXX',
      saveAs: req.param('fileName') + '.png',
    }, function (err, filesUploaded) {
            ....
      });
    });
  }
</code>```

答:
just add these params in photo this worked for me</p>
```<code>data.append('avatar', {
      uri: photo.uri,
      name: 'selfie.jpg',
      type: 'image/jpg'
    });
</code>```

Title: upload expo camera roll image to server

Body:
I'm using expo camera to take a picture. The output I get is a file in format file:///data/user/0/host.exp.exponent/..../Camera/1075d7ef-f88b-4252-ad64-e73238599e94.jpg

I send this file path to the following action and try to upload it to

export const uploadUserPhoto = (localUri,uid) => async dispatch => {
    let formData = new FormData();
    formData.append('avatar', { uri: localUri, fileName: uid});

    let res = await fetch(`${API_URL}api/uploadPhoto`, {
      method: 'POST',
      body: formData,
      header: {
        'content-type': 'multipart/form-data',
      },
    });

Afterward, I get [Unhandled promise rejection: TypeError: Network request failed] and nothing arrives to server. I tried using some string to send in the body and the fetch worked, so I guess it has something to do with my formData configuration.

The formData is:

{
   "_parts": Array [
            Array [
               "avatar",
                  Object {
                  "fileName": "6eAntcmoEsdBeSD2zfka9Nx9UHJ3",
                  "type": "jpg",
                   "uri": "file:///data/us....2e6e3e8d3223.jpg",
                  },
               ],
            ],
}

How I use postman to test my sails controller

Sails controller function:

uploadPhoto: function (req, res) {
    req.file('avatar').upload({
      adapter: require('skipper-s3'),
      key: 'XXXX',
      secret: 'XXX',
      bucket: 'XXX',
      saveAs: req.param('fileName') + '.png',
    }, function (err, filesUploaded) {
            ....
      });
    });
  }

Body:
just add these params in photo this worked for me

data.append('avatar', {
      uri: photo.uri,
      name: 'selfie.jpg',
      type: 'image/jpg'
    });


问:
Executing keyframes animation in JS or jQuery
I know that it is possible to set the animation of an element by id either in a stylesheet or in JS from the DOM. The issue is that I want the animation to execute every time a click action on a specific element is performed by the user. Adding the animation to an element's style in JS seems to add it permanently so that the keyframes animation cannot be performed again, (only performed once when the window finishes loading). I also thought about using jQuery's .animate() function however all documentation points to it animating over CSS specific styles and not setting/calling the animation style attribute as if I were to set it using CSS. I want to know the best way of executing my animation over an element when another element is clicked on by the user and consistently executing the animation for each click.

```<code>@keyframes fadeInDown {
  from {
   opacity: 0;
   transform: translate(0, -20%);
 }
 to {
   opacity: 1;
   transform: translate(0, 0);
 }
}
</code>```

The current way I'm setting animation for an element:

```<code>$("#element").css("animation", "fadeInDown 0.5s ease-in 0s 1");
</code>```

答:
It's my first answer on stack overflow.
I had the same question about animation.

What I did last was just like Vivek Patel's answer, but instead of toggling the css keyframe, I created a separated class only for css animation("animation-fadeInDown"), and toggle it.

Because the animation-name "fadeInDown" is correponding to the @keyframes name, so if you separate it you could apply the animation to other elements, by just toggling the animation class.

And, you can still do the css deco to the original box seperately, which might be more clear to read.

I hope this is close to what you looking for.

$('button').click(() => {
  $('.box').toggleClass('animation-fadeInDown');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  width: 50px;
  height: 50px;
  background: black;
}

.animation-fadeInDown {
  animation: fadeInDown 0.5s ease-in 0s 1
}

@keyframes fadeInDown {
    from {
      opacity: 0;
      transform: translate(0, -20%);
    }
    to {
      opacity: 1;
      transform: translate(0, 0);
    }
}</code>```

<button>
    Test
</button>```

Body:
I know that it is possible to set the animation of an element by id either in a stylesheet or in JS from the DOM. The issue is that I want the animation to execute every time a click action on a specific element is performed by the user. Adding the animation to an element's style in JS seems to add it permanently so that the keyframes animation cannot be performed again, (only performed once when the window finishes loading). I also thought about using jQuery's .animate() function however all documentation points to it animating over CSS specific styles and not setting/calling the animation style attribute as if I were to set it using CSS. I want to know the best way of executing my animation over an element when another element is clicked on by the user and consistently executing the animation for each click.

@keyframes fadeInDown {
  from {
   opacity: 0;
   transform: translate(0, -20%);
 }
 to {
   opacity: 1;
   transform: translate(0, 0);
 }
}

The current way I'm setting animation for an element:

$("#element").css("animation", "fadeInDown 0.5s ease-in 0s 1");

Body:
It's my first answer on stack overflow.
I had the same question about animation.

What I did last was just like Vivek Patel's answer, but instead of toggling the css keyframe, I created a separated class only for css animation("animation-fadeInDown"), and toggle it.

Because the animation-name "fadeInDown" is correponding to the @keyframes name, so if you separate it you could apply the animation to other elements, by just toggling the animation class.

And, you can still do the css deco to the original box seperately, which might be more clear to read.

I hope this is close to what you looking for.

$('button').click(() => {
  $('.box').toggleClass('animation-fadeInDown');
});

.box {
  width: 50px;
  height: 50px;
  background: black;
}

.animation-fadeInDown {
  animation: fadeInDown 0.5s ease-in 0s 1
}

@keyframes fadeInDown {
    from {
      opacity: 0;
      transform: translate(0, -20%);
    }
    to {
      opacity: 1;
      transform: translate(0, 0);
    }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>
<button>
    Test
</button>


问:
Redirect to old page at logout in PHP
I am developing a CMS. I have three scripts, and 2 session variables

```<code> $_SESSION['logged']
 $_SESSION['redirect']
</code>```

"auth.inc.php" - Run every time a user requests a page. It checks if $_SESSION['logged'] is set and equal to 1. If it isn't redirects ti main page using

```<code>header(location:index.php)
</code>```

and the page referrer link is saved in $_SESSION['redirect']. If $_SESSION['logged'] is set  inactivity time is less than a required value it redirects to the requested page other wise it redirects to logout.php

"index.php" - checks for user name and password. I successful sets

```<code>$_SESSION['logged']=1
</code>```

If  $_SESSION['redirect'] is set it redirects to that page otherwise to deafult page

"logout.php" - Its unsets and destroys the session using

```<code>session_unset();
session_destroy();
</code>```

But I want if user is logged out due to session timeout then after login it should be redirected to old page. Since I was unsetting the session  $_SESSION['redirect'] was lost. So instead of using  session_unset() I only unset $_SESSION['logged']

```<code>unset($_SESSION['logged']);
session_destroy();
</code>```

but still I am not able to retrieve $_SESSION['redirect'] after session_destroy(). The variable is still not set. How should I redirect to old page after logout due to session expire

答:
Well your first issue is that you are still destroying $_SESSION['redirect'] when you call session_destroy(). What you could do is either hard code a default URL into the system so that you can destroy the session and still redirect.
The other option is to remove the session_destroy() command until after you have redirected.... i.e. on the redirect page, check to see if the previous page (referer) was logout.php, if it was destroy the session otherwise dont</p>

Title: Redirect to old page at logout in PHP

Body:
I am developing a CMS. I have three scripts, and 2 session variables

 $_SESSION['logged']
 $_SESSION['redirect']

"auth.inc.php" - Run every time a user requests a page. It checks if $_SESSION['logged'] is set and equal to 1. If it isn't redirects ti main page using

header(location:index.php)

and the page referrer link is saved in $_SESSION['redirect']. If $_SESSION['logged'] is set  inactivity time is less than a required value it redirects to the requested page other wise it redirects to logout.php

"index.php" - checks for user name and password. I successful sets

$_SESSION['logged']=1

If  $_SESSION['redirect'] is set it redirects to that page otherwise to deafult page

"logout.php" - Its unsets and destroys the session using

session_unset();
session_destroy();

But I want if user is logged out due to session timeout then after login it should be redirected to old page. Since I was unsetting the session  $_SESSION['redirect'] was lost. So instead of using  session_unset() I only unset $_SESSION['logged']

unset($_SESSION['logged']);
session_destroy();

but still I am not able to retrieve $_SESSION['redirect'] after session_destroy(). The variable is still not set. How should I redirect to old page after logout due to session expire


问:
Use typescript to type function argument and return full argument type
I have the following function and object as its input:

```<code>const myResult = myFunc({
  someInnerFunction: (innerArgument) => {
    return innerArgument.myProperty
  }
})
</code>```

And a given type:

```<code>type MyType = {
  myProperty: number | boolean
}
</code>```

How can i make sure myFunc types innerArgument as type MyType BUT ALSO types myResult as the equivalent to the type

```<code>{
  someInnerFunction(innerArgument: MyType): number | boolean
}
</code>```

?

答:
If I understand your question, just this:</p>
```<code>declare function myFunc(p: {
  someInnerFunction: (innerArgument: MyType) => MyType['myProperty'];
}): void;
</code>```

Body:
I have the following function and object as its input:

const myResult = myFunc({
  someInnerFunction: (innerArgument) => {
    return innerArgument.myProperty
  }
})

And a given type:

type MyType = {
  myProperty: number | boolean
}

How can i make sure myFunc types innerArgument as type MyType BUT ALSO types myResult as the equivalent to the type

{
  someInnerFunction(innerArgument: MyType): number | boolean
}

?

Body:
If I understand your question, just this:

declare function myFunc(p: {
  someInnerFunction: (innerArgument: MyType) => MyType['myProperty'];
}): void;


问:
Is it possible to create coded animated wallpapers?
The idea is to ultimately have a program that runs in the background. This program paints pixels to the desktop wallpaper at a rate of at least 24 pixels per second.

I've already tried using certain dekstop handles but that does not have the desired result. This solution paints over cursor and icons as well.

Suggestions?

答:
This rust crate can change the wallpaper of many OS:
https://docs.rs/wallpaper/2.0.1/wallpaper/

It may not yield the performance you where talking about, in my experience it can change the background a few times per second.


问:
Angular add another row form
I am sending my form value as object to API, i want if user adds another row of same form save it in my finalData object. now it copys inputs with same value and overwrites with last ones data.
for example if user has 2 rows return object like this:

```<code>{
    "repairs": [
        {
            "repairId": "name",
            "comment": "test"
        },
        {
            "repairId": "name2",
            "comment": "test2"
        }
    ]
}
</code>```

here is my stackblitz

.ts

```<code>createEstimation!: FormGroup;
  finalData:any;

  defaultForm = {
    carParts: [],
  };

  defaultForm2 = {
    handicraft: [],
  };

  carParts: any[] = [this.defaultForm];
  handicraft: any[] = [this.defaultForm2];

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.createEstimation = this.fb.group({
      repairCategory: [''],
      repairComment: [''],
    });
  }

  // create another field
  create(array: any, form: any) {
    array.push(form);
  }

  sendForm() {
    let value = this.createEstimation.value;
    this.finalData = {
      repairs: [
        {
        repairId: value.repairCategory,
        comment: value.repairComment,
        }
      ],
    }
    console.log(this.finalData);
  }
</code>```

答:
For this type of form you need to use FormArray.

Here is the working Stackblitz

Component.ts

```<code>ngOnInit(): void {
 this.createForm();
}

createForm() {
  this.createEstimation = this.fb.group({
    repairs: this.fb.array([this.initData()]),
  });
}

initData() {
  return this.fb.group({
    repairCategory: [''],
    repairComment: [''],
  });
}

//getter function ease up to get the form controls
get formArr() {
  return this.createEstimation.get('repairs') as FormArray;
}

// create another field
create(array: any, form: any) {
  let formgroup = this.fb.group({
    repairCategory: [''],
    repairComment: [''],
  });
  this.formArr.push(formgroup);
}
</code>```

component.html

```<code><form [formGroup]="createEstimation">
<div formArrayName="repairs">
  <div
    class="content-desc mt-4"
    *ngFor="let obj of formArr.controls; let i = index; let l = last"
    [formGroupName]="i"
  >
  <div class="car-parts" first as isFirst>
    <div class="row">
      <div class="col-lg-6">
        <label class="form-label"
          >Repairs <span class="required">*</span></label
        >
      </div>
      <div class="col-lg-6">
        <label class="form-label">Comment</label>
      </div>
    </div>
    <div class="row mt-2">
      <div class="col-lg-6">
        <div class="row gray-bg">
          <div class="col-lg-4">
            <label class="form-label">category</label>
            <mat-form-field appearance="fill" class="nusx">
              <mat-label> category</mat-label>
              <mat-select #multiSelect formControlName="repairCategory">
                <mat-option> </mat-option>
                <mat-option *ngFor="let item of Repairs" [value]="item">{{
                  item
                }}</mat-option>
              </mat-select>
            </mat-form-field>
          </div>
        </div>
      </div>
      <div class="col-lg-6">
        <textarea
          class="form-control mt-2"
          name=""
          id=""
          cols="30"
          rows="10"
          formControlName="repairComment"
        ></textarea>
       </div>
     </div>
    </div>
  </div>
</div>
<div class="row mt-5">
  <div class="col-lg-10">
    <hr />
  </div>
  <div class="col-lg-2">
    <button
      type="button"
       class="btn-green add"
      (click)="create(this.handicraft, this.defaultForm2)"
    >
     <i class="fas fa-plus"></i> Add another row
   </button>
  </div>
</div>

<button (click)="sendForm()">Send</button>

```{{ createEstimation.value | json }}```
</form>
</code>```

Output

```<code>{
  "repairs": [
    {
      "repairCategory": "endDate",
      "repairComment": "test data 1 "
    },
    {
      "repairCategory": "sum",
      "repairComment": "test data 2"
    }
  ]
}
</code>```

Title: Angular add another row form

Body:
I am sending my form value as object to API, i want if user adds another row of same form save it in my finalData object. now it copys inputs with same value and overwrites with last ones data.
for example if user has 2 rows return object like this:

{
    "repairs": [
        {
            "repairId": "name",
            "comment": "test"
        },
        {
            "repairId": "name2",
            "comment": "test2"
        }
    ]
}

here is my stackblitz

.ts

createEstimation!: FormGroup;
  finalData:any;

  defaultForm = {
    carParts: [],
  };

  defaultForm2 = {
    handicraft: [],
  };

  carParts: any[] = [this.defaultForm];
  handicraft: any[] = [this.defaultForm2];

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.createEstimation = this.fb.group({
      repairCategory: [''],
      repairComment: [''],
    });
  }

  // create another field
  create(array: any, form: any) {
    array.push(form);
  }

  sendForm() {
    let value = this.createEstimation.value;
    this.finalData = {
      repairs: [
        {
        repairId: value.repairCategory,
        comment: value.repairComment,
        }
      ],
    }
    console.log(this.finalData);
  }

Body:
For this type of form you need to use FormArray.

Here is the working Stackblitz

Component.ts

ngOnInit(): void {
 this.createForm();
}

createForm() {
  this.createEstimation = this.fb.group({
    repairs: this.fb.array([this.initData()]),
  });
}

initData() {
  return this.fb.group({
    repairCategory: [''],
    repairComment: [''],
  });
}

//getter function ease up to get the form controls
get formArr() {
  return this.createEstimation.get('repairs') as FormArray;
}

// create another field
create(array: any, form: any) {
  let formgroup = this.fb.group({
    repairCategory: [''],
    repairComment: [''],
  });
  this.formArr.push(formgroup);
}

component.html

<form [formGroup]="createEstimation">
<div formArrayName="repairs">
  <div
    class="content-desc mt-4"
    *ngFor="let obj of formArr.controls; let i = index; let l = last"
    [formGroupName]="i"
  >
  <div class="car-parts" first as isFirst>
    <div class="row">
      <div class="col-lg-6">
        <label class="form-label"
          >Repairs <span class="required">*</span></label
        >
      </div>
      <div class="col-lg-6">
        <label class="form-label">Comment</label>
      </div>
    </div>
    <div class="row mt-2">
      <div class="col-lg-6">
        <div class="row gray-bg">
          <div class="col-lg-4">
            <label class="form-label">category</label>
            <mat-form-field appearance="fill" class="nusx">
              <mat-label> category</mat-label>
              <mat-select #multiSelect formControlName="repairCategory">
                <mat-option> </mat-option>
                <mat-option *ngFor="let item of Repairs" [value]="item">{{
                  item
                }}</mat-option>
              </mat-select>
            </mat-form-field>
          </div>
        </div>
      </div>
      <div class="col-lg-6">
        <textarea
          class="form-control mt-2"
          name=""
          id=""
          cols="30"
          rows="10"
          formControlName="repairComment"
        ></textarea>
       </div>
     </div>
    </div>
  </div>
</div>
<div class="row mt-5">
  <div class="col-lg-10">
    <hr />
  </div>
  <div class="col-lg-2">
    <button
      type="button"
       class="btn-green add"
      (click)="create(this.handicraft, this.defaultForm2)"
    >
     <i class="fas fa-plus"></i> Add another row
   </button>
  </div>
</div>

<button (click)="sendForm()">Send</button>

<pre>{{ createEstimation.value | json }}</pre>
</form>

Output

{
  "repairs": [
    {
      "repairCategory": "endDate",
      "repairComment": "test data 1 "
    },
    {
      "repairCategory": "sum",
      "repairComment": "test data 2"
    }
  ]
}


问:
react dangerouslySetInnerHTML not re-rendering content
Here's my setup:

string-file.properties

```<code>someKey=This is my <span class="hello">{0}</span> string!
</code>```

react-file.jsx

```<code>import stringAPI from 'string-file';

class MyComponent extends Component {

    get content() {
        return { __html: stringAPI.someKey(this.props.word) };
    }

    render() {
        return (
            <span dangerouslySetInnerHTML={this.content} />
        );
    }
}
</code>```

The argument to stringAPI.someKey get substituted for {0} in the string file and then the final html string is returned. My issue is that this.props.word is being updated while MyComponent is not being updated.

I read somewhere that dangerouslySetInnerHTML tells React that it doesn't need to watch the state of the component that the html is rendered in. If that's true, then I still need a way to do what I'm trying to do.

答: After adding unique key on div it's working fine.

Body:
Here's my setup:

string-file.properties

someKey=This is my {0} string!

react-file.jsx

import stringAPI from 'string-file';

class MyComponent extends Component {

    get content() {
        return { __html: stringAPI.someKey(this.props.word) };
    }

    render() {
        return (

        );
    }
}

The argument to stringAPI.someKey get substituted for {0} in the string file and then the final html string is returned. My issue is that this.props.word is being updated while MyComponent is not being updated.

I read somewhere that dangerouslySetInnerHTML tells React that it doesn't need to watch the state of the component that the html is rendered in. If that's true, then I still need a way to do what I'm trying to do.


问:
in python how to count the number of arguments passed after a specific argument?
in python how to count the number of arguments passed after a specific argument ?

Explanation :

```<code>[user]$ command1 -h 192.168.1.1 -p 8888 -t 50 -u -c ...etc  main.py arg1 arg2 arg3
</code>```

here when using sys.argv in main.py the number of arguments is 12 ( or more, it may differ every time )

i want to count only arguments after main.py so only : arg1 arg2 arg3 which is "3" .

Any solution ?

Thanks.

答:
You could get the index of main.py within the sys.argv, and then slice accordingly:

main_index = sys.argv.index('main.py')
arguments_after_main = sys.argv[main_index:] # Should contain only arg1 arg2 arg3
```

Body:
in python how to count the number of arguments passed after a specific argument ?

Explanation :

[user]$ command1 -h 192.168.1.1 -p 8888 -t 50 -u -c ...etc  main.py arg1 arg2 arg3

here when using sys.argv in main.py the number of arguments is 12 ( or more, it may differ every time )

i want to count only arguments after main.py so only : arg1 arg2 arg3 which is "3" .

Any solution ?

Thanks.


问:
How to grab the onSubmit event for a form?
I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)

I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.

Here is my code:

```<code>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
    <title>Hello World</title>
    </head>
    <body>
    <h2>Test</h2>
    <form action="#" method="post" id="commentform">

    <p><input type="text" name="author" id="author" size="22" tabindex="1" />
    <label for="author"><small>Name (required)</small></label></p>

    <p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />

    </form>

    <script type="text/JavaScript">
    <!--
    alert("Hello world");

    var formCheck = document.getElementById("commentform");

    formCheck.onSubmit = doMapping();

    function doMapping() {
        alert("form submitted");
        return false;
    }

    -->
    </script>

    </body>
    </html>
</code>```

答:
Change this:

```<code>formCheck.onSubmit = doMapping()
</code>```

to this:

```<code>formCheck.onSubmit = doMapping
</code>```

When you add parenthesis to the end of a function you execute that function.  When you assign a function (or pass it as a parameter to another function) you need to omit the parenthesis as that is the way to retrieve a function pointer in JavaScript.

Edit: You will also need to move the declaration of the doMapping function above the assignment of that function to the onsubmit event like this (good catch tvanfosson!):

```<code>function doMapping() {
        alert("form submitted");
        return false;
    }

formCheck.onSubmit = doMapping();
</code>```

However if the doMapping function is not used elsewhere you can declare the doMapping function as an anonymous function like this:

```<code>formCheck.onSubmit = function() {
        alert("form submitted");
        return false;
    }
</code>```

which seems a bit cleaner to me.

OwnerDisplayName: Dan

LastEditorDisplayName: Dan

Body:
I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)

I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.

Here is my code:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

    <title>Hello World</title>

Test

    <form action="#" method="post" id="commentform">

<input type="text" name="author" id="author" size="22" tabindex="1" />
    Name (required)

<input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />

    </form>

Body:
Change this:

formCheck.onSubmit = doMapping()

to this:

formCheck.onSubmit = doMapping

When you add parenthesis to the end of a function you execute that function.  When you assign a function (or pass it as a parameter to another function) you need to omit the parenthesis as that is the way to retrieve a function pointer in JavaScript.

Edit: You will also need to move the declaration of the doMapping function above the assignment of that function to the onsubmit event like this (good catch tvanfosson!):

function doMapping() {
        alert("form submitted");
        return false;
    }

formCheck.onSubmit = doMapping();

However if the doMapping function is not used elsewhere you can declare the doMapping function as an anonymous function like this:

formCheck.onSubmit = function() {
        alert("form submitted");
        return false;
    }

which seems a bit cleaner to me.

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Andrew Hare


问:
What exactly is the Windows AppFabric?
Microsoft released a beta of Windows Server AppFabric  that "makes it easier to build, scale and manage Web and composite applications that run on IIS".

MS has also said that you can deploy AppFabric on your own servers, on a 3rd party host  and on Windows Azure.

So far we haven't done any Azure development mostly because the API differs from ASP.NET and you can only deploy your app to the cloud (and not on your own servers).

So if I use the AppFabric API, will that let me create apps that I can deploy in house, at a 3rd party hoster or on the cloud with the same API? Will it be a 'first class citizen' in all of these?

Where does this leave the Azure API - is AppFabric a replacement? What about Azure SQL?

答: even after 2 years of its release, appfabric is still trying to make its name in the market, which so far looks like a mission impossible for them. Microsoft is in habit of enjoying the monopoly in the market but not in case of appfabric. some of the well establish and mature distributed caching products like NCache and some others are doing pretty well job so appfabric has to come up with something new and extraordinary to compete with them  </p>

Title: What exactly is the Windows AppFabric?


问:
How to to get value from Projected List and Map it to other Class in Spring Data JPA?
I am using nativeQuery which makes joins on multiple tables to get the resp:

```<code>@Query(
  value = "SELECT e.empname,c.countryName,r.RegionName
  FROM Employee e,Country c, Region r
  WHERE e.countryId=c.countryId
  AND c.regionId=r.regionId
  AND e.employeeId IN :empIds
  AND c.countryId IN :countryIds
  AND r.regionId IN :regionIds",
  nativeQuery = true)
List<ActiveUserDBResp> findAllActiveUsersNative(
  @Param("empIds") List<Long> empIds,
  @Param("countryIds") List<Long> countryIds,
  @Param("regionIds") List<Long> regionIds,
  Pageable pageable);
</code>```

I am mapping DB response to following interface in my service class.

```<code>interface ActiveUserDBResp{
public String getEmpName();
public String getCountryName();
public String getRegionName();
}
</code>```

And this is the class I want to return as a response:

```<code>@Data
class ActiveUserDTO{
public String empName;
public String countryName;
public String regionName;
}
</code>```

So My service class looks something like:

```<code>List<ActiveUserDBResp> responses= repository.findAllActiveUsersNative(
  customFilterRequest.getEmpIds(),
  customFilterRequest.getCountryIds(),
  customFilterRequest.getRegionIds(),
  pageable);

List<ActiveUserDTO> dtos= responses.stream()
                            .map(mapper::mapDBResponseToDTO)
                            .collect(Collectors.toList());

</code>```

my mapper class gets properties of ActiveUserDBResp and sets into properties of ActiveUserDTO.
But my final reposnse objects i.e ActiveUserDTO objects within dtos are getting null.

```<code>public ActiveUserDTO mapDBResponseToDTO(ActiveUserDBResp response)
{
ActiveUserDTO activeUserDTO=new ActiveUserDTO();
activeUserDTO.setEmpName(response.getEmpName());
//set other properties
return activeUserDTO;
}
</code>```

I tried printing indivdual ActiveUserDBResp in my mapper class but it is printing org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap@Hashcode. I am not getting any error just trying to figure out how should I map this projected query output to my custom class?
Also, If I directly map my query output to my DTO class by doing:

```<code>List<ActiveUserDTO> dtos= repository.findAllActiveUsersNative(
  customFilterRequest.getEmpIds(),
  customFilterRequest.getCountryIds(),
  customFilterRequest.getRegionIds(),
  pageable);
</code>```

Then I am getting

```<code>org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.example.dto.ActiveUserDTO]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
</code>```

This is the reason I decided to map it to Interface first and then DTO. but after mapping every property  is being set to null, even though my query in the DB is running fine and giving response.

答:
I would suggest you use JDBCTemplate and then map it directly.
It should be already in spring context, so you can make it like this:</p>
```<code>@Autowired
JDBCTemplate jdbcTemplate;

List<ActiveUserDTO> findAllActiveUsers(){
return jdbcTemplate.query("SELECT e.empname,c.countryName,r.RegionName
                     FROM Employee e,Country c, Region r
                     WHERE e.countryId=c.countryId
                     AND c.regionId=r.regionId
                     AND e.employeeId IN :empIds
                     AND c.countryId IN :countryIds
                     AND r.regionId IN :regionIds`",
 (row,rowNumber) -> {
           ActiveUserDTO dto = new ActiveUserDTO();
           dto.setEmpName(row.getString(1));
           ...
           return dto;
           })
           .addValue("empIds", 1)
           ...;

</code>```

Body:
I am using nativeQuery which makes joins on multiple tables to get the resp:

@Query(
  value = "SELECT e.empname,c.countryName,r.RegionName
  FROM Employee e,Country c, Region r
  WHERE e.countryId=c.countryId
  AND c.regionId=r.regionId
  AND e.employeeId IN :empIds
  AND c.countryId IN :countryIds
  AND r.regionId IN :regionIds",
  nativeQuery = true)
List<ActiveUserDBResp> findAllActiveUsersNative(
  @Param("empIds") List<Long> empIds,
  @Param("countryIds") List<Long> countryIds,
  @Param("regionIds") List<Long> regionIds,
  Pageable pageable);

I am mapping DB response to following interface in my service class.

interface ActiveUserDBResp{
public String getEmpName();
public String getCountryName();
public String getRegionName();
}

And this is the class I want to return as a response:

@Data
class ActiveUserDTO{
public String empName;
public String countryName;
public String regionName;
}

So My service class looks something like:

List<ActiveUserDBResp> responses= repository.findAllActiveUsersNative(
  customFilterRequest.getEmpIds(),
  customFilterRequest.getCountryIds(),
  customFilterRequest.getRegionIds(),
  pageable);

List<ActiveUserDTO> dtos= responses.stream()
                            .map(mapper::mapDBResponseToDTO)
                            .collect(Collectors.toList());

my mapper class gets properties of ActiveUserDBResp and sets into properties of ActiveUserDTO.
But my final reposnse objects i.e ActiveUserDTO objects within dtos are getting null.

public ActiveUserDTO mapDBResponseToDTO(ActiveUserDBResp response)
{
ActiveUserDTO activeUserDTO=new ActiveUserDTO();
activeUserDTO.setEmpName(response.getEmpName());
//set other properties
return activeUserDTO;
}

I tried printing indivdual ActiveUserDBResp in my mapper class but it is printing org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap@Hashcode. I am not getting any error just trying to figure out how should I map this projected query output to my custom class?
Also, If I directly map my query output to my DTO class by doing:

List<ActiveUserDTO> dtos= repository.findAllActiveUsersNative(
  customFilterRequest.getEmpIds(),
  customFilterRequest.getCountryIds(),
  customFilterRequest.getRegionIds(),
  pageable);

Then I am getting

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.example.dto.ActiveUserDTO]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]

This is the reason I decided to map it to Interface first and then DTO. but after mapping every property  is being set to null, even though my query in the DB is running fine and giving response.

Body:
I would suggest you use JDBCTemplate and then map it directly.
It should be already in spring context, so you can make it like this:

@Autowired
JDBCTemplate jdbcTemplate;

List<ActiveUserDTO> findAllActiveUsers(){
return jdbcTemplate.query("SELECT e.empname,c.countryName,r.RegionName
                     FROM Employee e,Country c, Region r
                     WHERE e.countryId=c.countryId
                     AND c.regionId=r.regionId
                     AND e.employeeId IN :empIds
                     AND c.countryId IN :countryIds
                     AND r.regionId IN :regionIds`",
 (row,rowNumber) -> {
           ActiveUserDTO dto = new ActiveUserDTO();
           dto.setEmpName(row.getString(1));
           ...
           return dto;
           })
           .addValue("empIds", 1)
           ...;


问:
Django : Invalid block tag on line 121: 'popular_products', expected 'endblock'. Did you forget to register or load this tag?
I have a custom template tag in my project and every thing looks fine but when i want to use this template tag i got this error:

Invalid block tag on line 122: 'popular_products', expected 'endblock'. Did you forget to register or load this tag?

base_tags.py:

```<code>from django import template
from django.db.models import Count, Q
from datetime import datetime, timedelta
from shop.models import Product

register = template.Library()

@register.inclusion_tag('shared/partials/popular_product_slider.html')
def popular_products():
    last_week = datetime.today() - timedelta(days=7)
    return {
        "popular_products": Product.objects.filter(available=True).annotate(
            count=Count('hits', filter=Q(producthit__date__gt=last_week))).order_by(
            '-count', '-created')[:3]
    }
</code>```

home_page.html template:

```<code> {% extends 'shared/_base.html' %}
 {% load base_tags %}
 {% load i18n %}
 {% load render_partial %}
 {% load static %}
 {% load ratings %}
 {% load thumbnail %}

 {% block content %}
    <div class="row">
      <div class="col-lg-12">
         <div class="tab-content">
            <div id="recent" class="tab-pane fade show active">
                <div class="row  product-slider">
                        {% popular_products %}
                </div>
            </div>
       </div>
  </div>
 </div>
{% endblock %}
</code>```

popular_product_slider.html

```<code>{% for product in popular_products %}
    {{product.image}}
    {{product.detail}}
    {{product.title}}
{% endfor %}

</code>```

views.py

```<code>def home_page(request):
    context = {}
    return render(request, 'Home_page.html', context)

</code>```

答:
You have wrongly used {% popular_products %}. You should use {% include 'popular_product_slider.html' %} to implement popular_product_slider.html into home_page.html.

If you use curly template brackets with precentage sign ({% %}), then first value is taken as a command. And file didn't recognize popular_products as command and it raises Error.

Body:
I have a custom template tag in my project and every thing looks fine but when i want to use this template tag i got this error:

Invalid block tag on line 122: 'popular_products', expected 'endblock'. Did you forget to register or load this tag?

base_tags.py:

from django import template
from django.db.models import Count, Q
from datetime import datetime, timedelta
from shop.models import Product

register = template.Library()

@register.inclusion_tag('shared/partials/popular_product_slider.html')
def popular_products():
    last_week = datetime.today() - timedelta(days=7)
    return {
        "popular_products": Product.objects.filter(available=True).annotate(
            count=Count('hits', filter=Q(producthit__date__gt=last_week))).order_by(
            '-count', '-created')[:3]
    }

home_page.html template:

 {% extends 'shared/_base.html' %}
 {% load base_tags %}
 {% load i18n %}
 {% load render_partial %}
 {% load static %}
 {% load ratings %}
 {% load thumbnail %}

 {% block content %}

                        {% popular_products %}

{% endblock %}

popular_product_slider.html

{% for product in popular_products %}
    {{product.image}}
    {{product.detail}}
    {{product.title}}
{% endfor %}

views.py

def home_page(request):
    context = {}
    return render(request, 'Home_page.html', context)


问:
Logger throws IncompatibleClassChangeError at runtime when processing a custom log message class
I have the implementation as follow in the library A

```<code>public class CustomLogMessage implements Message { //some implementation }
</code>```

then, that library A is taken into B (via maven dependency) and has the follow implementation in B:

```<code>public class JohnDoe {

    private static final Logger LOGGER = LogManager.getLogger(JohnDoe .class);

    public static void message(some args) {
        LOGGER.info(new CustomLogMessage(args));
    }

}
</code>```

Through the unit test, this work perfectly fine but when I deploy this app locally, the logger threw IncompatibleClassChangeError exception with the inner most stacktrace is AbstractAppender class from log4j.

```<code>org.apache.logging.log4j.spi.AbstractLogger.info(AbstractLogger.java:1290)
</code>```

Before this implementation, the B used to work with log4j (1.2.17) and back the the CustomLogMessage class just need to implement the Serializable interface and then it can already be passed into the logger's argument.

But after B is upgraded to log4j2 (2.17.1), the CustomLogMessage class now need to implement the Message interface. (see https://logging.apache.org/log4j/2.x/manual/messages.html)

I have no idea why this happened nor the actual meaning of the exception.
Can someone point out why I got this issue?

答: It turned out that there was Lib C that has a reference to the old implementation of the CustomLogMessage class and this lib C was loaded first by the JVM and therefore when it reached this line LOGGER.info(new CustomLogMessage(args)); during run-time, it threw the exception (binary incompatible).

Body:
I have the implementation as follow in the library A

public class CustomLogMessage implements Message { //some implementation }

then, that library A is taken into B (via maven dependency) and has the follow implementation in B:

public class JohnDoe {

    private static final Logger LOGGER = LogManager.getLogger(JohnDoe .class);

    public static void message(some args) {
        LOGGER.info(new CustomLogMessage(args));
    }

}

Through the unit test, this work perfectly fine but when I deploy this app locally, the logger threw IncompatibleClassChangeError exception with the inner most stacktrace is AbstractAppender class from log4j.

org.apache.logging.log4j.spi.AbstractLogger.info(AbstractLogger.java:1290)

Before this implementation, the B used to work with log4j (1.2.17) and back the the CustomLogMessage class just need to implement the Serializable interface and then it can already be passed into the logger's argument.

But after B is upgraded to log4j2 (2.17.1), the CustomLogMessage class now need to implement the Message interface. (see https://logging.apache.org/log4j/2.x/manual/messages.html)

I have no idea why this happened nor the actual meaning of the exception.
Can someone point out why I got this issue?


问:
Running python file on windows CMD vs VScode
I am running a Cryptocurrency-trading python program on my laptop
It monitors the market every second and when the condition is satisfied, it tries transactions.

When I run it on windows CMD, it causes many problems below.

1. Sometimes, it halts till I click the cmd window and press 'enter' key

2. Sometimes, it causes many unknown errors.

However, when I run that on VScode, it does not cause any problem.

I wonder what makes the difference between those two environments.

答:
I have had some issues with VSCode not finding libraries and similar, and the reason for that is that VSCode runs its own python. In IDLE (and CMD) you run the raw python in AppData, but VSCode runs an executable they have downloaded via extensions through the program files folder.
My hypothesis is that Python as in the AppData folder is corrupted or wrong in some way, but the Program Files folder is correct. It may even be on a different python version.

Try reinstalling python from the official python website, and run it again. Also double-check that the VSCode Python extension version is the same as the one saved in "C:\Users\YOURUSERNAME\AppData\Local\Programs\Python\Python39".

Hope it worked!


问:
I am having Issues counting values in a row with separators using SQL
I am new to snowflake and trying the count the number of values in a row with separators using SQL. I am not sure how to go about it. I've googled solutions for this but have not been able to find one.

table name: Lee_tab

user
names

id01
Jon;karl;lee;

id02
Abi;jackson;

id03
don;

id04

what I want to achieve

user
names
name_count

id01
Jon;karl;lee;
3

id02
Abi;jackson;
2

id03
don;
1

id04

0

答:
This is the answer for your query

```<code>select user,names,(len(names) - len(replace(names, ';',''))+1) names_count from Lee_tab;
</code>```

for more understanding check this ,i have done all
https://www.db-fiddle.com/f/BQuEjw2pthMDb1z8NTdHv/0

Body:
This is the answer for your query

select user,names,(len(names) - len(replace(names, ';',''))+1) names_count from Lee_tab;

for more understanding check this ,i have done all
https://www.db-fiddle.com/f/BQuEjw2pthMDb1z8NTdHv/0