问:
How to access a variable from another dart file . Flutter
I am new to Flutter and I need to access a variable from another dart file.I am using showDatePicker to select a date.I need to get that date in another file in which where dob.dart is calling to insert in database.

dob.dart

```<code>class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.circular(5),
      ),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

I need to use value of dateTime in another file addStudents.dart

addstudents.dart

```<code>class _AddStudentsState extends State<AddStudents> {
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _mobileController = TextEditingController();
  final _emailController = TextEditingController();
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>(); @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        child: Form(
          key: _formkey,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Enter your name';
                    }
                  },
                  controller: _nameController,
                  decoration: const InputDecoration(
                      labelText: 'Name',
                      hintText: 'Alex',
                      border: OutlineInputBorder()),
                ),
                DateOfBirth(),
                TextFormField(
                  maxLines: 5,
                  keyboardType: TextInputType.multiline,
                  controller: _addressController,
                  decoration: const InputDecoration(
                      labelText: 'Address',
                      hintText:
                          'House 21\nKolachery mukk\nP.O.Kolachery\nKannur\n670601',
                      border: OutlineInputBorder()),
                ),
                TextFormField(
                  maxLength: 10,
                  keyboardType: TextInputType.number,
                  controller: _mobileController,
                  decoration: const InputDecoration(
                    labelText: 'Mobile Number',
                    prefixText: '+91',
                    hintText: '0000000000',
                    border: OutlineInputBorder(),
                  ),
                ),
                TextFormField(
                  keyboardType: TextInputType.emailAddress,
                  controller: _emailController,
                  decoration: const InputDecoration(
                      labelText: 'Email',
                      hintText: 'name@example.com',
                      border: OutlineInputBorder()),
                ),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    child: const Text('Submit'),
                    onPressed: () async {
                      if (!_formkey.currentState!.validate()) {
                        return;
                      }

                      await DataBaseHelper.instance.addStudent(
                        StudentDetails(
                          name: _nameController.text,
                          dob:
                              // '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                          address: _addressController.text,
                          phone: _mobileController.text,
                          email: _emailController.text,
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

答:
You need to import the file with the variable dateTime.

Then you have 2 ways:

make the variable static: static var dateTime

for this way you don't need todo know anything

so if you have make the variable static you can use it also in a other file if you import the file with the static varible and you use it like this: ClassWithTheStaticVarible.dateTime.

and if you do way number 2 than you need to import the file with the variable and you can use it like this: ClassWithTheDateTimeVarible().dateTime

so what it does if you use way 1: it pick the varible out of the class without build the class again.

and if you use way 2 it does: build the class again and pick after this the variable

Body:
I am new to Flutter and I need to access a variable from another dart file.I am using showDatePicker to select a date.I need to get that date in another file in which where dob.dart is calling to insert in database.

dob.dart

class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.circular(5),
      ),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}

I need to use value of dateTime in another file addStudents.dart

addstudents.dart

class _AddStudentsState extends State<AddStudents> {
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _mobileController = TextEditingController();
  final _emailController = TextEditingController();
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>(); @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        child: Form(
          key: _formkey,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Enter your name';
                    }
                  },
                  controller: _nameController,
                  decoration: const InputDecoration(
                      labelText: 'Name',
                      hintText: 'Alex',
                      border: OutlineInputBorder()),
                ),
                DateOfBirth(),
                TextFormField(
                  maxLines: 5,
                  keyboardType: TextInputType.multiline,
                  controller: _addressController,
                  decoration: const InputDecoration(
                      labelText: 'Address',
                      hintText:
                          'House 21\nKolachery mukk\nP.O.Kolachery\nKannur\n670601',
                      border: OutlineInputBorder()),
                ),
                TextFormField(
                  maxLength: 10,
                  keyboardType: TextInputType.number,
                  controller: _mobileController,
                  decoration: const InputDecoration(
                    labelText: 'Mobile Number',
                    prefixText: '+91',
                    hintText: '0000000000',
                    border: OutlineInputBorder(),
                  ),
                ),
                TextFormField(
                  keyboardType: TextInputType.emailAddress,
                  controller: _emailController,
                  decoration: const InputDecoration(
                      labelText: 'Email',
                      hintText: 'name@example.com',
                      border: OutlineInputBorder()),
                ),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    child: const Text('Submit'),
                    onPressed: () async {
                      if (!_formkey.currentState!.validate()) {
                        return;
                      }

                      await DataBaseHelper.instance.addStudent(
                        StudentDetails(
                          name: _nameController.text,
                          dob:
                              // '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                          address: _addressController.text,
                          phone: _mobileController.text,
                          email: _emailController.text,
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


来源: stackexchange

问:
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 ?

答:
The Error :

The allTickets List contains an infinitely recursive User object, and therefore could not be parsed to a JSONObject.

What caused it ?

this query :

```<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>```

Emphasis on T.user here :

There is no column called User in the Tickets table, instead there is user_id, so query.list() method returned an instance of an infinitely recusive User Object instead of the user_id which is an integer, * i think *.

The Fix

Change T.user to T.user_id.

The List can now be parsed to a JSONObject now with no errors.

ContentLicense: CC BY-SA 4.0

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:
The Error :

The allTickets List contains an infinitely recursive User object, and therefore could not be parsed to a JSONObject.

What caused it ?

this query :

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);

Emphasis on T.user here :

There is no column called User in the Tickets table, instead there is user_id, so query.list() method returned an instance of an infinitely recusive User Object instead of the user_id which is an integer, * i think *.

The Fix

Change T.user to T.user_id.

The List can now be parsed to a JSONObject now with no errors.


Title: Multiple pattern matching guided string replacements with sed

Body:
File1 is an hard formatted pdb file containing protein coordinates:

ATOM      1  N   MET A   1     -37.809  27.446  34.618  1.00 43.34           N
ATOM      2  CA  MET A   1     -37.480  26.307  33.746  1.00 43.34           C
ATOM      3  C   MET A   1     -36.495  25.493  34.556  1.00 43.34           C
ATOM      4  CB  MET A   1     -36.919  26.801  32.394  1.00 43.34           C
ATOM      5  O   MET A   1     -35.346  25.898  34.661  1.00 43.34           O
ATOM      6  CG  MET A   1     -36.980  25.729  31.301  1.00 43.34           C
ATOM      7  SD  MET A   1     -35.977  26.080  29.826  1.00 43.34           S
ATOM      8  CE  MET A   1     -36.833  27.479  29.055  1.00 43.34           C
ATOM      9  N   GLU A   2     -36.991  24.516  35.314  1.00 37.48           N
ATOM     10  CA  GLU A   2     -36.090  23.617  36.039  1.00 37.48           C
ATOM     11  C   GLU A   2     -35.250  22.852  35.010  1.00 37.48           C
ATOM     12  CB  GLU A   2     -36.860  22.659  36.957  1.00 37.48           C
ATOM     13  O   GLU A   2     -35.776  22.534  33.938  1.00 37.48           O
ATOM     14  CG  GLU A   2     -37.467  23.407  38.153  1.00 37.48           C
..............................................................................
..............................................................................
..............................................................................
ATOM    981  N   CYS A 123     -15.659  -7.164  13.998  1.00 90.53           N
ATOM    982  CA  CYS A 123     -16.801  -7.332  13.106  1.00 90.53           C
ATOM    983  C   CYS A 123     -17.894  -8.234  13.699  1.00 90.53           C
ATOM    984  CB  CYS A 123     -16.321  -7.886  11.757  1.00 90.53           C
ATOM    985  O   CYS A 123     -18.918  -8.425  13.046  1.00 90.53           O
ATOM    986  SG  CYS A 123     -15.266  -6.683  10.904  1.00 90.53           S
ATOM    987  N   GLY A 124     -17.679  -8.840  14.874  1.00 90.37           N
ATOM    988  CA  GLY A 124     -18.641  -9.764  15.474  1.00 90.37           C
ATOM    989  C   GLY A 124     -18.851 -11.029  14.637  1.00 90.37           C
ATOM    990  O   GLY A 124     -19.970 -11.514  14.513  1.00 90.37           O
ATOM    991  N   SER A 125     -17.793 -11.536  13.996  1.00 92.09           N
ATOM    992  CA  SER A 125     -17.837 -12.749  13.159  1.00 92.09           C
ATOM    993  C   SER A 125     -17.220 -13.976  13.833  1.00 92.09           C
ATOM    994  CB  SER A 125     -17.117 -12.481  11.840  1.00 92.09           C
ATOM    995  O   SER A 125     -17.538 -15.108  13.459  1.00 92.09           O
ATOM    996  OG  SER A 125     -17.831 -11.523  11.084  1.00 92.09           O
....................... plus many more lines .................................

File2 is a list of representative lines obtained from fields 3,4, and 5 of the above
pdb file. To keep all simple, let's consider just to lines:

GLU A   2
GLY A 124

The desired output is:

ATOM      1  N   MET A   1     -37.809  27.446  34.618  1.00 43.34           N
ATOM      2  CA  MET A   1     -37.480  26.307  33.746  1.00 43.34           C
ATOM      3  C   MET A   1     -36.495  25.493  34.556  1.00 43.34           C
ATOM      4  CB  MET A   1     -36.919  26.801  32.394  1.00 43.34           C
ATOM      5  O   MET A   1     -35.346  25.898  34.661  1.00 43.34           O
ATOM      6  CG  MET A   1     -36.980  25.729  31.301  1.00 43.34           C
ATOM      7  SD  MET A   1     -35.977  26.080  29.826  1.00 43.34           S
ATOM      8  CE  MET A   1     -36.833  27.479  29.055  1.00 43.34           C
ATOM      9  N   GLU A   2     -36.991  24.516  35.314  1.00 00.00           N
ATOM     10  CA  GLU A   2     -36.090  23.617  36.039  1.00 00.00           C
ATOM     11  C   GLU A   2     -35.250  22.852  35.010  1.00 00.00           C
ATOM     12  CB  GLU A   2     -36.860  22.659  36.957  1.00 00.00           C
ATOM     13  O   GLU A   2     -35.776  22.534  33.938  1.00 00.00           O
ATOM     14  CG  GLU A   2     -37.467  23.407  38.153  1.00 00.00           C
..............................................................................
..............................................................................
..............................................................................
ATOM    981  N   CYS A 123     -15.659  -7.164  13.998  1.00 90.53           N
ATOM    982  CA  CYS A 123     -16.801  -7.332  13.106  1.00 90.53           C
ATOM    983  C   CYS A 123     -17.894  -8.234  13.699  1.00 90.53           C
ATOM    984  CB  CYS A 123     -16.321  -7.886  11.757  1.00 90.53           C
ATOM    985  O   CYS A 123     -18.918  -8.425  13.046  1.00 90.53           O
ATOM    986  SG  CYS A 123     -15.266  -6.683  10.904  1.00 90.53           S
ATOM    987  N   GLY A 124     -17.679  -8.840  14.874  1.00 00.00           N
ATOM    988  CA  GLY A 124     -18.641  -9.764  15.474  1.00 00.00           C
ATOM    989  C   GLY A 124     -18.851 -11.029  14.637  1.00 00.00           C
ATOM    990  O   GLY A 124     -19.970 -11.514  14.513  1.00 00.00           O
ATOM    991  N   SER A 125     -17.793 -11.536  13.996  1.00 92.09           N
ATOM    992  CA  SER A 125     -17.837 -12.749  13.159  1.00 92.09           C
ATOM    993  C   SER A 125     -17.220 -13.976  13.833  1.00 92.09           C
ATOM    994  CB  SER A 125     -17.117 -12.481  11.840  1.00 92.09           C
ATOM    995  O   SER A 125     -17.538 -15.108  13.459  1.00 92.09           O
ATOM    996  OG  SER A 125     -17.831 -11.523  11.084  1.00 92.09           O

i.e. a modified pdb with 00.00 in the 11th field if a File1's line contain a
File2 occurrence.

I already know how to do that with Bash while-read and awk but because these tools
change the format and require reformatting and/or specify the output format, in this
particular case dealing with hundreds of files they are not practical.
In order to avoid these problems I decided to look for a solution based on sed.
I got a working solution if I explicitly give a single search pattern. i.e. the
following code works:

digits=00.00
sed "/GLU A   2/s/\(.\{61\}\)\(.\{5\}\)/\1$digits/" File1.pdb  > out.pdb

but the following does not (the File1 lines are unchanged) and I did not manage
to figure out why:

digits=00.00
while read pattern; do
    sed "/$pattern/s/\(.\{61\}\)\(.\{5\}\)/\1$digits/" File1.pdb > out.pdb ;
done < File2.txt

Sorry for the lengthy message. Thanks in advance for any help.

@anubhava:

using my real data this is what happen at the first substitution site:

ATOM    293  CE1 HIS A  38     -18.278  19.735  13.486  1.00 67.94           C
ATOM    294  NE2 HIS A  38     -18.518  18.594  14.144  1.00 67.94           N
ATOM    295  N   GLY A  39     -13.836  00.00   9.206  1.00 71.50           N
ATOM    296  CA  GLY A  39     -12.628  00.00   8.447  1.00 71.50           C
ATOM    297  C   GLY A  39     -11.358  00.00   9.286  1.00 71.50           C
ATOM    298  O   GLY A  39     -11.411  18.636  10.344  1.00 00.00           O
ATOM    299  N   PRO A  40     -10.180  17.577   8.797  1.00 71.93           N
ATOM    300  CA  PRO A  40      -8.908  17.719   9.520  1.00 71.93           C
ATOM    301  C   PRO A  40      -8.580  19.169   9.912  1.00 71.93           C

In this case the site is /GLY A  39/. As you can see there is a shift in some lines and unwanted substitutions in the 8th field.
Strange enough such problems occur only for the first replacement i.e. the remaning output is just perfect. Thanks.

Body:
Using sed in a while loop which reads file 2 line by line, you can target only lines matches those found in file2 and carry out the sub on those lines where;

s/\(.*\)[0-9]\{2\}\.[0-9]\{2\}\([[:space:]]\+.*$\)/  - Group everything up to the last digits that matches the pattern and retain to be returned with back reference \1. Exclude the number matched in the pattern and once again group everything else after from the space to the end of the line and return with back-reference \2

$ cat file1
ATOM      1  N   MET A   1     -37.809  27.446  34.618  1.00 43.34           N
ATOM      2  CA  MET A   1     -37.480  26.307  33.746  1.00 43.34           C
ATOM      3  C   MET A   1     -36.495  25.493  34.556  1.00 43.34           C
ATOM      4  CB  MET A   1     -36.919  26.801  32.394  1.00 43.34           C
ATOM      5  O   MET A   1     -35.346  25.898  34.661  1.00 43.34           O
ATOM      6  CG  MET A   1     -36.980  25.729  31.301  1.00 43.34           C
ATOM      7  SD  MET A   1     -35.977  26.080  29.826  1.00 43.34           S
ATOM      8  CE  MET A   1     -36.833  27.479  29.055  1.00 43.34           C
ATOM      9  N   GLU A   2     -36.991  24.516  35.314  1.00 37.48           N
ATOM     10  CA  GLU A   2     -36.090  23.617  36.039  1.00 37.48           C
ATOM     11  C   GLU A   2     -35.250  22.852  35.010  1.00 37.48           C
ATOM     12  CB  GLU A   2     -36.860  22.659  36.957  1.00 37.48           C
ATOM     13  O   GLU A   2     -35.776  22.534  33.938  1.00 37.48           O
ATOM     14  CG  GLU A   2     -37.467  23.407  38.153  1.00 37.48           C
ATOM    981  N   CYS A 123     -15.659  -7.164  13.998  1.00 90.53           N
ATOM    982  CA  CYS A 123     -16.801  -7.332  13.106  1.00 90.53           C
ATOM    983  C   CYS A 123     -17.894  -8.234  13.699  1.00 90.53           C
ATOM    984  CB  CYS A 123     -16.321  -7.886  11.757  1.00 90.53           C
ATOM    985  O   CYS A 123     -18.918  -8.425  13.046  1.00 90.53           O
ATOM    986  SG  CYS A 123     -15.266  -6.683  10.904  1.00 90.53           S
ATOM    987  N   GLY A 124     -17.679  -8.840  14.874  1.00 90.37           N
ATOM    988  CA  GLY A 124     -18.641  -9.764  15.474  1.00 90.37           C
ATOM    989  C   GLY A 124     -18.851 -11.029  14.637  1.00 90.37           C
ATOM    990  O   GLY A 124     -19.970 -11.514  14.513  1.00 90.37           O
ATOM    991  N   SER A 125     -17.793 -11.536  13.996  1.00 92.09           N
ATOM    992  CA  SER A 125     -17.837 -12.749  13.159  1.00 92.09           C
ATOM    993  C   SER A 125     -17.220 -13.976  13.833  1.00 92.09           C
ATOM    994  CB  SER A 125     -17.117 -12.481  11.840  1.00 92.09           C
ATOM    995  O   SER A 125     -17.538 -15.108  13.459  1.00 92.09           O
ATOM    996  OG  SER A 125     -17.831 -11.523  11.084  1.00 92.09           O

$ while read -r line; do sed -i.bak "/$line/s/\(.*\)[0-9]\{2\}\.[0-9]\{2\}\([[:space:]]\+.*$\)/\100.00\2/" file1; done < file2
$ cat file1
ATOM      1  N   MET A   1     -37.809  27.446  34.618  1.00 43.34           N
ATOM      2  CA  MET A   1     -37.480  26.307  33.746  1.00 43.34           C
ATOM      3  C   MET A   1     -36.495  25.493  34.556  1.00 43.34           C
ATOM      4  CB  MET A   1     -36.919  26.801  32.394  1.00 43.34           C
ATOM      5  O   MET A   1     -35.346  25.898  34.661  1.00 43.34           O
ATOM      6  CG  MET A   1     -36.980  25.729  31.301  1.00 43.34           C
ATOM      7  SD  MET A   1     -35.977  26.080  29.826  1.00 43.34           S
ATOM      8  CE  MET A   1     -36.833  27.479  29.055  1.00 43.34           C
ATOM      9  N   GLU A   2     -36.991  24.516  35.314  1.00 00.00           N
ATOM     10  CA  GLU A   2     -36.090  23.617  36.039  1.00 00.00           C
ATOM     11  C   GLU A   2     -35.250  22.852  35.010  1.00 00.00           C
ATOM     12  CB  GLU A   2     -36.860  22.659  36.957  1.00 00.00           C
ATOM     13  O   GLU A   2     -35.776  22.534  33.938  1.00 00.00           O
ATOM     14  CG  GLU A   2     -37.467  23.407  38.153  1.00 00.00           C
ATOM    981  N   CYS A 123     -15.659  -7.164  13.998  1.00 90.53           N
ATOM    982  CA  CYS A 123     -16.801  -7.332  13.106  1.00 90.53           C
ATOM    983  C   CYS A 123     -17.894  -8.234  13.699  1.00 90.53           C
ATOM    984  CB  CYS A 123     -16.321  -7.886  11.757  1.00 90.53           C
ATOM    985  O   CYS A 123     -18.918  -8.425  13.046  1.00 90.53           O
ATOM    986  SG  CYS A 123     -15.266  -6.683  10.904  1.00 90.53           S
ATOM    987  N   GLY A 124     -17.679  -8.840  14.874  1.00 00.00           N
ATOM    988  CA  GLY A 124     -18.641  -9.764  15.474  1.00 00.00           C
ATOM    989  C   GLY A 124     -18.851 -11.029  14.637  1.00 00.00           C
ATOM    990  O   GLY A 124     -19.970 -11.514  14.513  1.00 00.00           O
ATOM    991  N   SER A 125     -17.793 -11.536  13.996  1.00 92.09           N
ATOM    992  CA  SER A 125     -17.837 -12.749  13.159  1.00 92.09           C
ATOM    993  C   SER A 125     -17.220 -13.976  13.833  1.00 92.09           C
ATOM    994  CB  SER A 125     -17.117 -12.481  11.840  1.00 92.09           C
ATOM    995  O   SER A 125     -17.538 -15.108  13.459  1.00 92.09           O
ATOM    996  OG  SER A 125     -17.831 -11.523  11.084  1.00 92.09           O


问:
How to use paginate_orphans in django function based views?
In Class-Based View We Can Use Like This.

```<code>class PostListView(ListView):
    model = Post
    template_name ='blog/index.html'
    ordering = ['id']
    paginate_by = 5
    paginate_orphans = 2
</code>```

But How can I Use this paginate_orphans in function-based views?

```<code>page = request.GET.get('page', 1)
paginator = Paginator(filter_qs, 2)
try:
   filter_qs = paginator.page(page)
except PageNotAnInteger:
   filter_qs = paginator.page(1)
except EmptyPage:
   filter_qs = paginator.page(paginator.num_pages)

</code>```

答:
You can pass orphans parameter to the Paginator class as mentioned below:</p>
```<code>paginator = Paginator(filter_qs, 2, orphans=2)
</code>```

Body:
In Class-Based View We Can Use Like This.

class PostListView(ListView):
    model = Post
    template_name ='blog/index.html'
    ordering = ['id']
    paginate_by = 5
    paginate_orphans = 2

But How can I Use this paginate_orphans in function-based views?

page = request.GET.get('page', 1)
paginator = Paginator(filter_qs, 2)
try:
   filter_qs = paginator.page(page)
except PageNotAnInteger:
   filter_qs = paginator.page(1)
except EmptyPage:
   filter_qs = paginator.page(paginator.num_pages)

Body:
You can pass orphans parameter to the Paginator class as mentioned below:

paginator = Paginator(filter_qs, 2, orphans=2)


问:
SQLServer - Is it possible to divide the results of the same column?
I have a table containing the input and output parameters of different APIs. Here is the structure of my database :

```<code>API : API_ID (PK), API_URI, API_DATE, API_DESCRIPTION

RELATION : API_PAR_ID (PK), APIPAR_API_ID (FK), APIPAR_PAR_ID (FK)

Parametre : PAR_ID (PK), PAR_NOM, PAR_TYPE
</code>```

The only way to differentiate if a parameter is input or output is the type.
If the type is NULL ? It is an output parameter.

So, I would like to know if it is possible in a simple query to make the difference between the two. That is, in my SELECT displayed in one column the name of the input parameters  and in another the output parameters, something that could look like this

SELECT
    [PAR_NOM] AS [INPUT]
    , [PAR_NOM] AS [OUPUT]
    , [PAR_type]
FROM Parametre AS P
    INNER JOIN RELATION AS R
        ON P.[PAR_ID] = R.[APIPAR_PAR_ID]
WHERE [APIPAR_PAR_ID] = 10```
</div>
</div>
</p>
<p>Or do I have to make two requests? One to get the input parameters, and another one for the output parameters?
Knowing that the columns are important because I intend to use them in an API</p>
<p>Sample data :</p>
```API : 1, 'API/DOC/V1', '08/02/2022', 'First api'
API : 2, 'API/SERVER/V1', '10/01/2022', 'Api call for the server'
API : 3, 'API/CITY/V2', '15/03/2022', 'Api to get name of cities'

PARAMETRE : 1, CODE_PO, 'string'
PARAMETRE : 2, REF_SO, NULL
PARAMETRE : 3, NB_AR, NULL

RELATION : 1, 1, 1
RELATION : 2, 1, 2
RELATION : 3, 2, 3
```
<p>Exemple result :</p>
```INPUT       OUTPUT      par_type
code_po     NULL        string
NULL        REF_SO      NULL
NULL        NB_AR       NULL
```

答:
In addition to a case, you can use IIF.</p>
```<code>SELECT IIF(PAR_type IS NOT NULL, PAR_NOM, NULL) [Input], IIF(PAR_type IS NULL, PAR_NOM, NULL) [Output], PAR_Type FROM Parametre
</code>```

Body:
I have a table containing the input and output parameters of different APIs. Here is the structure of my database :

API : API_ID (PK), API_URI, API_DATE, API_DESCRIPTION

RELATION : API_PAR_ID (PK), APIPAR_API_ID (FK), APIPAR_PAR_ID (FK)

Parametre : PAR_ID (PK), PAR_NOM, PAR_TYPE

The only way to differentiate if a parameter is input or output is the type.
If the type is NULL ? It is an output parameter.

So, I would like to know if it is possible in a simple query to make the difference between the two. That is, in my SELECT displayed in one column the name of the input parameters  and in another the output parameters, something that could look like this

SELECT
    [PAR_NOM] AS [INPUT]
    , [PAR_NOM] AS [OUPUT]
    , [PAR_type]
FROM Parametre AS P
    INNER JOIN RELATION AS R
        ON P.[PAR_ID] = R.[APIPAR_PAR_ID]
WHERE [APIPAR_PAR_ID] = 10

Or do I have to make two requests? One to get the input parameters, and another one for the output parameters?
Knowing that the columns are important because I intend to use them in an API

Sample data :

API : 1, 'API/DOC/V1', '08/02/2022', 'First api'
API : 2, 'API/SERVER/V1', '10/01/2022', 'Api call for the server'
API : 3, 'API/CITY/V2', '15/03/2022', 'Api to get name of cities'

PARAMETRE : 1, CODE_PO, 'string'
PARAMETRE : 2, REF_SO, NULL
PARAMETRE : 3, NB_AR, NULL

RELATION : 1, 1, 1
RELATION : 2, 1, 2
RELATION : 3, 2, 3

Exemple result :

INPUT       OUTPUT      par_type
code_po     NULL        string
NULL        REF_SO      NULL
NULL        NB_AR       NULL

Body:
In addition to a case, you can use IIF.

SELECT IIF(PAR_type IS NOT NULL, PAR_NOM, NULL) [Input], IIF(PAR_type IS NULL, PAR_NOM, NULL) [Output], PAR_Type FROM Parametre


问:
How to make dictionary using two lists which contains multiple values for one key?
I want to make a dictionary out of the two lists "a" and "b" in which a contains the keys and b contains values but the problem is that there are multiple values for one key

```<code>a=['Eng','Eng','Eng','Science', 'Science' ,'Hindi','Maths','Maths']
b=['Noun','Pronoun','Tenses','Light','Sound','Algebra','Probability']
</code>```

expected output should be like

```<code>{'Eng':['Noun','Pronoun','Tenses'],'Science':['Light','Sound'],'Maths':['Algebra','Probability']}
</code>```

答:
You can't do it directly because our system doesn't know why Noun belongs to English. To get this output, you must create a relation like.</p>
```<code>#Your expected relation
Eng = [ 'Noun' , ' Pronoun',  ' Tenses']
Hindi = ['Algebra']
Science = [ 'Light', 'Sound']
Maths = [' Probability']

#Your Given Data
a=['Eng','Eng','Eng','Science', 'Science' ,'Hindi','Maths','Maths']
b=['Noun','Pronoun','Tenses','Light','Sound','Algebra','Probability']

Answer={}
#eliminating multiple keys.
new_a=[]
for i in a:
    if i in new_a:
          new_a.append(i)
    else:
          pass

#Assign the values using key value pair.
</code>```

Body:
I want to make a dictionary out of the two lists "a" and "b" in which a contains the keys and b contains values but the problem is that there are multiple values for one key

a=['Eng','Eng','Eng','Science', 'Science' ,'Hindi','Maths','Maths']
b=['Noun','Pronoun','Tenses','Light','Sound','Algebra','Probability']

expected output should be like

{'Eng':['Noun','Pronoun','Tenses'],'Science':['Light','Sound'],'Maths':['Algebra','Probability']}

Body:
You can't do it directly because our system doesn't know why Noun belongs to English. To get this output, you must create a relation like.

#Your expected relation
Eng = [ 'Noun' , ' Pronoun',  ' Tenses']
Hindi = ['Algebra']
Science = [ 'Light', 'Sound']
Maths = [' Probability']

#Your Given Data
a=['Eng','Eng','Eng','Science', 'Science' ,'Hindi','Maths','Maths']
b=['Noun','Pronoun','Tenses','Light','Sound','Algebra','Probability']

Answer={}
#eliminating multiple keys.
new_a=[]
for i in a:
    if i in new_a:
          new_a.append(i)
    else:
          pass

#Assign the values using key value pair.


问:
HashMap Serializability
HashMap implements the Serializable interface; so it can be serialized. I have looked at the implementation of HashMap and the Entry[] table is marked as transient. Since the Entry[] table is the one that stores the entire contents of the Map and if it cannot be serialized, how is the Map constructed back during de-serialization</p>

答:
HashMaps don't serialize their Entry objects during serialization. Take a look at its writeObject method.

The javadocs explain:

The capacity of the HashMap (the length of the bucket array) is
  emitted (int), followed by the size (an int, the number of key-value
  mappings), followed by the key (Object) and value (Object) for each
  key-value mapping. The key-value mappings are emitted in no particular
  order.

If you look at the readObject method you will see how the Entry table is rebuilt using the size, keys and values.

ContentLicense: CC BY-SA 3.0

Title: HashMap Serializability


问:
Visual Studio Mac M1: Create android emulator
i am trying to create an android emulator for my project, however I cannot start the emulator from visual studio, only from android studio.

I find the created emulator in my list of emulators in both IDEs but only on android studio does it start.

This screenshot is from VS 2019:

You can see that the top emulator play button (created from android studio mac) is blank.

I then created my own emulatores using arm64.v8a architecture, and they both start but both stay blank.

I also noticed that in VS i can only give these emulators android 7.1 max all though i have never SDKs installed but only in 7.1 SDK manager states that there is arm64 included.

How can I start my emulator on M1 Mac from VS 2019 MAC?

Thank you!

答:
Allthough this states no longer needed, it IS still totally needed.

https://github.com/google/android-emulator-m1-preview

This will make all your problems dissappear in a heart beats. Supports XAML hot reload and is faster, even than iPhone simulators. Isnt that crazy


问:
How to refresh template of component by changing variable in other component Angular 13
I have component HeaderComponent with the following template :

```<code><button *ngIf="isConnected">Logout</button>
</code>```

And the template in composant LoginComponent

```<code><button (click)="login()">login</button>
</code>```

In AppComponent :

```<code><app-header></app-header>
<app-login></app-login>
</code>```

I would like to show Logout button when I click login button

Thank you for your helps

答:
Welcome Paul.

This is a good use case for a service. Generate a service with ng g service <path>/<serviceName>. Inside, we can put a subject that the HeaderComponent can subscribe to, and the LoginComponent can pass values to.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class LoginStateService {
  subject = new Subject<boolean>();
}
```
<p>You may actually want to bundle all of your login functions in this service, but I'll just describe setting the state for simplicity.</p>
<p>To subscribe in the <code>HeaderComponent</code></p>
<pre class="lang-js prettyprint-override"><code>loginSub = new Subscription();
isLoggedIn = false;

constructor(private loginState: LoginStateService) {}

ngOnInit(): void {
  this.loginSub = this.loginState.subject.subscribe(
    (value) => (this.isLoggedIn = value)
  );
}

ngOnDestroy(): void {
  this.loginSub.unsubscribe();
}
</code>```

Unsubscribing is probably not necessary here, but it's good practice to prevent memory leaks.

To pass a value from Login Component

constructor(private loginState: LoginStateService) {}

login() {
  //Do some login stuff
  this.loginState.subject.next(true);
}

logout() {
  //Do some logout stuff
  this.loginState.subject.next(false);
}
```

Body:
I have component HeaderComponent with the following template :

<button *ngIf="isConnected">Logout</button>

And the template in composant LoginComponent

<button (click)="login()">login</button>

In AppComponent :

<app-header></app-header>
<app-login></app-login>

I would like to show Logout button when I click login button

Thank you for your helps

Body:
Welcome Paul.

This is a good use case for a service. Generate a service with ng g service <path>/<serviceName>. Inside, we can put a subject that the HeaderComponent can subscribe to, and the LoginComponent can pass values to.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class LoginStateService {
  subject = new Subject<boolean>();
}

You may actually want to bundle all of your login functions in this service, but I'll just describe setting the state for simplicity.

To subscribe in the HeaderComponent

loginSub = new Subscription();
isLoggedIn = false;

constructor(private loginState: LoginStateService) {}

ngOnInit(): void {
  this.loginSub = this.loginState.subject.subscribe(
    (value) => (this.isLoggedIn = value)
  );
}

ngOnDestroy(): void {
  this.loginSub.unsubscribe();
}

Unsubscribing is probably not necessary here, but it's good practice to prevent memory leaks.

To pass a value from Login Component

constructor(private loginState: LoginStateService) {}

login() {
  //Do some login stuff
  this.loginState.subject.next(true);
}

logout() {
  //Do some logout stuff
  this.loginState.subject.next(false);
}


问:
Best way to merge the same feature to other branches
I have a terraform repo which has master, release, and develop branches. Each of the branch represent an environment (Dev, QA, Prod).

We manage changes or enhancement through feature branch. Question is after a new feature merged to develop branch, should we continue merging the same feature to release and master, or we should merge develop to release, and then merge release to master. Looks like either way will get the same the codes across all branches, but like to understand what's the best way for doing this. Thanks for any comments.

答:
There are two components to your questions. "What happens technically in Git?" and "What is a good work flow?" The first one is objective and you have answered yourself, and the second one is subjective as it is a matter of preference to which there is no right or wrong in Git. Stackoverflow is better suited for objective technical questions.

However, I am happy to give you my subjective personal preference which comes from GitFlow. Again, this is a workflow and not how Git works.

Create feature from develop. Once the new feature is done, merge feature to develop and then delete feature. Once you are ready to do a new release, then create release from master and merge develop to release. Do QA in release. Then merge release into master and then delete release. Then rebase develop to master and repeat.


问:
Emit after cancellation in Kotlin flow
I have a more complex version of the following code:

val testFlow = flow {
    try {
        // Continually emit some values
    } catch (e: CancellationException) {
        // Wrap up and emit finished state value
    }
}
```

When I collect this testFlow, I never receive the finished state value. It is documented that the flow builder performs ensureActive checks before emitting values. In this link is also an example using IntRange.asFlow that does not check for cancellation before emitting values and showing that those values are continued to be collected.

Is there a way to make a custom kotlin flow emit a last value to be collected after the cancellation of the coroutine?

Here's a Kotlin Playground example (thanks @Tenfour04) showing differing behaviour of emit after cancel depending on how the flow is constructed. I just don't know how to get a flow that's able to emit after cancel that is not constructed by IntRange.asFlow.

答:
IntRange.asFlow uses unsafeFlow internally which is defined as:

```<code>inline fun <T> unsafeFlow(crossinline block: suspend FlowCollector<T>.() -> Unit): Flow<T> {
    return object : Flow<T> {
        override suspend fun collect(collector: FlowCollector<T>) {
            collector.block()
        }
    }
}
</code>```

Using unsafeFlow one can emit even in cancelled coroutines, even though this solution is quite a hack and I would like to replace it with a more officially supported version that does not require to access internal Kotlin Coroutine APIs.

Note: Emitting after cancellation only works when using

```<code>try {
    ...
} catch (e: CancellationException) {
    ...
}
</code>```

and not using unsafeFlow.catch {}.

Title: Emit after cancellation in Kotlin flow

Body:
I have a more complex version of the following code:

val testFlow = flow {
    try {
        // Continually emit some values
    } catch (e: CancellationException) {
        // Wrap up and emit finished state value
    }
}

When I collect this testFlow, I never receive the finished state value. It is documented that the flow builder performs ensureActive checks before emitting values. In this link is also an example using IntRange.asFlow that does not check for cancellation before emitting values and showing that those values are continued to be collected.

Is there a way to make a custom kotlin flow emit a last value to be collected after the cancellation of the coroutine?

Here's a Kotlin Playground example (thanks @Tenfour04) showing differing behaviour of emit after cancel depending on how the flow is constructed. I just don't know how to get a flow that's able to emit after cancel that is not constructed by IntRange.asFlow.

Body:
IntRange.asFlow uses unsafeFlow internally which is defined as:

inline fun <T> unsafeFlow(crossinline block: suspend FlowCollector<T>.() -> Unit): Flow<T> {
    return object : Flow<T> {
        override suspend fun collect(collector: FlowCollector<T>) {
            collector.block()
        }
    }
}

Using unsafeFlow one can emit even in cancelled coroutines, even though this solution is quite a hack and I would like to replace it with a more officially supported version that does not require to access internal Kotlin Coroutine APIs.

Note: Emitting after cancellation only works when using

try {
    ...
} catch (e: CancellationException) {
    ...
}

and not using unsafeFlow.catch {}.


问:
What is int *(&) declaration in C++
I came across this piece of code

```<code>int a = 10;    ---> i)
int *p = &a;   ---> ii)
int *(&q) = p; ---> iii)
</code>```

Here in statement iii),  q seems to look like a pointer having the same value as p(after resolving)(reason). However, while we are still defining, &q tries to get the address of q which hasn't yet been created. So, how do you logically explain this in pointer terms? Any resources to explain this is also appreciated.

NOTE: I did compile and run the code, q points to a.

答:
Maybe you got confused by the brackets, lets remove them:

```<code>int *& q = p;
</code>```

Maybe you got confused by combination of * and & to form a reference to pointer, so lets try some obfuscation:

```<code>using T = int*;  // T is alias for pointer to int
T& q = p;
</code>```

T& q = p; declares q to be a reference to a T and initializes that reference with p.

Note that C does not have references as C++ has them.

Title: What is int *(&) declaration in C++

Body:
I came across this piece of code

int a = 10;    ---> i)
int *p = &a;   ---> ii)
int *(&q) = p; ---> iii)

Here in statement iii),  q seems to look like a pointer having the same value as p(after resolving)(reason). However, while we are still defining, &q tries to get the address of q which hasn't yet been created. So, how do you logically explain this in pointer terms? Any resources to explain this is also appreciated.

NOTE: I did compile and run the code, q points to a.

Body:
Maybe you got confused by the brackets, lets remove them:

int *& q = p;

Maybe you got confused by combination of * and & to form a reference to pointer, so lets try some obfuscation:

using T = int*;  // T is alias for pointer to int
T& q = p;

T& q = p; declares q to be a reference to a T and initializes that reference with p.

Note that C does not have references as C++ has them.


问:
Is there a way to use eval() and a dictionary if input could be None?
I have some code with a lot of stacked if statements that I'm trying to make more pythonic. One of the segments of code boils down to three separate "values".

```<code>0.9 if 10<x>=20
0.75 if x>20
1 if x<10 or x is None
</code>```

I tried sticking this in a dictionary to run through a function I made for a less complex (integers only) dictionary but am not sure how to handle None inputs.

```<code>def wallrat(val, table):
    try:
        # Create true/false list based on input value
        chks = [eval(v.replace('x',str(val))) for v in table.values()]
        # Find which value is true and verify that there's only one true value
        if True in chks and chks.count(True) == 1:
            # find the key that's true
            v = chks.index(True)
            table_list = list(table)
            # Loop through keys and values in dictionary
            return table_list[v]

age_dict = {0.9: '10< x >=20', 0.75: 'x > 20', 1:'x<10 or x is None'}
</code>```

The above code obviously errors since if x == None, it can't do the other evaluations of 10< None >=20. I'm not sure how to pythonically handle this situation. Is it even possible to have a dictionary that tests both None and ints/floats? Or am I stuck having to use only x < 10 and use a separate segment of code to output the value of 1 if the input is None?

EDIT: I don't want to delete the question, but ended up just utilizing an If ... is not 'None' and an else statement to capture the 'None' = 1 assignment.

Comments and answers may provide helpful reconsideration to others utilizing eval(). In my specific use-case, there is no way for the input to contain malicious strings due to what the input data is (GIS feature class tables with integer fields or a coded int variable based on input date fields). Regardless though, I wasn't aware of the concerns about using eval() and the comments provide good information IMO.

答:
If you want to achieve this if/else test in a single line, then using the python ternary syntax is probably the most readable option, and much safer & faster than eval with a dictionary of tests:

```<code>1 if x is None or x < 10 else 0.9 if 10 <= x <= 20 else 0.75
</code>```

Body:
I have some code with a lot of stacked if statements that I'm trying to make more pythonic. One of the segments of code boils down to three separate "values".

0.9 if 10<x>=20
0.75 if x>20
1 if x<10 or x is None

I tried sticking this in a dictionary to run through a function I made for a less complex (integers only) dictionary but am not sure how to handle None inputs.

def wallrat(val, table):
    try:
        # Create true/false list based on input value
        chks = [eval(v.replace('x',str(val))) for v in table.values()]
        # Find which value is true and verify that there's only one true value
        if True in chks and chks.count(True) == 1:
            # find the key that's true
            v = chks.index(True)
            table_list = list(table)
            # Loop through keys and values in dictionary
            return table_list[v]

age_dict = {0.9: '10< x >=20', 0.75: 'x > 20', 1:'x<10 or x is None'}

The above code obviously errors since if x == None, it can't do the other evaluations of 10< None >=20. I'm not sure how to pythonically handle this situation. Is it even possible to have a dictionary that tests both None and ints/floats? Or am I stuck having to use only x < 10 and use a separate segment of code to output the value of 1 if the input is None?

EDIT: I don't want to delete the question, but ended up just utilizing an If ... is not 'None' and an else statement to capture the 'None' = 1 assignment.

Comments and answers may provide helpful reconsideration to others utilizing eval(). In my specific use-case, there is no way for the input to contain malicious strings due to what the input data is (GIS feature class tables with integer fields or a coded int variable based on input date fields). Regardless though, I wasn't aware of the concerns about using eval() and the comments provide good information IMO.

Body:
If you want to achieve this if/else test in a single line, then using the python ternary syntax is probably the most readable option, and much safer & faster than eval with a dictionary of tests:

1 if x is None or x < 10 else 0.9 if 10 <= x <= 20 else 0.75


问:
error when i am installing yolo on ubuntu 20
when i run make command on darknet directory i get this error

./src/dark_cuda.c: In function ‘cuda_random’:
./src/dark_cuda.c:519:12: error: unknown type name ‘curandGenerator_t’

compilation terminated due to -Wfatal-errors.
make: *** [Makefile:177: obj/dark_cuda.o] Error 1

答:
Three things come to mind:

Don't build opencv yourself unless absolutely necessary.  It is a complex library, with many optional flags to pass in to get everything built correctly.  Instead, if you are on Ubuntu, you should be using a command such as sudo apt-get install libopencv-dev to get OpenCV installed correctly.

What version of CUDA and CUDNN are you using?  Are you certain they are installed correctly and are recent?  Darknet requirements are listed here:  https://github.com/AlexeyAB/darknet#requirements-for-windows-linux-and-macos
Note that specific versions of CUDA and CUDNN are listed.

Lastly, see the FAQ which contains an entry for building on Linux:  https://www.ccoderun.ca/programming/darknet_faq/#how_to_build_on_linux as well as a link to my youtube video showing you step-by-step how to build it: https://www.youtube.com/watch?v=pJ2iyf_E9PM


问:
How to save files to shared storage in Scoped storage?
I wanna save files to shared storage in scoped storage (in /storage/emulated/0/Download/), but As you know Environment.getExternalStorageDirectory() to access the root of external storage is deprecated in android 11 or higher (because Scoped storage is mandatory for all apps targeting Android 11).
Could you tell me a way to save and retrieve files to shared storage in scoped storage?</p>

答:
```<code>OutputStream outputStream;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName); // file name required to contain extestion file mime
            values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS+"/DIRECTORY_NAME"); //DIRECTORY
            Uri extVolumeUri = MediaStore.Files.getContentUri("external");
            Uri fileUri = context.getContentResolver().insert(extVolumeUri, values);
            outputStream = context.getContentResolver().openOutputStream(fileUri);
        }
        else {
            File root = new File(Environment.getExternalStorageDirectory()+File.separator+"DIRECTORY_NAME", "images");
            File file = new File(root, fileName );
            Log.d(TAG, "saveFile: file path - " + file.getAbsolutePath());
            outputStream = new FileOutputStream(file);
        }
        byte[] bytes = bodyData.getBytes();
        outputStream.write(bytes);
        outputStream.close();
</code>```