问:
Nifi cluster's second node fails to start again during unexpected shutdown
I have deployed a nifi cluster in k8 using the following yaml file.

```<code>apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: nifi
  namespace: release
  labels:
    app: nifi
    release: nifi
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nifi
      release: nifi
  template:
    metadata:
      labels:
        app: nifi
        release: nifi
      annotations:
        security.alpha.kubernetes.io/sysctls: net.ipv4.ip_local_port_range=10000 65000
    spec:
      volumes:
        - name: bootstrap-conf
          configMap:
            name: nifi-config
            items:
              - key: bootstrap.conf
                path: bootstrap.conf
            defaultMode: 420
        - name: nifi-properties
          configMap:
            name: nifi-config
            items:
              - key: nifi.properties
                path: nifi.temp
            defaultMode: 420
        - name: authorizers-temp
          configMap:
            name: nifi-config
            items:
              - key: authorizers.xml
                path: authorizers.temp
            defaultMode: 420
        - name: bootstrap-notification-services-xml
          configMap:
            name: nifi-config
            items:
              - key: bootstrap-notification-services.xml
                path: bootstrap-notification-services.xml
            defaultMode: 420
        - name: login-identity-providers-ldap-xml
          configMap:
            name: nifi-config
            items:
              - key: login-identity-providers-ldap.xml
                path: login-identity-providers-ldap.xml
            defaultMode: 420
        - name: state-management-xml
          configMap:
            name: nifi-config
            items:
              - key: state-management.xml
                path: state-management.xml
            defaultMode: 420
        - name: zookeeper-properties
          configMap:
            name: nifi-config
            items:
              - key: zookeeper.properties
                path: zookeeper.properties
            defaultMode: 420
        - name: flow-content
          configMap:
            name: nifi-config
            items:
              - key: flow.xml
                path: flow.xml
            defaultMode: 420
      containers:
        - name: server
          image: apache/nifi:latest
          command:
            - bash
            - '-ce'
            - >
              prop_replace () {
                target_file=${NIFI_HOME}/conf/${3:-nifi.properties}
                echo "updating ${1} in ${target_file}"
                if egrep "^${1}=" ${target_file} &> /dev/null; then
                  sed -i -e "s|^$1=.*$|$1=$2|"  ${target_file}
                else
                  echo ${1}=${2} >> ${target_file}
                fi
              }

              mkdir -p ${NIFI_HOME}/config-data/conf

              FQDN=$(hostname -f)

              cat "${NIFI_HOME}/conf/nifi.temp" >
              "${NIFI_HOME}/conf/nifi.properties"

              bin/nifi.sh set-single-user-credentials username changemechangeme

              if ! test -f /opt/nifi/data/flow.xml.gz && test -f
              /opt/nifi/data/flow.xml; then
                gzip /opt/nifi/data/flow.xml
              fi

              prop_replace nifi.remote.input.host ${FQDN}

              prop_replace nifi.cluster.node.address ${FQDN}

              prop_replace nifi.zookeeper.connect.string
              ${NIFI_ZOOKEEPER_CONNECT_STRING}

              prop_replace nifi.web.http.host ${FQDN}

              if [ ! -r "${NIFI_HOME}/conf/nifi-cert.pem" ]

              then
                /opt/nifi/nifi-toolkit-current/bin/tls-toolkit.sh standalone \
                  -n 'nifi-nifi-0.nifi-nifi-headless.release.svc.cluster.local' \
                  -C 'CN=admin, OU=NIFI' \
                  -o "${NIFI_HOME}/conf/" \
                  -P changeMe \
                  -S changeMe \
                  --nifiPropertiesFile /opt/nifi/nifi-current/conf/nifi.properties
              fi

              for f in "${NIFI_HOME}/conf/authorizers.xml"
              "${NIFI_HOME}/conf/login-identity-providers.xml"
              ${NIFI_HOME}/conf/nifi.properties

              do
                echo === $f ===
                cat $f
              done

              echo === end of files ===

              function prop () {
                target_file=${NIFI_HOME}/conf/nifi.properties
                egrep "^${1}=" ${target_file} | cut -d'=' -f2
              }

              function offloadNode() {
                  FQDN=$(hostname -f)
                  echo "disconnecting node '$FQDN'"
                  baseUrl=https://${FQDN}:8443

                  echo "keystoreType=$(prop nifi.security.keystoreType)" > secure.properties
                  echo "keystore=$(prop nifi.security.keystore)" >> secure.properties
                  echo "keystorePasswd=$(prop nifi.security.keystorePasswd)" >> secure.properties
                  echo "truststoreType=$(prop nifi.security.truststoreType)" >> secure.properties
                  echo "truststore=$(prop nifi.security.truststore)" >> secure.properties
                  echo "truststorePasswd=$(prop nifi.security.truststorePasswd)" >> secure.properties
                  echo "proxiedEntity=CN=admin, OU=NIFI" >> secure.properties

                  secureArgs="-p secure.properties"

                  echo baseUrl ${baseUrl}
                  echo "gracefully disconnecting node '$FQDN' from cluster"
                  ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi get-nodes -ot json -u ${baseUrl} ${secureArgs} > nodes.json
                  nnid=$(jq --arg FQDN "$FQDN" '.cluster.nodes[] | select(.address==$FQDN) | .nodeId' nodes.json)
                  echo "disconnecting node ${nnid}"
                  ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi disconnect-node -nnid $nnid -u ${baseUrl} ${secureArgs}
                  echo ""
                  echo "get a connected node"
                  connectedNode=$(jq -r 'first(.cluster.nodes|=sort_by(.address)| .cluster.nodes[] | select(.status=="CONNECTED")) | .address' nodes.json)
                  baseUrl=https://${connectedNode}:8443
                  echo baseUrl ${baseUrl}
                  echo ""
                  echo "wait until node has state 'DISCONNECTED'"
                  while [[ "${node_state}" != "DISCONNECTED" ]]; do
                      sleep 1
                      ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi get-nodes -ot json -u ${baseUrl} ${secureArgs} > nodes.json
                      node_state=$(jq -r --arg FQDN "$FQDN" '.cluster.nodes[] | select(.address==$FQDN) | .status' nodes.json)
                      echo "state is '${node_state}'"
                  done
                  echo ""
                  echo "node '${nnid}' was disconnected"
                  echo "offloading node"
                  ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi offload-node -nnid $nnid -u ${baseUrl} ${secureArgs}
                  echo ""
                  echo "wait until node has state 'OFFLOADED'"
                  while [[ "${node_state}" != "OFFLOADED" ]]; do
                      sleep 1
                      ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi get-nodes -ot json -u ${baseUrl} ${secureArgs} > nodes.json
                      node_state=$(jq -r --arg FQDN "$FQDN" '.cluster.nodes[] | select(.address==$FQDN) | .status' nodes.json)
                      echo "state is '${node_state}'"
                  done
              }

              deleteNode() {
                  echo "deleting node"
                  ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi delete-node -nnid ${nnid} -u ${baseUrl} ${secureArgs}
                  echo "node deleted"
              }

              executeTrap() {
                 echo Received trapped signal, beginning shutdown...;
                 ./bin/nifi.sh stop;
                 exit 0;
              }

              trap executeTrap TERM HUP INT;

              trap ":" EXIT

              exec bin/nifi.sh run & nifi_pid="$!"

              echo NiFi running with PID ${nifi_pid}.

              wait ${nifi_pid}
          ports:
            - name: https
              containerPort: 8443
              protocol: TCP
            - name: cluster
              containerPort: 6007
              protocol: TCP
          env:
            - name: NIFI_ZOOKEEPER_CONNECT_STRING
              value: nifi-zookeeper:2181
            - name: NIFI_WEB_HTTPS_HOST
              value: 0.0.0.0
          resources: {}
          volumeMounts:
            - name: my-logs
              mountPath: /opt/nifi/nifi-current/logs
            - name: my-data
              mountPath: /opt/nifi/data
            - name: my-auth-conf
              mountPath: /opt/nifi/nifi-current/auth-conf/
            - name: my-config-data
              mountPath: /opt/nifi/nifi-current/config-data
            - name: my-flowfile-repository
              mountPath: /opt/nifi/flowfile_repository
            - name: my-content-repository
              mountPath: /opt/nifi/content_repository
            - name: my-provenance-repository
              mountPath: /opt/nifi/provenance_repository
            - name: my-nifi-input
              mountPath: /opt/nifi/nifi_input
            - name: my-nifi-output
              mountPath: /opt/nifi/nifi_output
            - name: my-nifi-release-config
              mountPath: /opt/nifi/nifi_release_config
            - name: bootstrap-conf
              mountPath: /opt/nifi/nifi-current/conf/bootstrap.conf
              subPath: bootstrap.conf
            - name: nifi-properties
              mountPath: /opt/nifi/nifi-current/conf/nifi.temp
              subPath: nifi.temp
            - name: authorizers-temp
              mountPath: /opt/nifi/nifi-current/conf/authorizers.temp
              subPath: authorizers.temp
            - name: bootstrap-notification-services-xml
              mountPath: /opt/nifi/nifi-current/conf/bootstrap-notification-services.xml
              subPath: bootstrap-notification-services.xml
            - name: login-identity-providers-ldap-xml
              mountPath: /opt/nifi/nifi-current/conf/login-identity-providers-ldap.xml
              subPath: login-identity-providers-ldap.xml
            - name: state-management-xml
              mountPath: /opt/nifi/nifi-current/conf/state-management.xml
              subPath: state-management.xml
            - name: zookeeper-properties
              mountPath: /opt/nifi/nifi-current/conf/zookeeper.properties
              subPath: zookeeper.properties
            - name: flow-content
              mountPath: /opt/nifi/data/flow.xml
              subPath: flow.xml
          livenessProbe:
            tcpSocket:
              port: 8443
            initialDelaySeconds: 90
            timeoutSeconds: 1
            periodSeconds: 60
            successThreshold: 1
            failureThreshold: 3
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
        - name: app-log
          image: busybox:1.32.0
          args:
            - /bin/sh
            - '-c'
            - trap "exit 0" TERM; tail -n+1 -F /var/log/nifi-app.log & wait $!
          resources:
            limits:
              cpu: 50m
              memory: 50Mi
            requests:
              cpu: 10m
              memory: 10Mi
          volumeMounts:
            - name: my-logs
              mountPath: /var/log
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
        - name: bootstrap-log
          image: busybox:1.32.0
          args:
            - /bin/sh
            - '-c'
            - >-
              trap "exit 0" TERM; tail -n+1 -F /var/log/nifi-bootstrap.log &
              wait $!
          resources:
            limits:
              cpu: 50m
              memory: 50Mi
            requests:
              cpu: 10m
              memory: 10Mi
          volumeMounts:
            - name: my-logs
              mountPath: /var/log
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
        - name: user-log
          image: busybox:1.32.0
          args:
            - /bin/sh
            - '-c'
            - trap "exit 0" TERM; tail -n+1 -F /var/log/nifi-user.log & wait $!
          resources:
            limits:
              cpu: 50m
              memory: 50Mi
            requests:
              cpu: 10m
              memory: 10Mi
          volumeMounts:
            - name: my-logs
              mountPath: /var/log
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      serviceAccountName: default
      serviceAccount: default
      securityContext:
        runAsUser: 1000
        fsGroup: 1000
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 1
              podAffinityTerm:
                labelSelector:
                  matchExpressions:
                    - key: app
                      operator: In
                      values:
                        - nifi
                topologyKey: kubernetes.io/hostname
      schedulerName: default-scheduler
  volumeClaimTemplates:
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-logs
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 5Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-config-data
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 100Mi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-data
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 1Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-flowfile-repository
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-content-repository
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-provenance-repository
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-auth-conf
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 100Mi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-nifi-input
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-nifi-output
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-nifi-release-config
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 100Mi
        volumeMode: Filesystem
  serviceName: nifi-headless
  podManagementPolicy: Parallel
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      partition: 0
  revisionHistoryLimit: 10
</code>```

As you can see I have several local volumes that I am binding, so that my data persists even if the entire cluster fails. During testing, after feeding the flow some data and shutting down the k8 cluster, on restart I get the following issue.

```<code>2022-12-28 15:49:41,632 ERROR [NiFi logging handler] org.apache.nifi.StdErr Failed to start web server: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityFilterChain' defined in org.apache.nifi.web.NiFiWebApiSecurityConfiguration: Unsatisfied dependency expressed through method 'securityFilterChain' parameter 2; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.apache.nifi.web.security.configuration.JwtAuthenticationSecurityConfiguration': Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'idpUserGroupService' defined in class path resource [nifi-administration-context.xml]: Cannot resolve reference to bean 'idpTransactionBuilder' while setting bean property 'transactionBuilder'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'idpTransactionBuilder' defined in class path resource [nifi-administration-context.xml]: Cannot resolve reference to bean 'idpDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'idpDataSource': FactoryBean threw exception on object creation; nested exception is org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database may be already in use: "/opt/nifi/data/database_repository/nifi-identity-providers.mv.db". Possible solutions: close all other connection(s); use the server mode [90020-214]
2022-12-28 15:49:41,633 ERROR [NiFi logging handler] org.apache.nifi.StdErr Shutting down...
</code>```

Nifi-0 works, but nifi-1 keeps failing and going through multiple restarts. I'm assuming from the logs, the issue is that the database is still in use which is why the second node fails. I want to avoid deleting the contents of the database repository, so any other solutions are much appreciated. Thank you.

Body:
I have deployed a nifi cluster in k8 using the following yaml file.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: nifi
  namespace: release
  labels:
    app: nifi
    release: nifi
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nifi
      release: nifi
  template:
    metadata:
      labels:
        app: nifi
        release: nifi
      annotations:
        security.alpha.kubernetes.io/sysctls: net.ipv4.ip_local_port_range=10000 65000
    spec:
      volumes:
        - name: bootstrap-conf
          configMap:
            name: nifi-config
            items:
              - key: bootstrap.conf
                path: bootstrap.conf
            defaultMode: 420
        - name: nifi-properties
          configMap:
            name: nifi-config
            items:
              - key: nifi.properties
                path: nifi.temp
            defaultMode: 420
        - name: authorizers-temp
          configMap:
            name: nifi-config
            items:
              - key: authorizers.xml
                path: authorizers.temp
            defaultMode: 420
        - name: bootstrap-notification-services-xml
          configMap:
            name: nifi-config
            items:
              - key: bootstrap-notification-services.xml
                path: bootstrap-notification-services.xml
            defaultMode: 420
        - name: login-identity-providers-ldap-xml
          configMap:
            name: nifi-config
            items:
              - key: login-identity-providers-ldap.xml
                path: login-identity-providers-ldap.xml
            defaultMode: 420
        - name: state-management-xml
          configMap:
            name: nifi-config
            items:
              - key: state-management.xml
                path: state-management.xml
            defaultMode: 420
        - name: zookeeper-properties
          configMap:
            name: nifi-config
            items:
              - key: zookeeper.properties
                path: zookeeper.properties
            defaultMode: 420
        - name: flow-content
          configMap:
            name: nifi-config
            items:
              - key: flow.xml
                path: flow.xml
            defaultMode: 420
      containers:
        - name: server
          image: apache/nifi:latest
          command:
            - bash
            - '-ce'
            - >
              prop_replace () {
                target_file=${NIFI_HOME}/conf/${3:-nifi.properties}
                echo "updating ${1} in ${target_file}"
                if egrep "^${1}=" ${target_file} &> /dev/null; then
                  sed -i -e "s|^$1=.*$|$1=$2|"  ${target_file}
                else
                  echo ${1}=${2} >> ${target_file}
                fi
              }

              mkdir -p ${NIFI_HOME}/config-data/conf

              FQDN=$(hostname -f)

              cat "${NIFI_HOME}/conf/nifi.temp" >
              "${NIFI_HOME}/conf/nifi.properties"

              bin/nifi.sh set-single-user-credentials username changemechangeme

              if ! test -f /opt/nifi/data/flow.xml.gz && test -f
              /opt/nifi/data/flow.xml; then
                gzip /opt/nifi/data/flow.xml
              fi

              prop_replace nifi.remote.input.host ${FQDN}

              prop_replace nifi.cluster.node.address ${FQDN}

              prop_replace nifi.zookeeper.connect.string
              ${NIFI_ZOOKEEPER_CONNECT_STRING}

              prop_replace nifi.web.http.host ${FQDN}

              if [ ! -r "${NIFI_HOME}/conf/nifi-cert.pem" ]

              then
                /opt/nifi/nifi-toolkit-current/bin/tls-toolkit.sh standalone \
                  -n 'nifi-nifi-0.nifi-nifi-headless.release.svc.cluster.local' \
                  -C 'CN=admin, OU=NIFI' \
                  -o "${NIFI_HOME}/conf/" \
                  -P changeMe \
                  -S changeMe \
                  --nifiPropertiesFile /opt/nifi/nifi-current/conf/nifi.properties
              fi

              for f in "${NIFI_HOME}/conf/authorizers.xml"
              "${NIFI_HOME}/conf/login-identity-providers.xml"
              ${NIFI_HOME}/conf/nifi.properties

              do
                echo === $f ===
                cat $f
              done

              echo === end of files ===

              function prop () {
                target_file=${NIFI_HOME}/conf/nifi.properties
                egrep "^${1}=" ${target_file} | cut -d'=' -f2
              }

              function offloadNode() {
                  FQDN=$(hostname -f)
                  echo "disconnecting node '$FQDN'"
                  baseUrl=https://${FQDN}:8443

                  echo "keystoreType=$(prop nifi.security.keystoreType)" > secure.properties
                  echo "keystore=$(prop nifi.security.keystore)" >> secure.properties
                  echo "keystorePasswd=$(prop nifi.security.keystorePasswd)" >> secure.properties
                  echo "truststoreType=$(prop nifi.security.truststoreType)" >> secure.properties
                  echo "truststore=$(prop nifi.security.truststore)" >> secure.properties
                  echo "truststorePasswd=$(prop nifi.security.truststorePasswd)" >> secure.properties
                  echo "proxiedEntity=CN=admin, OU=NIFI" >> secure.properties

                  secureArgs="-p secure.properties"

                  echo baseUrl ${baseUrl}
                  echo "gracefully disconnecting node '$FQDN' from cluster"
                  ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi get-nodes -ot json -u ${baseUrl} ${secureArgs} > nodes.json
                  nnid=$(jq --arg FQDN "$FQDN" '.cluster.nodes[] | select(.address==$FQDN) | .nodeId' nodes.json)
                  echo "disconnecting node ${nnid}"
                  ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi disconnect-node -nnid $nnid -u ${baseUrl} ${secureArgs}
                  echo ""
                  echo "get a connected node"
                  connectedNode=$(jq -r 'first(.cluster.nodes|=sort_by(.address)| .cluster.nodes[] | select(.status=="CONNECTED")) | .address' nodes.json)
                  baseUrl=https://${connectedNode}:8443
                  echo baseUrl ${baseUrl}
                  echo ""
                  echo "wait until node has state 'DISCONNECTED'"
                  while [[ "${node_state}" != "DISCONNECTED" ]]; do
                      sleep 1
                      ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi get-nodes -ot json -u ${baseUrl} ${secureArgs} > nodes.json
                      node_state=$(jq -r --arg FQDN "$FQDN" '.cluster.nodes[] | select(.address==$FQDN) | .status' nodes.json)
                      echo "state is '${node_state}'"
                  done
                  echo ""
                  echo "node '${nnid}' was disconnected"
                  echo "offloading node"
                  ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi offload-node -nnid $nnid -u ${baseUrl} ${secureArgs}
                  echo ""
                  echo "wait until node has state 'OFFLOADED'"
                  while [[ "${node_state}" != "OFFLOADED" ]]; do
                      sleep 1
                      ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi get-nodes -ot json -u ${baseUrl} ${secureArgs} > nodes.json
                      node_state=$(jq -r --arg FQDN "$FQDN" '.cluster.nodes[] | select(.address==$FQDN) | .status' nodes.json)
                      echo "state is '${node_state}'"
                  done
              }

              deleteNode() {
                  echo "deleting node"
                  ${NIFI_TOOLKIT_HOME}/bin/cli.sh nifi delete-node -nnid ${nnid} -u ${baseUrl} ${secureArgs}
                  echo "node deleted"
              }

              executeTrap() {
                 echo Received trapped signal, beginning shutdown...;
                 ./bin/nifi.sh stop;
                 exit 0;
              }

              trap executeTrap TERM HUP INT;

              trap ":" EXIT

              exec bin/nifi.sh run & nifi_pid="$!"

              echo NiFi running with PID ${nifi_pid}.

              wait ${nifi_pid}
          ports:
            - name: https
              containerPort: 8443
              protocol: TCP
            - name: cluster
              containerPort: 6007
              protocol: TCP
          env:
            - name: NIFI_ZOOKEEPER_CONNECT_STRING
              value: nifi-zookeeper:2181
            - name: NIFI_WEB_HTTPS_HOST
              value: 0.0.0.0
          resources: {}
          volumeMounts:
            - name: my-logs
              mountPath: /opt/nifi/nifi-current/logs
            - name: my-data
              mountPath: /opt/nifi/data
            - name: my-auth-conf
              mountPath: /opt/nifi/nifi-current/auth-conf/
            - name: my-config-data
              mountPath: /opt/nifi/nifi-current/config-data
            - name: my-flowfile-repository
              mountPath: /opt/nifi/flowfile_repository
            - name: my-content-repository
              mountPath: /opt/nifi/content_repository
            - name: my-provenance-repository
              mountPath: /opt/nifi/provenance_repository
            - name: my-nifi-input
              mountPath: /opt/nifi/nifi_input
            - name: my-nifi-output
              mountPath: /opt/nifi/nifi_output
            - name: my-nifi-release-config
              mountPath: /opt/nifi/nifi_release_config
            - name: bootstrap-conf
              mountPath: /opt/nifi/nifi-current/conf/bootstrap.conf
              subPath: bootstrap.conf
            - name: nifi-properties
              mountPath: /opt/nifi/nifi-current/conf/nifi.temp
              subPath: nifi.temp
            - name: authorizers-temp
              mountPath: /opt/nifi/nifi-current/conf/authorizers.temp
              subPath: authorizers.temp
            - name: bootstrap-notification-services-xml
              mountPath: /opt/nifi/nifi-current/conf/bootstrap-notification-services.xml
              subPath: bootstrap-notification-services.xml
            - name: login-identity-providers-ldap-xml
              mountPath: /opt/nifi/nifi-current/conf/login-identity-providers-ldap.xml
              subPath: login-identity-providers-ldap.xml
            - name: state-management-xml
              mountPath: /opt/nifi/nifi-current/conf/state-management.xml
              subPath: state-management.xml
            - name: zookeeper-properties
              mountPath: /opt/nifi/nifi-current/conf/zookeeper.properties
              subPath: zookeeper.properties
            - name: flow-content
              mountPath: /opt/nifi/data/flow.xml
              subPath: flow.xml
          livenessProbe:
            tcpSocket:
              port: 8443
            initialDelaySeconds: 90
            timeoutSeconds: 1
            periodSeconds: 60
            successThreshold: 1
            failureThreshold: 3
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
        - name: app-log
          image: busybox:1.32.0
          args:
            - /bin/sh
            - '-c'
            - trap "exit 0" TERM; tail -n+1 -F /var/log/nifi-app.log & wait $!
          resources:
            limits:
              cpu: 50m
              memory: 50Mi
            requests:
              cpu: 10m
              memory: 10Mi
          volumeMounts:
            - name: my-logs
              mountPath: /var/log
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
        - name: bootstrap-log
          image: busybox:1.32.0
          args:
            - /bin/sh
            - '-c'
            - >-
              trap "exit 0" TERM; tail -n+1 -F /var/log/nifi-bootstrap.log &
              wait $!
          resources:
            limits:
              cpu: 50m
              memory: 50Mi
            requests:
              cpu: 10m
              memory: 10Mi
          volumeMounts:
            - name: my-logs
              mountPath: /var/log
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
        - name: user-log
          image: busybox:1.32.0
          args:
            - /bin/sh
            - '-c'
            - trap "exit 0" TERM; tail -n+1 -F /var/log/nifi-user.log & wait $!
          resources:
            limits:
              cpu: 50m
              memory: 50Mi
            requests:
              cpu: 10m
              memory: 10Mi
          volumeMounts:
            - name: my-logs
              mountPath: /var/log
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      serviceAccountName: default
      serviceAccount: default
      securityContext:
        runAsUser: 1000
        fsGroup: 1000
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 1
              podAffinityTerm:
                labelSelector:
                  matchExpressions:
                    - key: app
                      operator: In
                      values:
                        - nifi
                topologyKey: kubernetes.io/hostname
      schedulerName: default-scheduler
  volumeClaimTemplates:
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-logs
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 5Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-config-data
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 100Mi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-data
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 1Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-flowfile-repository
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-content-repository
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-provenance-repository
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-auth-conf
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 100Mi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-nifi-input
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-nifi-output
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
        volumeMode: Filesystem
    - kind: PersistentVolumeClaim
      apiVersion: v1
      metadata:
        name: my-nifi-release-config
        namespace: release
      spec:
        storageClassName: nifi-storage
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 100Mi
        volumeMode: Filesystem
  serviceName: nifi-headless
  podManagementPolicy: Parallel
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      partition: 0
  revisionHistoryLimit: 10

As you can see I have several local volumes that I am binding, so that my data persists even if the entire cluster fails. During testing, after feeding the flow some data and shutting down the k8 cluster, on restart I get the following issue.

2022-12-28 15:49:41,632 ERROR [NiFi logging handler] org.apache.nifi.StdErr Failed to start web server: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityFilterChain' defined in org.apache.nifi.web.NiFiWebApiSecurityConfiguration: Unsatisfied dependency expressed through method 'securityFilterChain' parameter 2; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.apache.nifi.web.security.configuration.JwtAuthenticationSecurityConfiguration': Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'idpUserGroupService' defined in class path resource [nifi-administration-context.xml]: Cannot resolve reference to bean 'idpTransactionBuilder' while setting bean property 'transactionBuilder'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'idpTransactionBuilder' defined in class path resource [nifi-administration-context.xml]: Cannot resolve reference to bean 'idpDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'idpDataSource': FactoryBean threw exception on object creation; nested exception is org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database may be already in use: "/opt/nifi/data/database_repository/nifi-identity-providers.mv.db". Possible solutions: close all other connection(s); use the server mode [90020-214]
2022-12-28 15:49:41,633 ERROR [NiFi logging handler] org.apache.nifi.StdErr Shutting down...

Nifi-0 works, but nifi-1 keeps failing and going through multiple restarts. I'm assuming from the logs, the issue is that the database is still in use which is why the second node fails. I want to avoid deleting the contents of the database repository, so any other solutions are much appreciated. Thank you.


来源: stackexchange

问:
Multi_line_string stay nil after update
I added a multi_line_string field in my database :

```<code>t.geometry "zmpath", limit: {:srid=>4326, :type=>"multi_line_string", :has_z=>true, :has_m=>true}
</code>```

If I update my table by pgAdmin, the result is persisted but the field stay empty on my update form.

But if I try to update the field by erb or via my app, the field stay nil but I get this error :

```<code>[59] pry(main)> Track.find(9).update_columns(zmpath: "MULTILINESTRING ZM ((0 0 4 6,5 5 4 6),(10 10 4 6,5 5 4 6,0 0 4 6),(0 0 4 6,10 10 4 6,10 0 4 6))")
  Track Load (5.3ms)  SELECT "tracks".* FROM "tracks" WHERE "tracks"."id" = $1 LIMIT $2  [["id", 9], ["LIMIT", 1]]
NoMethodError: undefined method `factory' for nil:NilClass
from /Users/ben/.rbenv/versions/2.7.6/lib/ruby/gems/2.7.0/gems/rgeo-2.3.1/lib/rgeo/wkrep/wkb_generator.rb:101:in `generate'
</code>```

All other geoms work fine on this table

rgeo.rb

```<code>RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config|
  config.default = RGeo::Geographic.spherical_factory(srid: 4326)
end
</code>```

ContentLicense: CC BY-SA 4.0

Title: Multi_line_string stay nil after update

Body:
I added a multi_line_string field in my database :

t.geometry "zmpath", limit: {:srid=>4326, :type=>"multi_line_string", :has_z=>true, :has_m=>true}

If I update my table by pgAdmin, the result is persisted but the field stay empty on my update form.

But if I try to update the field by erb or via my app, the field stay nil but I get this error :

[59] pry(main)> Track.find(9).update_columns(zmpath: "MULTILINESTRING ZM ((0 0 4 6,5 5 4 6),(10 10 4 6,5 5 4 6,0 0 4 6),(0 0 4 6,10 10 4 6,10 0 4 6))")
  Track Load (5.3ms)  SELECT "tracks".* FROM "tracks" WHERE "tracks"."id" = $1 LIMIT $2  [["id", 9], ["LIMIT", 1]]
NoMethodError: undefined method `factory' for nil:NilClass
from /Users/ben/.rbenv/versions/2.7.6/lib/ruby/gems/2.7.0/gems/rgeo-2.3.1/lib/rgeo/wkrep/wkb_generator.rb:101:in `generate'

All other geoms work fine on this table

rgeo.rb

RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config|
  config.default = RGeo::Geographic.spherical_factory(srid: 4326)
end


问:
Collection_check_boxes error after upgrading to Rails 7.0
I recently upgraded a project from Rails 4 to Rails 7. I have a view page that uses checkboxes that is now throwing an error stating

ArgumentError - wrong number of arguments (given 2, expected 1):

app/views/messages/new.html.erb:86

app/views/messages/new.html.erb:84

app/views/messages/new.html.erb:37

This view is a form that allows the user to submit a new message and check off multiple categories they want to associate with the message. The code for the view messages/new.html.erb is below:

```<code>

    <nav class="navbar navbar-custom sticky-top center font-weight-bold">
            <h2>New Question
            </h2>

          <div class="container">
           <div class="page-header">
          <%= form_with model: @message, url: new_user_message_path, class: "form-
    control" do
         |f| %>
                <% if @message.errors.any? %>
                  <div id="error_explanation">
                    <h2>There were some errors:</h2>
                    <ul>
                      <% @message.errors.full_messages.each do |message| %>
                        <li><%= message %></li>
                      <% end %>
                    </ul>
                  </div>
                <% end %>
            </div>
          </nav>

        <div class="container">
          <div class="container-fluid mx-auto text-nowrap text-dark" style="width:
     500px;">
            <table class="table table-striped">
                  <div class="col sign-in card-title card-body">

                    <div class="field<%= ' field_with_errors' if
     @message.errors[:title].any?
        %>">
                      <%= f.label :title %><br>
                      <%= f.text_field :title, value: @message.title, class: "span5" %>
    </div>
                    <br>
                    <br>
                    <div class="field<%= ' field_with_errors' if
        @message.errors[:question].any? %>">
                      <%= f.label :question %><br>
                      <%= f.text_field :question, value: @message.question, class:
     "span5" %>
       </div>
                     <br>
                     <br>
                    <div class="form-group">
                     <br>
                      <%= f.hidden_field :patient_id, value: current_user.id, class:
    "form-
       control" %>
                    </div>
                    <br>
                    <div class="form-group">
                      <%= f.label :new_or_preexisting_condition%><br>
                      <%= f.collection_check_boxes :category_ids, Category.all[0..1],
    :id,
        :category do |b| %>
                      <div>
                      <%=b.label %>
                      </div>
                      <% end %>
                    </div>
                    <br>
                    <div class="form-group">
                      <%= f.label :affected_system%><br>
                      <%= f.collection_check_boxes :category_ids, Category.all[2..11],
     :id,
        :category do |b| %>
                      <div>
                      <%=b.check_box %>
                      <%= b.label %>
                      </div>
                      <% end %>
                    </div>
                    <br>
                    <div class="actions">
                      <%= f.submit class: "btn btn-primary" %>
                    </div>
                  <% end %>
                </div>
              </div>
            </table>
          </div>
        </div>
        </div>
        </div>

</code>```

The models are as follows:

Message.rb

```<code>

    class Message < ApplicationRecord
          belongs_to :patient, foreign_key: :patient_id
          has_many :message_categories
          has_many :categories, through: :message_categories
          has_many :responses
          has_many :physicians, through: :responses
          validates :title, presence: true
          validates :question, presence: true
          accepts_nested_attributes_for :categories
          accepts_nested_attributes_for :message_categories
          scope :new_condition, -> {joins(:categories).merge(Category.new_condition)}
          scope :existing_condition, ->
          {joins(:categories).merge(Category.existing_condition)}
          scope :unanswered_questions, -> {left_outer_joins(:responses).where(responses:
         {message_id: nil})}

          def responses_attributes=(responses_attributes)
              responses_attributes.values.each do |response_attribute|
              response = Response.find_or_create_by(response_attribute)
              self.response_attributes.build(response: response)
            end
          end
        end

</code>```

Category.rb

```<code>
    class Category < ApplicationRecord
      has_many :message_categories
      has_many :messages, through: :message_categories
      scope :new_condition, -> { where("category_id == 1") }
      scope :existing_condition, -> { where("category_id == 2") }

    end

</code>```

MessageCategory.rb

```<code>
    class MessageCategory < ApplicationRecord
      belongs_to :message
      belongs_to :category
    end

</code>```

Patient.rb

```<code>
    class Patient < User
      has_secure_password
      belongs_to :user, optional: true
      has_many :messages, dependent: :destroy
      validates :name, :email, :password_digest, presence: true
      validates :email, uniqueness: true
      validates :name, length: { minimum: 2 }

    #validations specific to this model

      def self.model_namev#build correct path
        User.model_name
      end
    end

</code>```

User.rb

```<code>
    Class User < ApplicationRecord
       has_secure_password
       scope :patients, -> { where(type: 'Patient') }
       scope :physicians, -> { where(type: 'Physician') }
       has_many :physicians
       has_many :patients

    end

</code>```

The Messages controller:

```<code>
    # frozen_string_literal: true

    # class containing messages CRUD methods
    class MessagesController < ApplicationController
      before_action :logged_in?
      before_action :patient_user, only: [:new, :edit, :update]

      def new
           if params[:user_id] && Patient.exists?(params[:user_id])
           @message = Message.new(patient_id: params[:user_id])
           @categories = Category.all
          else
          flash[:notice] = 'You do not have access to this feature.'
          redirect_to controller: 'users', action: 'show', id: current_user.id
          end
      end

      def show
         @message = Message.find(params[:id])
      end

      def index
        @messages = if params[:user_id]
                  Message.where(patient_id: params[:user_id])
                else
                  Message.all
                end
      end

      def create
        @message = Message.new(message_params)
        if @message.save
          flash[:notice] = 'Message successfully created'
          redirect_to controller: 'users', action: 'show', id: current_user.id
        else
          render :new
        end
      end

      def edit
          if params[:user_id]
            patient = Patient.find_by(id: params[:patient_id])
            if patient = nil
              redirect_to controller: 'users', action: 'show', id: current_user.id
            else
              @message = Message.find_by(id: params[:id])
            end
          else
            flash[:notice] = 'You do not have access to this feature.'
            redirect_to controller: 'users', action: 'show', id: current_user.id
          end
      end

      def update
          @message = Message.find(params[:id])
          @message.update(message_params)
          flash[:notice] = 'Message successfully updated'
          render :show
      end

      def destroy
        @message = Message.find(params[:id])
        @message.delete
        flash[:notice] = 'Message successfully deleted'
        redirect_to controller: 'users', action: 'show'
      end

      private

      def message_params
        params.require(:message).permit(:title, :question, :patient_id, category_ids: [])
      end
    end

</code>```

The Categories controller

```<code>
    # frozen_string_literal: true

    # class containing categories CRUD methods
    class CategoriesController < ApplicationController

      def show
        @category = Category.find(params[:id])
      end

      def create
        @category = Category.create(category_params)
        if @category.save
          redirect_to 'messages/show'
        else
          flash[:notice] = 'Unable to save categories. Please try again.'
          redirect_to 'messages/new'
        end
      end

      def index
        @categories = Category.all
      end

      private

      def category_params
        params.require(:category).permit(:category, :id)
      end
    end

</code>```

I'm not sure if it has something to do with the fact that categories is related to messages through message categories?

Body:
I recently upgraded a project from Rails 4 to Rails 7. I have a view page that uses checkboxes that is now throwing an error stating

ArgumentError - wrong number of arguments (given 2, expected 1):

app/views/messages/new.html.erb:86

app/views/messages/new.html.erb:84

app/views/messages/new.html.erb:37

This view is a form that allows the user to submit a new message and check off multiple categories they want to associate with the message. The code for the view messages/new.html.erb is below:

New Question

          <%= form_with model: @message, url: new_user_message_path, class: "form-
    control" do
         |f| %>
                <% if @message.errors.any? %>

There were some errors:

                      <% @message.errors.full_messages.each do |message| %>

<%= message %>

                      <% end %>

                <% end %>

                    <div class="field<%= ' field_with_errors' if
     @message.errors[:title].any?
        %>">
                      <%= f.label :title %>

                      <%= f.text_field :title, value: @message.title, class: "span5" %>

                    <div class="field<%= ' field_with_errors' if
        @message.errors[:question].any? %>">
                      <%= f.label :question %>

                      <%= f.text_field :question, value: @message.question, class:
     "span5" %>

                      <%= f.hidden_field :patient_id, value: current_user.id, class:
    "form-
       control" %>

                      <%= f.label :new_or_preexisting_condition%>

                      <%= f.collection_check_boxes :category_ids, Category.all[0..1],
    :id,
        :category do |b| %>

                      <%=b.label %>

                      <% end %>

                      <%= f.label :affected_system%>

                      <%= f.collection_check_boxes :category_ids, Category.all[2..11],
     :id,
        :category do |b| %>

                      <%=b.check_box %>
                      <%= b.label %>

                      <% end %>

                      <%= f.submit class: "btn btn-primary" %>

                  <% end %>

The models are as follows:

Message.rb

    class Message < ApplicationRecord
          belongs_to :patient, foreign_key: :patient_id
          has_many :message_categories
          has_many :categories, through: :message_categories
          has_many :responses
          has_many :physicians, through: :responses
          validates :title, presence: true
          validates :question, presence: true
          accepts_nested_attributes_for :categories
          accepts_nested_attributes_for :message_categories
          scope :new_condition, -> {joins(:categories).merge(Category.new_condition)}
          scope :existing_condition, ->
          {joins(:categories).merge(Category.existing_condition)}
          scope :unanswered_questions, -> {left_outer_joins(:responses).where(responses:
         {message_id: nil})}

          def responses_attributes=(responses_attributes)
              responses_attributes.values.each do |response_attribute|
              response = Response.find_or_create_by(response_attribute)
              self.response_attributes.build(response: response)
            end
          end
        end

Category.rb

    class Category < ApplicationRecord
      has_many :message_categories
      has_many :messages, through: :message_categories
      scope :new_condition, -> { where("category_id == 1") }
      scope :existing_condition, -> { where("category_id == 2") }

    end

MessageCategory.rb

    class MessageCategory < ApplicationRecord
      belongs_to :message
      belongs_to :category
    end

Patient.rb

    class Patient < User
      has_secure_password
      belongs_to :user, optional: true
      has_many :messages, dependent: :destroy
      validates :name, :email, :password_digest, presence: true
      validates :email, uniqueness: true
      validates :name, length: { minimum: 2 }

    #validations specific to this model

      def self.model_namev#build correct path
        User.model_name
      end
    end

User.rb

    Class User < ApplicationRecord
       has_secure_password
       scope :patients, -> { where(type: 'Patient') }
       scope :physicians, -> { where(type: 'Physician') }
       has_many :physicians
       has_many :patients

    end

The Messages controller:

    # frozen_string_literal: true

    # class containing messages CRUD methods
    class MessagesController < ApplicationController
      before_action :logged_in?
      before_action :patient_user, only: [:new, :edit, :update]

      def new
           if params[:user_id] && Patient.exists?(params[:user_id])
           @message = Message.new(patient_id: params[:user_id])
           @categories = Category.all
          else
          flash[:notice] = 'You do not have access to this feature.'
          redirect_to controller: 'users', action: 'show', id: current_user.id
          end
      end

      def show
         @message = Message.find(params[:id])
      end

      def index
        @messages = if params[:user_id]
                  Message.where(patient_id: params[:user_id])
                else
                  Message.all
                end
      end

      def create
        @message = Message.new(message_params)
        if @message.save
          flash[:notice] = 'Message successfully created'
          redirect_to controller: 'users', action: 'show', id: current_user.id
        else
          render :new
        end
      end

      def edit
          if params[:user_id]
            patient = Patient.find_by(id: params[:patient_id])
            if patient = nil
              redirect_to controller: 'users', action: 'show', id: current_user.id
            else
              @message = Message.find_by(id: params[:id])
            end
          else
            flash[:notice] = 'You do not have access to this feature.'
            redirect_to controller: 'users', action: 'show', id: current_user.id
          end
      end

      def update
          @message = Message.find(params[:id])
          @message.update(message_params)
          flash[:notice] = 'Message successfully updated'
          render :show
      end

      def destroy
        @message = Message.find(params[:id])
        @message.delete
        flash[:notice] = 'Message successfully deleted'
        redirect_to controller: 'users', action: 'show'
      end

      private

      def message_params
        params.require(:message).permit(:title, :question, :patient_id, category_ids: [])
      end
    end

The Categories controller

    # frozen_string_literal: true

    # class containing categories CRUD methods
    class CategoriesController < ApplicationController

      def show
        @category = Category.find(params[:id])
      end

      def create
        @category = Category.create(category_params)
        if @category.save
          redirect_to 'messages/show'
        else
          flash[:notice] = 'Unable to save categories. Please try again.'
          redirect_to 'messages/new'
        end
      end

      def index
        @categories = Category.all
      end

      private

      def category_params
        params.require(:category).permit(:category, :id)
      end
    end

I'm not sure if it has something to do with the fact that categories is related to messages through message categories?


问:
What github api data can be used to measure number of external commits
I want to measure the number of non-owner or external contributor commits or PRs in a repo and also the ratio of non-owner/owner commits in a repo. What api data is available to construct these metrics?</p>


问:
LoopBack4 generate uml model diagram

I'm thinking of generate a uml model for all models in my project. I tried the following packages but they didn't work for LoopBack4.

loopback-component-model-diagram

loopback-component-explorer

I added mountPath to component-config.json file. But it did not work!

I only see the swagger page, I can't see any uml model generated page.

```<code>{ "mountPath": "/modeldiagram" }
</code>```

What should I do other than add mountpath or do you know of any package that generates uml model for the models?

Title: LoopBack4 generate uml model diagram

Body:
I'm thinking of generate a uml model for all models in my project. I tried the following packages but they didn't work for LoopBack4.

loopback-component-model-diagram

loopback-component-explorer

I added mountPath to component-config.json file. But it did not work!

I only see the swagger page, I can't see any uml model generated page.

{ "mountPath": "/modeldiagram" }

What should I do other than add mountpath or do you know of any package that generates uml model for the models?


问:
How to update the values in the array when changing language nuxt i18n
I am finding difficulty updating the values in the array of objects for nuxt i18n. How I can update the message in the validation array when the language got changed?

I found solutions to update single properties by moving them to the computed method but what to do with the array of objects?

//Template

    <v-alert type="danger">{{validations.message}} </v-alert>

//component
data() {

        validations: []

    },

methods() {

        submit() {

            //pushing validations array on submit method
            this.validations.push('part', message: this.$t('error.required'));

            this.validations.push('part', message: this.$t('error.mandatory'));

        }
}```
</div>
</div>
</p>
<p>en.json</p>
```error:{
required:"required en",
mandatory:"mandatory en"
}
```
<p>fr.json</p>
```error:{
required:"required fr",
mandatory:"mandatory fr"
}
```

Body:
I am finding difficulty updating the values in the array of objects for nuxt i18n. How I can update the message in the validation array when the language got changed?

I found solutions to update single properties by moving them to the computed method but what to do with the array of objects?

//Template

    <v-alert type="danger">{{validations.message}} </v-alert>

//component
data() {

        validations: []

    },

methods() {

        submit() {

            //pushing validations array on submit method
            this.validations.push('part', message: this.$t('error.required'));

            this.validations.push('part', message: this.$t('error.mandatory'));

        }
}

en.json

error:{
required:"required en",
mandatory:"mandatory en"
}

fr.json

error:{
required:"required fr",
mandatory:"mandatory fr"
}


问:
Enable USB Debugging and remote control (scrcpy) with broken screen
and happy holidays. Apologies if this question is more appropriate for SuperUser, I ask here in case there is a programmatic solution to my problem.

In summary: On an Android device with a broken screen, assuming that USB Debugging is enabled or that the connected device is not trusted, is there any way to perform remote control?

So I have a Pixel 3a which I used to control just fine via scrcpy 1.21. Today the screen broke to the point that I only see a few glitchy lines, even though it looks like I can theoretically control it (based on the sounds, I managed to enter the log-in pattern).

The problem is that adb devices does not recognize it, even though the system (Ubuntu or Windows) recognizes that a Pixel 3a was connected for charging.

Is there any way I can salvage this situation?

ADB commands failed. scrcpy failed.


问:
Cannot find module '@typescript-eslint' when linting and 'plugin:prettier/recommended' is enabled in eslitrc.js
I have a node project using nestjs and eslint_d for linting. My eslint.js file looks like the following:

```<code>module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    tsconfigRootDir : __dirname,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],

...
</code>```

when I disable the line 'plugin:prettier/recommended' I can run eslint_d without a problem, but if I run it for a file with that line enabled I get the following output:

```<code>.../app/documents/documents.controller.ts
Error: Cannot find module '@typescript-eslint'
Require stack:
- /.../node_modules/prettier/index.js
- /.../node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js
- /.../node_modules/@eslint/eslintrc/dist/eslintrc.cjs
Occurred while linting /.../src/<MYPROJECT>/src/.../app/documents/xxx.controller.ts:1
Rule: "prettier/prettier"
</code>```

I don't know what I'm doing wrong. The plugin looks like it's installed. Can anyone help?

I tried enabling debugging but couldn't get better output. Disabling the plugin is a workaround. Happy to answer any other questions.

Body:
I have a node project using nestjs and eslint_d for linting. My eslint.js file looks like the following:

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    tsconfigRootDir : __dirname,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],

...

when I disable the line 'plugin:prettier/recommended' I can run eslint_d without a problem, but if I run it for a file with that line enabled I get the following output:

.../app/documents/documents.controller.ts
Error: Cannot find module '@typescript-eslint'
Require stack:
- /.../node_modules/prettier/index.js
- /.../node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js
- /.../node_modules/@eslint/eslintrc/dist/eslintrc.cjs
Occurred while linting /.../src/<MYPROJECT>/src/.../app/documents/xxx.controller.ts:1
Rule: "prettier/prettier"

I don't know what I'm doing wrong. The plugin looks like it's installed. Can anyone help?

I tried enabling debugging but couldn't get better output. Disabling the plugin is a workaround. Happy to answer any other questions.


问:
Convert PowerShell script importing within other PowerShell script to EXE
I have been trying to convert a powershell script to exe, So I came across this tool PS2EXE
by this thread. Now the exe is successfully created but the issue is, the converting powershell script on top imports another powershell scripts and use it.
So on running the exe, it throws erorrs.

my powershell script:

`source.ps1

```<code>. "$PSScriptRoot\Start_Common.ps1" #importing the other ps script

set_start_default_values "n" "y" # Set both
use_args($args)
print_parameters`
</code>```

Now exe converted with ps2exe with command ps2exe .\source.ps1 .\target.exe

on executing throws the below error

```<code>ERROR: The term '\Start_Common.ps1' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
</code>```

Body:
I have been trying to convert a powershell script to exe, So I came across this tool PS2EXE
by this thread. Now the exe is successfully created but the issue is, the converting powershell script on top imports another powershell scripts and use it.
So on running the exe, it throws erorrs.

my powershell script:

`source.ps1

. "$PSScriptRoot\Start_Common.ps1" #importing the other ps script

set_start_default_values "n" "y" # Set both
use_args($args)
print_parameters`

Now exe converted with ps2exe with command ps2exe .\source.ps1 .\target.exe

on executing throws the below error

ERROR: The term '\Start_Common.ps1' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.


问:
Core Wars 8086 safe challenge
I'm doing a safes competition and I created this safe:

```<code>start:

mov bx, 0

label:
mov cx, [1234]
inc cx
shl cx, 1
mov [1234], cx
dec cx
shl cx, 1
dec cx
loop label

mov bx, cx
mov [bx], ax
jmp start
</code>```

Im need to create the key of this safe, but i dont know how to.

This simulation of a safe and key is done inside the Core Wars 8086 engine. The rules are as follows where both safe and key are survivors in the war:

The survivors cannot place a load on fixed addresses, because the game
engine loads them every turn to a random address. The programs that
are generated must be COM and not EXEs and contain only 8086
instructions.

Each survivor receives a set of its own complete registers
(registers), which is not accessible to the other survivors. In
addition, each survivor has a "personal" stack of 2048 bytes, which is
also inaccessible to the other survivors.

Before running the first round of the game, the game engine
initializes all the bytes in the arena to the value 0CCh (note: this
byte value is an "unsupported" instruction - details below). The
engine then loads each survivor to a random location in the arena
memory, ie - copies the contents of the survivor file exactly as it
is. The distance between two survivors, as well as the distance
between the survivor and the edge of the arena, is guaranteed to be at
least 1024 bytes. The code for each survivor has a maximum of 512
bytes.

Before the first round, the game engine initializes the registers (of
each survivor) to the following values:

BX, CX, DX, SI, DI, BP - Reset.

Flags - Reset.

AX, IP - The position of the initial survivor, the random offset in    the arena to which the survivor is loaded by the game engine.

CS, DS - The segment of the arena common to all survivors.

ES - A segment (segment) for the memory shared by survivors of the    same group (see Advanced Techniques ).

SS - Beginning section of the personal stack of the survivor.

SP - Offset The start of the personal stack of the survivor.

At this point the game begins in rounds, with each round running the
game engine running the next instruction of each survivor, until the
end of the game: after 200,000 rounds, or when a single survivor
remains in the arena. The order in which the survivors will play in
each round is determined at the beginning of the game at random, and
does not change during it.

A survivor is disqualified in the following cases:

Running an illegal instruction (example: byte 060h that does not    translate into any assembly instruction).

Running an "unsupported" instruction by the game engine (example:    "INT 021h"). The game engine prevents running instructions that try

to initiate direct communication with the operating system or

computer hardware. Attempt to access memory that is not within the

realm of the arena, and not within the realm of the "personal" stack

of the survivor.

Attacking other survivors is done by writing information about their    code in the arena memory (in order to get them to perform one
of the    above three actions), and consequently to disqualify them.
Earlier,    therefore, one has to find where they are hiding :)

Title: Core Wars 8086 safe challenge

Body:
I'm doing a safes competition and I created this safe:

start:

mov bx, 0

label:
mov cx, [1234]
inc cx
shl cx, 1
mov [1234], cx
dec cx
shl cx, 1
dec cx
loop label

mov bx, cx
mov [bx], ax
jmp start

Im need to create the key of this safe, but i dont know how to.

This simulation of a safe and key is done inside the Core Wars 8086 engine. The rules are as follows where both safe and key are survivors in the war:

The survivors cannot place a load on fixed addresses, because the game
engine loads them every turn to a random address. The programs that
are generated must be COM and not EXEs and contain only 8086
instructions.

Each survivor receives a set of its own complete registers
(registers), which is not accessible to the other survivors. In
addition, each survivor has a "personal" stack of 2048 bytes, which is
also inaccessible to the other survivors.

Before running the first round of the game, the game engine
initializes all the bytes in the arena to the value 0CCh (note: this
byte value is an "unsupported" instruction - details below). The
engine then loads each survivor to a random location in the arena
memory, ie - copies the contents of the survivor file exactly as it
is. The distance between two survivors, as well as the distance
between the survivor and the edge of the arena, is guaranteed to be at
least 1024 bytes. The code for each survivor has a maximum of 512
bytes.

Before the first round, the game engine initializes the registers (of
each survivor) to the following values:

BX, CX, DX, SI, DI, BP - Reset.

Flags - Reset.

AX, IP - The position of the initial survivor, the random offset in    the arena to which the survivor is loaded by the game engine.

CS, DS - The segment of the arena common to all survivors.

ES - A segment (segment) for the memory shared by survivors of the    same group (see Advanced Techniques ).

SS - Beginning section of the personal stack of the survivor.

SP - Offset The start of the personal stack of the survivor.

At this point the game begins in rounds, with each round running the
game engine running the next instruction of each survivor, until the
end of the game: after 200,000 rounds, or when a single survivor
remains in the arena. The order in which the survivors will play in
each round is determined at the beginning of the game at random, and
does not change during it.

A survivor is disqualified in the following cases:

Running an illegal instruction (example: byte 060h that does not    translate into any assembly instruction).

Running an "unsupported" instruction by the game engine (example:    "INT 021h"). The game engine prevents running instructions that try

to initiate direct communication with the operating system or

computer hardware. Attempt to access memory that is not within the

realm of the arena, and not within the realm of the "personal" stack

of the survivor.

Attacking other survivors is done by writing information about their    code in the arena memory (in order to get them to perform one
of the    above three actions), and consequently to disqualify them.
Earlier,    therefore, one has to find where they are hiding :)


问:
How do I use a class written in Python in a class written in C?
I am writting a custom module for Micropython called System. The System class is written in C and has the function testpass.

```<code>// System class test function
STATIC mp_obj_t system_testpass( mp_obj_t self_in, mp_obj_t thing_in )
{
    // How do I get the Thing object so I can access its members?
    printf("Thing: %d\r\n", thing->test );
    return MP_ROM_NONE;
}
MP_DEFINE_CONST_FUN_OBJ_2(system_testpass_obj, system_testpass);
</code>```

I have another class called Thing that is written in Python.

```<code>class Thing():
    def __init__( self, test ):
        self.test = test
</code>```

How do I use the Thing class in the System class?

Body:
I am writting a custom module for Micropython called System. The System class is written in C and has the function testpass.

// System class test function
STATIC mp_obj_t system_testpass( mp_obj_t self_in, mp_obj_t thing_in )
{
    // How do I get the Thing object so I can access its members?
    printf("Thing: %d\r\n", thing->test );
    return MP_ROM_NONE;
}
MP_DEFINE_CONST_FUN_OBJ_2(system_testpass_obj, system_testpass);

I have another class called Thing that is written in Python.

class Thing():
    def __init__( self, test ):
        self.test = test

How do I use the Thing class in the System class?


问:
Local state variable on load page - flutter
I have a problem with local state variables on flutter, i want to create a first loading page in my app, on this page i want to show a simple image, on loading this page i want to get two variables to use for login, these variables are correctly saved in the device, but i can't recover them. The variable is empty How can I fix?

i want call an api and send two local state variables

```<code>import '../flutter_flow/flutter_flow_theme.dart';
import '../flutter_flow/flutter_flow_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;

class SplashpageWidget extends StatefulWidget {
  const SplashpageWidget({Key? key}) : super(key: key);

  @override
  _SplashpageWidgetState createState() => _SplashpageWidgetState();
}

class _SplashpageWidgetState extends State<SplashpageWidget> {
  final _unfocusNode = FocusNode();
  final scaffoldKey = GlobalKey<ScaffoldState>();

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

    // On page load action.

    SchedulerBinding.instance.addPostFrameCallback((_) async {

      var username =  FFAppState().userName;
      var password =  FFAppState().userPassword;

      print(FFAppState().userName);
      print(username.isEmpty);
      print(username);

      if(username.isEmpty || password.isEmpty) {

        context.pushNamed(
          'login',
          extra: <String, dynamic>{
            kTransitionInfoKey: TransitionInfo(
              hasTransition: true,
              transitionType: PageTransitionType.scale,
              alignment: Alignment.bottomCenter,
              duration: Duration(milliseconds: 200),
            ),
          },
        );

      } else {

        var client = http.Client();

        Map<String, String> _requestHeader = {
          'Content-type': 'application/x-www-form-urlencoded',
        };

        var response = await client.post(Uri.parse(
            "myPath"),
            headers: _requestHeader,
            body: {
              "username": FFAppState().userName,
              "password": FFAppState().userPassword
            }
        );
        print(response.statusCode);

        if(response.statusCode == 200){

          var decodedUserData = jsonDecode(response.body);

          decodedUserData.forEach((key, value){

            if(key == "user_display_name") {

              FFAppState().userRealName = value;

            }

          });

          context.pushNamed(
            'HomePage',
            extra: <String, dynamic>{
              kTransitionInfoKey: TransitionInfo(
                hasTransition: true,
                transitionType: PageTransitionType.leftToRight,
                duration: Duration(milliseconds: 300),
              ),
            },
          );

        } else {

          context.pushNamed(
            'login',
            extra: <String, dynamic>{
              kTransitionInfoKey: TransitionInfo(
                hasTransition: true,
                transitionType: PageTransitionType.scale,
                alignment: Alignment.bottomCenter,
                duration: Duration(milliseconds: 200),
              ),
            },
          );

        }
      }

      await Future.delayed(const Duration(milliseconds: 2000));

    });
  }

  @override
  void dispose() {
    _unfocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    context.watch<FFAppState>();

    return Scaffold(
      key: scaffoldKey,
      backgroundColor: Color(0xFF205B97),
      body: SafeArea(
        child: GestureDetector(
          onTap: () => FocusScope.of(context).requestFocus(_unfocusNode),
          child: Padding(
            padding: EdgeInsetsDirectional.fromSTEB(15, 0, 15, 0),
            child: Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Image.asset(
                  'assets/images/mm-checkstar-splash.png',
                  width: 200,
                  height: 200,
                  fit: BoxFit.contain,
                ),
                Text(
                  'My APP',
                  textAlign: TextAlign.center,
                  style: FlutterFlowTheme.of(context).title1.override(
                    fontFamily: 'Poppins',
                    color: Color(0xFFF7F7F7),
                    fontSize: 30,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

Body:
I have a problem with local state variables on flutter, i want to create a first loading page in my app, on this page i want to show a simple image, on loading this page i want to get two variables to use for login, these variables are correctly saved in the device, but i can't recover them. The variable is empty How can I fix?

i want call an api and send two local state variables

import '../flutter_flow/flutter_flow_theme.dart';
import '../flutter_flow/flutter_flow_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;

class SplashpageWidget extends StatefulWidget {
  const SplashpageWidget({Key? key}) : super(key: key);

  @override
  _SplashpageWidgetState createState() => _SplashpageWidgetState();
}

class _SplashpageWidgetState extends State<SplashpageWidget> {
  final _unfocusNode = FocusNode();
  final scaffoldKey = GlobalKey<ScaffoldState>();

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

    // On page load action.

    SchedulerBinding.instance.addPostFrameCallback((_) async {

      var username =  FFAppState().userName;
      var password =  FFAppState().userPassword;

      print(FFAppState().userName);
      print(username.isEmpty);
      print(username);

      if(username.isEmpty || password.isEmpty) {

        context.pushNamed(
          'login',
          extra: <String, dynamic>{
            kTransitionInfoKey: TransitionInfo(
              hasTransition: true,
              transitionType: PageTransitionType.scale,
              alignment: Alignment.bottomCenter,
              duration: Duration(milliseconds: 200),
            ),
          },
        );

      } else {

        var client = http.Client();

        Map<String, String> _requestHeader = {
          'Content-type': 'application/x-www-form-urlencoded',
        };

        var response = await client.post(Uri.parse(
            "myPath"),
            headers: _requestHeader,
            body: {
              "username": FFAppState().userName,
              "password": FFAppState().userPassword
            }
        );
        print(response.statusCode);

        if(response.statusCode == 200){

          var decodedUserData = jsonDecode(response.body);

          decodedUserData.forEach((key, value){

            if(key == "user_display_name") {

              FFAppState().userRealName = value;

            }

          });

          context.pushNamed(
            'HomePage',
            extra: <String, dynamic>{
              kTransitionInfoKey: TransitionInfo(
                hasTransition: true,
                transitionType: PageTransitionType.leftToRight,
                duration: Duration(milliseconds: 300),
              ),
            },
          );

        } else {

          context.pushNamed(
            'login',
            extra: <String, dynamic>{
              kTransitionInfoKey: TransitionInfo(
                hasTransition: true,
                transitionType: PageTransitionType.scale,
                alignment: Alignment.bottomCenter,
                duration: Duration(milliseconds: 200),
              ),
            },
          );

        }
      }

      await Future.delayed(const Duration(milliseconds: 2000));

    });
  }

  @override
  void dispose() {
    _unfocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    context.watch<FFAppState>();

    return Scaffold(
      key: scaffoldKey,
      backgroundColor: Color(0xFF205B97),
      body: SafeArea(
        child: GestureDetector(
          onTap: () => FocusScope.of(context).requestFocus(_unfocusNode),
          child: Padding(
            padding: EdgeInsetsDirectional.fromSTEB(15, 0, 15, 0),
            child: Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Image.asset(
                  'assets/images/mm-checkstar-splash.png',
                  width: 200,
                  height: 200,
                  fit: BoxFit.contain,
                ),
                Text(
                  'My APP',
                  textAlign: TextAlign.center,
                  style: FlutterFlowTheme.of(context).title1.override(
                    fontFamily: 'Poppins',
                    color: Color(0xFFF7F7F7),
                    fontSize: 30,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


问:
How Can I Fix Inconsistent Text Downscaling with a Rich Text Label In Godot?
I have a rich text label that works fine under a resolution of 1920x1080. However, when scaled down to the resolution on my laptop, which has a 1366x768 resolution, the text on said label becomes janky and malformed.

Some lines are cut off at the top or the bottom, and others are squished (as you can see in the image at lines 3, 6, and 13).

I'm using Godot v3.5.1 and the text font is Noto Sans Regular from here

I tried enabling mipmaps, using the filter, disabling anti aliasing, disabling font oversampling and enabling GPU pixel snap under Project Settings > Rendering > 2D > Snapping. And out of all of those, only the pixel snap setting worked. Completely fixes the issue and the text is rendered properly.

However, this completely breaks an animation of a spinning circle that plays at basically all times during the actual gameplay. It becomes stuttered and shakes instead of the normally smooth animation it has otherwise. I realize this may possibly be fixed by using SVG instead of PNG sprites, but I feel like that's not an ideal solution in case other sprites get added. Especially since my game will also allow community members to add their own sprites for their own game play.

So is there any way to fix the text without breaking the animations, or make it so that the animations don't break with pixel snap enabled?


问:
For loop is not being executed yet the condition is true
Am trying to fill a file panel with all the files names in the filesList which is just an array.

When i run my app, the filesList content is loaded and at the console it shows that the list contains file objects but no elements get append to the listGroup in the DOM. I have tried to log the ==entries== but nothing gets logged.
This is confusing because in the console, the filesList array contains the file Objects and  filesList.length > 0 when i log it to the console.

import { FILE_PANEL } from "../../app.js";

export function fillFilePanel(filesList)
 {
  console.log(filesList);
  for (let i = 0; i < filesList.length; i++) {
    let entries = filesList[i]
    if (entries.isDirectory == true) {
      FILE_PANEL.append(`<button id="F${entries.name}" type="button" class="list-group-item list-group-item-action" key="folder" data-toggle="#F${entries.name}Group">${entries.name}</button>

`);
      let parentDir = entries.name + '/';
      // showSubFolder(parentDir)
    }
    else {
      FILE_PANEL.append(`<button type="button" class="list-group-item list-group-item-action">${entries.name}</button>`);
    }
  }
}
```
<p>Code in ==MainFs.js==</p>
<pre class="lang-js prettyprint-override"><code>import { fillFilePanel } from "./ui/sideBar.js"
{
//...some code that does other things
let filesList = [];
  listDir().then(val => (val.forEach((f) => { filesList.push(f);
  })));

  fillFilePanel(filesList)

}

/**
 * Read the local storage and fill the sidebar with files in it
 **/

export function listDir(url = '') {
  return new Promise(function(res, reject) {
    let path = cordova.file.externalRootDirectory + url
    console.log();
    window.resolveLocalFileSystemURL(path,
      function(fs) {
        const reader = fs.createReader();
        reader.readEntries(function(entries) {
          res(entries)
        }, (rej) => { return rej });
      }, (rej) => { return rej });
  });
}
</code>```

Sample output when i console.log(filesList)

[{"isFile":false,"isDirectory":true,"name":".face","fullPath":"/.face/","filesystem":"<FileSystem: sdcard>","nativeURL":"file:///storage/emulated/0/.face/"},{"isFile":false,"isDirectory":true,"name":".audio_param","fullPath":"/.audio_param/","filesystem":"<FileSystem: sdcard>","nativeURL":"file:///storage/emulated/0/.audio_param/"},{"isFile":false,"isDirectory":true,"name":"Music","fullPath":"/Music/","filesystem":"<FileSystem: sdcard>","nativeURL":"file:///storage/emulated/0/Music/"},{"isFile":false,"isDirec ...}]
```

The app uses cordova file plugin to read files.

Body:
Am trying to fill a file panel with all the files names in the filesList which is just an array.

When i run my app, the filesList content is loaded and at the console it shows that the list contains file objects but no elements get append to the listGroup in the DOM. I have tried to log the ==entries== but nothing gets logged.
This is confusing because in the console, the filesList array contains the file Objects and  filesList.length > 0 when i log it to the console.

import { FILE_PANEL } from "../../app.js";

export function fillFilePanel(filesList)
 {
  console.log(filesList);
  for (let i = 0; i < filesList.length; i++) {
    let entries = filesList[i]
    if (entries.isDirectory == true) {
      FILE_PANEL.append(`<button id="F${entries.name}" type="button" class="list-group-item list-group-item-action" key="folder" data-toggle="#F${entries.name}Group">${entries.name}</button>

`);
      let parentDir = entries.name + '/';
      // showSubFolder(parentDir)
    }
    else {
      FILE_PANEL.append(`<button type="button" class="list-group-item list-group-item-action">${entries.name}</button>`);
    }
  }
}

Code in ==MainFs.js==

import { fillFilePanel } from "./ui/sideBar.js"
{
//...some code that does other things
let filesList = [];
  listDir().then(val => (val.forEach((f) => { filesList.push(f);
  })));

  fillFilePanel(filesList)

}

/**
 * Read the local storage and fill the sidebar with files in it
 **/

export function listDir(url = '') {
  return new Promise(function(res, reject) {
    let path = cordova.file.externalRootDirectory + url
    console.log();
    window.resolveLocalFileSystemURL(path,
      function(fs) {
        const reader = fs.createReader();
        reader.readEntries(function(entries) {
          res(entries)
        }, (rej) => { return rej });
      }, (rej) => { return rej });
  });
}

Sample output when i console.log(filesList)

[{"isFile":false,"isDirectory":true,"name":".face","fullPath":"/.face/","filesystem":"<FileSystem: sdcard>","nativeURL":"file:///storage/emulated/0/.face/"},{"isFile":false,"isDirectory":true,"name":".audio_param","fullPath":"/.audio_param/","filesystem":"<FileSystem: sdcard>","nativeURL":"file:///storage/emulated/0/.audio_param/"},{"isFile":false,"isDirectory":true,"name":"Music","fullPath":"/Music/","filesystem":"<FileSystem: sdcard>","nativeURL":"file:///storage/emulated/0/Music/"},{"isFile":false,"isDirec ...}]

The app uses cordova file plugin to read files.


问:
Could not write JSON Spring boot when entity return null
I'm using spring boot 3.0.1 and java 17

When I call entityManager.getById(entityId);

there are two cases when there is already an entity it returns well.

but when the entity returned is null this exception is thrown

```<code>Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Unable to find entity.Users with id 11]
</code>```

and added this property to application.properties file

```<code>spring.jackson.serialization.fail-on-empty-beans=false
</code>```

but no result.

please don't don't refer another answer because I'm checked most StackOverflow questions like this.

any advice will be good.

code snippet

```<code> public Users getById(Long entityId) {
        Optional.ofNullable(entityId).orElseThrow(() -> new RuntimeException("Failed to retrieve NULL entityId parameter"));
        return userRepository.getById(entityId);
    }
</code>```

i call this method in the restcontroller layer

Body:
I'm using spring boot 3.0.1 and java 17

When I call entityManager.getById(entityId);

there are two cases when there is already an entity it returns well.

but when the entity returned is null this exception is thrown

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Unable to find entity.Users with id 11]

and added this property to application.properties file

spring.jackson.serialization.fail-on-empty-beans=false

but no result.

please don't don't refer another answer because I'm checked most StackOverflow questions like this.

any advice will be good.

code snippet

 public Users getById(Long entityId) {
        Optional.ofNullable(entityId).orElseThrow(() -> new RuntimeException("Failed to retrieve NULL entityId parameter"));
        return userRepository.getById(entityId);
    }

i call this method in the restcontroller layer


问:
Can I draw a line between two plotshape? Pinescript
I have an indicator in tradingview that has many plotshapes I need to draw a line with the last two plotshapes. How I can draw a line for those plotshapes is there any way?   Image with Plotshape

```<code>enter code here
</code>```

//@version=5
indicator('Ahmad Saleh Supertrend', overlay=true, format=format.price, precision=2, timeframe='')

Periods = input(title='ATR Period', defval=10)
src = input(hl2, title='Source')
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=3.0)
changeATR = input(title='Change ATR Calculation Method ?', defval=true)
showsignals = input(title='Show Buy/Sell Signals ?', defval=true)
highlighting = input(title='Highlighter On/Off ?', defval=true)
atr2 = ta.sma(ta.tr, Periods)
atr = changeATR ? ta.atr(Periods) : atr2
up = src - Multiplier * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + Multiplier * atr
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title='UpTrend Begins', location=location.absolute, style=shape.cross, size=size.tiny, color=color.new(color.green, 0))
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title='DownTrend Begins', location=location.absolute, style=shape.cross, size=size.tiny, color=color.red)
mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0)
alertcondition(buySignal, title='SuperTrend Buy', message='SuperTrend Buy!')
alertcondition(sellSignal, title='SuperTrend Sell', message='SuperTrend Sell!')
changeCond = trend != trend[1]
alertcondition(changeCond, title='SuperTrend Direction Change', message='SuperTrend has changed direction!')```

Body:
I have an indicator in tradingview that has many plotshapes I need to draw a line with the last two plotshapes. How I can draw a line for those plotshapes is there any way?   Image with Plotshape

enter code here

//@version=5
indicator('Ahmad Saleh Supertrend', overlay=true, format=format.price, precision=2, timeframe='')

Periods = input(title='ATR Period', defval=10)
src = input(hl2, title='Source')
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=3.0)
changeATR = input(title='Change ATR Calculation Method ?', defval=true)
showsignals = input(title='Show Buy/Sell Signals ?', defval=true)
highlighting = input(title='Highlighter On/Off ?', defval=true)
atr2 = ta.sma(ta.tr, Periods)
atr = changeATR ? ta.atr(Periods) : atr2
up = src - Multiplier * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + Multiplier * atr
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title='UpTrend Begins', location=location.absolute, style=shape.cross, size=size.tiny, color=color.new(color.green, 0))
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title='DownTrend Begins', location=location.absolute, style=shape.cross, size=size.tiny, color=color.red)
mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0)
alertcondition(buySignal, title='SuperTrend Buy', message='SuperTrend Buy!')
alertcondition(sellSignal, title='SuperTrend Sell', message='SuperTrend Sell!')
changeCond = trend != trend[1]
alertcondition(changeCond, title='SuperTrend Direction Change', message='SuperTrend has changed direction!')


问:
Getting Total unread messages count in Twilio Conversations
we're using Twilio Conversations to power 1-to-1 chat for a webapp. I see that the unreadMessagesCount implemented via Read Horizon can indicate the number of unread messages in a particular conversation for a participant.

My question: Is there a way to get the total unread messages for ALL of a user's ongoing conversations?  E.g., if a user has 3 ongoing conversations that each have 5 unread messages, I would like to provide the user with an badge showing they have 15 unread messages (i.e., the customary user experience using messaging apps).

Would we have to loop through all the conversations that a user is a participant of and call unreadMessagesCount for each? If so, have some concern if that would bog down performance too much as some users could be a participant to a large number of conversations.

If total count of unread messages in all conversations is not able to be implemented efficiently, would also be fine if could just identify the total number of 1-on-1 conversations that have 1+ unread messages. But have not found a way to do this either.

Appreciate any thoughts on the best way to implement this.


问:
Sum time based chart data
I have a chart which displays data over time (months in my case). The data for this chart is randomly generated by getting any date from now to 500 days in the past (chartDate), and a random number (sales). It generates 500 of these rows.

```<code>func dailySales2() -> [(chartDate: Date, year: String, sales: Int)] {
    var temp: [(chartDate: Date, year: String, sales: Int)] = []

    for _ in 1...500 {
        let dateT = Calendar.current.date(byAdding: .day, value: -Int.random(in: 1...500), to: Date())!
        temp.append((chartDate: dateT, year: dateT.formatted(.dateTime.year()), sales: Int.random(in: 100...500)))
    }

    return temp.sorted(by: { $0.chartDate < $1.chartDate })
}

Chart {
            ForEach(dailySales2(), id: \.chartDate) { chartD in
                BarMark(
                    x: .value("Day", chartD.chartDate, unit: .month),
                    y: .value("Sales", chartD.sales)
                )
                .foregroundStyle(by: .value("Year:", chartD.year))
            }
        }
</code>```

The above takes all the rows for each month and totals them, so each bar is a sum of all the sales for each month. If I change this to a LineMark, it displays each row individually, how can I stop this and instead sum all the individual rows into one point for each month? Thanks.

I'm expecting each month column to display a single point which sums all the rows that contains data for that month.

Title: Sum time based chart data

Body:
I have a chart which displays data over time (months in my case). The data for this chart is randomly generated by getting any date from now to 500 days in the past (chartDate), and a random number (sales). It generates 500 of these rows.

func dailySales2() -> [(chartDate: Date, year: String, sales: Int)] {
    var temp: [(chartDate: Date, year: String, sales: Int)] = []

    for _ in 1...500 {
        let dateT = Calendar.current.date(byAdding: .day, value: -Int.random(in: 1...500), to: Date())!
        temp.append((chartDate: dateT, year: dateT.formatted(.dateTime.year()), sales: Int.random(in: 100...500)))
    }

    return temp.sorted(by: { $0.chartDate < $1.chartDate })
}

Chart {
            ForEach(dailySales2(), id: \.chartDate) { chartD in
                BarMark(
                    x: .value("Day", chartD.chartDate, unit: .month),
                    y: .value("Sales", chartD.sales)
                )
                .foregroundStyle(by: .value("Year:", chartD.year))
            }
        }

The above takes all the rows for each month and totals them, so each bar is a sum of all the sales for each month. If I change this to a LineMark, it displays each row individually, how can I stop this and instead sum all the individual rows into one point for each month? Thanks.

I'm expecting each month column to display a single point which sums all the rows that contains data for that month.