fluentbit connection to fluentd refused

Question: The issue
I have been trying to use the fluent-operator to deploy fluentbit and fluentd in a multi-tenant scenario in EKS cluster.
The goal is to collect logs with fluentbit and then forward to fluentd to process and send to OpenSearch.
The logs are being collected by fluentbit, but then fluentbit pod logs the following error when trying to communicate with fluentd:
[2023/02/10 17:54:57] [error] [net] TCP connection failed: fluentd.fluent.svc:24224 (Connection refused)
[2023/02/10 17:54:57] [error] [output:forward:forward.0] no upstream connections available

[2023/02/10 17:54:57] [error] [engine] chunk '12-1676051688.632628964.flb' cannot be retried: task_id=16, input=tail.1 > output=forward.0
[2023/02/10 17:54:57] [ warn] [engine] failed to flush chunk '12-1676051696.570563472.flb', retry in 6 seconds: task_id=7, input=tail.1 > output=forward.0 (out_id=0)
[2023/02/10 17:54:57] [error] [engine] chunk '12-1676051685.661115204.flb' cannot be retried: task_id=8, input=tail.1 > output=forward.0
[2023/02/10 17:54:57] [ warn] [engine] failed to flush chunk '12-1676051696.742618827.flb', retry in 6 seconds: task_id=10, input=tail.1 > output=forward.0 (out_id=0)
[2023/02/10 17:54:57] [ info] [input:tail:tail.1] inode=45094081 handle rotation(): /var/log/containers/fluent-bit-dj2j8_fluent_fluent-bit-a1d1b1304f8a9f66bb394f20e2400898f9dbe354992f4190e44d2f6b2d48d80f.log => /var/log/pods/fluent_fluent-bit-dj2j8_b907b949-bc53-47e6-91f0-709647fd7733/fluent-bit/0.log.20230210-175457
[2023/02/10 17:54:57] [ info] [input:tail:tail.1] inotify_fs_remove(): inode=45094081 watch_fd=966

Fluentd starts up fine, and then can't connect to OpenSearch:
level=info msg="Fluentd started"
2023-02-14 21:22:23 +0000 [info]: init supervisor logger path=nil rotate_age=nil rotate_size=nil
2023-02-14 21:22:23 +0000 [info]: parsing config file is succeeded path="/fluentd/etc/fluent.conf"
2023-02-14 21:22:24 +0000 [info]: gem 'fluentd' version '1.15.3'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-aws-elasticsearch-service' version '2.4.1'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-dedot_filter' version '1.0.0'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-detect-exceptions' version '0.0.14'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-elasticsearch' version '5.2.4'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-grafana-loki' version '1.2.20'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-kafka' version '0.18.1'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-label-router' version '0.2.10'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-multi-format-parser' version '1.0.0'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-opensearch' version '1.0.10'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-oss' version '0.0.2'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-record-modifier' version '2.1.1'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-rewrite-tag-filter' version '2.4.0'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-s3' version '1.7.2'
2023-02-14 21:22:24 +0000 [info]: gem 'fluent-plugin-sumologic_output' version '1.8.0'
2023-02-14 21:22:25 +0000 [info]: using configuration file: <ROOT>
  <system>
    rpc_endpoint "127.0.0.1:24444"
    log_level info
    workers 1
  </system>
  <source>
    @type forward
    bind "0.0.0.0"
    port 24224
  </source>
  <match **>
    @id main
    @type label_router
    <route>
      @label "@d2d59c6c703bc71418b747e394ea26bb"
      <match>
        namespaces fluent,kube-system,kyverno,observability-system
      </match>
    </route>
  </match>

    <match **>
      @id ClusterFluentdConfig-cluster-fluentd-config::cluster::clusteroutput::fluentd-output-opensearch-0
      @type opensearch
      host "vpc-XXXXX-us-west-2-XXXXXXX.us-west-2.es.amazonaws.com"
      logstash_format true
      logstash_prefix "logs"
      port 9200
    </match>

  <match **>
    @type null
    @id main-no-output
  </match>

    <match fluent.*>
      @type null
      @id main-fluentd-log
    </match>

</ROOT>
2023-02-14 21:22:25 +0000 [info]: starting fluentd-1.15.3 pid=13 ruby="3.1.3"
2023-02-14 21:22:25 +0000 [info]: spawn command to main:  cmdline=["/usr/bin/ruby", "-Eascii-8bit:ascii-8bit", "/usr/bin/fluentd", "-c", "/fluentd/etc/fluent.conf", "-p", "/fluentd/plugins", "--under-supervisor"]
2023-02-14 21:22:25 +0000 [info]: init supervisor logger path=nil rotate_age=nil rotate_size=nil
2023-02-14 21:22:27 +0000 [info]: #0 init worker0 logger path=nil rotate_age=nil rotate_size=nil
2023-02-14 21:22:27 +0000 [info]: adding match in @d2d59c6c703bc71418b747e394ea26bb pattern="**" type="opensearch"
2023-02-14 21:22:36 +0000 [warn]: #0 [ClusterFluentdConfig-cluster-fluentd-config::cluster::clusteroutput::fluentd-output-opensearch-0] Could not communicate to OpenSearch, resetting connection and trying again. connect_write timeout reached
2023-02-14 21:22:36 +0000 [warn]: #0 [ClusterFluentdConfig-cluster-fluentd-config::cluster::clusteroutput::fluentd-output-opensearch-0] Remaining retry: 14. Retry to communicate after 2 second(s).
2023-02-14 21:22:45 +0000 [warn]: #0 [ClusterFluentdConfig-cluster-fluentd-config::cluster::clusteroutput::fluentd-output-opensearch-0] Could not communicate to OpenSearch, resetting connection and trying again. connect_write timeout reached

The configuration of fluentd-output-opensearch, fluentd service, fluentbit service, clusteroutput.fluentbit, fluentd pod and fluentbit pod seem ok:
apiVersion: fluentd.fluent.io/v1alpha1
kind: ClusterOutput
metadata:
  annotations:
    meta.helm.sh/release-name: fluent-operator
    meta.helm.sh/release-namespace: fluent
  creationTimestamp: "2023-02-10T14:28:57Z"
  generation: 1
  labels:
    app.kubernetes.io/managed-by: Helm
    output.fluentd.fluent.io/enabled: "true"
  name: fluentd-output-opensearch
  resourceVersion: "8982613"
  uid: dcacb711-72b5-4fb3-9ec8-fab78f85e171
spec:
  outputs:
  - buffer:
      path: /buffers/opensearch
      type: file
    opensearch:
      host: vpc-XXXX-us-west-2-XXXXXXXXXX.us-west-2.es.amazonaws.com
      logstashFormat: true
      logstashPrefix: logs
      port: 9200

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2023-02-10T12:29:53Z"
  labels:
    app.kubernetes.io/component: fluentd
    app.kubernetes.io/instance: fluentd
    app.kubernetes.io/name: fluentd
  name: fluentd
  namespace: fluent
  ownerReferences:
  - apiVersion: fluentd.fluent.io/v1alpha1
    blockOwnerDeletion: true
    controller: true
    kind: Fluentd
    name: fluentd
    uid: 98e29fa5-c0c0-4239-a7d8-61eb3ff59c18
  resourceVersion: "8902659"
  uid: 62273018-9921-41b9-a38a-32c703264a4c
spec:
  clusterIP: 10.100.195.123
  clusterIPs:
  - 10.100.195.123
  internalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - name: forward
    port: 24224
    protocol: TCP
    targetPort: forward
  selector:
    app.kubernetes.io/component: fluentd
    app.kubernetes.io/instance: fluentd
    app.kubernetes.io/name: fluentd
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2023-02-13T18:44:57Z"
  labels:
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: fluent-bit
  name: fluent-bit
  namespace: fluent
  ownerReferences:
  - apiVersion: fluentbit.fluent.io/v1alpha2
    blockOwnerDeletion: true
    controller: true
    kind: FluentBit
    name: fluent-bit
    uid: 4fae4404-bea4-4cdd-aaf3-52b97d758bff
  resourceVersion: "12053875"
  uid: 89fa21db-cd70-4bcd-81f6-a1bd47cab74c
spec:
  clusterIP: 10.100.253.128
  clusterIPs:
  - 10.100.253.128
  internalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - name: metrics
    port: 2020
    protocol: TCP
    targetPort: 2020
  selector:
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: fluent-bit
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}

apiVersion: fluentbit.fluent.io/v1alpha2
kind: ClusterOutput
metadata:
  annotations:
    meta.helm.sh/release-name: fluent-operator
    meta.helm.sh/release-namespace: fluent
  creationTimestamp: "2023-02-10T12:29:44Z"
  generation: 1
  labels:
    app.kubernetes.io/managed-by: Helm
    fluentbit.fluent.io/component: logging
    fluentbit.fluent.io/enabled: "true"
  name: fluentd
  resourceVersion: "8902495"
  uid: b333b5e4-128d-419c-a726-cd8a8edeb4cf
spec:
  forward:
    host: fluentd.fluent.svc
    port: 24224
  matchRegex: (?:kube|service)\.(.*)

apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubernetes.io/psp: eks.privileged
  creationTimestamp: "2023-02-13T18:44:58Z"
  generateName: fluentd-
  labels:
    app.kubernetes.io/component: fluentd
    app.kubernetes.io/instance: fluentd
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: fluentd
    controller-revision-hash: fluentd-d8ddb8bd9
    statefulset.kubernetes.io/pod-name: fluentd-0
  name: fluentd-0
  namespace: fluent
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: StatefulSet
    name: fluentd
    uid: 7c239d83-7421-4ed6-88a8-2e5f6c76facd
  resourceVersion: "12054209"
  uid: 2a3b0d84-78e6-4ae1-a90c-4a3d6fccba71
spec:
  containers:
  - env:
    - name: BUFFER_PATH
      value: /buffers
    image: kubesphere/fluentd:v1.15.3
    imagePullPolicy: IfNotPresent
    name: fluentd
    ports:
    - containerPort: 2021
      name: metrics
      protocol: TCP
    - containerPort: 24224
      name: forward
      protocol: TCP
    resources:
      limits:
        cpu: 500m
        memory: 500Mi
      requests:
        cpu: 100m
        memory: 128Mi
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /fluentd/etc
      name: config
      readOnly: true
    - mountPath: /buffers
      name: fluentd-buffer-pvc
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-n7vbs
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  hostname: fluentd-0
  nodeName: ip-172-23-137-214.us-west-2.compute.internal
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: fluentd
  serviceAccountName: fluentd
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - name: fluentd-buffer-pvc
    persistentVolumeClaim:
      claimName: fluentd-buffer-pvc-fluentd-0
  - name: config
    secret:
      defaultMode: 420
      secretName: fluentd-config
  - name: kube-api-access-n7vbs
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          expirationSeconds: 3607
          path: token
      - configMap:
          items:
          - key: ca.crt
            path: ca.crt
          name: kube-root-ca.crt
      - downwardAPI:
          items:
          - fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
            path: namespace
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2023-02-13T18:45:02Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2023-02-13T18:45:14Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2023-02-13T18:45:14Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2023-02-13T18:45:02Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: containerd://729776240915f3377c6a9bf06a7e19a5213672da96468cd9c8b599f157d6386c
    image: docker.io/kubesphere/fluentd:v1.15.3
    imageID: docker.io/kubesphere/fluentd@sha256:58caf053b0f903ce3d0fc86b7bc748839e1a4aed6c7d8c1d3285d28553e93bce
    lastState: {}
    name: fluentd
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2023-02-13T18:45:13Z"
  hostIP: 172.23.137.214
  phase: Running
  podIP: 172.30.43.227
  podIPs:
  - ip: 172.30.43.227
  qosClass: Burstable
  startTime: "2023-02-13T18:45:02Z"

apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubernetes.io/psp: eks.privileged
  creationTimestamp: "2023-02-13T18:44:57Z"
  generateName: fluent-bit-
  labels:
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: fluent-bit
    controller-revision-hash: 7b98cd9f49
    pod-template-generation: "1"
  name: fluent-bit-2sx6v
  namespace: fluent
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: DaemonSet
    name: fluent-bit
    uid: d33dcff3-2e04-42dd-816c-0edb3ea63a19
  resourceVersion: "12053982"
  uid: 296d44ba-b761-47f0-a4ec-ed55dfa507dd
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchFields:
          - key: metadata.name
            operator: In
            values:
            - ip-172-23-137-29.us-west-2.compute.internal
  containers:
  - env:
    - name: NODE_NAME
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: spec.nodeName
    - name: HOST_IP
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: status.hostIP
    image: kubesphere/fluent-bit:v2.0.9
    imagePullPolicy: IfNotPresent
    name: fluent-bit
    ports:
    - containerPort: 2020
      name: metrics
      protocol: TCP
    resources:
      limits:
        cpu: 500m
        memory: 200Mi
      requests:
        cpu: 10m
        memory: 25Mi
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /containers
      name: varlibcontainers
      readOnly: true
    - mountPath: /fluent-bit/config
      name: config
      readOnly: true
    - mountPath: /var/log/
      name: varlogs
      readOnly: true
    - mountPath: /var/log/journal
      name: systemd
      readOnly: true
    - mountPath: /fluent-bit/tail
      name: positions
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-gzqz8
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: ip-172-23-137-29.us-west-2.compute.internal
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: fluent-bit
  serviceAccountName: fluent-bit
  terminationGracePeriodSeconds: 30
  tolerations:
  - operator: Exists
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
  - effect: NoSchedule
    key: node.kubernetes.io/disk-pressure
    operator: Exists
  - effect: NoSchedule
    key: node.kubernetes.io/memory-pressure
    operator: Exists
  - effect: NoSchedule
    key: node.kubernetes.io/pid-pressure
    operator: Exists
  - effect: NoSchedule
    key: node.kubernetes.io/unschedulable
    operator: Exists
  volumes:
  - hostPath:
      path: /containers
      type: ""
    name: varlibcontainers
  - name: config
    secret:
      defaultMode: 420
      secretName: fluent-bit-config
  - hostPath:
      path: /var/log
      type: ""
    name: varlogs
  - hostPath:
      path: /var/log/journal
      type: ""
    name: systemd
  - hostPath:
      path: /var/lib/fluent-bit/
      type: ""
    name: positions
  - name: kube-api-access-gzqz8
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          expirationSeconds: 3607
          path: token
      - configMap:
          items:
          - key: ca.crt
            path: ca.crt
          name: kube-root-ca.crt
      - downwardAPI:
          items:
          - fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
            path: namespace
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2023-02-13T18:44:57Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2023-02-13T18:44:59Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2023-02-13T18:44:59Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2023-02-13T18:44:57Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: containerd://7e5101ec69c0b0f4749f3462306801b41ff41e6c288eff74a75e253e79626720
    image: docker.io/kubesphere/fluent-bit:v2.0.9
    imageID: docker.io/kubesphere/fluent-bit@sha256:7b66bfc157e60f17e26c5e1dbbe1ae79768446ffaad06b4a013a3efb65815cce
    lastState: {}
    name: fluent-bit
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2023-02-13T18:44:58Z"
  hostIP: 172.23.137.29
  phase: Running
  podIP: 172.30.30.141
  podIPs:
  - ip: 172.30.30.141
  qosClass: Burstable
  startTime: "2023-02-13T18:44:57Z"

Also, the fluentd globalInputs seem to be correct for forward inputs:
apiVersion: fluentd.fluent.io/v1alpha1
kind: Fluentd
metadata:
  annotations:
    meta.helm.sh/release-name: fluent-operator
    meta.helm.sh/release-namespace: fluent
  creationTimestamp: "2023-02-13T20:13:59Z"
  finalizers:
  - fluentd.fluent.io
  generation: 1
  labels:
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: fluentd
  name: fluentd
  namespace: fluent
  resourceVersion: "12115920"
  uid: f1448972-45d5-4a36-8d0d-ed2cf65ff730
spec:
  fluentdCfgSelector:
    matchLabels:
      config.fluentd.fluent.io/enabled: "true"
  globalInputs:
  - forward:
      bind: 0.0.0.0
      port: 24224
  image: kubesphere/fluentd:v1.15.3
  replicas: 1
  resources:
    limits:
      cpu: 500m
      memory: 500Mi
    requests:
      cpu: 100m
      memory: 128Mi
status:
  messages: all matched cfgs is valid
  state: active

I have all fluentbit, fluentd and fluent-operator pods up and running in the same namespace.
I also execd' into both fluentbit and fluentd pods. Running ping from fluentbit container to fluentd's podIP. It seems to work.
root@fluent-bit-gtslr:/# ping  172.30.30.141
PING 172.30.30.141 (172.30.30.141) 56(84) bytes of data.
64 bytes from 172.30.30.141: icmp_seq=1 ttl=253 time=0.742 ms
64 bytes from 172.30.30.141: icmp_seq=2 ttl=253 time=0.711 ms
64 bytes from 172.30.30.141: icmp_seq=3 ttl=253 time=0.693 ms
64 bytes from 172.30.30.141: icmp_seq=4 ttl=253 time=0.730 ms
64 bytes from 172.30.30.141: icmp_seq=5 ttl=253 time=0.730 ms
^C
--- 172.30.30.141 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4093ms
rtt min/avg/max/mdev = 0.693/0.721/0.742/0.017 ms

Why am I getting this error?
fluent-operator installation
I installed the fluent-operator via Helm:
helm install fluent-operator --create-namespace -n fluent https://github.com/fluent/fluent-operator/releases/download/v2.0.1/fluent-operator.tgz --values values.yaml

The values.yaml has the following configuration:
# Default values for fluentbit-operator.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

#Set this to containerd or crio if you want to collect CRI format logs
containerRuntime: docker
#  If you want to deploy a default Fluent Bit pipeline (including Fluent Bit Input, Filter, and output) to collect Kubernetes logs, you'll need to set the Kubernetes parameter to true
# see https://github.com/fluent/fluent-operator/tree/master/manifests/logging-stack
Kubernetes: true

operator:
# The init container is to get the actual storage path of the docker log files so that it can be mounted to collect the logs.
# see https://github.com/fluent/fluent-operator/blob/master/manifests/setup/fluent-operator-deployment.yaml#L26
  initcontainer:
    repository: "docker"
    tag: "20.10"
  container:
    repository: "kubesphere/fluent-operator"
    tag: "latest"
    # FluentBit operator resources. Usually user needn't to adjust these.
  resources:
    limits:
      cpu: 100m
      memory: 60Mi
    requests:
      cpu: 100m
      memory: 20Mi
  # Specify custom annotations to be added to each Fluent Operator pod.
  annotations: {}
  ## Reference to one or more secrets to be used when pulling images
  ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
  imagePullSecrets: []
  # - name: "image-pull-secret"
  # Reference one more key-value pairs of labels that should be attached to fluent-operator
  labels: {}
#  myExampleLabel: someValue
  logPath:
    # The operator currently assumes a Docker container runtime path for the logs as the default, for other container runtimes you can set the location explicitly below.
    # crio: /var/log
    containerd: /var/log

fluentbit:
  image:
    repository: "kubesphere/fluent-bit"
    tag: "v2.0.9"
  # fluentbit resources. If you do want to specify resources, adjust them as necessary
  #You can adjust it based on the log volume.
  resources:
    limits:
      cpu: 500m
      memory: 200Mi
    requests:
      cpu: 10m
      memory: 25Mi
  # Specify custom annotations to be added to each FluentBit pod.
  annotations: {}
    ## Request to Fluent Bit to exclude or not the logs generated by the Pod.
    # fluentbit.io/exclude: "true"
    ## Prometheus can use this tag to automatically discover the Pod and collect monitoring data
    # prometheus.io/scrape: "true"
  # Specify additional custom labels for fluentbit-pods
  labels: {}

  ## Reference to one or more secrets to be used when pulling images
  ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
  ##
  imagePullSecrets: [ ]
  # - name: "image-pull-secret"
  secrets: []
  # List of volumes that can be mounted by containers belonging to the pod.
  additionalVolumes: []
  # Pod volumes to mount into the container's filesystem.
  additionalVolumesMounts: []

  # Remove the above empty volumes and volumesMounts, and then set additionalVolumes and additionalVolumesMounts as below if you want to collect node exporter metrics
# additionalVolumes:
#   - name: hostProc
#     hostPath:
#       path: /proc/
#   - name: hostSys
#     hostPath:
#       path: /sys/
# additionalVolumesMounts:
#   - mountPath: /host/sys
#     mountPropagation: HostToContainer
#     name: hostSys
#     readOnly: true
#   - mountPath: /host/proc
#     mountPropagation: HostToContainer
#     name: hostProc
#     readOnly: true

  #Set a limit of memory that Tail plugin can use when appending data to the Engine.
  # You can find more details here: https://docs.fluentbit.io/manual/pipeline/inputs/tail#config
  #If the limit is reach, it will be paused; when the data is flushed it resumes.
  #if the inbound traffic is less than 2.4Mbps, setting memBufLimit to 5MB is enough
  #if the inbound traffic is less than 4.0Mbps, setting memBufLimit to 10MB is enough
  #if the inbound traffic is less than 13.64Mbps, setting memBufLimit to 50MB is enough
  input:
    tail:
      memBufLimit: 5MB
    nodeExporterMetrics: {}
    # uncomment below nodeExporterMetrics section if you want to collect node exporter metrics
#   nodeExporterMetrics:
#     tag: node_metrics
#     scrapeInterval: 15s
#     path:
#       procfs: /host/proc
#       sysfs: /host/sys

  #Configure the output plugin parameter in FluentBit.
  #You can set enable to true to output logs to the specified location.
  output:
#  You can find more supported output plugins here: https://github.com/fluent/fluent-operator/tree/master/docs/plugins/fluentbit/clusteroutput
    es:
      enable: false
      host: "<Elasticsearch url like elasticsearch-logging-data.kubesphere-logging-system.svc>"
      port: 9200
      logstashPrefix: ks-logstash-log
#      path: ""
#      bufferSize: "4KB"
#      index: "fluent-bit"
#      httpUser:
#      httpPassword:
#      logstashFormat: true
#      replaceDots: false
#      enableTLS: false
#      tls:
#        verify: On
#        debug: 1
#        caFile: "<Absolute path to CA certificate file>"
#        caPath: "<Absolute path to scan for certificate files>"
#        crtFile: "<Absolute path to private Key file>"
#        keyFile: "<Absolute path to private Key file>"
#        keyPassword:
#        vhost: "<Hostname to be used for TLS SNI extension>"
    kafka:
      enable: false
      brokers: "<kafka broker list like xxx.xxx.xxx.xxx:9092,yyy.yyy.yyy.yyy:9092>"
      topics: ks-log
    opentelemetry: {}
# You can configure the opentelemetry-related configuration here
    opensearch: {}
# You can configure the opensearch-related configuration here
    stdout:
      enable: true
    forward:
      enable: true
      host: fluentd
      port: 24224

  #Configure the default filters in FluentBit.
  # The `filter` will filter and parse the collected log information and output the logs into a uniform format. You can choose whether to turn this on or not.
  filter:
    kubernetes:
      enable: true
      labels: true
      annotations: true
    containerd:
  # This is customized lua containerd log format converter, you can refer here:
  # https://github.com/fluent/fluent-operator/blob/master/charts/fluent-operator/templates/fluentbit-clusterfilter-containerd.yaml
  # https://github.com/fluent/fluent-operator/blob/master/charts/fluent-operator/templates/fluentbit-containerd-config.yaml
      enable: true
    systemd:
      enable: true

fluentd:
  enable: true
  name: fluentd
  port: 24224
  image:
    repository: "kubesphere/fluentd"
    tag: "v1.15.3"
  replicas: 1
  forward:
    port: 24224
  watchedNamespaces:
    - default
    - kube-system
    - test-namespace
    - fluent
  resources:
    limits:
      cpu: 500m
      memory: 500Mi
    requests:
      cpu: 100m
      memory: 128Mi
  # Configure the output plugin parameter in Fluentd.
  # Fluentd is disabled by default, if you enable it make sure to also set up an output to use.
  output:
    es:
      enable: false
      host: elasticsearch-logging-data.kubesphere-logging-system.svc
      port: 9200
      logstashPrefix: ks-logstash-log
      buffer:
        enable: false
        type: file
        path: /buffers/es
    kafka:
      enable: false
      brokers: "my-cluster-kafka-bootstrap.default.svc:9091,my-cluster-kafka-bootstrap.default.svc:9092,my-cluster-kafka-bootstrap.default.svc:9093"
      topicKey: kubernetes_ns
      buffer:
        enable: false
        type: file
        path: /buffers/kafka
    stdout:
      enable: true
    opensearch:
      enable: true
      host: vpc-XXX-us-west-2-XXXXXXXX.us-west-2.es.amazonaws.com
      port: 9200
      logstashPrefix: logs
      buffer:
        enable: true
        type: file
        path: /buffers/opensearch

nameOverride: ""
fullnameOverride: ""
namespaceOverride: ""

Comment: Right. Also, please verify if the fluentd pod indeed exposes its port for listening and include that output in your question. This looks like a connectivity issue. You can check the connectivity from these pods, just to make sure everything is connected.
Comment: Right. Please check and verify the `fluentd` connectivity with OpenSearch as well with `ping` and `telnet`.
Comment: The above code blocks show the configurations after the helm charts were rendered with the `values.yaml`, right?
Comment: Exactly, @Azeem . I ran `kubectl get -o yaml` on these resources
Comment: @Azeem done. I ran `kubectl get -o yaml` on the fluentd and fluentbit pods. The fluentd pod shows `- containerPort: 24224` for TCP forward.
Comment: @Azeem Also added fluentbit service.
Comment: Did you try to `ping` or `telnet` pods from each other?
Comment: @Azeem i did. Pinging fluentd podIP seems to work. Added this test to the question. –
Comment: Good. What about `telent` to the exposed port? And, are there any network policies there?
Comment: `telnet: Unable to connect to remote host: Connection refused.`. I ran telnote on the service ip:port from inside the fluentbit container. No network policies...
Comment: So, you have a connectivity issue. In an earlier comment, you said that you see that the service port is being exposed. Did you check whether the container is actually running? What about its logs? Have you verified whether the fluentd instance actually starts?
Comment: @Azeem as you can see in the Fluentd yaml:  ` globalInputs: - forward: bind: 0.0.0.0 port: 24224`.  And the Service one: ` ports: - name: forward port: 24224 protocol: TCP targetPort: forward`
Comment: Those configs look fine. I'm referring to the deployed services e.g. `kubectl get` and then using `kubectl logs`. See https://kubernetes.io/docs/reference/kubectl/cheatsheet/.
Comment: I've done all that. fluentbit logs are included in the question
Comment: Yes, fluentbit logs are there and it is unable to connect to fluentd. Have you checked the fluentd startup logs? is it able to start properly? Please check those and add those also. Thanks!
Comment: Yes, fluentd is running fine. Added logs to the question. Only problem is that it can't connect to OpenSearch. I'd be surprised, but it may be the central reason why fluentbit can't connect to fluentd since it is working as a mere proxy.
Answer: I have found a solution.
It seems that fluentd refuses fluentbit connection if it can't connect to OpenSearch beforehand.
I was sending logs to OpenSearch on port 9200(http). Then, I tested it on port 443.
Pinging OpenSearch from the node and from the pod on port 443 was the only request that worked.
So, I just added port 443 and scheme https to values.yaml. After that, logs starded popping up on OpenSearch Dashboards(Kibana). It ended like this:
# Default values for fluentbit-operator.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

#Set this to containerd or crio if you want to collect CRI format logs
containerRuntime: docker
#  If you want to deploy a default Fluent Bit pipeline (including Fluent Bit Input, Filter, and output) to collect Kubernetes logs, you'll need to set the Kubernetes parameter to true
# see https://github.com/fluent/fluent-operator/tree/master/manifests/logging-stack
Kubernetes: true

operator:
# The init container is to get the actual storage path of the docker log files so that it can be mounted to collect the logs.
# see https://github.com/fluent/fluent-operator/blob/master/manifests/setup/fluent-operator-deployment.yaml#L26
  initcontainer:
    repository: "docker"
    tag: "20.10"
  container:
    repository: "kubesphere/fluent-operator"
    tag: "latest"
    # FluentBit operator resources. Usually user needn't to adjust these.
  resources:
    limits:
      cpu: 100m
      memory: 60Mi
    requests:
      cpu: 100m
      memory: 20Mi
  # Specify custom annotations to be added to each Fluent Operator pod.
  annotations: {}
  ## Reference to one or more secrets to be used when pulling images
  ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
  imagePullSecrets: []
  # - name: "image-pull-secret"
  # Reference one more key-value pairs of labels that should be attached to fluent-operator
  labels: {}
#  myExampleLabel: someValue
  logPath:
    # The operator currently assumes a Docker container runtime path for the logs as the default, for other container runtimes you can set the location explicitly below.
    # crio: /var/log
    containerd: /var/log

fluentbit:
  image:
    repository: "kubesphere/fluent-bit"
    tag: "v2.0.9"
  # fluentbit resources. If you do want to specify resources, adjust them as necessary
  #You can adjust it based on the log volume.
  resources:
    limits:
      cpu: 500m
      memory: 200Mi
    requests:
      cpu: 10m
      memory: 25Mi
  # Specify custom annotations to be added to each FluentBit pod.
  annotations: {}
    ## Request to Fluent Bit to exclude or not the logs generated by the Pod.
    # fluentbit.io/exclude: "true"
    ## Prometheus can use this tag to automatically discover the Pod and collect monitoring data
    # prometheus.io/scrape: "true"
  # Specify additional custom labels for fluentbit-pods
  labels: {}

  ## Reference to one or more secrets to be used when pulling images
  ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
  ##
  imagePullSecrets: [ ]
  # - name: "image-pull-secret"
  secrets: []
  # List of volumes that can be mounted by containers belonging to the pod.
  additionalVolumes: []
  # Pod volumes to mount into the container's filesystem.
  additionalVolumesMounts: []

  # Remove the above empty volumes and volumesMounts, and then set additionalVolumes and additionalVolumesMounts as below if you want to collect node exporter metrics
# additionalVolumes:
#   - name: hostProc
#     hostPath:
#       path: /proc/
#   - name: hostSys
#     hostPath:
#       path: /sys/
# additionalVolumesMounts:
#   - mountPath: /host/sys
#     mountPropagation: HostToContainer
#     name: hostSys
#     readOnly: true
#   - mountPath: /host/proc
#     mountPropagation: HostToContainer
#     name: hostProc
#     readOnly: true

  #Set a limit of memory that Tail plugin can use when appending data to the Engine.
  # You can find more details here: https://docs.fluentbit.io/manual/pipeline/inputs/tail#config
  #If the limit is reach, it will be paused; when the data is flushed it resumes.
  #if the inbound traffic is less than 2.4Mbps, setting memBufLimit to 5MB is enough
  #if the inbound traffic is less than 4.0Mbps, setting memBufLimit to 10MB is enough
  #if the inbound traffic is less than 13.64Mbps, setting memBufLimit to 50MB is enough
  input:
    tail:
      memBufLimit: 5MB
    nodeExporterMetrics: {}
    # uncomment below nodeExporterMetrics section if you want to collect node exporter metrics
#   nodeExporterMetrics:
#     tag: node_metrics
#     scrapeInterval: 15s
#     path:
#       procfs: /host/proc
#       sysfs: /host/sys

  #Configure the output plugin parameter in FluentBit.
  #You can set enable to true to output logs to the specified location.
  output:
#  You can find more supported output plugins here: https://github.com/fluent/fluent-operator/tree/master/docs/plugins/fluentbit/clusteroutput
    es:
      enable: false
      host: "<Elasticsearch url like elasticsearch-logging-data.kubesphere-logging-system.svc>"
      port: 9200
      logstashPrefix: ks-logstash-log
#      path: ""
#      bufferSize: "4KB"
#      index: "fluent-bit"
#      httpUser:
#      httpPassword:
#      logstashFormat: true
#      replaceDots: false
#      enableTLS: false
#      tls:
#        verify: On
#        debug: 1
#        caFile: "<Absolute path to CA certificate file>"
#        caPath: "<Absolute path to scan for certificate files>"
#        crtFile: "<Absolute path to private Key file>"
#        keyFile: "<Absolute path to private Key file>"
#        keyPassword:
#        vhost: "<Hostname to be used for TLS SNI extension>"
    kafka:
      enable: false
      brokers: "<kafka broker list like xxx.xxx.xxx.xxx:9092,yyy.yyy.yyy.yyy:9092>"
      topics: ks-log
    opentelemetry: {}
# You can configure the opentelemetry-related configuration here
    opensearch: {}
# You can configure the opensearch-related configuration here
    stdout:
      enable: true
    # forward: # {{- if .Values.Kubernetes -}} {{- if .Values.fluentd.enable -}}
    #   host: fluentd.fluent.svc.cluster.local # host: {{ .Values.fluentd.name }}.{{ .Release.Namespace }}.svc on fluentbit-output-forward.yaml
    #   port: 24224 # {{ .Values.fluentd.forward.port }}

  #Configure the default filters in FluentBit.
  # The `filter` will filter and parse the collected log information and output the logs into a uniform format. You can choose whether to turn this on or not.
  filter:
    kubernetes:
      enable: true
      labels: true
      annotations: true
    containerd:
  # This is customized lua containerd log format converter, you can refer here:
  # https://github.com/fluent/fluent-operator/blob/master/charts/fluent-operator/templates/fluentbit-clusterfilter-containerd.yaml
  # https://github.com/fluent/fluent-operator/blob/master/charts/fluent-operator/templates/fluentbit-containerd-config.yaml
      enable: false
    systemd:
      enable: false

fluentd:
  enable: true
  name: fluentd
  port: 24224 # port: {{ .Values.fluentd.port }} on fluentd-fluentd.yaml
  image:
    repository: "kubesphere/fluentd"
    tag: "v1.15.3"
  replicas: 1
  forward:
    port: 24224 # port: {{ .Values.fluentd.forward.port }} on fluentbit-output-forward.yaml
  watchedNamespaces:
    - fluent
    - observability-system
    - default
  resources:
    limits:
      cpu: 500m
      memory: 500Mi
    requests:
      cpu: 100m
      memory: 128Mi
  # Configure the output plugin parameter in Fluentd.
  # Fluentd is disabled by default, if you enable it make sure to also set up an output to use.
  output:
    es:
      enable: false
      host: elasticsearch-logging-data.kubesphere-logging-system.svc
      port: 9200
      logstashPrefix: ks-logstash-log
      buffer:
        enable: false
        type: file
        path: /buffers/es
    kafka:
      enable: false
      brokers: "my-cluster-kafka-bootstrap.default.svc:9091,my-cluster-kafka-bootstrap.default.svc:9092,my-cluster-kafka-bootstrap.default.svc:9093"
      topicKey: kubernetes_ns
      buffer:
        enable: false
        type: file
        path: /buffers/kafka
    stdout:
      enable: true
    opensearch:
      enable: true
      host: vpc-XXXXX-us-west-2-XXXXXXXX.us-west-2.es.amazonaws.com
      port: 443
      logstashPrefix: logs
      scheme: https
      # buffer:
      #   enable: false
      #   type: file
      #   path: /buffers/opensearch

nameOverride: ""
fullnameOverride: ""
namespaceOverride: ""

Keep in mind that fluentd is running on Kubernetes cluster(EKS).
Another issue that I had to face was that after upgrading the fluent-operator release, the changes weren't applied to the fluentd pod.
This is because the fluentd template doesn't handle parameters like scheme.
But the CRD does: https://github.com/fluent/helm-charts/blob/main/charts/fluent-operator/crds/fluentd.fluent.io_clusteroutputs.yaml#L1411 .
So, I just had to apply this change manually and then kill the fluentd pod. After that, the pod recognized the changes and rendered the https scheme:
kubectl get clusteroutput fluentd-output-opensearch -o yaml

apiVersion: fluentd.fluent.io/v1alpha1
kind: ClusterOutput
metadata:
  annotations:
    meta.helm.sh/release-name: fluent-operator
    meta.helm.sh/release-namespace: fluent
  creationTimestamp: "2023-02-15T20:35:26Z"
  generation: 2
  labels:
    app.kubernetes.io/managed-by: Helm
    output.fluentd.fluent.io/enabled: "true"
  name: fluentd-output-opensearch
  resourceVersion: "14073767"
  uid: 9705d00f-5c10-4b32-916c-f6a487a3ac70
spec:
  outputs:
  - opensearch:
      host: vpc-XXXXX-us-west-2-XXXXXX.us-west-2.es.amazonaws.com
      logstashFormat: true
      logstashPrefix: logs
      port: 443
      scheme: https

fluentbit connection to fluentd refused


Is there any set of 2-6 notes that doesn't have a chord name?

Question: Is there any combination of up to six notes in the chromatic scale that could not be classified and named as a chord? Can anyone give me an example and explanation if so?
Comment: A chord is simply several notes played simultaneously. The combination of said notes doesn't *have* to sound good, but obviously is better when it does! Just about any combination will be a chord that can be named, but there comes a point where the name is so unwieldy that it gets ridiculous, and ceases to be anything sensible. Imagine C, C#, D, D#, E and F being played together, each a semitone apart. Even split by an octave or so wouldn't help much.  A chord, yes, but a good sound? And, what name should it have? Or, are you looking for the *lost chord*..?
Comment: I'm no chord naming aficionado but I might call that your classic Cmajno5add4addb3add2addb2 chord. But as for the reason for my inquiry, I was calculating the total possible chord combinations on a 22 fret 6 string guitar just for fun and had been working under the assumption that any combination of between 2 and 6 notes could be classified as a chord. ( It came out to be over 6 trillion and for many of them you might have to get your toes involved )
Comment: Why 6 chromatic notes?  What does this have to do with making a chord?  The 13th chord has 7 diatonic notes (and each diatonic is on the chromatic scale).  So this is a confusing question as worded.
Comment: @Todd Wilcox - somebody edited my original title, that's not how I had phrased it. the original question was is there any combination of between 2 and 6 notes on the chromatic scale that can't be classified and named as a chord.
Comment: @ggcg - because it's a question about guitar. guitars have 6 strings and therefor have a maximum of 6 notes that can be played at once
Comment: Guitar was not mentioned in the original post nor is it one of the flags.  I'd interpret it as a general theory question.
Comment: @EthanRichardson, when I say "original" I mean the first view I got of it.  Perhaps the term guitar was deleted.
Comment: I've edited it again. I added the guitar tag and put in what I thought was a clearer title. You can always edit your own questions, titles, and tags, so feel free to change it if you're not happy with anyone else's changes.
Comment: Thanks @ToddWilcox, I'd suggest an explicit edit "...up to six chromatic notes on the guitar, ...".
Answer: No, and for at least three reasons:

Assuming "chord" to be a tonal entity, we can explain anything as having alterations, omissions, and extensions. With add11, ♭13, no5, etc., we can make sense of any combination of tones.
We can understand harmonies as combinations of chords; such polychords allow any and all possibilities.
We have systems of understanding "chord" that do not assume tonality. Pitch-class set analysis—a system in which we assign integers to members of a harmony—is perhaps the most common. No matter how wild of a chord you come up with, there is a pitch-class set label for it.
Answer: Depends on your definitions.  There are certainly pitch sets that would be difficult (and pointless) to label in the 'C, Gm7, F#m7(b5)(b9)' naming system, or that defy functional analysis in the 'bii7 of iii' way.   But some will say that ANY pitch set is, by definition, a chord.  And, as @Richard says, any pitch-class set can be labelled.
Answer:
Is there any combination of up to six chromatic notes that could not be classified and named as a chord?

From the point of view of naming and classification, some would consider that groups/sets of 2 notes aren't named 'chords' as such: A chord is three notes? What do you call just two notes?.
Comment: I were only jesting! However, I really like chords with a group of zero notes when playing with specific guitarists.
Comment: @badjohn - I've heard *about* that Cage piece, but never had the pleasure of actually hearing it...
Comment: 'Groups of 1 or 2 notes'? A group of one? Interesting concept...
Comment: @Tim John Cage used some zero note chords in 4'33".
Comment: @Tim I have seen it but not heard it.  It is hard to analyze the harmonies because of division by zero errors with the frequencies.
Comment: @badjohn I was in an anechoic room once - acoustically I guess it's close to being in space (no floor - just a mesh of wires!). Not sure if I stayed in there for 4'33" though!
Comment: @Tim I thought that avoiding the notion of a group of zero would be enough to avoid controversy! I've edited slightly as OP specified 'combination' - though thinking in terms of mathematical sets, I guess you can have sets and combinations that are 0 or 1 in size.
Comment: @Tim joking aside (?) I did actually hear it performed recently. Not like I expected at all. I found it very tense actually.
Comment: @topomorto You managed to hear it?  You have better ears than me.
Comment: @badjohn well, in the performance, you hear everything that's happening. Aircon, people shuffling, the sound of your own blood pumping round your head... every performance is different, of course!
Comment: Ah, I made my own arrangement by writing a program to generate a WAV file of zero bytes.  Played on a good system in a nice room, it is as quiet as you can get with a medium budget.  I was in an audio lab once which was so quiet that I found it unpleasant.  I would struggle to bear 4'33" of that.
Comment: @topomorto The room I was in had a floor but I still found it quite unpleasant.  I probably didn't even manage 33".
Comment: Do the 'players' even turn over their music?
Comment: @Tim in the performance I saw, no (it was solo piano on that occasion). I don't actually recall if that was done from a score, or "from memory"...
Comment: Yes, I asked a friend who'd attended, and his memory was blank too!
Comment: What a relief. I thought I was the only one that felt that way about Cage. The guy very successfully convinced a lot of people to buy tickets to see nothing at all.
Answer: Interesting question. I would submit that if we take chord theory and apply it to pitches either above or below the ranges of human hearing that the resultant Chords would no longer exist simply because we can't hear them and therefore they would never be played. My thinking is that music isn't really music until it's being played, but that's just my own thoughts on the matter.
Comment: https://youtu.be/JTEFKFiXSx4
Comment: @b3ko- Some folks can call that music if they like, I'm inclined to call it a misnomer, kind of like saying you"re going somewhere if you just sit in your car, but thanks for pointing that out, I'd forgotten about Cage a long time ago.
Comment: I'd say it's closer to "art" than music. But [shrug].
Comment: @b3ko- I look for art and music to  move me in some way, and Cage failed miserably to do that. I found the price of the ticket to be a waste of my money. But, as you say, [shrug].
Answer: A chord can be defined as several notes sounding simoultaneously. No matter what notes you use. Some refer to clusters though, if you arrange the notes in close position, neighboring each other within the same octave.
For example a Cmaj7 chord uses a half step from 7th to root. You can raise the 7th an octave up and the chord loses its "cluster" character.
You could change octaves of your 6 note chromatic row, too and see what results you get.
A good orientation is the Schoenberg, Berg, Webern connection called "Zweite Wiener Schule" around the beginning of the 20th century. They do a lot with more or less mathematical constructions over tone rows. Even Bernstein´s West Side Story uses tone rows. It is impressing what he gets out of symmetric scales in terms of arranging, themes and chords...


How to get a decomposition(factorization) from sum of decompositions of a symmetric matrix?

Question: Suppose I have a symmetric matrix $S$ (unknown) to be computed, which is represented by:
$$ S = \sum_{i=0}^{\infty} A^{i\top}A^{i} = I + A^{\top}A + A^{2\top}A^{2} + \cdots, $$
where powers of $A$ (known) would decay to 0.
Now I want a decomposition of $S$, such that:
$$S = R^{\top}R.$$
Since $S$ is unknown, how can I get this decomposition $R^{\top}R$? Is there any relationship between $R$ and $A$, thus I don't need to compute $S$ to decompose $S$.
Comment: The decomposition is not unique. Even if you specify some unique decomposition, I don't think there is any nice explicit formula for $R$. Anyway, if $\rho(A)<1$, the series is guaranteed to converge to the unique solution of $A^TSA=S-I$. Perhaps this can help.
Comment: If $A$ is real and normal, then $S=(I-A^TA)^{-1}$ which is easy to calculate.
Comment: @greg  I think you have made a mistake. $(I-A^{\top}A)^{-1} = I + A^{\top}A + (A^{\top}A)^{2}+ \cdots, $ which is not equal to $S$. Since $A^{k\top}A^{k} \neq (A^{\top}A)^{k}$.
Comment: Yes, but if $A$ is real and _**normal**_  then $AA^T=A^TA$.
Comment: @greg, got it, but we cannot assume that $A$ is normal...
Answer: To follow up on a comment by user1551, we have a relationship
$$S-A^TSA = I$$
which admits a closed-form solution for $S$.
$$\eqalign{
 (I\otimes I - A^T\otimes A^T)\,{\rm vec}(S) = {\rm vec}(I) \cr
 {\rm vec}(S) = (I\otimes I - A^T\otimes A^T)^{-1}\,{\rm vec}(I) \cr
 S = {\rm devec}\Big((I\otimes I - A^T\otimes A^T)^{-1}\,{\rm vec}(I)\Big) \cr
}$$
Now choose a factorization (Cholesky) that has the desired form.
Comment: this method computes $S$ explicitly. And we also can compute $S$ by the original definition. Is there any closed-form solution for $R$?


Increasing function $f: \mathbb{N} \to \mathbb{R}^{\ge 0}$ such that $f(3^n) = 2^n$ and $\forall n \exists c : f(n+c)+f(n-c) \ge 2f(n).$

Question: Can we build $f: \mathbb{N} \to \mathbb{R}^{\ge 0}$ which is increasing and satisfies the following criterions?

$f(3^n) = 2^n$ for all $n.$
There exists $N$ such that for all $n \ge N,$ there exists some $c$ (which may depend on $n$) such that $f(n+c)+f(n-c) \ge 2f(n)$

I introduced the first criterion to make it easier to come up with the function on paper. I made a table using graph paper listing $n$ and $f(n)$ for $n = 1, \dots, 33$ and then put $1,2,4,8,\dots$ under the powers of $3.$ Now I'm having difficulties filling out this table so that the second criterion is satisfied
Remark: Even if this task is possible, $N$ might be insanely large. However, trying to beg for a larger $N$ is just delaying the inevitable. In any case, I can just let the first $N$ terms be something like $\epsilon, 2\epsilon \dots, \epsilon N,$ but the real challenge begins after I've put down those terms because from then on, there is no violation of the second criterion. With that being said, you might as well try to see if a low value of $N$ works.
1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33
1|?|2|?|?|?|?|?|4|?|?|?|?|?|?|?|?|?|?|?|?|?|?|?|?|?|8|?|?|?|?|?|?|
Update: An arithmetic progression between the powers of two almost works. It only  fails right on the powers of $2.$ So maybe there's some way to modify this idea that works.
Comment: I conjecture that the answer is ***no***.  The function $\phi:\mathbb{R}_{>0}\to\mathbb{R}_{>0}$ given by $\phi(x):=2^{\log_3(x)}$ for all $x>0$ is concave.  Since $f$ and $\phi$ coincide on $\{3^n\,|\,n\in\mathbb{Z}_{\geq 0}\}$, it is *unlikely* that $f$ will satisfy Condition 2 (please don't press me on this claim, I am guessing).  (Perhaps, you should state whether $\mathbb{N}=\{1,2,3,\ldots\}$ or $\mathbb{N}=\{0,1,2,\ldots\}$.)
Answer: No, such $f$ can't exist.  Consider an increasing function on $\mathbb N$ satisfying (1), and take any $N \in \mathbb N$.
If $3^m \le x < 3^{m+1}$ we have
$2^m \le f(x) < 2^{m+1}$, so for any constant $\alpha > 0$, $f(x) - \alpha x \to -\infty$ as $x \to \infty$.
Take $\alpha$ so $f(N) - N \alpha > f(x) - x\alpha$ for all $x < N$, i.e. $$\alpha < \min_{x < N} \frac{f(N) - f(x)}{N-x}.$$  Then the maximum of $f(x) - \alpha x$  for all $x \in \mathbb N$ is attained at some
$x_0$ with $x_0 \ge N$.  Moreover by choosing $\alpha$ appropriately we can ensure this maximum is unique (because there are only countably many $\alpha$ for which there is a tie).  Now for any $c > 0$, adding
$f(x_0) - \alpha x_0 > f(x_0 - c) - \alpha (x_0 - c)$ and
$f(x_0) - \alpha x_0 > f(x_0 + c) - \alpha (x_0 + c)$ we get
$2 f(x_0) - 2 \alpha x_0 > f(x_0 - c) + f(x_0 + c) - 2 \alpha x_0$,
i.e. $2 f(x_0) > f(x_0 - c) + f(x_0 + c)$, contradicting (2).
Comment: It is clear $f$ grows slower than $cx$ for any $c>0.$ But what motivated you from this observation to consider the maximum of $f(x)-cx$?
Comment: The geometric picture:  an extreme point of the convex hull of the graph is the maximum of a linear functional.


Determine the splitting field for a polynomial

Question:
Let $P(X)=X^4+1 \in \mathbb{Q[X]}$. Find the splitting field for $P$
  over $\mathbb{C}$ and determine the degree of it over $\mathbb{C}$.

My attempt: Roots of $P$ are $\alpha_1 = \sqrt{i},\alpha_2=-\sqrt{i},\alpha_3=i^{3/2},\alpha_4=-i^{3/2}$
Now the splitting field is $\mathbb{Q}(\sqrt{i},i)$. Since, $i$ has minimal polynomial of degree 2, $\sqrt{i}$ has minimal polynomial of degree 4, thus $[\mathbb{Q}(\sqrt{i},i):\mathbb{Q}]=[\mathbb{Q}(\sqrt{i}):\mathbb{Q}]=4$
Is there a more elegant argument? Can the roots of $P$ be expressed in a better form (analogue to roots of unity for $X^n-1$)?
Comment: The roots of $P$ _are_ roots of unity. They are the zeroes of $X^8-1$ which aren't roots of $X^2+1$, $X+1$ or $X-1$. In other words, they are the _primitive_ 8th roots of unity.
Comment: You may want to use that $$x^4+1=(x^2+\sqrt2\,x+1)(x^2-\sqrt2\,x+1)$$
Comment: What is $\sqrt i$? The number $i$ has two square roots.
Comment: Hint to connect above two comments: calculate $(1+i)^2$ and find (both values of) $\sqrt i$ explicitly.
Comment: Over $\Bbb C$??
Answer: Let $\alpha=\dfrac1{\sqrt 2}(1+i)$. The roots of $P$ are $\alpha$, $\alpha^3$, $\alpha^5$ and $\alpha^7$. So the splitting field over $\Bbb Q$ is $\Bbb Q(\alpha)$.
Answer: I'd use the decomposition $$X^4+1 = (X^2-i)(X^2+i).$$
Then
$$X^2-i = (X-\alpha)(X+\alpha)\quad\mbox{and}\quad X^2+i = (X+\beta)(X-\beta),$$ where $i=\alpha^2$ and $-i=\beta^2$. So $\alpha$ and $\beta$ are 8-th roots of unity.
Take the primitive 8-th root of unity $\xi=e^{2\pi i/8}$. Then $\alpha=\xi$ and $\beta=\xi^3$.
Added: There is a simpler way to arrive at the decomposition. For this, consider
$$X^8-1 = (X^4+1)(X^4-1).$$
The decomposition of $X^4-1$ are the 4th roots of unity:
$$X^4-1 = (X-1)(X+1)(X-i)(X+i).$$
So in view of the above notation, $\xi^0=1$, $\xi^2=i$, $\xi^4=-1$, $\xi^6=-i$, and so
$$X^4+1 = (X-\xi)(X-\xi^3)(X-\xi^5)(X-\xi^7).$$
The zeros are all the primitive 8th roots of unity. Cheers!


Repeated Measures, or just measuring the same thing, repeatedly?

Question: I understand what "repeated measures" denotes - given a set of subjects, if each subject receives more than one treatment, we call this repeated measures, or "within subjects." But what if we are giving the same subject the same treatment at different times, but time itself is not a relevant factor?
Let me give a more specific, albeit graphic example -
Say that I am giving a patient a pill that will cause their body to purge in a multitude of ways. They will sweat, cry, urinate, etc. The same pill is used each time, there is no difference in the treatment. I will measure the quantity of each output. I will do this 7 times to each patient, in order to try to get an accurate representation of these outputs. The independent variables are patient and type of excretion (both categorical, non-ordinal). The dependent variable is simply the amount of liquid excreted (continuous).
I want to ask two questions of my data -

Is there a statistically significant difference between the patients?
Is there a statistically significant difference between the type of secretions, given the amount that is released?

Do these two questions require two separate statistical analyses, or is there a single test that can help me answer both questions?
I have been breaking the data into separate sets by secretion type and doing a Kruskall-Wallis test (the data is non-parametric) to identify if there is a difference between patients for each secretion type, but what if I want to talk about the difference across patients more generally?
Is this considered repeated measures?
I have dug myself into quite a statistical rabbit hole on this one.
Answer: The question comes down to the independence among the observations. Even if you don't care about the time course,  an individual who cried more than others in one exposure to the drug is likely to do so in other exposures. You can't treat the 7 drug exposures of that individual as independent observations--it's not the same as having 7 separate individuals who happened to have the same responses to the drug. Yet simple statistical tests assume that all observations are independent.
One way to model this for a small number of patients (say 6 or fewer) and continuous outcomes would be with a multivariate analysis of variance, with patientID as a predictor and separate outcome columns for each type of secretion. A textbook appendix by Fox and Weisberg illustrates that with the classic iris data set. Alternatively, you could use both patientID and a categorical predictor of secretionType, including an interaction between the two predictors to allow for differences among patients with respect to secretion types.
With a larger number of patients you might be more interested in the overall variance of responses among patients rather than specific individuals. That could be handled with a mixed model, with secretionType as the "fixed" predictor and patientID included for random effects. To allow for differences among patients with respect to secretion types, you could use both random intercepts and random slopes (coefficients for the secretion types) as you have a large number of replicates.
You say that "the data is non-parametric", but all data are non-parametric. "Parametric" is about the type of model used to describe the data. You might do well with the parametric models described above, perhaps with some transformations of outcome values. A proportional odds model can be considered a semi-parametric extension of non-parametric tests like Wilcoxon-Mann-Whitney and Kruskal-Wallis if your data can't readily be represented with parametric models.
Comment: Thank you for the thoughtful and thorough response.
And my apologies, what I mean is that the data is not normally distributed; it actually appears to be log-normal, but typically data transformations are not a heuristic in my field. Can the multivariate anova be applied to non-normally distributed data?
Comment: @DataOnToast the distributions of the data values themselves (whether outcomes or predictors) don't matter for ANOVA. What matters is the distribution of the _error terms_ of observations around the model predictions. If they are close enough to normal, ANOVA is OK. There's nothing wrong with log transformations to make error distributions closer to normal, but then you're modeling the mean of the _logs_ of the outcomes, not the mean of the outcomes.  I would lean toward the second choice in that paragraph (patientID, secretionType and their interaction in a linear model), or a mixed model.
Comment: Thanks again, EdM. Two more questions for you, if I may -

1. If the errors are NOT normally distributed (very cone-shaped residual plot / does not pass normality of residuals tests), then what?
2. Where can I take your class? (;
Comment: @DataOnToast 1. see [this page](https://stats.stackexchange.com/q/100214/28500) and its links for suggestions about non-normal residuals. You often don't need normal residuals, if residuals don't change a lot as a function of estimated values and you have enough cases. [Proportional odds (PO) models](https://hbiostat.org/blog/post/rpo/) don't make assumptions about residuals; you can test the PO assumption and you can [often get away with violations](https://hbiostat.org/blog/post/po/). 2. Almost everything I know about statistics I learned on this site, following its links to other resources.


Cannot access nested json key value

Question: My json structure:
http://snag.gy/da0nf.jpg
my jquery: (  http://jsfiddle.net/EAcs9/2/  )
var wotAPI = "http://api.worldoftanks.com/2.0/clan/info/?";
$.getJSON( wotAPI, {application_id: "16924c431c705523aae25b6f638c54dd",clan_id: "1000013300"})

.done( function( jsonData ) {
$.each( jsonData.data, function( i ) {
        $('#result').append(i);
    });
});

I would like to iterate the members in my JSON object and access each member to get their account_name.  I can't seem to get this to work.  Can someone have a look at tell me how to resolve this.  I think I am missing a concept here.
Comment: JavaScript in HTML pane?
Comment: You probably meant to do something closer to: http://jsfiddle.net/EAcs9/2/
Answer: Your real issue is in this code.  What is it supposed to do, because I dont think it's doing what you think it's doing.
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;

        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }

    return objects;
}

Looks like objects is reset to be an empty array on every iteration of the recursion.
Comment: I'm referring to jsfiddle.net/EAcs9/2 I was playing around with the /1/ version of which you've commented on. You were very quick to respond before i managed to correct the url.

Cannot access nested json key value


How to find a closed form of this simple factorial sequence

Question: $$S_1=1\\ S_n=n!+S_{n-1}$$
Is there a simple way to express $S_n$ without summing up all the previous terms? Sorry I haven't put any effort in the problem but I don't know where to start.
So this means that $$S_1=1\\ S_2=3\\ S_3=9\\ S_4=33$$ and so on. Thanks in advance.
Comment: Even if you (understandably) want to avoid summing up a series like this, it's still a good idea to compute the first few terms in order to get a feel for the sequence. (And it's an easy thing to include in your question.)
Comment: @Semiclassical Done!
Answer: According to a CAS, there is effectively a closed form $$S_n=-(-1)^n \Gamma (n+2)~ \text{Subfactorial}[-n-2]-2 ~\text{Subfactorial}[-3]+1$$ in which function $\text{Subfactorial}[k]$ gives the number of permutations of $n$ objects that leave no object fixed.
I bet that this will not be very practical.
Answer: $S_n=1!+2!+\cdots + n!$. Now, a detailed discussion of this sum can be obtained here.
Answer: OEIS sequence A007489.  No "closed form" is listed.


Como distribuir igualmente os itens de uma lista horizontal independente da quantidade dos mesmos?

Question: O snippet abaixo está funcionando corretamente, dividindo a barra de navegação em quatro itens igualmente distribuídos na horizontal. Execute-o para observar. Porém não está como eu gostaria: o campo largura (width) de cada item da lista é 25%, e isso só funciona porque há exatamente quatro itens na lista. Gostaria que o CSS mantivesse a distribuição igualitária dos itens independente da quantidade dos mesmos no HTML. É possível?

* {
    border: 0px;
    margin: 0px;
    padding: 0px;
    border-width: 0px;
    outline-width: 0px;
}

nav {
    background-color: #a9eaff;
}

nav ul {
    display: table;
    width: 100%;
}

nav ul li {
    list-style-type: none;
    display: table-cell;
    width: 25%;
    text-align: center;
    font-weight: bold;
}

nav ul li:hover {
    background-color: blue;
    text-color: white;
}

nav ul li a {
    display: block;
    text-decoration: none;
    width: 100%;
    height: 100%;
}

nav ul li a:hover {
    color: white;
}

Início

Ideias

Tecnologias

Demonstrações

Answer: Isso é bem simples de fazer utilizando display:flex. Precisa de aplicar essa regra de estilo no elemento pai dos que quer distribuir, e depois define a forma como eles se alinham com a regra justify-content.
No seu caso dá jeito ter:
justify-content:space-around;

Que distribui o espaço à volta dos elementos. Veja como fica:

* {
    border: 0px;
    margin: 0px;
    padding: 0px;
    border-width: 0px;
    outline-width: 0px;
}

nav {
    background-color: #a9eaff;
}

nav ul {
    /*display: table; - removido*/
    display:flex; /*flex aqui - novo*/
    justify-content:space-around; /*e distribuição de espaço aqui - novo*/
    width: 100%;
}

nav ul li {
    list-style-type: none;
    /*display: table-cell; - removido
    width: 25%; - removido*/
    text-align: center;
    font-weight: bold;
    width: 100%;
}

nav ul li:hover {
    background-color: blue;
    text-color: white;
}

nav ul li a {
    display: block;
    text-decoration: none;
    width: 100%;
    height: 100%;
}

nav ul li a:hover {
    color: white;
}

Início

Ideias

Tecnologias

Demonstrações

Se tiver 5 elementos funciona na mesma:

* {
    border: 0px;
    margin: 0px;
    padding: 0px;
    border-width: 0px;
    outline-width: 0px;
}

nav {
    background-color: #a9eaff;
}

nav ul {
    display:flex;
    justify-content:space-around;
    width: 100%;
}

nav ul li {
    list-style-type: none;
    text-align: center;
    font-weight: bold;
    width: 100%;
}

nav ul li:hover {
    background-color: blue;
    text-color: white;
}

nav ul li a {
    display: block;
    text-decoration: none;
    width: 100%;
    height: 100%;
}

nav ul li a:hover {
    color: white;
}

Início

Ideias

Tecnologias

Demonstrações

Outro link

A forma como os elementos se distribuem é controlada pela regra flex-direction que por defeito é row e faz com que os elementos fiquem todos na mesma linha.
Comment: Muito bom! Só acrescentei `width: 100%;` nos itens de lista do segundo exemplo para o efeito ficar totalmente igual ao do snippet da pergunta (o link ficar maior que o comprimento do texto).
Comment: @Piovezan Sim tem razão, retirei quando estava a testar e esqueci-me de colocar de novo com a dimensão que interessa.


Evaluate $\int_0^{\pi} \frac{\cos m\theta-\cos m \phi}{\cos \theta - \cos \phi} \text{d}\theta$

Question: In the Hardy's book Divergent series is proved the equality
$$\frac{\cos m\theta-\cos m \phi}{\cos \theta - \cos \phi} \text{d}\theta=2\sum_{n=1}^{\infty} \frac{\sin n\phi}{\sin \phi} \cos n\theta(\cos m\theta-\cos m \phi)$$
With $m\in\mathbb{N}$. Then integrating that equality $0<\theta<\pi$ (he says "ignoring any difficulties about the range of $\theta$ over which it may be expected to be valid) we obtain
$$\int_0^{\pi} \frac{\cos m\theta-\cos m \phi}{\cos \theta - \cos \phi} \text{d}\theta=\pi \frac{\sin m\phi}{\sin \phi}$$
How that result is reached? I've tried, in a sloppy way (because I didn't proved the possibility to exchange series and integral), this approach with Werner identities
$$\int_0^\pi 2\sum_{n=1}^{\infty} \frac{\sin n\phi}{\sin \phi} \cos n\theta(\cos m\theta-\cos m \phi) \text{d}\theta=$$
$$2\sum_{n=1}^{\infty} \frac{\sin n\phi}{\sin \phi} \int_0^\pi (\cos n\theta \cos m\theta-\cos n\theta\cos m \phi) \text{d}\theta=$$
$$\sum_{n=1}^{\infty} \frac{\sin n\phi}{\sin \phi} \int_0^\pi (\cos (n\theta+m\theta)+\cos (n\theta-m\theta) -\cos (n\theta+m\phi) -\cos (n\theta-m\phi)) \text{d}\theta=$$
$$\sum_{n=1}^{\infty} \frac{\sin n\phi}{\sin \phi} \left[\frac{\sin (n\theta+m\theta)}{n+m}+\frac{\sin(n\theta-m\theta)}{n-m} -\frac{\sin(n\theta+m\phi)}{n} -\frac{\sin(n\theta-m\phi)}{n}\right]_{\theta=0}^{\theta=\pi}=$$
$$\sum_{n=1}^{\infty} \frac{\sin n\phi}{\sin \phi} \left[\frac{\sin (n\pi+m\pi)}{n+m}+\frac{\sin(n\pi-m\pi)}{n-m} -\frac{\sin(n\pi+m\phi)}{n} -\frac{\sin(n\pi-m\phi)}{n}\right]$$
And here I'm stuck. Any help is appreciated.
Comment: Using approach0.xyz research tool, I found this proof by induction by "vanstraelen" : https://artofproblemsolving.com/community/c7h627103p3762369
Comment: See as well https://math.stackexchange.com/questions/3061827/compute-int-0-pi-frac-cosnx-cosx-cosnt-cost-cosx-cost
Answer: Here is my approach to the problem. It is natural to think of complex analysis. Let $\sqrt{-1}=i$. Now we will prove that:
$$I_m:=\int_{0}^{\pi} \frac{\cos mx}{\cos x - \cos \phi}\mathrm{d}x = \pi\cdot \frac{\sin m\phi}{\sin \phi}=\frac{1}{2}\int_{-\pi}^{\pi} \frac{\cos mx}{\cos x - \cos \phi}\mathrm{d}x$$$$=\frac{1}{2}\int_{-\pi}^{\pi} \frac{e^{imx}+e^{-imx}}{\left(e^{ix}-e^{i\phi}\right)\left(e^{ix}-e^{-i\phi}\right)}\mathrm{d}x$$
Let $z=e^{ix}$, $\mathrm{d}z = ie^{ix}\mathrm{d}x$. Hence:
$$I_m = \frac{-1}{4\sin\phi}\left(\int_{\vert z\vert=1}\frac{z^m}{\left(z-e^{i\phi}\right)\left(z-e^{-i\phi}\right)}\mathrm{d}z-\int_{\vert z\vert=1}\frac{z^{-m}}{\left(z-e^{i\phi}\right)\left(z-e^{i\phi}\right)}\mathrm{d}z\right)=A_m-B_m$$
Where:
$$A_m:=\frac{-1}{4\sin\phi}\int_{\vert z\vert=1}\frac{z^m}{\left(z-e^{i\phi}\right)\left(z-e^{-i\phi}\right)}\mathrm{d}z$$
$$B_m:=\frac{-1}{4\sin\phi}\int_{\vert z\vert=1}\frac{z^{-m}}{\left(z-e^{i\phi}\right)\left(z-e^{-i\phi}\right)}\mathrm{d}z$$
We need to show that $B_m = 0, \forall m \in \mathbb{N}$.It is obvious for $n=1$ We only need to show that:
$$J_m:=\int_{\vert z \vert = 1} \frac{1}{z^m (z-z_1)}\mathrm{d}z = 0, \forall m\in \mathbb{N}, z_1 = e^{i\phi}. $$
By induction, it is obvious that for $m=1$, we have $J_1= 0$. Assume that $J_m =0$ for $m=n-1$. We need to show that $J_n =0$.Since $\frac{1}{z^m}, m>1$ is a meromorphic function, by partial fraction decomposition:
$$J_n=z_1^{-1}\int_{\vert z \vert = 1}\frac{1}{z^{n}} - \frac{1}{z^{n-1}(z-z_1)}\mathrm{d}z=0 - J_{n-1}=0.$$
By obtaining this result, it follows directly that $B_m=0$.Finally, for $A_m$ by Residue theorem, leads us:
$$I_m:=A_m=\frac{-2\pi i}{4\sin\phi}\left(e^{im\phi}-e^{-im\phi}\right)=\pi \frac{\sin m\phi}{\sin \phi}$$
Then your result follows easily since:
$$\int_0^{\pi} \frac{\cos m\theta-\cos m \phi}{\cos \theta - \cos \phi} \text{d}\theta=I_m - I_0 =\pi \frac{\sin m\phi}{\sin \phi}$$
Comment: This can be turned into a workable method, but $I_m$ diverges for real $\phi$. If $\phi \not \in \mathbb R$ or $I_m, A_m, B_m, J_m$ are understood as p.v. integrals (although neither is the simplest way), then $A_m = B_m$ and $J_m \neq 0$. Also, there should be an $e^{ix}$ factor in the second line, and the third line should be $I_m = 2 i (A_m + B_m) \sin \phi$.
Answer: I understand that perhaps my answer isn't exactly what this post is looking for but I thought you would all appreciate seeing the question being done using techniques taught at high school.
We will need to make use of the following result...
$$
\text{(1)}\hspace{1cm}\frac{\sin nz}{\sin z}=e^{i(n-1)z}+e^{i(n-3)z}+\ldots+e^{-i(n-1)z}
$$
We can show this by using Euler's formula to express the sine function.
$$
\begin{align*}
\frac{\sin nz}{\sin z}&=\frac{\frac{e^{inz}-e^{-inz}}{2i}}{\frac{e^{iz}-e^{-iz}}{2i}}\\
&=\frac{e^{inz}-e^{-inz}}{e^{iz}-e^{-iz}}\\
&=e^{i(n-1)z}+e^{i(n-3)z}+\ldots+e^{-i(n-1)z}\\
&=\sum_{k=1}^n e^{i(n+1-2k)\theta}\\
&=\sum_{l=1}^n e^{i(2l-(n+1))\theta}
\end{align*}
$$
Begin by using the sum to product identities and employing (1)...
$$
\begin{align*}
\int_0^\pi\frac{\cos n\theta-\cos n\phi}{\cos \theta-\cos\phi}\,\mathrm{d}\theta&=\int_0^\pi\frac{-2\sin\left(n\frac{\theta+\phi}{2}\right)\sin\left(n\frac{\theta-\phi}{2}\right)}{-2\sin\left(\frac{\theta+\phi}{2}\right)\sin\left(\frac{\theta-\phi}{2}\right)}\,\mathrm{d}\theta\\
&=\int_0^\pi\frac{\sin\left(n\frac{\theta+\phi}{2}\right)}{\sin\left(\frac{\theta+\phi}{2}\right)}\times\frac{\sin\left(n\frac{\theta-\phi}{2}\right)}{\sin\left(\frac{\theta-\phi}{2}\right)}\,\mathrm{d}\theta\\
&\stackrel{\text{(1)}}{=}\int_0^\pi\left(\sum_{k=1}^n e^{i(n+1-2k)\frac{\theta+\phi}2}\right)\left(\sum_{l=1}^n e^{i(2l-(n+1))\frac{\theta-\phi}2}\right)\,\mathrm{d}\theta\\
&=\sum_{k=1}^n\sum_{l=1}^n\int_0^\pi e^{i[(l-k)\theta+(n+1-k-l)\phi]}\,\mathrm{d}\theta\\
&=e^{i(n+1)\phi}\sum_{k=1}^n\sum_{l=1}^ne^{-i(k+l)\phi}\int_0^\pi e^{i(l-k)\theta}\,\mathrm{d}\theta\\
&=e^{i(n+1)\phi}\left(\sum_{k=2}^n\sum_{l=1}^{k-1}e^{-i(k+l)\phi}\int_0^\pi e^{i(l-k)\theta}\,\mathrm{d}\theta+\sum_{l=2}^n\sum_{k=1}^{l-1}e^{-i(k+l)\phi}\int_0^\pi e^{i(l-k)\theta}\,\mathrm{d}\theta+\sum_{k=1}^n\sum_{l=k}^ke^{-i(k+l)\phi}\int_0^\pi e^{i(l-k)\theta}\,\mathrm{d}\theta\right)\\
&=e^{i(n+1)\phi}\left(\sum_{k=2}^n\sum_{l=1}^{k-1}e^{-i(k+l)\phi}\int_0^\pi e^{i(l-k)\theta}\,\mathrm{d}\theta+\sum_{k=2}^n\sum_{l=1}^{k-1}e^{-i(k+l)\phi}\int_0^\pi e^{-i(l-k)\theta}\,\mathrm{d}\theta+\sum_{k=1}^n\sum_{l=k}^ke^{-i(k+l)\phi}\int_0^\pi e^{i(l-k)\theta}\,\mathrm{d}\theta\right)\\
&=e^{i(n+1)\phi}\left(\sum_{k=2}^n\sum_{l=1}^{k-1}e^{-i(k+l)\phi}\int_0^\pi e^{i(l-k)\theta}+e^{-i(l-k)\theta}\,\mathrm{d}\theta+\sum_{k=1}^ne^{-i(k+k)\phi}\int_0^\pi e^{i(k-k)\theta}\,\mathrm{d}\theta\right)\\
&=e^{i(n+1)\phi}\left(\sum_{k=2}^n\sum_{l=1}^{k-1}e^{-i(k+l)\phi}\int_0^\pi 2\cos\left((l-k)\theta\right)\,\mathrm{d}\theta+\sum_{k=1}^ne^{-i(k+k)\phi}\int_0^\pi\,\mathrm{d}\theta\right)\\
&=e^{i(n+1)\phi}\left(\sum_{k=2}^n\sum_{l=1}^{k-1}e^{-i(k+l)\phi}\left[\frac2{l-k}\sin\left((l-k)\theta\right)\right]_0^\pi+\pi\sum_{k=1}^ne^{-i2k\phi}\right)\\
&=\pi e^{i(n+1)\phi}\sum_{k=1}^ne^{-i2k\phi}=\pi \sum_{k=1}^ne^{n+1-i2k\phi}\\
&\stackrel{\text{(1)}}{=}\pi\frac{\sin n\phi}{\sin\phi}
\end{align*}
$$


Programmatically append multiple paragraphs to entity reference field on node

Question: I have a paragraph type that contains a text field and a text format field.
I also have a content type that takes an unlimited number of paragraphs of this type.
The paragraph type is called 'questions_and_answers' and the two fields are 'field_question' and 'field_answer'. I'd like to be able to programmatically append 'questions_and_answers' paragraphs to a content type.
In the example below I'm grabbing the content from a 'double' field and importing them into the paragraph reference field.
Here's my code so far.
<code>    $nids = \Drupal::entityQuery('node')
        ->condition('type', 'faq')
        ->execute();
    foreach ($nids as $nid) {
        $node      = \Drupal\node\Entity\NODE::load($nid);
        $questions = $node->field_questions_and_answers->getValue();
        foreach ($questions as $question) {
            $q         = $question['first'];
            $a         = $question['second'];
            $paragraph = Paragraph::create([
                    'title'          => $q,
                    'type'           => 'questions_and_answers',
                    'field_question' => $q,
                    'field_answer'   => $a,
                ]);
            $paragraph->save();
            $node->field_qs_and_as[] = $paragraph->id();
        }
        $node->save();
    }
</code>
However when I perform this action the node gets a number of question paragraphs added but they're completely empty and they can't even be deleted. What am I missing? How do you append multiple paragraphs you created to an entity reference field on a node?
Answer: When you add a paragraph you also need to pass the revision id:
<code>  $node->field_qs_and_as[] = [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ];
</code>
Comment: Yes, I assume field_qs_and_as is an entity_reference_revisions field because paragraphs doesn't support core entity_reference fields.
Comment: Hi, I have added like this, I can see all paragraphs on node view but when I edit node I can edit only last paragraph. Do you know why?
Answer: I've found it preferable to pass the entity object instead of manually setting the IDs yourself:
<code>$node->field_qs_and_as[] = $paragraph;
$node->save();
</code>
Only make one call to $node->save() of course, after you've added/edited all the paragraph entities you want.
The primary reason for this is that when I set the reference array values instead, at least in the case of a newly created paragraph, the paragraph does not end up with a parent entity set. If you later need to call $paragraph->getParentEntity() or otherwise make use of Paragraphs' ability to trace the relationship in the reverse direction, that will be a problem.
I haven't looked at the code paths but it makes sense that if you call ->save() on the Paragraph it will not be able to detect a parent on its own. I would imagine the Entity Reference Revisions code handling array values then assumes that the relationship must already established on the child entity, if it's being passed existing IDs instead of an object.
Answer: I spent hours make it work, the problem was when adding a paragraph to my multivalues node field, the existing values were lost.
I finally came to this working solution (retrieving existing paragraphs and adding them back together with the new paragraph), but I feel I'm missing something...
<code>$currentUser = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$product = Node::load($form_state->getValue('product_id'));

//create new ordered_item paragraph
$order = Paragraph::create(['type' =>'item_ordered']);
$order->field_item_ordered_number = $form_state->getValue('quantity');
$order->field_item_ordered_product = $product->id();
$order->uid = $currentUser->id();
$order->save();

$order_items[] = [
'target_id' => $order->id(),
'target_revision_id' => $order->getRevisionId(),
];

//check if user has already a cart
$cart=\Drupal::service('dpnews_home.get_user_infos')->getUserCart($currentUser);

foreach ($cart->field_ordered_item as $item) {
  $existing_order=$item->entity;
  $order_items[] = [
  'target_id' => $existing_order->id(),
  'target_revision_id' => $existing_order->getRevisionId(),
  ];
}
//if not create new cart for user
if(!isset($cart)){
  $cart = Node::create(['type' => 'panier']);
  $cart->uid = $currentUser->id();
  $cart->title= 'Panier en cours - utilisateur '.$currentUser->id();
  $cart->save();
}

//add ordered item to cart
$cart->set('field_ordered_item',$order_items);
$cart->save();
</code>


If $X$ is well-ordered set, how to prove that $\mathcal{P}(X)$ can be linearly ordered?

Question: I'm having troubles solving the following exercise, proposed in T. Jech, 'Set theory' Exercises 5.4.

Let $X$ is well-ordered set then $\mathcal{P}(X)$ can be linear ordered.
[Let $X<Y$ if the least element of $X\triangle Y$ belongs to $X$.]

I can prove that $<$ satisfies totality (i.e. $X<Y$ or $X=Y$ or $Y<X$) and $X\not< X$, but I can't prove transitivity of $<$. Thanks for any help.
Comment: Suppose $X<Y$ and $Y<Z$. Let $x$ be the least element of $X\triangle Y$ and $y$ the least element of $Y\triangle Z$. What do you think we need to prove?
Answer: Suppose that $A<B$ and $B<C$; Let $a=\min(A\mathbin{\triangle}B)\in A$ and $b=\min(B\mathbin{\triangle}C)\in B$. Then $a\notin B$, so $a\ne b$.

Suppose that $a<b$. If $x\in X$ and $x<a$, then $x\in A$ iff $x\in B$ iff $x\in C$, so $x\notin A\mathbin{\triangle}C$. Since $a\notin B$ and $a<b$, $a\notin C$, and therefore $a=\min(A\mathbin{\triangle}C)$, i.e., $A<C$.
Now suppose that $b<a$. If $x\in X$ and $x<b$, then $x\in A$ iff $x\in B$ iff $x\in C$, so $x\notin A\mathbin{\triangle}C$. And $b\in A\setminus C$ (why?), so $b=\min(A\mathbin{\triangle}C)\in A$, and again $A<C$.


StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Lcom/android/org/conscrypt/ConscryptEngineSocket;->setHostname(

Question: I have following Error in Google Play before app publish. It is not a warning but an error. I can see warnings with similar stack trace.  I am not sure if the app will be rejected because of these because the summary of the Pre-launch report is confusing. It says no issues. But under stability it shows the warnings and error under Android compatibility. It seems to be caused by some library used by react-native (from some similar posts its seems like okhttp) but I am not sure what this trace means.
I am very new to react-native and am not sure how to resolve this. I could not find any solution whatsoever, just a few similar posts but no solutions. Our app release is stuck because of this issue. Any help would be greatly appreciated.
StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Lcom/android/org/conscrypt/ConscryptEngineSocket;->setHostname(Ljava/lang/String;)V
    at android.os.StrictMode.lambda$static$1(StrictMode.java:416)
    at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2)
    at java.lang.Class.getDeclaredMethodInternal(Native Method)
    at java.lang.Class.getPublicMethodRecursive(Class.java:2079)
    at java.lang.Class.getMethod(Class.java:2066)
    at java.lang.Class.getMethod(Class.java:1693)
    at okhttp3.internal.platform.OptionalMethod.getPublicMethod(OptionalMethod.java:164)
    at okhttp3.internal.platform.OptionalMethod.getMethod(OptionalMethod.java:149)
    at okhttp3.internal.platform.OptionalMethod.invokeOptional(OptionalMethod.java:66)
    at okhttp3.internal.platform.OptionalMethod.invokeOptionalWithoutCheckedException(OptionalMethod.java:86)
    at okhttp3.internal.platform.AndroidPlatform.configureTlsExtensions(AndroidPlatform.java:123)
    at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:314)
    at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:283)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:168)
    at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
    at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
    at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:923)

Comment: Thanks @Bink The Google Play Console has highlighted that the error needs to be fixed before moving to prod.
There are 2 errors and 10 warnings. The one above is marked as error
Comment: While you'll want to try to resolve this, I don't believe this will prevent your app from being published.
Comment: I see.  I have lots of StrictMode policy violations for my own app, but none that have ever prevented me from publishing.  Perhaps this is an issue in OkHttp like you noted.  I don't use React Native, but this sounds like something that might be resolved by upgrading to the latest version if you haven't already.
Comment: @ManishHaldankar I'm having the same issue with RN. Were you able to resolve this?
Comment: I have the same issue in Flutter app. Is there any updates on this?
Comment: @ManishHaldankar did your app got rejected because of this? I am facing a similar problem but could n't found out any issue in the app. so was checking pre-release report and stumbled here. App got rejected because of the crash they were facing, but couldn't reproduce on all devices available.
Answer: I found that change to okhttp3 3.12.13 can fix the error
https://square.github.io/okhttp/changelog_3x/
In android/app/build.gradle, add the following two lines
implementation("com.squareup.okhttp3:okhttp:3.12.13")
implementation("com.squareup.okhttp3:okhttp-urlconnection:3.12.13")

However, there still exists some warnings, but at least no errors.
Comment: can this be used in React Native versions too?
Answer: with gradlew app_name:dependencies command I found out what old firebase crashlytics version use old com.squareup.okhttp3version. Changing my gradle config to use newest firebase crashlytics solved the problem.


Embed view block with JSON data output

Question: How can I embed the output of a view in another page, as a JSON Data Document, without stopping the page processing ?
I have a view with format set to JSON data document and am attempting to embed the block output in a node with views_embed_view('nec_map_data','block').
This embeds the block but with Views API mode unchecked page processing is stopped at the JSON and the page doesn't render.
If I enable Views API Mode then the block output is wrapped in a div.
I would like the JSON output from the view to be assigned to a javascript variable in the node. How can I achieve this ?
Answer: You can do that by adding this function ( a customized version of the original views_json_get in the view_datasource module ) in your template or custom module
/**
 * Gets JSON data from a View rendered in the JSON data document style.
 *
 * This is useful for when working with a JSON view in code.
 *
 * @param $name
 *   The name of the view.
 * @param $display_id
 *   The display of the view to use.
 * @param $args
 *   The arguments to pass to the view.
 * @param $raw
 *   If TRUE, the JSON data is returned as a string.  Otherwise, an object
 *   representation is returned.
 * @return
 *   The JSON data in the form of an object or a string or NULL otherwise.
 */
function views_json_noheader_get($name, $display_id = 'default', $args = array(), $raw = FALSE) {
  $view = views_get_view($name);
  if (!is_object($view)) {
    return NULL;
  }

   $view->display[$display_id]->display_options['style_options']['using_views_api_mode'] = 1;

  $preview = $view->preview($display_id, $args);
  $start_pos = strpos($preview, '{');
  $finish_pos = strrpos($preview, '}');
  $length = $finish_pos - $start_pos + 1;
  $json = trim(substr($preview, $start_pos, $length));

  if ($raw) {
    return $json;
  }

  return json_decode($json);
}

and  get the result of your view  by typing in your function:
$json = views_json_noheader_get('yourviewname', 'yourview json display id', null, true);

Embed view block with JSON data output


How to ignore modified configuration file in Git

Question: I have a project in Git that I'm going to install in many PC. There's a configuration file named config.ts and has the following structure:
export var config = {
   apiUrl: "",
   local: "",
   scannerUrl: "",
   reportPrinterUrl: ""
}

What I need is to create the file if not exists when I execute the git pull origin master command, but stop tracking it when it's modified so it can be modified in any pc and the configuration won't be pushed or erased in the next pull.
I've read some questions and articles but I've seen many options like git stash, --asume-unchanged and still not pretty sure how to do it.
(Sorry for bad english)
EDIT
The most simple way that I've found to just forget about the file is to execute this command in every pc
git update-index --assume-unchanged <file>

Credits from here
EDIT 2
Like torek said in the comments, the current best solution is to create the "template" file and name it "config.blank.ts" (or something like that) and then add to .gitignore the "config.ts" file. So the procedure should be cloning the repo and then copy the file to config.ts and then modify it.
Comment: In general, the right way to do this is to omit the actual configuration file entirely, and commit instead a *sample* configuration file, that users of the software copy and modify to local requirements during installation. You can even have your program do this installation automatically, and/or read the sample / default file first, then read any *overrides* from the (never-committed, in-`.gitignore`) *local* configuration.
Comment: Use `--skip-worktree`, not `--assume-unchanged`. Both bits generally have the same effect but `--skip-worktree` has a different *intent:* it tells Git to *skip* the worktree version, while `--assume-unchanged` tells Git that *testing* the work-tree version is too expensive to do if there's no call to do it, but that Git *could* test the work-tree version if it wanted to. (But it's far better to never commit the local configuration in the first place.)
Comment: Add this file to your .gitignore
Comment: but that only works if the file has never been commited, and if that's the case then i wont be able to get the "clean" version of it the first time for the structure
Answer: Simply don't push the changes to your config file.
When you clone this project onto different local machines, you want to make your necessary changes to the config file. In order to keep these changes from being pushed back to the remote repository, don't add or commit these changes to your git history.
Say you have files x, y and z. You make changes to all three of these files but you don't want to push the changes made in file y.
git add /path/to/x
git add /path/to/z
git commit
# etc

Add to your .gitignore
If say your config file has been adding in previous commits, you would have to run the following.
echo "config.ts" > .gitignore
git rm --cached config.ts

If you then run a git status, you'll see that your config file has been deleted. This is only deleted on your git-index, not actually deleted on your machine.
Comment: I guess it's the most simple way to do this
Comment: It is saying Access denied


How to send a voice message using flutter?

Question: Actually I need to send a voice message to my contacts using flutter.I have searched a lot.But I didn't get any idea on this.Is there any way to do this.?
Comment: Whats to send prerecorded message or record and send?
Comment: I need to send an Instant records.
Comment: Can you please check https://pub.dartlang.org/flutter/packages?q=share+file where many plugins available for sharing files
Comment: Thanks @Rahul Mahadik .But I have checked on that also.Still I didn't get any idea.
Comment: Did you find a way?
Answer: if you want to share a voice message in a chat(e.g firebase chat) you can use flutter_sound, send a voice file to your cloud, and you can play it again with flutter_sound too.
Answer: You can use the audio_recorder package:
https://pub.dev/packages/audio_recorder
<code>// Import package
import 'package:audio_recorder/audio_recorder.dart';

// Check permissions before starting
bool hasPermissions = await AudioRecorder.hasPermissions;

// Get the state of the recorder
bool isRecording = await AudioRecorder.isRecording;

// Start recording
await AudioRecorder.start(path: _controller.text, audioOutputFormat: AudioOutputFormat.AAC);

// Stop recording
Recording recording = await AudioRecorder.stop();
print("Path : ${recording.path},  Format : ${recording.audioOutputFormat},  Duration : ${recording.duration},  Extension : ${recording.extension},");
</code>


keepalived 2 VIP and 2 servers

Question: Is it possible to configure keepalived in such a way?
In normal state VIP_1 assigned to SERVER_1 and VIP_2 assigned to SERVER_2
On server failure all VIP's going to working server, and after failed server becomes live we don't migrate his VIP back to him, we need to do it manual due to some content-replication reasons.
configuration at the moment:
#SERVER_1
vrrp_sync_group VG1 {
        group {
          content
        }
    }

    vrrp_instance content {
        state BACKUP
        interface eth1
        virtual_router_id 1
        priority 100
        advert_int 1
        authentication {
            auth_type PASS
            auth_pass 1212
        }
        virtual_ipaddress {
            192.168.100.111/24
        }
    }

    # SERVER_2

    vrrp_sync_group VG1 {
        group {
          content
        }
    }

    vrrp_instance content {
        state BACKUP
        interface eth1
        virtual_router_id 1
        priority 100
        advert_int 1
        authentication {
            auth_type PASS
            auth_pass 1212
        }
        virtual_ipaddress {
            192.168.100.111/24     }
    }

Answer: On host 1:
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    dont_track_primary
    virtual_router_id 1
    priority 150
    advert_int 5
    mcast_src_ip 172.16.40.1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
    10.0.0.1/24 dev eth0
    }
}

vrrp_instance VI_2 {
    state BACKUP
    interface eth0
    dont_track_primary
    virtual_router_id 5
    priority 100
    advert_int 5
    mcast_src_ip 172.16.40.1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        10.0.0.2/24 dev eth0
    }
}

On host 2:
vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    dont_track_primary
    virtual_router_id 1
    priority 100
    advert_int 5
    mcast_src_ip 172.16.40.2
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        10.0.0.1/24 dev eth0
    }
}

vrpp_instance VI_2 {
    state MASTER
    interface eth0
    dont_track_primary
    virtual_router_id 5
    priority 150
    advert_int 5
    mcast_src_ip 172.16.40.2
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        10.0.0.2/24 dev eth0
    }
}

For the no-auto-failback, look at nopreempt in the keepalived.conf man page but also see:
http://article.gmane.org/gmane.linux.keepalived.devel/1537%22
Comment: errm, can't correct IPs instead of  `blah blah blah` sections in your answer, always get 2 IPs on same server. can you make more detailed configuration?
Comment: Updated with sample RFC 1918 addresses on dev eth0 10.0.0.1 is primary on VIP on host1, 10.0.0.2 is for host2.  Failover is bidirectional.  See note about about nopreempt but use BACKUP for initial states for all VIPs.

keepalived 2 VIP and 2 servers


Requisição OPTIONS não chegando até o servidor

Question: Estou fazendo requisições POST enviando e recebendo JSON em minha API PHP. Quando estou no localhost funciona como esperado, porém quando estou em produção recebo o erro abaixo no chromium:
OPTIONS http://myserver.com/my-dir/api/person/exists net::ERR_EMPTY_RESPONSE

E no firefox:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myserver.com/my-dir/api/person/exists. (Reason: CORS request did not succeed).[Learn More]
Error: "0"
    onreadystatechange http://examplesite.com/js/app.ec842a5c.js:1:25207

No servidor tenho:
header("Access-Control-Allow-Origin: http://examplesite.com");
header("Content-Type: multipart/form-data; application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Expose-Headers: Authorization");
header("Access-Control-Allow-Headers: Origin, Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Credentials, Authorization, X-Requested-With");

if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   http_response_code(200);
   echo json_encode(array("message" => "OK!"));
   exit(0);
}

No cliente:
const request = new XMLHttpRequest();
request.onreadystatechange = function() {
  if(request.readyState === XMLHttpRequest.DONE) {
    if(request.status === 200) {
      console.log(request);
    }
  }
}
request.onerror = function() {
  console.log(Error("Network Error"));
};
request.open('POST', 'http://myserver.com/my-dir/api/person/exists', true);
const jwt = localStorage.getItem('jwt');
if(jwt) {
  request.withCredentials = true;
  request.setRequestHeader('Authorization', 'Baerer ' + jwt);
}
request.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
request.setRequestHeader('Accept', 'application/json');
request.send(JSON.stringify(data));

Os Headers do Chromium:
General

Request URL: http://myserver.com/my-dir/api/person/exists
Referrer Policy: no-referrer-when-downgrade

Request Headers

Provisional headers are shown
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://examplesite.com
Referer: http://examplesite.com/
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36

Os Headers do firefox:
Request URL: http://myserver.com/my-dir/api/person/exists
Request method: OPTIONS

Request headers (482 B)
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Access-Control-Request-Headers
content-type
Access-Control-Request-Method
POST
Cache-Control
max-age=0
Connection
keep-alive
DNT
1
Host
myserver.com
Origin
http://examplesite.com
User-Agent
Mozilla/5.0 (X11; Linux x86_64…) Gecko/20100101 Firefox/60.0

No localhost funciona, mas quando mudo para o "http://examplesite.com" não funciona. Não sei qual é o problema para eu tentar resolver, o que parece estar acontecendo é a requisição OPTIONS nem está chegando no servidor.

up

No servidor se eu coloco já nas primeiras linhas de meu arquivo "index.php":
http_response_code(401);
echo json_encode(array("message" => "Not authorized."));
exit(0);

Ainda recebo os mesmos erros, é como se a requisição não chegasse nem no servidor.
Faço um teste usando o CURL:
eu@eu:~$ curl -X POST http://myserver.com/my-dir/api/person/exists
{"message":"Not authorized."}

e funciona como esperado.
Talvez algo está errado no cliente.
Comment: https://www.html5rocks.com/en/tutorials/cors/
Comment: Se não me engano a requisição de seu cliente deve ter esse cabeçalho, `request.setRequestHeader('Access-Control-Allow-Origin', 'http://examplesite.com');`
Comment: @AugustoVasques Não faz sentido a requisição ter esse cabeçalho, porque esse é o cabeçalho que o servidor utiliza para informar ao navegador quais são as origens que ele aceita. Mas como no caso do CORS eu tento de tudo, eu tentei, mas não funcionou.
Answer: Finalmente encontrei o problema, e era o cabeçalho "Content-Type" que estou acrescentando na requisição do cliente.Não é necessário incluí-lo, o navegador fará o trabalho para você, eles estava sendo o motivo do erro, pois quando acrescento a linha:
request.setRequestHeader('Content-Type', 'application/json; charset=utf-8')

Recebo o erro:
OPTIONS http://myserver.com/my-dir/api/person/exists net::ERR_EMPTY_RESPONSE

Quando comento ela, tudo funciona como esperado. Então meu código ficou assim no servidor:
header("Access-Control-Allow-Origin: http://examplesite.com");
header("Content-Type: multipart/form-data; application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Expose-Headers: Authorization");
header("Access-Control-Allow-Headers: Origin, Content-Type, Authorization");

if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   http_response_code(200);
   echo json_encode(array("message" => "OK!"));
   exit(0);
}

No cliente:
const request = new XMLHttpRequest();
request.onreadystatechange = function() {
  if(request.readyState === XMLHttpRequest.DONE) {
    if(request.status === 200) {
      console.log(request);
    }
  }
}
request.onerror = function() {
  console.log(Error("Network Error"));
};
request.open('POST', 'http://myserver.com/my-dir/api/person/exists', true);
const jwt = localStorage.getItem('jwt');
if(jwt) {
  request.withCredentials = true;
  request.setRequestHeader('Authorization', 'Baerer ' + jwt);
}
request.send(JSON.stringify(data));

Com isso está funcionando, o estranho é no localhost não receber o erro, e quando quando está em produção sim, ainda não entendi muito bem o motivo, o navegador não ajuda dando uma mensagem de erro mais detalhada. Acredito que seja porque no localhost não estava sendo acrescentado o 'Content-Type' por algum motivo e tudo funcionava bem. Mas realmente não sei, enfim, voltou a funcionar após retirar essa linha do código.