问:
Pod is not able to connect with local kafka running in my Kubernetes cluster at EKS
I have deployed confluent kafka cluster using the helm chart with following command in voice namespace.

```<code>helm install local-kafka --set cp-schema-registry.enabled=false,cp-kafka-rest.enabled=false,cp-kafka-connect.enabled=false confluentinc/cp-helm-charts --namespace voice
</code>```

As a result three zookeeper and three kafka brokers are up accessible at -

```<code>local-kafka-cp-kafka-headless:9092
or
local-kafka-cp-kafka.voice.svc.cluster.local:9092
</code>```

Later I installed the other  microservices in the cluster who will be producing data on topic and some other microservice would be consuming.

But I am getting following error when a microservice tried to produce event -

```<code>"message":"producer::error writing msg: dial tcp: lookup local-kafka-cp-kafka.voice.svc.cluster.local on 20.0.0.2:53: no such host"
</code>```

My services has some internal load balancer is also deployed. which is like -

```<code>internal-k8s-voice-myserver-85998808d7-3930233333.us-east-1.elb.amazonaws.com
</code>```

As per k8s documentation - the standard method to connect is

```<code>"{{ .Values.kafkasvc.name }}.{{ .Values.namespace }}.svc.cluster.local:9092

</code>```

EDIT -
Here are the kafka service definition -

Here are the pod description which is trying to access the kafka broker on local-kafka-cp-kafka.voice.svc.cluster.local:9092

P.S. - both kafka and microservice which is trying to connect the kafka are in same namespace voice.

Please help Thanks.

Body:
I have deployed confluent kafka cluster using the helm chart with following command in voice namespace.

helm install local-kafka --set cp-schema-registry.enabled=false,cp-kafka-rest.enabled=false,cp-kafka-connect.enabled=false confluentinc/cp-helm-charts --namespace voice

As a result three zookeeper and three kafka brokers are up accessible at -

local-kafka-cp-kafka-headless:9092
or
local-kafka-cp-kafka.voice.svc.cluster.local:9092

Later I installed the other  microservices in the cluster who will be producing data on topic and some other microservice would be consuming.

But I am getting following error when a microservice tried to produce event -

"message":"producer::error writing msg: dial tcp: lookup local-kafka-cp-kafka.voice.svc.cluster.local on 20.0.0.2:53: no such host"

My services has some internal load balancer is also deployed. which is like -

internal-k8s-voice-myserver-85998808d7-3930233333.us-east-1.elb.amazonaws.com

As per k8s documentation - the standard method to connect is

"{{ .Values.kafkasvc.name }}.{{ .Values.namespace }}.svc.cluster.local:9092

EDIT -
Here are the kafka service definition -

Here are the pod description which is trying to access the kafka broker on local-kafka-cp-kafka.voice.svc.cluster.local:9092

P.S. - both kafka and microservice which is trying to connect the kafka are in same namespace voice.

Please help Thanks.


来源: stackexchange

问:
Is it a bad thing to use window.location.reload instead of a form submit button?
I'm quite new to Web Dev and I'm making a management system app in react. I have a React bootstrap Form that the user can use to edit the details of an entry in a Modal. However, the way things are set up, I can't use the Form Submit event to reload the page after the entry has been changed because the buttons in the Modal need to be in a Form component to use the Form Submit an event. If I were to put the buttons in a Form component in the Modal Footer then it messes with the bootstrap stylings.

Is it a bad thing to just use window.location.reload() in my own onClick event to reload the page after editing?

my handleDetailsChange function will change the details and hide the modal (showing an updated form with all users)

is it bad to call window.location.reload() like this?

```<code>const EditRecordComp = (props) => {

  //gets the user details from the context and allows for it to be changed

  const userDetails = useContext(UserDetailsContext)
  //holding the new details in state
  const [newUserName, setNewUserName] = useState(userDetails.Name);
  const [newUserAddress, setNewUserAddress] = useState(userDetails.Address);

  const handleDetailsChange = () => {
    console.log("updating...")
    //updates the record in the server
    Axios.put('http://localhost:3001/updateuser', { newName: newUserName, newAddress: newUserAddress, IDRecord: userDetails.idBillingList })
      .then((response) => {
        console.log("updated client side")
      })
      .catch(error => {
        console.log(error.response)
      })
      .then(() => {
        //closes modal after
        props.handleEditClose();
        window.location.reload();
      });
  }

  return (

    <Modal show={props.showModal}>

      <Modal.Header closeButton>
        <Modal.Title>Edit User Details</Modal.Title>
      </Modal.Header>

      <Modal.Body>
        <Form>
          <Form.Group className="mb-3" controlId="formBasicEmail">
            <Form.Label>Name</Form.Label>
            <Form.Control
              type="email"
              placeholder={newUserName}
              value={newUserName}
              onChange={(e) => setNewUserName(e.target.value)} />
          </Form.Group>

          <Form.Group className="mb-3" controlId="formBasicText">
            <Form.Label>Address</Form.Label>
            <Form.Control
              type="text"
              placeholder={newUserAddress}
              value={newUserAddress}
              onChange={(e) => setNewUserAddress(e.target.value)} />
          </Form.Group>
        </Form>
      </Modal.Body>

      <Modal.Footer>
        <Button variant="secondary" onClick={props.handleEditClose}>
          Close
        </Button>
        <Button variant="primary" type="submit" onClick={handleDetailsChange}>
          Save Changes
        </Button>
      </Modal.Footer>
    </Modal>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm quite new to Web Dev and I'm making a management system app in react. I have a React bootstrap Form that the user can use to edit the details of an entry in a Modal. However, the way things are set up, I can't use the Form Submit event to reload the page after the entry has been changed because the buttons in the Modal need to be in a Form component to use the Form Submit an event. If I were to put the buttons in a Form component in the Modal Footer then it messes with the bootstrap stylings.

Is it a bad thing to just use window.location.reload() in my own onClick event to reload the page after editing?

my handleDetailsChange function will change the details and hide the modal (showing an updated form with all users)

is it bad to call window.location.reload() like this?

const EditRecordComp = (props) => {

  //gets the user details from the context and allows for it to be changed

  const userDetails = useContext(UserDetailsContext)
  //holding the new details in state
  const [newUserName, setNewUserName] = useState(userDetails.Name);
  const [newUserAddress, setNewUserAddress] = useState(userDetails.Address);

  const handleDetailsChange = () => {
    console.log("updating...")
    //updates the record in the server
    Axios.put('http://localhost:3001/updateuser', { newName: newUserName, newAddress: newUserAddress, IDRecord: userDetails.idBillingList })
      .then((response) => {
        console.log("updated client side")
      })
      .catch(error => {
        console.log(error.response)
      })
      .then(() => {
        //closes modal after
        props.handleEditClose();
        window.location.reload();
      });
  }

  return (

    <Modal show={props.showModal}>

      <Modal.Header closeButton>
        <Modal.Title>Edit User Details</Modal.Title>
      </Modal.Header>

      <Modal.Body>
        <Form>
          <Form.Group className="mb-3" controlId="formBasicEmail">
            <Form.Label>Name</Form.Label>
            <Form.Control
              type="email"
              placeholder={newUserName}
              value={newUserName}
              onChange={(e) => setNewUserName(e.target.value)} />
          </Form.Group>

          <Form.Group className="mb-3" controlId="formBasicText">
            <Form.Label>Address</Form.Label>
            <Form.Control
              type="text"
              placeholder={newUserAddress}
              value={newUserAddress}
              onChange={(e) => setNewUserAddress(e.target.value)} />
          </Form.Group>
        </Form>
      </Modal.Body>

      <Modal.Footer>
        <Button variant="secondary" onClick={props.handleEditClose}>
          Close
        </Button>
        <Button variant="primary" type="submit" onClick={handleDetailsChange}>
          Save Changes
        </Button>
      </Modal.Footer>
    </Modal>


问:
ffmpeg re-encode rtsp stream to H264 ONLY if stream is not H264
I have 100 rtsp cams streaming to my server, which does RTSP --> HLS for web viewers.

Most (about 90) rtsp cams are H264, but some can't be configured back to HEVC for some reasons.

Is there a command in FFMPEG to:

re-encode to H264 (preferrably using libx264) if stream is not H264

just do copy-frame if stream is already H264
?

ps: it's run using python/node with no-shell mode, so I'm not sure if bash-redirects/pipes work

tried ffmpeg commands


问:
WCF WebHttp Service using POCO from EntityFramework 4.1 - dbContext
I am trying to return a POCO in WCF WebHttp Service.  I am using EntityFramework 4.1 and generating the The entity is created entities using the DbContext Generator.

All works well with the EF.  I can query the database and work with the entities.  The problem comes from my WebHttp service.  When I try to return a list of these entities, I get Error 324 (empty response) and when I try to return a single entity object, I get the WCF error - "Request Error".  The service help page looks fine and sample responses are fine.

I tested the services by returning only the firstname of the entity changing the return type of the services to List and string.  This works fine.

I assumed (having looked at a tutorial on WCF WebHttp Service) that there is no need to add  [Serialize()] or other attributes to the entities.

I am lost as you why the service will not return an entity.

Thanks for any/all help.
ROB

Here is the code for the service...

```<code>[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class SearchService
{

    [WebGet(UriTemplate = "Students")]
    public List<coop_Students> GetStudents()
    {
        List<string> ret = new List<string>();

        CottageDataEntities db = new CottageDataEntities();
        var students = from s in db.coop_Students
                       where s.status == "enrolled"
                       orderby s.lastname, s.firstname
                       select s;
        return students.ToList();

    }

    [WebGet(UriTemplate = "Echo/{text}")]
    public string Echo(string text)
    {
        return "Hello " + text;
    }

    [WebGet(UriTemplate = "Students/{studentID}")]
    public coop_Students GetStudent(string studentID)
    {
        using (CottageDataEntities db = new CottageDataEntities())
        {
            int id = int.Parse(studentID);
            var student = db.coop_Students.FirstOrDefault(s => s.studentID == id);
            return student;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to return a POCO in WCF WebHttp Service.  I am using EntityFramework 4.1 and generating the The entity is created entities using the DbContext Generator.

All works well with the EF.  I can query the database and work with the entities.  The problem comes from my WebHttp service.  When I try to return a list of these entities, I get Error 324 (empty response) and when I try to return a single entity object, I get the WCF error - "Request Error".  The service help page looks fine and sample responses are fine.

I tested the services by returning only the firstname of the entity changing the return type of the services to List and string.  This works fine.

I assumed (having looked at a tutorial on WCF WebHttp Service) that there is no need to add  [Serialize()] or other attributes to the entities.

I am lost as you why the service will not return an entity.

Thanks for any/all help.
ROB

Here is the code for the service...

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class SearchService
{

    [WebGet(UriTemplate = "Students")]
    public List<coop_Students> GetStudents()
    {
        List<string> ret = new List<string>();

        CottageDataEntities db = new CottageDataEntities();
        var students = from s in db.coop_Students
                       where s.status == "enrolled"
                       orderby s.lastname, s.firstname
                       select s;
        return students.ToList();

    }

    [WebGet(UriTemplate = "Echo/{text}")]
    public string Echo(string text)
    {
        return "Hello " + text;
    }

    [WebGet(UriTemplate = "Students/{studentID}")]
    public coop_Students GetStudent(string studentID)
    {
        using (CottageDataEntities db = new CottageDataEntities())
        {
            int id = int.Parse(studentID);
            var student = db.coop_Students.FirstOrDefault(s => s.studentID == id);
            return student;
        }
    }
}


问:
How can I to get reactive overflowing of the component content
I get data from the API. Then I display them as a table using the q-table component. The description text can be large and if it does not fit, then I need to know this for each row(cell). Below is the code, how I get overflow now, but it is very costly. According to the terms of reference, it is necessary to display 600 lines at once.  And now it makes you wait...

May be there is a way to get it done cheaper?

Overflow detection function:

```<code>export function isOverflown({ clientWidth, clientHeight, scrollWidth, scrollHeight }: HTMLElement) {
  return scrollHeight > clientHeight || scrollWidth > clientWidth;
}
</code>```

Vue component:

```<code><template>
  <div class="q-pa-none">
    <q-table
      :columns="columns"
      :filter="filter"
      :loading="loading"
      :pagination="{ rowsPerPage: 0 }"
      :rows="$rows"
      binary-state-sort
      class="montserrat-medium no-shadow"
      hide-pagination
      row-key="id"
    >
      <template v-slot:body-cell-desc="props">
        <q-td :props="props">
          <p
            :ref="(e) => elements[props.rowIndex] = e as HTMLElement"
            :class="
              elements[props.rowIndex] && isOverflown(elements[props.rowIndex])
                ? 'td-desc-content-plate'
                : 'td-desc-content'
            "
            class="q-ma-none q-pa-none"
            v-text="props.row.desc"
          />
        </q-td>
      </template>
    </q-table>
  </div>
</template>

<script setup lang="ts">
  import { computed } from 'vue';

  import { isOverflown } from 'Shared/lib/dom';

  import type { QTableProps } from 'quasar';

  defineEmits([/* some emits*/]);

  const props = withDefaults(defineProps<{}>(),{/* some props */});

  const columns = computed<QTableProps['columns']>(() => [
    /* some columns */
    {
      align: 'left',
      field: 'desc',
      label: 'description',
      name: 'desc',
      sortable: false,
      style: 'white-space: pre-line; height: 100px; vertical-align: top',
    },
    /* some columns */
  ]);

  const $rows = computed<VerificationsValue[]>(() => props.rows);

  const elements: HTMLElement[] = [];
</script>
</code>```

Body:
I get data from the API. Then I display them as a table using the q-table component. The description text can be large and if it does not fit, then I need to know this for each row(cell). Below is the code, how I get overflow now, but it is very costly. According to the terms of reference, it is necessary to display 600 lines at once.  And now it makes you wait...

May be there is a way to get it done cheaper?

Overflow detection function:

export function isOverflown({ clientWidth, clientHeight, scrollWidth, scrollHeight }: HTMLElement) {
  return scrollHeight > clientHeight || scrollWidth > clientWidth;
}

Vue component:

<template>

    <q-table
      :columns="columns"
      :filter="filter"
      :loading="loading"
      :pagination="{ rowsPerPage: 0 }"
      :rows="$rows"
      binary-state-sort
      class="montserrat-medium no-shadow"
      hide-pagination
      row-key="id"
    >
      <template v-slot:body-cell-desc="props">
        <q-td :props="props">

 elements[props.rowIndex] = e as HTMLElement"
            :class="
              elements[props.rowIndex] && isOverflown(elements[props.rowIndex])
                ? 'td-desc-content-plate'
                : 'td-desc-content'
            "
            class="q-ma-none q-pa-none"
            v-text="props.row.desc"
          />
        </q-td>
      </template>
    </q-table>

</template>


问:
Powershell - The result of the previous command is displayed
I have a weird problem with my script.

The goal is to display a summary of the configuration of a server, and everything went fine until I arrived to Firewall and Disk configuration.

So, if I enter this command:

```<code>Get-NetFirewallProfile | Select-Object Name, Enabled
</code>```

It works, I have my Firewall status:
FW_status

if I enter this command:

```<code>get-volume | Select-Object -property DriveLetter, FileSystem, {$_.size /1GB} | Where-Object {$_.DriveLetter -ne $null -and $_.FileSystem -ne "`O"}
</code>```

it works too! I have my volume configuration:
Volume_conf

But... If I use these commands in a script, it doesn't work anymore. If the FW command is first and volume command is second, I only have the result of the FW.
If the Volume command is first, and the FW command is second, I only have the result of the Volume!

For example, if I do:

```<code>Write-host "Firewall command" -backgroundcolor green
Get-NetFirewallProfile | Select-Object Name, Enabled
Write-host "Volume command" -backgroundcolor green
get-volume | Select-Object -property DriveLetter, FileSystem, {$_.size /1GB} | Where-Object {$_.DriveLetter -ne $null -and $_.FileSystem -ne "`O"}
</code>```

I have this result:
FW_first

if I change the order, I have this result:
Volume_First

```<code>Firewall command

Volume command
Name    Enabled
----    -------
Domain     True
Private    True
Public     True
</code>```

I add that the problem is the same if I delete "Write-host" commands. I try on Powershell, Powershell ISE, and Visual Studio Code, and by using variables...Always the same result...

Does someone know what's going on, or what I do wrong?

Thanks for your help !

Body:
I have a weird problem with my script.

The goal is to display a summary of the configuration of a server, and everything went fine until I arrived to Firewall and Disk configuration.

So, if I enter this command:

Get-NetFirewallProfile | Select-Object Name, Enabled

It works, I have my Firewall status:
FW_status

if I enter this command:

get-volume | Select-Object -property DriveLetter, FileSystem, {$_.size /1GB} | Where-Object {$_.DriveLetter -ne $null -and $_.FileSystem -ne "`O"}

it works too! I have my volume configuration:
Volume_conf

But... If I use these commands in a script, it doesn't work anymore. If the FW command is first and volume command is second, I only have the result of the FW.
If the Volume command is first, and the FW command is second, I only have the result of the Volume!

For example, if I do:

Write-host "Firewall command" -backgroundcolor green
Get-NetFirewallProfile | Select-Object Name, Enabled
Write-host "Volume command" -backgroundcolor green
get-volume | Select-Object -property DriveLetter, FileSystem, {$_.size /1GB} | Where-Object {$_.DriveLetter -ne $null -and $_.FileSystem -ne "`O"}

I have this result:
FW_first

if I change the order, I have this result:
Volume_First

Firewall command

Volume command
Name    Enabled
----    -------
Domain     True
Private    True
Public     True

I add that the problem is the same if I delete "Write-host" commands. I try on Powershell, Powershell ISE, and Visual Studio Code, and by using variables...Always the same result...

Does someone know what's going on, or what I do wrong?

Thanks for your help !


问:
Can I use python structured unpacking to do general type checking?
I am reading that Python matching can do type-checking.

```<code>def sum_two_integers(num1, num2):
    match num1, num2:
        case int(num1), int(num2):
            return num1 + num2
        case _:    # Wrong type
</code>```

Is it possible to write a decorator that reads the function arguments' annotations and wraps any function with some matching to do strict run-time type checking?

I would like to do something along the lines of:

```<code>def my_checker(func):
   def wrapper(*args):
      for ((name, annotation), arg) in zip(func.__annotations__.items(), args):
           match arg:
              case (annotation??):
                  pass
              case _:
                  raise BadType
      func(*args)
   return wrapper

@my_checker
def some_func(...):
   ...
</code>```

The annotation is <class 'int'>. How can I use it in the match?

Are there any libraries already doing this? This is related, but doesn't use annotations.
Python: type checking decorator. (Also, yes I know type-checking isn't Pythonic).

Body:
I am reading that Python matching can do type-checking.

def sum_two_integers(num1, num2):
    match num1, num2:
        case int(num1), int(num2):
            return num1 + num2
        case _:    # Wrong type

Is it possible to write a decorator that reads the function arguments' annotations and wraps any function with some matching to do strict run-time type checking?

I would like to do something along the lines of:

def my_checker(func):
   def wrapper(*args):
      for ((name, annotation), arg) in zip(func.__annotations__.items(), args):
           match arg:
              case (annotation??):
                  pass
              case _:
                  raise BadType
      func(*args)
   return wrapper

@my_checker
def some_func(...):
   ...

The annotation is <class 'int'>. How can I use it in the match?

Are there any libraries already doing this? This is related, but doesn't use annotations.
Python: type checking decorator. (Also, yes I know type-checking isn't Pythonic).


问:
Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar (default-cli) on project maven-web-application
```<code>Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar (default-cli) on project maven-web-application.
NFO] --- sonar-maven-plugin:3.9.1.2184:sonar (default-cli) @ maven-web-application ---
[INFO] User cache: /var/lib/jenkins/.sonar/cache
[INFO] SonarQube version: 7.6.0
[INFO] Default locale: "en", source code encoding: "UTF-8"
[INFO] Load global settings
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.379 s
[INFO] Finished at: 2022-12-26T14:03:44Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar (default-cli) on project maven-web-application: Unable to load component class org.sonar.scanner.bootstrap.ScannerPluginInstaller: Unable to load component class org.sonar.scanner.bootstrap.PluginFiles: Unable to load component class org.sonar.scanner.bootstrap.GlobalConfiguration: Unable to load component class org.sonar.scanner.bootstrap.GlobalServerSettings: Unable to load settings: Protocol message end-group tag did not match expected tag. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

I have build maven project using java 8 and tomcat 8 and configured sonar with jdk 11. but I am getting below error after running command mvn sonar:sonar Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.7.0.1746:sonar (default-cli) on project project-name : Unable to execute SonarQube: Fail to get bootstrap index from server: Failed to connect to localhost/0:0:0:0:0:0:0:1:9000: Connection refused
I have tried changing the java version in the POM.xml file `

Body:
Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar (default-cli) on project maven-web-application.
NFO] --- sonar-maven-plugin:3.9.1.2184:sonar (default-cli) @ maven-web-application ---
[INFO] User cache: /var/lib/jenkins/.sonar/cache
[INFO] SonarQube version: 7.6.0
[INFO] Default locale: "en", source code encoding: "UTF-8"
[INFO] Load global settings
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.379 s
[INFO] Finished at: 2022-12-26T14:03:44Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar (default-cli) on project maven-web-application: Unable to load component class org.sonar.scanner.bootstrap.ScannerPluginInstaller: Unable to load component class org.sonar.scanner.bootstrap.PluginFiles: Unable to load component class org.sonar.scanner.bootstrap.GlobalConfiguration: Unable to load component class org.sonar.scanner.bootstrap.GlobalServerSettings: Unable to load settings: Protocol message end-group tag did not match expected tag. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

I have build maven project using java 8 and tomcat 8 and configured sonar with jdk 11. but I am getting below error after running command mvn sonar:sonar Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.7.0.1746:sonar (default-cli) on project project-name : Unable to execute SonarQube: Fail to get bootstrap index from server: Failed to connect to localhost/0:0:0:0:0:0:0:1:9000: Connection refused
I have tried changing the java version in the POM.xml file `


问:
How do I create a relationship from a nodeA to another specific child node related to the nodeA in a tree using cypher
'Alice'-[WORKS_FOR]->'Twitter'

'Tax2022'-[PROJECT_OF]->'Twitter'

I want to create a [HAS_READ_ACCESS] relation between 'Alice' that [WORKS_FOR] 'Twitter' and the 'Tax2022' [PROJECT_OF] 'Twitter'

Tried but did not work.

```<code>MATCH (u:User), (t:Tenant), (p:Project)
WHERE u.name = 'Alice' AND t.name = 'Twitter' AND p.Name = 'TAX2022'
MERGE (u)-[r:HAS_READ_ACCESS]->(p)
</code>```

Kindly Advice

Body:
'Alice'-[WORKS_FOR]->'Twitter'

'Tax2022'-[PROJECT_OF]->'Twitter'

I want to create a [HAS_READ_ACCESS] relation between 'Alice' that [WORKS_FOR] 'Twitter' and the 'Tax2022' [PROJECT_OF] 'Twitter'

Tried but did not work.

MATCH (u:User), (t:Tenant), (p:Project)
WHERE u.name = 'Alice' AND t.name = 'Twitter' AND p.Name = 'TAX2022'
MERGE (u)-[r:HAS_READ_ACCESS]->(p)

Kindly Advice


问:
Jackson JsonSerialize annotation not picked up when additional property is added to data class
I have two data classes and I'm trying to serialize them as follows:

```<code>data class Test1(@JsonSerialize (using = ToStringSerializer::class) val date: LocalDate, val number: Int)
data class Test2(@JsonSerialize (using = ToStringSerializer::class) val date: LocalDate, val number: Int, val duration: Duration)

class SerializeTest {
    @Test
    fun test(){
        val mapper = ObjectMapper().apply{
            enable(SerializationFeature.INDENT_OUTPUT)
            registerModule(kotlinModule())
            registerModule(JavaTimeModule())
        }
        val x = Test1(Clock.System.todayAt(TimeZone.UTC), 123)
        val y = Test2(Clock.System.todayAt(TimeZone.UTC), 1, 1.seconds)

        println(mapper.writeValueAsString(x))
        println(mapper.writeValueAsString(y))
    }
}
</code>```

(Note: the LocalDate and Duration types are Kotlin types, not the Java ones)

The output is:

```<code>{
  "date" : {
    "year" : 2022,
    "dayOfMonth" : 26,
    "month" : "DECEMBER",
    "dayOfWeek" : "MONDAY",
    "dayOfYear" : 360,
    "monthNumber" : 12,
    "value$kotlinx_datetime" : [ 2022, 12, 26 ]
  },
  "number" : 1,
  "duration" : 2000000000
}

{
  "date" : "2022-12-26",
  "number" : 123
}
</code>```

In the second class, ToStringSerializer is clearly not used to serialize the date property. As soon as I remove the duration property, or I change its class to e.g. String, it works as expected.

Why is this?

Body:
I have two data classes and I'm trying to serialize them as follows:

data class Test1(@JsonSerialize (using = ToStringSerializer::class) val date: LocalDate, val number: Int)
data class Test2(@JsonSerialize (using = ToStringSerializer::class) val date: LocalDate, val number: Int, val duration: Duration)

class SerializeTest {
    @Test
    fun test(){
        val mapper = ObjectMapper().apply{
            enable(SerializationFeature.INDENT_OUTPUT)
            registerModule(kotlinModule())
            registerModule(JavaTimeModule())
        }
        val x = Test1(Clock.System.todayAt(TimeZone.UTC), 123)
        val y = Test2(Clock.System.todayAt(TimeZone.UTC), 1, 1.seconds)

        println(mapper.writeValueAsString(x))
        println(mapper.writeValueAsString(y))
    }
}

(Note: the LocalDate and Duration types are Kotlin types, not the Java ones)

The output is:

{
  "date" : {
    "year" : 2022,
    "dayOfMonth" : 26,
    "month" : "DECEMBER",
    "dayOfWeek" : "MONDAY",
    "dayOfYear" : 360,
    "monthNumber" : 12,
    "value$kotlinx_datetime" : [ 2022, 12, 26 ]
  },
  "number" : 1,
  "duration" : 2000000000
}

{
  "date" : "2022-12-26",
  "number" : 123
}

In the second class, ToStringSerializer is clearly not used to serialize the date property. As soon as I remove the duration property, or I change its class to e.g. String, it works as expected.

Why is this?


问:
What is the situation 'header has been sent' when retrying during connection reset error in reactor-netty?
According to the source code and comments of HttpClientConnect.HttpObserver in reactor-netty, it retries to send request to the server when it got connection reset error unless it doesn't have headers sent.

            else if (handler.shouldRetry && AbortedException.isConnectionReset(error)) {
                HttpClientOperations ops = connection.as(HttpClientOperations.class);
                if (ops != null && ops.hasSentHeaders()) {
                    // In some cases the channel close event may be delayed and thus the connection to be
                    // returned to the pool and later the eviction functionality to remote it from the pool.
                    // In some rare cases the connection might be acquired immediately, before the channel close
                    // event and the eviction functionality be able to remove it from the pool, this may lead to I/O
                    // errors.
                    // Mark the connection as non-persistent here so that it is never returned to the pool and leave
                    // the channel close event to invalidate it.
                    ops.markPersistent(false);
                    // Disable retry if the headers or/and the body were sent
                    handler.shouldRetry = false;
```

What does 'have headers sent' mean in this?

Can you explain the situations or the process it works in high-level view?

Body:
According to the source code and comments of HttpClientConnect.HttpObserver in reactor-netty, it retries to send request to the server when it got connection reset error unless it doesn't have headers sent.

            else if (handler.shouldRetry && AbortedException.isConnectionReset(error)) {
                HttpClientOperations ops = connection.as(HttpClientOperations.class);
                if (ops != null && ops.hasSentHeaders()) {
                    // In some cases the channel close event may be delayed and thus the connection to be
                    // returned to the pool and later the eviction functionality to remote it from the pool.
                    // In some rare cases the connection might be acquired immediately, before the channel close
                    // event and the eviction functionality be able to remove it from the pool, this may lead to I/O
                    // errors.
                    // Mark the connection as non-persistent here so that it is never returned to the pool and leave
                    // the channel close event to invalidate it.
                    ops.markPersistent(false);
                    // Disable retry if the headers or/and the body were sent
                    handler.shouldRetry = false;

What does 'have headers sent' mean in this?

Can you explain the situations or the process it works in high-level view?


问:
ionic android app open white screen after splash and show Failed to get FIS auth token in logcat
I am trying to build and run moodle mobile app on android, but when I try to run it on real device it show splash screen and then show white screen and show in the logcat this error

```<code>E/FirebaseMessaging: Failed to get FIS auth token
    java.util.concurrent.ExecutionException: com.google.firebase.installations.FirebaseInstallationsException: Firebase Installations Service is unavailable. Please try again later.
        at com.google.android.gms.tasks.Tasks.zza(com.google.android.gms:play-services-tasks@@18.0.1:5)
        at com.google.android.gms.tasks.Tasks.await(com.google.android.gms:play-services-tasks@@18.0.1:8)
        at com.google.firebase.messaging.GmsRpc.setDefaultAttributesToBundle(GmsRpc.java:260)
        at com.google.firebase.messaging.GmsRpc.startRpc(GmsRpc.java:222)
        at com.google.firebase.messaging.GmsRpc.getToken(GmsRpc.java:180)
        at com.google.firebase.messaging.FirebaseMessaging.lambda$blockingGetToken$10$FirebaseMessaging(FirebaseMessaging.java:613)
        at com.google.firebase.messaging.-$$Lambda$FirebaseMessaging$1AYfBMlbEOJoTvXNS_TEZqpK2SY.start(Unknown Source:6)
        at com.google.firebase.messaging.RequestDeduplicator.getOrStartGetTokenRequest(RequestDeduplicator.java:67)
        at com.google.firebase.messaging.FirebaseMessaging.blockingGetToken(FirebaseMessaging.java:609)
        at com.google.firebase.messaging.SyncTask.maybeRefreshToken(SyncTask.java:123)
        at com.google.firebase.messaging.SyncTask.run(SyncTask.java:93)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at com.google.android.gms.common.util.concurrent.zza.run(com.google.android.gms:play-services-basement@@18.1.0:2)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: com.google.firebase.installations.FirebaseInstallationsException: Firebase Installations Service is unavailable. Please try again later.
        at com.google.firebase.installations.remote.FirebaseInstallationServiceClient.createFirebaseInstallation(FirebaseInstallationServiceClient.java:208)
        at com.google.firebase.installations.FirebaseInstallations.registerFidWithServer(FirebaseInstallations.java:536)
        at com.google.firebase.installations.FirebaseInstallations.doNetworkCallIfNecessary(FirebaseInstallations.java:390)
        at com.google.firebase.installations.FirebaseInstallations.lambda$doRegistrationOrRefresh$3$FirebaseInstallations(FirebaseInstallations.java:375)
        at com.google.firebase.installations.-$$Lambda$FirebaseInstallations$Kl2wdAe5utVajeTmV5LyfWUz3Bo.run(Unknown Source:4)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
</code>```

can anyone please help?

Body:
I am trying to build and run moodle mobile app on android, but when I try to run it on real device it show splash screen and then show white screen and show in the logcat this error

E/FirebaseMessaging: Failed to get FIS auth token
    java.util.concurrent.ExecutionException: com.google.firebase.installations.FirebaseInstallationsException: Firebase Installations Service is unavailable. Please try again later.
        at com.google.android.gms.tasks.Tasks.zza(com.google.android.gms:play-services-tasks@@18.0.1:5)
        at com.google.android.gms.tasks.Tasks.await(com.google.android.gms:play-services-tasks@@18.0.1:8)
        at com.google.firebase.messaging.GmsRpc.setDefaultAttributesToBundle(GmsRpc.java:260)
        at com.google.firebase.messaging.GmsRpc.startRpc(GmsRpc.java:222)
        at com.google.firebase.messaging.GmsRpc.getToken(GmsRpc.java:180)
        at com.google.firebase.messaging.FirebaseMessaging.lambda$blockingGetToken$10$FirebaseMessaging(FirebaseMessaging.java:613)
        at com.google.firebase.messaging.-$$Lambda$FirebaseMessaging$1AYfBMlbEOJoTvXNS_TEZqpK2SY.start(Unknown Source:6)
        at com.google.firebase.messaging.RequestDeduplicator.getOrStartGetTokenRequest(RequestDeduplicator.java:67)
        at com.google.firebase.messaging.FirebaseMessaging.blockingGetToken(FirebaseMessaging.java:609)
        at com.google.firebase.messaging.SyncTask.maybeRefreshToken(SyncTask.java:123)
        at com.google.firebase.messaging.SyncTask.run(SyncTask.java:93)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at com.google.android.gms.common.util.concurrent.zza.run(com.google.android.gms:play-services-basement@@18.1.0:2)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: com.google.firebase.installations.FirebaseInstallationsException: Firebase Installations Service is unavailable. Please try again later.
        at com.google.firebase.installations.remote.FirebaseInstallationServiceClient.createFirebaseInstallation(FirebaseInstallationServiceClient.java:208)
        at com.google.firebase.installations.FirebaseInstallations.registerFidWithServer(FirebaseInstallations.java:536)
        at com.google.firebase.installations.FirebaseInstallations.doNetworkCallIfNecessary(FirebaseInstallations.java:390)
        at com.google.firebase.installations.FirebaseInstallations.lambda$doRegistrationOrRefresh$3$FirebaseInstallations(FirebaseInstallations.java:375)
        at com.google.firebase.installations.-$$Lambda$FirebaseInstallations$Kl2wdAe5utVajeTmV5LyfWUz3Bo.run(Unknown Source:4)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)

can anyone please help?


问:
how can i get the current id of the document in flutter
i want to retrieve data from firestore by id and i can not get the current Id of user</p>
```<code>User? user = FirebaseAuth.instance.currentUser ;

   TextEditingController emailController = TextEditingController();
   TextEditingController nameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    getData();
  }

  void getData() async {
     final uid = user?.uid.toString();
    nameController.text = (await FirestoreService().getUsername('We1cubPzOO99YWYLVARB'))!;//my method here works correctly when i provide the id
    emailController.text = (await FirestoreService().getUseremail(uid))!  ;//here doesn't work
  }
</code>```

Body:
i want to retrieve data from firestore by id and i can not get the current Id of user

User? user = FirebaseAuth.instance.currentUser ;

   TextEditingController emailController = TextEditingController();
   TextEditingController nameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    getData();
  }

  void getData() async {
     final uid = user?.uid.toString();
    nameController.text = (await FirestoreService().getUsername('We1cubPzOO99YWYLVARB'))!;//my method here works correctly when i provide the id
    emailController.text = (await FirestoreService().getUseremail(uid))!  ;//here doesn't work
  }


问:
Unsatisfied dependency expressed. Error creating bean
When I run my AdminApplication I have these errors:

2022-12-26T17:48:50.618+03:00 ERROR 7276 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adminServiceImpl': Unsatisfied dependency expressed through field 'adminRepository': Error creating bean with name 'adminRepository' defined in com.store.library.repository.AdminRepository defined in @EnableJpaRepositories declared on AdminApplication: Not a managed type: class com.store.library.model.Admin
Error creating bean with name 'adminRepository' defined in com.store.library.repository.AdminRepository defined in @EnableJpaRepositories declared on AdminApplication: Not a managed type: class com.store.library.model.Admin
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.store.library.model.Admin

https://github.com/surbacim/storee

Perhaps the problem is related to the version of Spring Boot, since the video in which I did this uses the old version. But I still haven't figured out how to fix it.


问:
Performing update and delete operations with dropdown-list
I do it by typing the ids while updating or inserting the room information.
but it doesn't make sense to show id to the user. so I want to select the name of the dormitory over the id with dropdown.//////////////////////////////////////////

```<code>const client = require('../../db')
const express = require('express');
const app = express();
const cors = require("cors");

app.use(cors());
app.use(express.json()); //req.body

app.listen(2906, ()=>{
    console.log("Sever is now listening at port 5000");
})

client.connect();

app.get('/rooms', (req, res)=>{
    client.query(`Select * from rooms`, (err, result)=>{
        if(!err){
            res.send(result.rows);
        }
    });

})

app.get('/rooms/:roomid', (req, res)=>{
    client.query(`Select * from rooms where roomid=${req.params.roomid}`, (err, result)=>{
        if(!err){
            res.send(result.rows);
        }
    });

})

const bodyParser = require("body-parser");

app.use(bodyParser.json());

app.post('/rooms', (req, res)=> {
    const rooms = req.body;
    let insertQuery = `insert into rooms(dormitoryid ,capacity ,wc,price,roomno) values(
        '${rooms.dormitoryid}',
        '${rooms.capacity}',
        '${rooms.wc}',
        '${rooms.price}',
        '${rooms.roomno}')`

    client.query(insertQuery, (err, result)=>{
        if(!err){
            res.send('Insertion was successful')
        }
        else{ console.log(err.message) }
    })

})

app.put('/rooms/:roomid', (req, res)=> {
    let rooms = req.body;
    let updateQuery = `update rooms set
    dormitoryid= '${rooms.dormitoryid}',
    capacity= '${rooms.capacity}',
    wc= '${rooms.wc}',
    price= '${rooms.price}',
    roomno='${rooms.roomno}'
    where roomid = ${req.params.roomid}`

    client.query(updateQuery, (err, result)=>{
        if(!err){
            res.send('Update was successful')
        }
        else{ console.log(err.message) }
    })
    client.end;
    })

app.delete('/rooms/:roomid', (req, res)=> {
    const rooms = req.body;
    let insertQuery = `delete from rooms where roomid=${req.params.roomid}`

    client.query(insertQuery, (err, result)=>{
        if(!err){
            res.send('Deletion was successful')
        }
        else{ console.log(err.message) }
    })

})

</code>```

This is my database code.

```<code>import React, { useState } from 'react'

const AddDormitory = () => {

  const [nameofdormitory, setNameofdormitory] = useState("");
  const [locationid, setLocationid] = useState("");
  const [typeofdormitory ,setTypeofdormitory] = useState("");
  const [capacity, setCapacity] = useState("");
  const [checkintime, setCheckintime] = useState("");
  const [checkouttime, setCheckouttime] = useState("");
  const [numberofmeals, setNumberofmeals] = useState("");
  const [phone, setPhone] = useState("");

  const AddDormitory = async e => {
    e.preventDefault();
    try {
      const body = {nameofdormitory,locationid,typeofdormitory,capacity,checkintime,checkouttime,numberofmeals,phone};
      const response = await fetch("http://localhost:2103/dormitory1", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body)
      });

    } catch (err) {
      console.error(err.message);
    }
  };

  return (
    <>
    <body><script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"></link>
         <div className="mb-3 ">
          <form action="">
            <div className="form-row mx-auto">
              <div className="col col-lg-3">
                <input
                  value={nameofdormitory}
                  onChange={(e) => setNameofdormitory(e.target.value)}
                  className="form-control"
                  type="text"
                  placeholder="nameofdormitory"
                />
              </div>
              <div className="col col-lg-3">
                <input
                  value={locationid}
                  onChange={(e) => setLocationid(e.target.value)}
                  className="form-control"
                  type="text"
                  placeholder="locationid"
                />
              </div>
              <div className="col col-lg-3">
                <input
                  value={typeofdormitory}
                  onChange={(e) => setTypeofdormitory(e.target.value)}
                  className="form-control"
                  type="text"
                  placeholder="typeofdormitory"
                />
              </div>
              <div className="col col-lg-3">
                <input
                  value={capacity}
                  onChange={(e) => setCapacity(e.target.value)}
                  className="form-control"
                  type="number"
                  placeholder="capacity"
                />
              </div>
              <div className="col col-lg-3">
                <input
                  value={checkintime}
                  onChange={(e) => setCheckintime(e.target.value)}
                  className="form-control"
                  type="time"
                  placeholder="checkintime"
                />
              </div>
              <div className="col col-lg-3">
                <input
                  value={checkouttime}
                  onChange={(e) => setCheckouttime(e.target.value)}
                  className="form-control"
                  type="time"
                  placeholder="checkouttime"
                />
              </div>
              <div className="col col-lg-3">
                <input
                  value={numberofmeals}
                  onChange={(e) => setNumberofmeals(e.target.value)}
                  className="form-control"
                  type="number"
                  placeholder="numberofmeals"
                />
              </div>
              <div className="col col-lg-3">
                <input
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className="form-control"
                  type="text"
                  placeholder="phone"
                />
              </div>

              <button
                onClick={AddDormitory}
                type="submit"
                className="btn btn-primary"
              >
                Add
              </button>

            </div>
          </form>

        </div>
    </>
  )
}

export default AddDormitory
</code>```

my code where i add room

```<code>import React, { useState } from 'react'

const UpdateRooms = ({rooms}) => {
  const [dormitoryid, setDormitoryid] = useState(rooms.dormitoryid);
  const [capacity, setCapacity] = useState(rooms.capacity);
  const [wc, setWc] = useState(rooms.wc);
  const [price, setPrice] = useState(rooms.price);
  const [roomno, setRoomno] = useState(rooms.roomno);

  const UpdateValues = async e => {
    e.preventDefault();
    try {
      const body = { dormitoryid,capacity,wc,price,roomno};
      const response = await fetch(
        `http://localhost:2906/rooms/${rooms.roomid}`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body)
        }
      );

    } catch (err) {
      console.error(err.message);
    }
  };

  return (
    <>
   <button
        type="button"
        class="btn btn-warning"
        data-toggle="modal"
        data-target={`#id${rooms.roomid}`}
      >
        Edit
      </button>

      <div
        class="modal"
        id={`id${rooms.roomid}`}
        onClick={() => {setDormitoryid(rooms.dormitoryid)}}

      >
         <div
        class="modal1"
        id={`id${rooms.roomid}`}
        onClick={() => {setCapacity(rooms.capacity)}}

      >

      </div>
      <div
        class="modal2"
        id={`id${rooms.roomid}`}
        onClick={() => {setWc(rooms.wc)}}

      >

      </div>
       <div
        class="modal3"
        id={`id${rooms.roomid}`}
        onClick={() => {setPrice(rooms.price)}}

      >
       <div
        class="modal4"
        id={`id${rooms.roomid}`}
        onClick={() => {setRoomno(rooms.roomno)}}

      >

      </div>
      </div>
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title">Edit Location</h4>
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                onClick={() => setDormitoryid(rooms.dormitoryid)}
              >

              </button>
              <button
                type="button"
                class="close"
                data-dismiss="modal1"
                onClick={() => setCapacity(rooms.capacity)}
              >

              </button>
              <button
                type="button"
                class="close"
                data-dismiss="modal2"
                onClick={() => setWc(rooms.wc)}
              >

              </button>
              <button
                type="button"
                class="close"
                data-dismiss="modal3"
                onClick={() => setPrice(rooms.price)}
              >

              </button>
              <button
                type="button"
                class="close"
                data-dismiss="modal4"
                onClick={() => setRoomno(rooms.roomno)}
              >

              </button>
            </div>

            <div class="modal-body">
              <input
                type="text"
                className="form-control"
                value={dormitoryid}
                onChange={e => setDormitoryid(e.target.value)}
              />
              <input
                type="text"
                className="form-control"
                value={capacity}
                onChange={e => setCapacity(e.target.value)}
              />
              <input
                type="text"
                className="form-control"
                value={wc}
                onChange={e => setWc(e.target.value)}
              />
              <input
                type="text"
                className="form-control"
                value={price}
                onChange={e => setPrice(e.target.value)}
              />
               <input
                type="text"
                className="form-control"
                value={roomno}
                onChange={e => setRoomno(e.target.value)}
              />
            </div>

            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-warning"
                data-dismiss="modal"
                onClick={e => UpdateValues(e)}
              >
                Edit
              </button>
              <button
                type="button"
                class="btn btn-danger"
                data-dismiss="modal"
                onClick={() => (setDormitoryid(rooms.dormitoryid),setCapacity(rooms.capacity),setWc(rooms.wc),setPrice(rooms.price),setRoomno(rooms.roomno))}
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

    </>
  )
}

export default UpdateRooms

</code>```

my code where i update room

website

Body:
I do it by typing the ids while updating or inserting the room information.
but it doesn't make sense to show id to the user. so I want to select the name of the dormitory over the id with dropdown.//////////////////////////////////////////

const client = require('../../db')
const express = require('express');
const app = express();
const cors = require("cors");

app.use(cors());
app.use(express.json()); //req.body

app.listen(2906, ()=>{
    console.log("Sever is now listening at port 5000");
})

client.connect();

app.get('/rooms', (req, res)=>{
    client.query(`Select * from rooms`, (err, result)=>{
        if(!err){
            res.send(result.rows);
        }
    });

})

app.get('/rooms/:roomid', (req, res)=>{
    client.query(`Select * from rooms where roomid=${req.params.roomid}`, (err, result)=>{
        if(!err){
            res.send(result.rows);
        }
    });

})

const bodyParser = require("body-parser");

app.use(bodyParser.json());

app.post('/rooms', (req, res)=> {
    const rooms = req.body;
    let insertQuery = `insert into rooms(dormitoryid ,capacity ,wc,price,roomno) values(
        '${rooms.dormitoryid}',
        '${rooms.capacity}',
        '${rooms.wc}',
        '${rooms.price}',
        '${rooms.roomno}')`

    client.query(insertQuery, (err, result)=>{
        if(!err){
            res.send('Insertion was successful')
        }
        else{ console.log(err.message) }
    })

})

app.put('/rooms/:roomid', (req, res)=> {
    let rooms = req.body;
    let updateQuery = `update rooms set
    dormitoryid= '${rooms.dormitoryid}',
    capacity= '${rooms.capacity}',
    wc= '${rooms.wc}',
    price= '${rooms.price}',
    roomno='${rooms.roomno}'
    where roomid = ${req.params.roomid}`

    client.query(updateQuery, (err, result)=>{
        if(!err){
            res.send('Update was successful')
        }
        else{ console.log(err.message) }
    })
    client.end;
    })

app.delete('/rooms/:roomid', (req, res)=> {
    const rooms = req.body;
    let insertQuery = `delete from rooms where roomid=${req.params.roomid}`

    client.query(insertQuery, (err, result)=>{
        if(!err){
            res.send('Deletion was successful')
        }
        else{ console.log(err.message) }
    })

})

This is my database code.

import React, { useState } from 'react'

const AddDormitory = () => {

  const [nameofdormitory, setNameofdormitory] = useState("");
  const [locationid, setLocationid] = useState("");
  const [typeofdormitory ,setTypeofdormitory] = useState("");
  const [capacity, setCapacity] = useState("");
  const [checkintime, setCheckintime] = useState("");
  const [checkouttime, setCheckouttime] = useState("");
  const [numberofmeals, setNumberofmeals] = useState("");
  const [phone, setPhone] = useState("");

  const AddDormitory = async e => {
    e.preventDefault();
    try {
      const body = {nameofdormitory,locationid,typeofdormitory,capacity,checkintime,checkouttime,numberofmeals,phone};
      const response = await fetch("http://localhost:2103/dormitory1", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body)
      });

    } catch (err) {
      console.error(err.message);
    }
  };

  return (
    <>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"></link>

          <form action="">

                <input
                  value={nameofdormitory}
                  onChange={(e) => setNameofdormitory(e.target.value)}
                  className="form-control"
                  type="text"
                  placeholder="nameofdormitory"
                />

                <input
                  value={locationid}
                  onChange={(e) => setLocationid(e.target.value)}
                  className="form-control"
                  type="text"
                  placeholder="locationid"
                />

                <input
                  value={typeofdormitory}
                  onChange={(e) => setTypeofdormitory(e.target.value)}
                  className="form-control"
                  type="text"
                  placeholder="typeofdormitory"
                />

                <input
                  value={capacity}
                  onChange={(e) => setCapacity(e.target.value)}
                  className="form-control"
                  type="number"
                  placeholder="capacity"
                />

                <input
                  value={checkintime}
                  onChange={(e) => setCheckintime(e.target.value)}
                  className="form-control"
                  type="time"
                  placeholder="checkintime"
                />

                <input
                  value={checkouttime}
                  onChange={(e) => setCheckouttime(e.target.value)}
                  className="form-control"
                  type="time"
                  placeholder="checkouttime"
                />

                <input
                  value={numberofmeals}
                  onChange={(e) => setNumberofmeals(e.target.value)}
                  className="form-control"
                  type="number"
                  placeholder="numberofmeals"
                />

                <input
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className="form-control"
                  type="text"
                  placeholder="phone"
                />

              <button
                onClick={AddDormitory}
                type="submit"
                className="btn btn-primary"
              >
                Add
              </button>

          </form>

    </>
  )
}

export default AddDormitory

my code where i add room

import React, { useState } from 'react'

const UpdateRooms = ({rooms}) => {
  const [dormitoryid, setDormitoryid] = useState(rooms.dormitoryid);
  const [capacity, setCapacity] = useState(rooms.capacity);
  const [wc, setWc] = useState(rooms.wc);
  const [price, setPrice] = useState(rooms.price);
  const [roomno, setRoomno] = useState(rooms.roomno);

  const UpdateValues = async e => {
    e.preventDefault();
    try {
      const body = { dormitoryid,capacity,wc,price,roomno};
      const response = await fetch(
        `http://localhost:2906/rooms/${rooms.roomid}`,
        {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body)
        }
      );

    } catch (err) {
      console.error(err.message);
    }
  };

  return (
    <>
   <button
        type="button"
        class="btn btn-warning"
        data-toggle="modal"
        data-target={`#id${rooms.roomid}`}
      >
        Edit
      </button>

      <div
        class="modal"
        id={`id${rooms.roomid}`}
        onClick={() => {setDormitoryid(rooms.dormitoryid)}}

      >
         <div
        class="modal1"
        id={`id${rooms.roomid}`}
        onClick={() => {setCapacity(rooms.capacity)}}

      >

      <div
        class="modal2"
        id={`id${rooms.roomid}`}
        onClick={() => {setWc(rooms.wc)}}

      >

       <div
        class="modal3"
        id={`id${rooms.roomid}`}
        onClick={() => {setPrice(rooms.price)}}

      >
       <div
        class="modal4"
        id={`id${rooms.roomid}`}
        onClick={() => {setRoomno(rooms.roomno)}}

      >

Edit Location

              <button
                type="button"
                class="close"
                data-dismiss="modal"
                onClick={() => setDormitoryid(rooms.dormitoryid)}
              >

              </button>
              <button
                type="button"
                class="close"
                data-dismiss="modal1"
                onClick={() => setCapacity(rooms.capacity)}
              >

              </button>
              <button
                type="button"
                class="close"
                data-dismiss="modal2"
                onClick={() => setWc(rooms.wc)}
              >

              </button>
              <button
                type="button"
                class="close"
                data-dismiss="modal3"
                onClick={() => setPrice(rooms.price)}
              >

              </button>
              <button
                type="button"
                class="close"
                data-dismiss="modal4"
                onClick={() => setRoomno(rooms.roomno)}
              >

              </button>

              <input
                type="text"
                className="form-control"
                value={dormitoryid}
                onChange={e => setDormitoryid(e.target.value)}
              />
              <input
                type="text"
                className="form-control"
                value={capacity}
                onChange={e => setCapacity(e.target.value)}
              />
              <input
                type="text"
                className="form-control"
                value={wc}
                onChange={e => setWc(e.target.value)}
              />
              <input
                type="text"
                className="form-control"
                value={price}
                onChange={e => setPrice(e.target.value)}
              />
               <input
                type="text"
                className="form-control"
                value={roomno}
                onChange={e => setRoomno(e.target.value)}
              />

              <button
                type="button"
                class="btn btn-warning"
                data-dismiss="modal"
                onClick={e => UpdateValues(e)}
              >
                Edit
              </button>
              <button
                type="button"
                class="btn btn-danger"
                data-dismiss="modal"
                onClick={() => (setDormitoryid(rooms.dormitoryid),setCapacity(rooms.capacity),setWc(rooms.wc),setPrice(rooms.price),setRoomno(rooms.roomno))}
              >
                Close
              </button>

    </>
  )
}

export default UpdateRooms

my code where i update room

website


问:
How to index and search on LocalDateTime MultiField
I have a field of type LocalDateTime. I want to perform the wildcard and the range searches on this field. Initially, I defined it as:

```<code>// @formatter:off
@Field(
    name = "submission_date",
    type = FieldType.Date,
    format = DateFormat.date_hour_minute_second_fraction
)
// @formatter:on
private LocalDateTime submissionDate;
</code>```

When I indexed a Document, GET https://localhost:9200/my_index/_mapping returned the generated mapping as:

```<code>{
  "my_index": {
    "mappings": {
      "properties": {
        "_class": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "submission_date": {
          "type": "date"
        }
      }
    }
  }
}
</code>```

And GET https://localhost:9200/my_index/_search?q=*:* returned:

```<code>"_source": {
    "_class": "someclass",
    "submission_date": "2022-11-17T00:00:00.000"
}
</code>```

But I performed wildcard on it I got an error saying Can only use wildcard queries on keyword, text and wildcard fields - not on [submission_date] which is of type [date].

So I used MultiField as:

```<code>@MultiField(
    mainField = @Field(
        name = "submission_date",
        type = FieldType.Date,
        format = DateFormat.date_hour_minute_second_fraction
    ),
    otherFields = @InnerField(
        suffix = "verbatim",
        type = FieldType.Keyword,
        format = DateFormat.date_hour_minute_second_fraction
    )
)
// @formatter:on
private LocalDateTime submissionDate;
</code>```

Next after recreating the index when I indexed the Document again, the GET https://localhost:9200/my_index/_mapping returned the generated mapping as:

```<code>{
  "my_index": {
    "mappings": {
      "properties": {
        "_class": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "submission_date": {
          "type": "long"
        }
      }
    }
  }
}
</code>```

And GET https://localhost:9200/my_index/_search?q=*:* returned:

```<code>"_source": {
    "_class": "someclass",
    "submission_date": 1668623400000
}
</code>```

Clearly, the submission_date is not formatted as uuuu-MM-dd'T'HH:mm:ss.SSS.

Then when I performed the search, I got an error that says: No converter found capable of converting from type [java.lang.Long] to type [java.time.LocalDateTime] from org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound.

When this error occurred I was searching as

```<code>Mono<SearchResponse> response = elasticsearchOperations.searchForPage(query, MyClass.class)
</code>```

But when I changed it to

```<code>Mono<SearchResponse> response = elasticsearchOperations.searchForPage(query, AllDocuments.class, IndexCoordinates.of("my_index"))
</code>```

by following this blog-post, I got the result as {submission_date=1668623400000, id=7v8yT4UBHcWU9D_4JE6L}.

I am looking for the right way to achieve searching on this type of field where I will be able to perform both wildcard and range queries. Any pointers would be appreciated.

Body:
I have a field of type LocalDateTime. I want to perform the wildcard and the range searches on this field. Initially, I defined it as:

// @formatter:off
@Field(
    name = "submission_date",
    type = FieldType.Date,
    format = DateFormat.date_hour_minute_second_fraction
)
// @formatter:on
private LocalDateTime submissionDate;

When I indexed a Document, GET https://localhost:9200/my_index/_mapping returned the generated mapping as:

{
  "my_index": {
    "mappings": {
      "properties": {
        "_class": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "submission_date": {
          "type": "date"
        }
      }
    }
  }
}

And GET https://localhost:9200/my_index/_search?q=*:* returned:

"_source": {
    "_class": "someclass",
    "submission_date": "2022-11-17T00:00:00.000"
}

But I performed wildcard on it I got an error saying Can only use wildcard queries on keyword, text and wildcard fields - not on [submission_date] which is of type [date].

So I used MultiField as:

@MultiField(
    mainField = @Field(
        name = "submission_date",
        type = FieldType.Date,
        format = DateFormat.date_hour_minute_second_fraction
    ),
    otherFields = @InnerField(
        suffix = "verbatim",
        type = FieldType.Keyword,
        format = DateFormat.date_hour_minute_second_fraction
    )
)
// @formatter:on
private LocalDateTime submissionDate;

Next after recreating the index when I indexed the Document again, the GET https://localhost:9200/my_index/_mapping returned the generated mapping as:

{
  "my_index": {
    "mappings": {
      "properties": {
        "_class": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "submission_date": {
          "type": "long"
        }
      }
    }
  }
}

And GET https://localhost:9200/my_index/_search?q=*:* returned:

"_source": {
    "_class": "someclass",
    "submission_date": 1668623400000
}

Clearly, the submission_date is not formatted as uuuu-MM-dd'T'HH:mm:ss.SSS.

Then when I performed the search, I got an error that says: No converter found capable of converting from type [java.lang.Long] to type [java.time.LocalDateTime] from org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound.

When this error occurred I was searching as

Mono<SearchResponse> response = elasticsearchOperations.searchForPage(query, MyClass.class)

But when I changed it to

Mono<SearchResponse> response = elasticsearchOperations.searchForPage(query, AllDocuments.class, IndexCoordinates.of("my_index"))

by following this blog-post, I got the result as {submission_date=1668623400000, id=7v8yT4UBHcWU9D_4JE6L}.

I am looking for the right way to achieve searching on this type of field where I will be able to perform both wildcard and range queries. Any pointers would be appreciated.


问:
Address Sanitizer exit status
Address sanitizer always sets exit status ($?) 1 if it detects any memory leak, even if the test case passed successfully. I am using "$?" in my script to detect test case pass/fail status and need to ignore this mem error. Is there any option to disable this ? For ref we can use below example

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char *argv[]) {
    char *s = malloc(100);
    strcpy(s, "Hello world!");
    printf("string is: %s\n", s);
    //free(s);
    return 0;
}
</code>```

gcc ca.c -o leak -fsanitize=address -static-libasan

```<code>./leak
string is: Hello world!

=================================================================
==25465==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 100 byte(s) in 1 object(s) allocated from:
    #0 0x48c1ff in __interceptor_malloc ../../.././libsanitizer/asan/asan_malloc_linux.cpp:145
    #1 0x4cb1cd in main (/home/nipandey/junk1/leak+0x4cb1cd)
    #2 0x7f61f8886554 in __libc_start_main (/lib64/libc.so.6+0x22554)

SUMMARY: AddressSanitizer: 100 byte(s) leaked in 1 allocation(s).
</code>```

echo $?
1

Tries few options but no luck

Title: Address Sanitizer exit status

Body:
Address sanitizer always sets exit status ($?) 1 if it detects any memory leak, even if the test case passed successfully. I am using "$?" in my script to detect test case pass/fail status and need to ignore this mem error. Is there any option to disable this ? For ref we can use below example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char *argv[]) {
    char *s = malloc(100);
    strcpy(s, "Hello world!");
    printf("string is: %s\n", s);
    //free(s);
    return 0;
}

gcc ca.c -o leak -fsanitize=address -static-libasan

./leak
string is: Hello world!

=================================================================
==25465==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 100 byte(s) in 1 object(s) allocated from:
    #0 0x48c1ff in __interceptor_malloc ../../.././libsanitizer/asan/asan_malloc_linux.cpp:145
    #1 0x4cb1cd in main (/home/nipandey/junk1/leak+0x4cb1cd)
    #2 0x7f61f8886554 in __libc_start_main (/lib64/libc.so.6+0x22554)

SUMMARY: AddressSanitizer: 100 byte(s) leaked in 1 allocation(s).

echo $?
1

Tries few options but no luck


问:
What can I do to fix the Converter Error that happens to appear in application.yml file used to connect to Amazon Cognito user pool?
I have created an Elastic Beanstalk web app that uses Amazon Cognito and its user pool and Hosted UI for sign-in before the user can reach a page with the form. I currently have my own domain and SSL certificate for the app so the sign-in can be done via a secure connection. The issue is that the YAML file needed to use Amazon Cognito gives me this error:

```<code>Failed to bind properties under 'spring.security.oauth2.client.registration.clientsecret' to org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties$Registration:
    Reason: No converter found capable of converting from type [java.lang.String] to type [org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties$Registration]
</code>```

The YAML file structure looks like this:

```<code>spring:
  security:
    oauth2:
      client:
        registration:
          cognito:
          clientId: 47earg9gbo****
          clientSecret: bbvgpirvegmnr4gp4sunmp****
          scope: openid, email, aws.cognito.signin.user.admin, phone
          redirectUriTemplate: https://authorise.student.co.uk
          clientName: spring-boot
    provider:
      cognito:
        issuerUri: https://cognito-idp.eu-west-2.amazonaws.com/eu-west-2_BnR5***
</code>```

What I have done to try to fix this issue was recreated the whole user pool for Amazon Cognito and update the configuration of the pom.xml (<--spring has proposed this in the error message) file that looks as such:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>StudentCognito</groupId>
    <artifactId>StudentCognito</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>2.16.29</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <!--CORE-->
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>dynamodb-enhanced</artifactId>
            <version>2.11.0-PREVIEW</version>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>dynamodb</artifactId>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>sns</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${project.parent.version}</version>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Body:
I have created an Elastic Beanstalk web app that uses Amazon Cognito and its user pool and Hosted UI for sign-in before the user can reach a page with the form. I currently have my own domain and SSL certificate for the app so the sign-in can be done via a secure connection. The issue is that the YAML file needed to use Amazon Cognito gives me this error:

Failed to bind properties under 'spring.security.oauth2.client.registration.clientsecret' to org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties$Registration:
    Reason: No converter found capable of converting from type [java.lang.String] to type [org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties$Registration]

The YAML file structure looks like this:

spring:
  security:
    oauth2:
      client:
        registration:
          cognito:
          clientId: 47earg9gbo****
          clientSecret: bbvgpirvegmnr4gp4sunmp****
          scope: openid, email, aws.cognito.signin.user.admin, phone
          redirectUriTemplate: https://authorise.student.co.uk
          clientName: spring-boot
    provider:
      cognito:
        issuerUri: https://cognito-idp.eu-west-2.amazonaws.com/eu-west-2_BnR5***

What I have done to try to fix this issue was recreated the whole user pool for Amazon Cognito and update the configuration of the pom.xml (<--spring has proposed this in the error message) file that looks as such:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>StudentCognito</groupId>
    <artifactId>StudentCognito</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>2.16.29</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>dynamodb-enhanced</artifactId>
            <version>2.11.0-PREVIEW</version>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>dynamodb</artifactId>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>sns</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${project.parent.version}</version>
            </plugin>
        </plugins>
    </build>
</project>


问:
freemarker.getTemplate() in junit5
I have problem with test
This is my Service

```<code>@Service
@RequiredArgsConstructor
public class TextService {
    private final Configuration freemarker;
    private final TextRepository textRepository;
    private final ModelMaper modelMapper;

    public String search(String string, Pageable pageable) throws IOException, TemplateException {
            Request request = new Request();
            try {
                JAXBContext jaxbContext = JAXBContext.newInstance(Request.class);
                Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                request = (Request) unmarshaller.unmarshal(new StringReader(string));
            } catch (JAXBException e) {
                e.printStackTrace();
            }
            Page<Text> texts =
                  textRepository.findAllByTextContainingIgnoreCase(request.getText(), pageable);
            List<TextDTO> dtoList = modelMapper.mapAll(texts, TextDTO.class);
            List<Request> requestList = new ArrayList<>();

            for (TextDTO dto : dtoList) {
                Request r = new Request();
                r.setId(dto.getId());
                r.setText(dto.getText());
                r.setDateReg(dto.getDateReg().toString());
                requestList.add(r);
            }

            Template template = freemarker.getTemplate("response/request_response.xml");
            Writer writer = new StringWriter();
            template.process(Map.of("requests", requestList), writer);

            return writer.toString();
    }
</code>```

template.process(Map.of("requests", requestList), writer);

and this block give me

java.lang.NullPointerException: Cannot invoke "freemarker.template.Template.process(Object, java.io.Writer)" because "template" is null

And this is my Test

```<code>@ContextConfiguration(classes = {TextService.class})
@ExtendWith(SpringExtension.class)
@RunWith(SpringRunner.class)
class TextServiceTest {
    @Autowired
    private TextService textService;
    @MockBean
    private ModelMaper modelMapper;
    @MockBean
    private TextRepository textRepository;
    @MockBean
    private Configuration freemarker;

    @Test
    void testSearch() throws IOException, TemplateException {

        Writer writer = new StringWriter();

        Template template = freemarker.getTemplate("request_response.xml");;

        template.process(Map.of("requests", requestList), writer);
        Assert.assertEquals(expected, writer.toString());

    }
}
</code>```

Title: freemarker.getTemplate() in junit5

Body:
I have problem with test
This is my Service

@Service
@RequiredArgsConstructor
public class TextService {
    private final Configuration freemarker;
    private final TextRepository textRepository;
    private final ModelMaper modelMapper;

    public String search(String string, Pageable pageable) throws IOException, TemplateException {
            Request request = new Request();
            try {
                JAXBContext jaxbContext = JAXBContext.newInstance(Request.class);
                Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                request = (Request) unmarshaller.unmarshal(new StringReader(string));
            } catch (JAXBException e) {
                e.printStackTrace();
            }
            Page<Text> texts =
                  textRepository.findAllByTextContainingIgnoreCase(request.getText(), pageable);
            List<TextDTO> dtoList = modelMapper.mapAll(texts, TextDTO.class);
            List<Request> requestList = new ArrayList<>();

            for (TextDTO dto : dtoList) {
                Request r = new Request();
                r.setId(dto.getId());
                r.setText(dto.getText());
                r.setDateReg(dto.getDateReg().toString());
                requestList.add(r);
            }

            Template template = freemarker.getTemplate("response/request_response.xml");
            Writer writer = new StringWriter();
            template.process(Map.of("requests", requestList), writer);

            return writer.toString();
    }

template.process(Map.of("requests", requestList), writer);

and this block give me

java.lang.NullPointerException: Cannot invoke "freemarker.template.Template.process(Object, java.io.Writer)" because "template" is null

And this is my Test

@ContextConfiguration(classes = {TextService.class})
@ExtendWith(SpringExtension.class)
@RunWith(SpringRunner.class)
class TextServiceTest {
    @Autowired
    private TextService textService;
    @MockBean
    private ModelMaper modelMapper;
    @MockBean
    private TextRepository textRepository;
    @MockBean
    private Configuration freemarker;

    @Test
    void testSearch() throws IOException, TemplateException {

        Writer writer = new StringWriter();

        Template template = freemarker.getTemplate("request_response.xml");;

        template.process(Map.of("requests", requestList), writer);
        Assert.assertEquals(expected, writer.toString());

    }
}


问:
Display data of the current user in flutter
I want to display the trips saved by the current user. However, the app displayed every trip that is in the database even the ones that does not have the same uid as the current user. How do I fix this?

Here is the data saved in firestore:

below is how I grab the information:

```<code>Future getTrip() async{
FirebaseFirestore.instance
  .collection('trip')
  .where("userid", isEqualTo: user?.uid)
  .orderBy('date', descending: false)
  .orderBy('time', descending: false)
  .get()
  .then((ds) {
  ds.docs.forEach((data) {
    var tempList = {
      'dest': data['destination'],
      'desc': data['description'],
      'image': data['image'],
      'time': data['time'],
      'date': data['date'],
      'doc': data.id,
    };
    setState(() {
      trips.add(tempList);
    });
  });
});
</code>```

}

Then this is how I display my data:

```<code>trips.isNotEmpty ? ListView.builder(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemCount: trips.length,
        itemBuilder: (_, index){
          return Column(
            children: [
              Card(
                child: ListTile(
                leading: Image.network("${trips.elementAt(index)['image']}",fit: BoxFit.fitWidth,),
                title: Text("${trips.elementAt(index)['date']}"),
                subtitle: Text("${trips.elementAt(index)['dest']}\n${trips.elementAt(index)['time']}"),
                trailing:Wrap(
                  spacing: 5,
                  children: [
                    GestureDetector(
                      onTap:(){
                        Navigator.of(context).push(
                          MaterialPageRoute(builder: (context) => EditTrip(trip: trips[index])),
                        );
                      },
                      child: Icon(Icons.edit,color: Colors.lightBlue)
                    ),
                    GestureDetector(
                      onTap:(){
                        FirebaseFirestore.instance.collection('trip').doc('${trips.elementAt(index)['doc']}')
                        .delete()
                        .then((value) {
                          setState(() {
                            trips.removeAt(index);
                          });
                          Fluttertoast.showToast(
                            msg:'Trip Deleted',
                          );
                        }
                        ).catchError((e) => Fluttertoast.showToast(msg: "Error updating document $e"));
                      },
                      child: Icon(Icons.delete,color: Colors.red)
                    ),
                  ]
                ),
              ),
            ),
            ]
          );
        },
      )
      :Text('Your Itinerary is Empty...', style: TextStyle(fontSize: 16),),
</code>```

Body:
I want to display the trips saved by the current user. However, the app displayed every trip that is in the database even the ones that does not have the same uid as the current user. How do I fix this?

Here is the data saved in firestore:

below is how I grab the information:

Future getTrip() async{
FirebaseFirestore.instance
  .collection('trip')
  .where("userid", isEqualTo: user?.uid)
  .orderBy('date', descending: false)
  .orderBy('time', descending: false)
  .get()
  .then((ds) {
  ds.docs.forEach((data) {
    var tempList = {
      'dest': data['destination'],
      'desc': data['description'],
      'image': data['image'],
      'time': data['time'],
      'date': data['date'],
      'doc': data.id,
    };
    setState(() {
      trips.add(tempList);
    });
  });
});

}

Then this is how I display my data:

trips.isNotEmpty ? ListView.builder(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemCount: trips.length,
        itemBuilder: (_, index){
          return Column(
            children: [
              Card(
                child: ListTile(
                leading: Image.network("${trips.elementAt(index)['image']}",fit: BoxFit.fitWidth,),
                title: Text("${trips.elementAt(index)['date']}"),
                subtitle: Text("${trips.elementAt(index)['dest']}\n${trips.elementAt(index)['time']}"),
                trailing:Wrap(
                  spacing: 5,
                  children: [
                    GestureDetector(
                      onTap:(){
                        Navigator.of(context).push(
                          MaterialPageRoute(builder: (context) => EditTrip(trip: trips[index])),
                        );
                      },
                      child: Icon(Icons.edit,color: Colors.lightBlue)
                    ),
                    GestureDetector(
                      onTap:(){
                        FirebaseFirestore.instance.collection('trip').doc('${trips.elementAt(index)['doc']}')
                        .delete()
                        .then((value) {
                          setState(() {
                            trips.removeAt(index);
                          });
                          Fluttertoast.showToast(
                            msg:'Trip Deleted',
                          );
                        }
                        ).catchError((e) => Fluttertoast.showToast(msg: "Error updating document $e"));
                      },
                      child: Icon(Icons.delete,color: Colors.red)
                    ),
                  ]
                ),
              ),
            ),
            ]
          );
        },
      )
      :Text('Your Itinerary is Empty...', style: TextStyle(fontSize: 16),),


问:
Can two browser windows cause race conditions in synchronous JavaScript code?
I have the following function that synchronizes some locally cached data with my online database.

In the process, existing values are retrieved from the database, added to the locally cached values, and then sent as an update to the database. Because of this summing process, this procedure must not run multiple times in parallel because it could result in invalid values (adding more than it should).

I implemented a locking mechanism using local storage. It seems to work well because JavaScript is single-threaded and runs all the locking code synchronously, even if this function is called rapidly in succession.

The problem is, how do I also make this thread-safe across browser tabs/windows? The way I see it, multiple windows behave like separate threads, taking away the benefit of JavaScript's single-threading approach.

So 1) Is my assumption about multiple browser windows behaving like multiple threads correct and 2) How do I make my particular code safe across these different threads/processes?

```<code>export async function mergeCachedGameStats(supabaseClient: SupabaseClient) {
    const lockKey = "merge_cached_game_stats_lock";

    const lock = localStorage.getItem(lockKey);

    if (lock && (Date.now() - parseInt(lock) > 15_000)) localStorage.removeItem(lockKey);

    if (lock) return;

    localStorage.setItem(lockKey, Date.now().toString());

    try {
        const { data, error } = await supabaseClient?.auth.getSession();

        if (error) throw error;

        const loggedInUser = data.session?.user;

        for (const key of Object.values(gameStatsKeys)) {
            if (!localStorage.getItem(key + "_cached")) continue;

            const gameStats = await loadCombinedGameStats(key, supabaseClient);

            if (loggedInUser) {
                const { error } = await supabaseClient
                    .from("user_profiles")
                    .update({ [key]: JSON.stringify(gameStats) })
                    .eq("id", loggedInUser.id);

                if (error) throw error;
            } else {
                localStorage.setItem(key, JSON.stringify(gameStats));
            }
            localStorage.removeItem(key + "_cached");
        }
    } catch (error) {
        console.error(error);
    } finally {
        localStorage.removeItem(lockKey)
    }
}
</code>```

Body:
I have the following function that synchronizes some locally cached data with my online database.

In the process, existing values are retrieved from the database, added to the locally cached values, and then sent as an update to the database. Because of this summing process, this procedure must not run multiple times in parallel because it could result in invalid values (adding more than it should).

I implemented a locking mechanism using local storage. It seems to work well because JavaScript is single-threaded and runs all the locking code synchronously, even if this function is called rapidly in succession.

The problem is, how do I also make this thread-safe across browser tabs/windows? The way I see it, multiple windows behave like separate threads, taking away the benefit of JavaScript's single-threading approach.

So 1) Is my assumption about multiple browser windows behaving like multiple threads correct and 2) How do I make my particular code safe across these different threads/processes?

export async function mergeCachedGameStats(supabaseClient: SupabaseClient) {
    const lockKey = "merge_cached_game_stats_lock";

    const lock = localStorage.getItem(lockKey);

    if (lock && (Date.now() - parseInt(lock) > 15_000)) localStorage.removeItem(lockKey);

    if (lock) return;

    localStorage.setItem(lockKey, Date.now().toString());

    try {
        const { data, error } = await supabaseClient?.auth.getSession();

        if (error) throw error;

        const loggedInUser = data.session?.user;

        for (const key of Object.values(gameStatsKeys)) {
            if (!localStorage.getItem(key + "_cached")) continue;

            const gameStats = await loadCombinedGameStats(key, supabaseClient);

            if (loggedInUser) {
                const { error } = await supabaseClient
                    .from("user_profiles")
                    .update({ [key]: JSON.stringify(gameStats) })
                    .eq("id", loggedInUser.id);

                if (error) throw error;
            } else {
                localStorage.setItem(key, JSON.stringify(gameStats));
            }
            localStorage.removeItem(key + "_cached");
        }
    } catch (error) {
        console.error(error);
    } finally {
        localStorage.removeItem(lockKey)
    }
}


问:
How to customise Tutor LMS Quiz Pagination Section? As I want to give colour codes to unanswered questions
I am using Tutor LMS and I want to know how to customize Tutor LMS Quiz Pagination Section. As I want to give colour codes to unanswered questions!

I was able to find the same functions in LearnDash LMS go by the name of review questions and I am expecting something similar to that. Please find the image as ref.

Review questions while attempting quiz by color code