问:
Dynamically removing control from the panel and updating the panel
I have a following scenario , in which I am dynamically creating bunch of controls in the panel and I have also the feature of removing and adding controls in the panel later on.

Following controls , I want to remove from the panel using the selection of the checkbox that is inside the each of the subcontrol .

Removal Code

Using the Idea mentioned in Stackoverflow , I avoided foreach loop and came up with the following code.

```<code>for (int i = 0; i < panelDetection.Controls.Count; i++)
{
  if (panelDetection.Controls[i] is ImageControl)
  {
    ImageControl imageControl = (ImageControl)panelDetection.Controls[i];
    for(int j = 0; j < imageControl.Controls.Count; j++)
    {
      if (imageControl.Controls[j] is CheckBox)
      {
        CheckBox chkBox = (CheckBox)(imageControl.Controls[j]);
        if (chkBox.Checked)
        {
          chkBox.Click -= CheckBox_Click;
          panelDetection.Controls.Remove(imageControl);
          imageControl.Dispose();
        }
      }
    }
  }
}
</code>```

But the result is very strange as the controls are not getting removed of from the panel in an expected way. You can see that all selected controls are not getting removed from the panel.

Is there any way to achieve this functionality using some other idea?

Body:
I have a following scenario , in which I am dynamically creating bunch of controls in the panel and I have also the feature of removing and adding controls in the panel later on.

Following controls , I want to remove from the panel using the selection of the checkbox that is inside the each of the subcontrol .

Removal Code

Using the Idea mentioned in Stackoverflow , I avoided foreach loop and came up with the following code.

for (int i = 0; i < panelDetection.Controls.Count; i++)
{
  if (panelDetection.Controls[i] is ImageControl)
  {
    ImageControl imageControl = (ImageControl)panelDetection.Controls[i];
    for(int j = 0; j < imageControl.Controls.Count; j++)
    {
      if (imageControl.Controls[j] is CheckBox)
      {
        CheckBox chkBox = (CheckBox)(imageControl.Controls[j]);
        if (chkBox.Checked)
        {
          chkBox.Click -= CheckBox_Click;
          panelDetection.Controls.Remove(imageControl);
          imageControl.Dispose();
        }
      }
    }
  }
}

But the result is very strange as the controls are not getting removed of from the panel in an expected way. You can see that all selected controls are not getting removed from the panel.

Is there any way to achieve this functionality using some other idea?


来源: stackexchange

问:
How to use a Regex pattern in a Django form field widget attribute using JQuery
I'm using JQuery Mask Plugin in a Django form to specify input masks. I'm able to specify simple masks like the following simple mask which works:

```<code>cost = forms.DecimalField(widget = forms.TextInput(attrs={'class':'js-input-mask form-control', 'data-hs-mask-options':'{"mask":"00.00"}')
</code>```

My problem is specifying regex patterns; I don't know how to pass the pattern to the 'data-hs-mask-options'. See the example below. How can I pass the translation dictionary to the 'data-hs-mask-options'?

```<code>ip_address = forms.CharField(widget = forms.TextInput(attrs={'class':'js-input-mask form-control', 'data-hs-mask-options':'{"mask":"0ZZ.0ZZ.0ZZ.0ZZ"}')

('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {
translation: {
  'Z': {
    pattern: /[0-9]/, optional: true
  }
}
</code>```

})

ContentLicense: CC BY-SA 4.0

Body:
I'm using JQuery Mask Plugin in a Django form to specify input masks. I'm able to specify simple masks like the following simple mask which works:

cost = forms.DecimalField(widget = forms.TextInput(attrs={'class':'js-input-mask form-control', 'data-hs-mask-options':'{"mask":"00.00"}')

My problem is specifying regex patterns; I don't know how to pass the pattern to the 'data-hs-mask-options'. See the example below. How can I pass the translation dictionary to the 'data-hs-mask-options'?

ip_address = forms.CharField(widget = forms.TextInput(attrs={'class':'js-input-mask form-control', 'data-hs-mask-options':'{"mask":"0ZZ.0ZZ.0ZZ.0ZZ"}')

('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {
translation: {
  'Z': {
    pattern: /[0-9]/, optional: true
  }
}

})


问:
Decrypt a string with a decrypted key CryptographicException: Bad PKCS7 padding. Invalid length 205
I'm trying to save game data on the user's device and encrypt it to make it secure, to make the data even more secure i am doing that the key used be different for everyone (so save it on the device and encrypt it using another key constant, the same for everyone). So you will first have to decrypt the key using a constant key, then decrypt the data using the key that was decrypted.

Before reporting I removed the non-essential parts from the script to make it more readable.

this is the script

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Security.Cryptography;
using System.Text;

public class PlayerScript : MonoBehaviour
{
    public string FileName = "/datiDIGioco.txt";
    public string DataContent;

    public string chiave = "";
    public string KeyFileName = "/chiave.txt";
    string ConstantKey = "AnyConstantKeyEqualsForEveryone.";

    void Start()
    {
        if ((File.Exists(Application.persistentDataPath + KeyFileName)))
        {
            LoadData();
        }
    }

    void LoadData()
    {
        chiave = File.ReadAllText(Application.persistentDataPath + KeyFileName);//the content of the key file, so the encripted key
        DecriptKey(); //decrypt the chiave variable using a constant key

        DataContent = File.ReadAllText(Application.persistentDataPath + FileName);//the content of the data file
        Decript(); //decrypts the ContenutoDati variable using the decrypted key
    }

    public void DecriptKey()
    {
        byte[] TestoCriptato = Convert.FromBase64String(chiave);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.BlockSize = 128;
        aes.KeySize = 256;
        aes.Key = ASCIIEncoding.ASCII.GetBytes(ConstantKey);
        byte[] iv = new byte[aes.BlockSize / 8];
        aes.IV = iv;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;
        ICryptoTransform tdc = aes.CreateDecryptor(aes.Key, aes.IV);
        byte[] testoDecriptato = tdc.TransformFinalBlock(TestoCriptato, 0, TestoCriptato.Length);
        tdc.Dispose();

        chiave = ASCIIEncoding.ASCII.GetString(testoDecriptato);
    }

    public void Decript()
    {
        byte[] TestoCriptato = Convert.FromBase64String(DataContent);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.BlockSize = 128;
        aes.KeySize = 256;
        aes.Key = ASCIIEncoding.ASCII.GetBytes(chiave);
        byte[] iv = new byte[aes.BlockSize / 8];
        aes.IV = iv;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;
        ICryptoTransform tdc = aes.CreateDecryptor(aes.Key, aes.IV);
        byte[] testoDecriptato = tdc.TransformFinalBlock(TestoCriptato, 0, TestoCriptato.Length);
        tdc.Dispose();

        DataContent = ASCIIEncoding.ASCII.GetString(testoDecriptato);
    }
}
</code>```

this is the error

```<code>CryptographicException: Bad PKCS7 padding. Invalid length 205.
 Mono.Security.Cryptography.SymmetricTransform.ThrowBadPaddingException (System.Security.Cryptography.PaddingMode padding, System.Int32 length, System.Int32 position) (at <695d1cc93cca45069c528c15c9fdd749>:0)
 Mono.Security.Cryptography.SymmetricTransform.FinalDecrypt (System.Byte[] inputBuffer, System.Int32 inputOffset, System.Int32 inputCount) (at <695d1cc93cca45069c528c15c9fdd749>:0)
 Mono.Security.Cryptography.SymmetricTransform.TransformFinalBlock (System.Byte[] inputBuffer, System.Int32 inputOffset, System.Int32 inputCount) (at <695d1cc93cca45069c528c15c9fdd749>:0)
 PlayerScript.DecriptKey () (at Assets/script/salva dati/PlayerScript.cs:52)
 PlayerScript.LoadData () (at Assets/script/salva dati/PlayerScript.cs:33)
 PlayerScript.Start () (at Assets/script/salva dati/PlayerScript.cs:25)
</code>```

Any help fixing this error would be greatly appreciated! Thank you.

Body:
I'm trying to save game data on the user's device and encrypt it to make it secure, to make the data even more secure i am doing that the key used be different for everyone (so save it on the device and encrypt it using another key constant, the same for everyone). So you will first have to decrypt the key using a constant key, then decrypt the data using the key that was decrypted.

Before reporting I removed the non-essential parts from the script to make it more readable.

this is the script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Security.Cryptography;
using System.Text;

public class PlayerScript : MonoBehaviour
{
    public string FileName = "/datiDIGioco.txt";
    public string DataContent;

    public string chiave = "";
    public string KeyFileName = "/chiave.txt";
    string ConstantKey = "AnyConstantKeyEqualsForEveryone.";

    void Start()
    {
        if ((File.Exists(Application.persistentDataPath + KeyFileName)))
        {
            LoadData();
        }
    }

    void LoadData()
    {
        chiave = File.ReadAllText(Application.persistentDataPath + KeyFileName);//the content of the key file, so the encripted key
        DecriptKey(); //decrypt the chiave variable using a constant key

        DataContent = File.ReadAllText(Application.persistentDataPath + FileName);//the content of the data file
        Decript(); //decrypts the ContenutoDati variable using the decrypted key
    }

    public void DecriptKey()
    {
        byte[] TestoCriptato = Convert.FromBase64String(chiave);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.BlockSize = 128;
        aes.KeySize = 256;
        aes.Key = ASCIIEncoding.ASCII.GetBytes(ConstantKey);
        byte[] iv = new byte[aes.BlockSize / 8];
        aes.IV = iv;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;
        ICryptoTransform tdc = aes.CreateDecryptor(aes.Key, aes.IV);
        byte[] testoDecriptato = tdc.TransformFinalBlock(TestoCriptato, 0, TestoCriptato.Length);
        tdc.Dispose();

        chiave = ASCIIEncoding.ASCII.GetString(testoDecriptato);
    }

    public void Decript()
    {
        byte[] TestoCriptato = Convert.FromBase64String(DataContent);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.BlockSize = 128;
        aes.KeySize = 256;
        aes.Key = ASCIIEncoding.ASCII.GetBytes(chiave);
        byte[] iv = new byte[aes.BlockSize / 8];
        aes.IV = iv;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;
        ICryptoTransform tdc = aes.CreateDecryptor(aes.Key, aes.IV);
        byte[] testoDecriptato = tdc.TransformFinalBlock(TestoCriptato, 0, TestoCriptato.Length);
        tdc.Dispose();

        DataContent = ASCIIEncoding.ASCII.GetString(testoDecriptato);
    }
}

this is the error

CryptographicException: Bad PKCS7 padding. Invalid length 205.
 Mono.Security.Cryptography.SymmetricTransform.ThrowBadPaddingException (System.Security.Cryptography.PaddingMode padding, System.Int32 length, System.Int32 position) (at <695d1cc93cca45069c528c15c9fdd749>:0)
 Mono.Security.Cryptography.SymmetricTransform.FinalDecrypt (System.Byte[] inputBuffer, System.Int32 inputOffset, System.Int32 inputCount) (at <695d1cc93cca45069c528c15c9fdd749>:0)
 Mono.Security.Cryptography.SymmetricTransform.TransformFinalBlock (System.Byte[] inputBuffer, System.Int32 inputOffset, System.Int32 inputCount) (at <695d1cc93cca45069c528c15c9fdd749>:0)
 PlayerScript.DecriptKey () (at Assets/script/salva dati/PlayerScript.cs:52)
 PlayerScript.LoadData () (at Assets/script/salva dati/PlayerScript.cs:33)
 PlayerScript.Start () (at Assets/script/salva dati/PlayerScript.cs:25)

Any help fixing this error would be greatly appreciated! Thank you.


问:
Rabbit cluster in k8s slower than EC2
Right now we are working with 5 EC2 instances (AWS) of rabbitmq and we try to migrate to k8s cluster.

We deployed with EKS a cluster that works fine until 45K users.
The 5 separate instances can handle 75K users.

We discovered that the latency was higher in k8s cluster than the connection with EC2 instances.

We used this tool: https://www.rabbitmq.com/rabbitmq-diagnostics.8.html and we didn't find a problem. The file descriptors looks fine, the memory, CPU and etc...

we deployed with https://github.com/rabbitmq/cluster-operator

values.yaml

```<code>serviceName: rabbitmq
namespace: berlin
regionCode: use1
env: dev

resourcesConfig:
  replicas: 9
  nodeGroupName: r-large
  storageType: gp2
  storageSize: 100Gi
  resources:
    limits:
      cpu: 8
      memory: 60Gi
    requests:
      cpu: 7
      memory: 60Gi

definitionsConf:
  vhosts:
    - name: /
  exchanges:
    - name: test
      vhost: /
      type: direct
      durable: true
      auto_delete: false
      internal: false
      arguments: {}
  policies:
    - vhost: /
      name: Test Policy
      pattern: test.*.*.*
      apply-to: queues
      definition:
        federation-upstream-set: all
      priority: 0

additionalPlugins:
  - rabbitmq_event_exchange
  - rabbitmq_auth_backend_cache
  - rabbitmq_auth_backend_http
  - rabbitmq_prometheus
  - rabbitmq_shovel

rabbitmqConf:
  load_definitions: /etc/rabbitmq/definitions.json
#  definitions.skip_if_unchanged: 'true'
  cluster_partition_handling: pause_minority
  auth_backends.1: cache
  auth_cache.cached_backend: http
  auth_cache.cache_ttl: '10000'
  auth_http.http_method: post
  auth_http.user_path: http://XXXX:3000/authentication/users
  auth_http.vhost_path: http://XXX:3000/authentication/vhosts
  auth_http.resource_path: http://XXX:3000/authentication/resources
  auth_http.topic_path: http://XXX:3000/authentication/topics
  prometheus.path: /metrics
  prometheus.tcp.port: '15692'
  log.console: 'true'
  log.console.level: error
  log.console.formatter: json
  log.default.level: error
  tcp_listen_options.backlog: '4096'
  tcp_listen_options.nodelay: 'true'
  tcp_listen_options.sndbuf: '32768'
  tcp_listen_options.recbuf: '32768'
  tcp_listen_options.keepalive: 'true'
  tcp_listen_options.linger.on: 'true'
  tcp_listen_options.linger.timeout: '0'
  disk_free_limit.relative: '1.0'
  num_acceptors.tcp: '40'
  hipe_compile: 'true'
  collect_statistics_interval: '30000'
  mnesia_table_loading_retry_timeout: '60000'
  heartbeat: '60'
  vm_memory_high_watermark.relative: '0.9'
  management_agent.disable_metrics_collector: 'true'
  management.disable_stats: 'true'

metricsConfig:
  metricsPath: /metrics
  metricsPort: '15692'
</code>```

Chart.yaml

```<code>apiVersion: v2
name: rabbitmq
description: RabbitMQ Cluster

type: application

version: 0.0.1
</code>```

charts/templates/configmap.yaml

```<code>{{- $varNamespace := .Values.namespace }}
apiVersion: v1
kind: ConfigMap
metadata:
  namespace: {{ .Values.namespace }}
  name: {{ .Values.serviceName }}-definitions-conf
data:
  definitions.json: |
    {{ .Values.definitionsConf | toJson |replace "NAMESPACE" $varNamespace }}
</code>```
```<code>{{- $varNamespace := .Values.namespace}}
{{- $varRegionCode := .Values.regionCode}}
{{- $varEnv := .Values.env}}
apiVersion: rabbitmq.com/v1beta1
kind: RabbitmqCluster
metadata:
  name: {{ .Values.serviceName }}
  namespace: {{ .Values.namespace }}
spec:
  replicas: {{ .Values.resourcesConfig.replicas }}
  rabbitmq:
    envConfig: |
      ERL_MAX_PORTS=10000000
      RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS="+S 4:4 +P 2000000"
    advancedConfig: |
      [
        {kernel, [
          {inet_default_connect_options, [{nodelay, true}]},
          {inet_default_listen_options,  [{nodelay, true}]}
        ]}
      ].
    additionalPlugins: {{ .Values.additionalPlugins | toJson | indent 4 }}
    additionalConfig: |
      {{- range $key, $val := .Values.rabbitmqConf }}
        {{ $key }} = {{ $val | replace "NAMESPACE" $varNamespace | replace "REGION_CODE" $varRegionCode | replace "ENV" $varEnv }}
      {{- end }}
  resources:
    requests:
      cpu: {{ .Values.resourcesConfig.resources.requests.cpu }}
      memory: {{ .Values.resourcesConfig.resources.requests.memory }}
    limits:
      cpu: {{ .Values.resourcesConfig.resources.limits.cpu }}
      memory: {{ .Values.resourcesConfig.resources.limits.memory }}
  persistence:
    storageClassName: {{ .Values.resourcesConfig.storageType }}
    storage: {{ .Values.resourcesConfig.storageSize }}
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
            - key: app.kubernetes.io/name
              operator: In
              values:
              - {{ .Values.serviceName }}
        topologyKey: kubernetes.io/hostname
  service:
    type: LoadBalancer
    annotations:
      service.beta.kubernetes.io/aws-load-balancer-type: nlb
      service.beta.kubernetes.io/aws-load-balancer-name: {{ .Values.serviceName }}
      service.beta.kubernetes.io/load-balancer-source-ranges: {{ .Values.service.allowedVpcCidrRange }}
      service.beta.kubernetes.io/aws-load-balancer-internal: 'true'
      service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp
      service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags: Name={{ .Values.serviceName }}
      external-dns.alpha.kubernetes.io/hostname: {{ .Values.serviceName }}.{{ .Values.service.hostedZone }}
  override:
    statefulSet:
      spec:
        template:
          metadata:
            annotations:
              platform.vonage.com/logging: enabled
              telegraf.influxdata.com/class: influxdb
              telegraf.influxdata.com/inputs: |+
                [[inputs.prometheus]]
                  urls = ["http://127.0.0.1:{{ .Values.metricsConfig.metricsPort }}{{ .Values.metricsConfig.metricsPath }}"]
                  metric_version = 1
                  tagexclude = ["url"]
              telegraf.influxdata.com/env-literal-NAMESPACE: {{ $.Values.namespace }}
              telegraf.influxdata.com/env-literal-SERVICENAME: {{ $.Values.serviceName }}
          spec:
            nodeSelector:
              node-group-label: {{ .Values.resourcesConfig.nodeGroupName }}
            containers:
              - name: rabbitmq
                volumeMounts:
                  - name: definitions
                    mountPath: {{ .Values.rabbitmqConf.load_definitions }}
                    subPath: definitions.json
            volumes:
              - name: definitions
                configMap:
                  name: {{ .Values.serviceName }}-definitions-conf
</code>```

Can someone gives us an advice what we can check or how can we solve our issue?

Thanks.

I'm trying to replace the rabbitmq instances to rabbitmq k8s cluster. We want the same results (or better) than the separate instances.

Title: Rabbit cluster in k8s slower than EC2

Body:
Right now we are working with 5 EC2 instances (AWS) of rabbitmq and we try to migrate to k8s cluster.

We deployed with EKS a cluster that works fine until 45K users.
The 5 separate instances can handle 75K users.

We discovered that the latency was higher in k8s cluster than the connection with EC2 instances.

We used this tool: https://www.rabbitmq.com/rabbitmq-diagnostics.8.html and we didn't find a problem. The file descriptors looks fine, the memory, CPU and etc...

we deployed with https://github.com/rabbitmq/cluster-operator

values.yaml

serviceName: rabbitmq
namespace: berlin
regionCode: use1
env: dev

resourcesConfig:
  replicas: 9
  nodeGroupName: r-large
  storageType: gp2
  storageSize: 100Gi
  resources:
    limits:
      cpu: 8
      memory: 60Gi
    requests:
      cpu: 7
      memory: 60Gi

definitionsConf:
  vhosts:
    - name: /
  exchanges:
    - name: test
      vhost: /
      type: direct
      durable: true
      auto_delete: false
      internal: false
      arguments: {}
  policies:
    - vhost: /
      name: Test Policy
      pattern: test.*.*.*
      apply-to: queues
      definition:
        federation-upstream-set: all
      priority: 0

additionalPlugins:
  - rabbitmq_event_exchange
  - rabbitmq_auth_backend_cache
  - rabbitmq_auth_backend_http
  - rabbitmq_prometheus
  - rabbitmq_shovel

rabbitmqConf:
  load_definitions: /etc/rabbitmq/definitions.json
#  definitions.skip_if_unchanged: 'true'
  cluster_partition_handling: pause_minority
  auth_backends.1: cache
  auth_cache.cached_backend: http
  auth_cache.cache_ttl: '10000'
  auth_http.http_method: post
  auth_http.user_path: http://XXXX:3000/authentication/users
  auth_http.vhost_path: http://XXX:3000/authentication/vhosts
  auth_http.resource_path: http://XXX:3000/authentication/resources
  auth_http.topic_path: http://XXX:3000/authentication/topics
  prometheus.path: /metrics
  prometheus.tcp.port: '15692'
  log.console: 'true'
  log.console.level: error
  log.console.formatter: json
  log.default.level: error
  tcp_listen_options.backlog: '4096'
  tcp_listen_options.nodelay: 'true'
  tcp_listen_options.sndbuf: '32768'
  tcp_listen_options.recbuf: '32768'
  tcp_listen_options.keepalive: 'true'
  tcp_listen_options.linger.on: 'true'
  tcp_listen_options.linger.timeout: '0'
  disk_free_limit.relative: '1.0'
  num_acceptors.tcp: '40'
  hipe_compile: 'true'
  collect_statistics_interval: '30000'
  mnesia_table_loading_retry_timeout: '60000'
  heartbeat: '60'
  vm_memory_high_watermark.relative: '0.9'
  management_agent.disable_metrics_collector: 'true'
  management.disable_stats: 'true'

metricsConfig:
  metricsPath: /metrics
  metricsPort: '15692'

Chart.yaml

apiVersion: v2
name: rabbitmq
description: RabbitMQ Cluster

type: application

version: 0.0.1

charts/templates/configmap.yaml

{{- $varNamespace := .Values.namespace }}
apiVersion: v1
kind: ConfigMap
metadata:
  namespace: {{ .Values.namespace }}
  name: {{ .Values.serviceName }}-definitions-conf
data:
  definitions.json: |
    {{ .Values.definitionsConf | toJson |replace "NAMESPACE" $varNamespace }}

{{- $varNamespace := .Values.namespace}}
{{- $varRegionCode := .Values.regionCode}}
{{- $varEnv := .Values.env}}
apiVersion: rabbitmq.com/v1beta1
kind: RabbitmqCluster
metadata:
  name: {{ .Values.serviceName }}
  namespace: {{ .Values.namespace }}
spec:
  replicas: {{ .Values.resourcesConfig.replicas }}
  rabbitmq:
    envConfig: |
      ERL_MAX_PORTS=10000000
      RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS="+S 4:4 +P 2000000"
    advancedConfig: |
      [
        {kernel, [
          {inet_default_connect_options, [{nodelay, true}]},
          {inet_default_listen_options,  [{nodelay, true}]}
        ]}
      ].
    additionalPlugins: {{ .Values.additionalPlugins | toJson | indent 4 }}
    additionalConfig: |
      {{- range $key, $val := .Values.rabbitmqConf }}
        {{ $key }} = {{ $val | replace "NAMESPACE" $varNamespace | replace "REGION_CODE" $varRegionCode | replace "ENV" $varEnv }}
      {{- end }}
  resources:
    requests:
      cpu: {{ .Values.resourcesConfig.resources.requests.cpu }}
      memory: {{ .Values.resourcesConfig.resources.requests.memory }}
    limits:
      cpu: {{ .Values.resourcesConfig.resources.limits.cpu }}
      memory: {{ .Values.resourcesConfig.resources.limits.memory }}
  persistence:
    storageClassName: {{ .Values.resourcesConfig.storageType }}
    storage: {{ .Values.resourcesConfig.storageSize }}
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
            - key: app.kubernetes.io/name
              operator: In
              values:
              - {{ .Values.serviceName }}
        topologyKey: kubernetes.io/hostname
  service:
    type: LoadBalancer
    annotations:
      service.beta.kubernetes.io/aws-load-balancer-type: nlb
      service.beta.kubernetes.io/aws-load-balancer-name: {{ .Values.serviceName }}
      service.beta.kubernetes.io/load-balancer-source-ranges: {{ .Values.service.allowedVpcCidrRange }}
      service.beta.kubernetes.io/aws-load-balancer-internal: 'true'
      service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp
      service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags: Name={{ .Values.serviceName }}
      external-dns.alpha.kubernetes.io/hostname: {{ .Values.serviceName }}.{{ .Values.service.hostedZone }}
  override:
    statefulSet:
      spec:
        template:
          metadata:
            annotations:
              platform.vonage.com/logging: enabled
              telegraf.influxdata.com/class: influxdb
              telegraf.influxdata.com/inputs: |+
                [[inputs.prometheus]]
                  urls = ["http://127.0.0.1:{{ .Values.metricsConfig.metricsPort }}{{ .Values.metricsConfig.metricsPath }}"]
                  metric_version = 1
                  tagexclude = ["url"]
              telegraf.influxdata.com/env-literal-NAMESPACE: {{ $.Values.namespace }}
              telegraf.influxdata.com/env-literal-SERVICENAME: {{ $.Values.serviceName }}
          spec:
            nodeSelector:
              node-group-label: {{ .Values.resourcesConfig.nodeGroupName }}
            containers:
              - name: rabbitmq
                volumeMounts:
                  - name: definitions
                    mountPath: {{ .Values.rabbitmqConf.load_definitions }}
                    subPath: definitions.json
            volumes:
              - name: definitions
                configMap:
                  name: {{ .Values.serviceName }}-definitions-conf

Can someone gives us an advice what we can check or how can we solve our issue?

Thanks.

I'm trying to replace the rabbitmq instances to rabbitmq k8s cluster. We want the same results (or better) than the separate instances.


问:
Flutter- App working on emulator but not on device (uses the package geolocator: ^9.0.2 & geocoding: ^2.0.5)
I am trying to fetch the current location of the user using geolocator and geocoding flutter package. It's working nicely in android emulator but if I try to run on my real android phone through the project APK file it's not working. Could anyone please leave your precious suggestions? Thanks in advance!

**android.useAndroidX=true
android.enableJetifier=true

I have ensure above code in gradle.properties.**
**The project compileSdkVersion is 33.
Beside my AndroidMenifest.xml is:

```<code>   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.weather_forecasting_app">
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />**
</code>```

Here you go with pubspec.yaml:

cupertino_icons: ^1.0.2
google_fonts: ^3.0.1
dio: ^4.0.6
intl: ^0.17.0
get: ^4.6.5
flutter_switch: ^0.3.2
glassmorphism: ^3.0.0
animated_splash_screen: ^1.3.0
rename: ^2.0.1
geolocator: ^9.0.2
geocoding: ^2.0.5

Here you go with my code:

```<code>   class HomeScreen extends StatefulWidget {
        HomeScreen({Key? key}) : super(key: key);

      @override
      State<HomeScreen> createState() => _HomeScreenState();
    }

    class _HomeScreenState extends State<HomeScreen> {
       WeatherResultState stateController = Get.put(WeatherResultState());
       late bool _isLoading = false;
       late String currentLocation = '';
       late TextEditingController locationController = TextEditingController(text: currentLocation);

       Future<Position> _determinePosition() async {
         bool serviceEnabled;
         LocationPermission permission;

         serviceEnabled = await Geolocator.isLocationServiceEnabled();
         if (!serviceEnabled) {
           return Future.error('Location services are disabled.');
         }

         permission = await Geolocator.checkPermission();
         if (permission == LocationPermission.denied) {
           permission = await Geolocator.requestPermission();
           if (permission == LocationPermission.denied) {
             return Future.error('Location permissions are denied');
           }
         }

         if (permission == LocationPermission.deniedForever) {
           return Future.error(
               'Location permissions are permanently denied, we cannot request permissions.');
         }

         final position = await Geolocator.getCurrentPosition(desiredAccuracy:LocationAccuracy.low);
         List<Placemark> placemarks = await placemarkFromCoordinates(
           position.latitude,
           position.longitude,
         );
         setState(() {
           currentLocation = placemarks[0].locality ?? 'New York';
         });
         return await Geolocator.getCurrentPosition(desiredAccuracy:LocationAccuracy.low);

       }

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

      }

      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Scaffold(
              body: GetBuilder<WeatherResultState>(builder: (_){
                return Container(
                  height: double.infinity,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    gradient: stateController.isDarkMode == true ? darkMode : lightMode,
                  ),
                  child: Padding(
                    padding:
                    const EdgeInsets.symmetric(horizontal: 32, vertical: 32),
                    child: currentLocation == '' ? Loader() : SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          _buildToggleButton(context),
                          const PrimaryVerticalSpacer(),
                          _searchBar(context),
                          const PrimaryVerticalSpacer(),
                          Container(
                            height: 200,
                            width: 200,
                            decoration: const BoxDecoration(
                                image: DecorationImage(
                                  image:
                                  AssetImage('assets/images/cloudwithquestion.png'),
                                  fit: BoxFit.cover,
                                )),
                          ),
                          Text(
                            'Enter Your Location',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.lobster(
                                textStyle: const TextStyle(
                                    fontSize: 60,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w700)),
                          ),
                          const PrimaryVerticalSpacer(),
                          PrimaryButton(
                            onTap: () {
                              stateController.loadWeatherData(locationController.text);
                              stateController.getDate();
                              Get.to(()=> ResultScreen());
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              })),
        );
      }

        Widget _searchBar(BuildContext context) {
          return TextFormField(
            controller: locationController,
            decoration: InputDecoration(
              filled: true,
              fillColor: Colors.white,
              contentPadding: const EdgeInsets.all(16),
              hintText: 'Enter your location',
              hintStyle: const TextStyle(
                  color: assColor,
                  fontSize: 16,
                  fontWeight: FontWeight.w500),
              prefixIcon: Icon(Icons.search),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(16.0),
                borderSide: BorderSide(color:  Colors.transparent),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(16.0),
                borderSide: BorderSide(color:  Colors.transparent),
              ),
              focusColor: Colors.blue,
            ),
          );
        }
</code>```

Body:
I am trying to fetch the current location of the user using geolocator and geocoding flutter package. It's working nicely in android emulator but if I try to run on my real android phone through the project APK file it's not working. Could anyone please leave your precious suggestions? Thanks in advance!

**android.useAndroidX=true
android.enableJetifier=true

I have ensure above code in gradle.properties.**
**The project compileSdkVersion is 33.
Beside my AndroidMenifest.xml is:

   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.weather_forecasting_app">
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />**

Here you go with pubspec.yaml:

cupertino_icons: ^1.0.2
google_fonts: ^3.0.1
dio: ^4.0.6
intl: ^0.17.0
get: ^4.6.5
flutter_switch: ^0.3.2
glassmorphism: ^3.0.0
animated_splash_screen: ^1.3.0
rename: ^2.0.1
geolocator: ^9.0.2
geocoding: ^2.0.5

Here you go with my code:

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

      @override
      State<HomeScreen> createState() => _HomeScreenState();
    }

    class _HomeScreenState extends State<HomeScreen> {
       WeatherResultState stateController = Get.put(WeatherResultState());
       late bool _isLoading = false;
       late String currentLocation = '';
       late TextEditingController locationController = TextEditingController(text: currentLocation);

       Future<Position> _determinePosition() async {
         bool serviceEnabled;
         LocationPermission permission;

         serviceEnabled = await Geolocator.isLocationServiceEnabled();
         if (!serviceEnabled) {
           return Future.error('Location services are disabled.');
         }

         permission = await Geolocator.checkPermission();
         if (permission == LocationPermission.denied) {
           permission = await Geolocator.requestPermission();
           if (permission == LocationPermission.denied) {
             return Future.error('Location permissions are denied');
           }
         }

         if (permission == LocationPermission.deniedForever) {
           return Future.error(
               'Location permissions are permanently denied, we cannot request permissions.');
         }

         final position = await Geolocator.getCurrentPosition(desiredAccuracy:LocationAccuracy.low);
         List<Placemark> placemarks = await placemarkFromCoordinates(
           position.latitude,
           position.longitude,
         );
         setState(() {
           currentLocation = placemarks[0].locality ?? 'New York';
         });
         return await Geolocator.getCurrentPosition(desiredAccuracy:LocationAccuracy.low);

       }

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

      }

      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Scaffold(
              body: GetBuilder<WeatherResultState>(builder: (_){
                return Container(
                  height: double.infinity,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    gradient: stateController.isDarkMode == true ? darkMode : lightMode,
                  ),
                  child: Padding(
                    padding:
                    const EdgeInsets.symmetric(horizontal: 32, vertical: 32),
                    child: currentLocation == '' ? Loader() : SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          _buildToggleButton(context),
                          const PrimaryVerticalSpacer(),
                          _searchBar(context),
                          const PrimaryVerticalSpacer(),
                          Container(
                            height: 200,
                            width: 200,
                            decoration: const BoxDecoration(
                                image: DecorationImage(
                                  image:
                                  AssetImage('assets/images/cloudwithquestion.png'),
                                  fit: BoxFit.cover,
                                )),
                          ),
                          Text(
                            'Enter Your Location',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.lobster(
                                textStyle: const TextStyle(
                                    fontSize: 60,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w700)),
                          ),
                          const PrimaryVerticalSpacer(),
                          PrimaryButton(
                            onTap: () {
                              stateController.loadWeatherData(locationController.text);
                              stateController.getDate();
                              Get.to(()=> ResultScreen());
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              })),
        );
      }

        Widget _searchBar(BuildContext context) {
          return TextFormField(
            controller: locationController,
            decoration: InputDecoration(
              filled: true,
              fillColor: Colors.white,
              contentPadding: const EdgeInsets.all(16),
              hintText: 'Enter your location',
              hintStyle: const TextStyle(
                  color: assColor,
                  fontSize: 16,
                  fontWeight: FontWeight.w500),
              prefixIcon: Icon(Icons.search),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(16.0),
                borderSide: BorderSide(color:  Colors.transparent),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(16.0),
                borderSide: BorderSide(color:  Colors.transparent),
              ),
              focusColor: Colors.blue,
            ),
          );
        }


问:
Add Django pytest test database migrations only for tests
I am looking for a decent solution for any migrations in database itself.

We have custom SQL script which adds pg_trgm extention to PostgreSQL database, which is simply

CREATE EXTENSION pg_trgm;

```
<p>and</p>
```FROM postgres:14.5-alpine
COPY init.sql /docker-entrypoint-initdb.d/init.sql
```
<p>in database`s Dockerfile</p>
<p>After that I can easily add specialized GIN indexes to models, i.e.</p>
<pre class="lang-py prettyprint-override"><code>
class MyModel(models.Model):
    """
    My model comment
    """

    objects = MyManager()

    field = models.CharField(max_length=100)

    class Meta:
        indexes = (
            models.Index(Upper("field"), name="field_idx"),
            GinIndex(
                fields=["field"],
                opclasses=["gin_trgm_ops"],
                name="field_gin_idx",
            ),
            GinIndex(
                OpClass(Upper("field"), name="gin_trgm_ops"),
                name="field_gin_idx",
            ),

</code>```

So I want to reflect that "custom script" in Django pytest tests.

P.S.: I know there is a trigram extention for that purpose, but it was a TL decision to put custom database migration in separate place

Do you have any idea on how to prepare such fixture?

I was looking for related pytest fixtures but haven't found any solution

Body:
I am looking for a decent solution for any migrations in database itself.

We have custom SQL script which adds pg_trgm extention to PostgreSQL database, which is simply

CREATE EXTENSION pg_trgm;

and

FROM postgres:14.5-alpine
COPY init.sql /docker-entrypoint-initdb.d/init.sql

in database`s Dockerfile

After that I can easily add specialized GIN indexes to models, i.e.

class MyModel(models.Model):
    """
    My model comment
    """

    objects = MyManager()

    field = models.CharField(max_length=100)

    class Meta:
        indexes = (
            models.Index(Upper("field"), name="field_idx"),
            GinIndex(
                fields=["field"],
                opclasses=["gin_trgm_ops"],
                name="field_gin_idx",
            ),
            GinIndex(
                OpClass(Upper("field"), name="gin_trgm_ops"),
                name="field_gin_idx",
            ),

So I want to reflect that "custom script" in Django pytest tests.

P.S.: I know there is a trigram extention for that purpose, but it was a TL decision to put custom database migration in separate place

Do you have any idea on how to prepare such fixture?

I was looking for related pytest fixtures but haven't found any solution


问:
Problems with WiredTiger in order to deploy a config server in MongoDB
I'm trying to deploy a shared and replicated cluster of MongoDB.
I did the installation like it is indicated in the official page for Ubuntu 20.04: https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/.
But, when I executed:

```<code>mongod --configsvr --port 27001 --replSet config_server --dbpath mongo/data_patients/config/ --bind_ip localhost
</code>```

I have the following trouble:

and I can't access to the configuration server.

Body:
I'm trying to deploy a shared and replicated cluster of MongoDB.
I did the installation like it is indicated in the official page for Ubuntu 20.04: https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/.
But, when I executed:

mongod --configsvr --port 27001 --replSet config_server --dbpath mongo/data_patients/config/ --bind_ip localhost

I have the following trouble:

and I can't access to the configuration server.


问:
Why is my JSON body coming through as 'undefined' for this simple https POST?
I am trying to create a simple test of one Azure function app calling another. Both are written in Node.js. I can make the request easily with Postman, but for some reason I can't get the JSON body to come through when sending from my function app. When I send the request the receiving function app logs the body as 'undefined'

Here is the code of my calling function app:

```<code>const https = require('https');

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var urlHostname = "receiving-app.azurewebsites.net"
    var urlPath = "/api/receiving-app?code=secret"

    var options = {
        hostname: urlHostname,
        port: 443,
        path: urlPath,
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        }
    };

    const request = https.request(options, (response) => {
        context.log(`statusCode: ${response.statusCode}`)

        response.on('data', (data) => {
            context.log('response data: ${data}')
        })
    })

    request.on('error', (error) => {
        context.log(error)
    })

    const payload = {
        name: "test"
    }
    context.log('payload: ' + JSON.stringify(payload))

    request.write(JSON.stringify(payload))
    request.end()

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: "done"
    };
}
</code>```

Here is the receiving function app:

```<code>module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    context.log(context.req);
    context.log(req.body);

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: "Hello "
    };
}
</code>```

edit:

modified my calling function to this:

```<code>const https = require('https');

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var urlHostname = "xxxxx.azurewebsites.net"
    var urlPath = "/api/xxxxx?code=xxxxxxxxx"

    var options = {
        hostname: urlHostname,
        port: 443,
        path: urlPath,
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        }
    };

    var request = https.request(options, function (res) {
        console.log("STATUS: " + res.statusCode);
        console.log("HEADERS: " + JSON.stringify(res.headers));
        res.setEncoding("utf8");
        res.on("data", function (chunk) {
          console.log("BODY: " + chunk);
        });
      });

    request.on("error", function (e) {
        console.log("Problem with request: " + e);
    });

    // write data to request body
    var payload = {
        id: 12345,
        value: "abc-def-ghi",
    };

    request.write(JSON.stringify(payload));
    request.end();

    context.res = {

        // status: 200, /* Defaults to 200 */
        body: "done"
    };
}
</code>```

Now I'm receiving this 401 error:

```<code>{
  "error": {
    "code": "ExpiredAuthenticationToken",
    "message": "The access token expiry UTC time '12/26/2022 6:39:13 PM' is earlier than current UTC time '12/26/2022 6:44:34 PM'."
  }
}
</code>```

Body:
I am trying to create a simple test of one Azure function app calling another. Both are written in Node.js. I can make the request easily with Postman, but for some reason I can't get the JSON body to come through when sending from my function app. When I send the request the receiving function app logs the body as 'undefined'

Here is the code of my calling function app:

const https = require('https');

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var urlHostname = "receiving-app.azurewebsites.net"
    var urlPath = "/api/receiving-app?code=secret"

    var options = {
        hostname: urlHostname,
        port: 443,
        path: urlPath,
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        }
    };

    const request = https.request(options, (response) => {
        context.log(`statusCode: ${response.statusCode}`)

        response.on('data', (data) => {
            context.log('response data: ${data}')
        })
    })

    request.on('error', (error) => {
        context.log(error)
    })

    const payload = {
        name: "test"
    }
    context.log('payload: ' + JSON.stringify(payload))

    request.write(JSON.stringify(payload))
    request.end()

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: "done"
    };
}

Here is the receiving function app:

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    context.log(context.req);
    context.log(req.body);

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: "Hello "
    };
}

edit:

modified my calling function to this:

const https = require('https');

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var urlHostname = "xxxxx.azurewebsites.net"
    var urlPath = "/api/xxxxx?code=xxxxxxxxx"

    var options = {
        hostname: urlHostname,
        port: 443,
        path: urlPath,
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        }
    };

    var request = https.request(options, function (res) {
        console.log("STATUS: " + res.statusCode);
        console.log("HEADERS: " + JSON.stringify(res.headers));
        res.setEncoding("utf8");
        res.on("data", function (chunk) {
          console.log("BODY: " + chunk);
        });
      });

    request.on("error", function (e) {
        console.log("Problem with request: " + e);
    });

    // write data to request body
    var payload = {
        id: 12345,
        value: "abc-def-ghi",
    };

    request.write(JSON.stringify(payload));
    request.end();

    context.res = {

        // status: 200, /* Defaults to 200 */
        body: "done"
    };
}

Now I'm receiving this 401 error:

{
  "error": {
    "code": "ExpiredAuthenticationToken",
    "message": "The access token expiry UTC time '12/26/2022 6:39:13 PM' is earlier than current UTC time '12/26/2022 6:44:34 PM'."
  }
}


问:
How to use "cv2.estimateAffine3D" correctly, to align two 3d coordinate systems?
I have to align two 3d coordinate systems and I have 32 coordinates of points in the real world for each coordinate system.

I already know that I have to calculate the translation and the rotation and I (think) that I also understand what the calculation is. Because some smart people already had solve this problem I just want to use openCV for this and I asked the aiChatBot of how to do this calculation without and with openCV.

But I think using "cv2.estimateAffine3D" looks right.

Maybe some can just give me an example how to use it correctly?
At the moment the code with example I have from the aiChatBot looks like this:

```<code>import cv2
import numpy as np

# Define the coordinates of the three points in the first coordinate system
p1 = np.array([[1, 2, 3]], dtype=np.float32)
p2 = np.array([[4, 5, 6]], dtype=np.float32)
p3 = np.array([[7, 8, 9]], dtype=np.float32)

# Define the coordinates of the three points in the second coordinate system
q1 = np.array([[1, 2, 3]], dtype=np.float32)
q2 = np.array([[5, 6, 7]], dtype=np.float32)
q3 = np.array([[9, 10, 11]], dtype=np.float32)

# Calculate the affine transformation that aligns the two coordinate systems
T = cv2.estimateAffine3D(p1, p2, p3)

# Reshape the point arrays to 2D or 3D
q1_reshaped = q1.reshape(1, -1, 3)
q2_reshaped = q2.reshape(1, -1, 3)
q3_reshaped = q3.reshape(1, -1, 3)

# Apply the transformation to the second coordinate system
q1_aligned = cv2.transform(q1_reshaped, T)
q2_aligned = cv2.transform(q2_reshaped, T)
q3_aligned = cv2.transform(q3_reshaped, T)

# Print the transformed points
print(q1_aligned)
print(q2_aligned)
print(q3_aligned)

</code>```

the error I get is :

error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'transform'

Overload resolution failed:

m is not a numerical tuple

Expected Ptr<cv::UMat> for argument 'm

the answer form the aiChatBot to solve this is:
"It looks like the error you are experiencing is caused by passing an incorrect argument to the cv2.transform function. The cv2.transform function expects a 2D or 3D point array as the first argument and a 3x3 or 3x4 transformation matrix as the second argument, but you are passing a 1D point array and a 3x3 or 3x4 transformation matrix as arguments.

To fix this error, you need to pass a 2D or 3D point array as the first argument to the cv2.transform function. You can do this by reshaping the 1D point arrays q1, q2, and q3 using the np.reshape function, as follows:"

but there we come in a loop because this "solution" is already in the code.

So I do not really find any information about that. Can anybody help me with this?

cheers!

I want to align two coordinate systems.

Body:
I have to align two 3d coordinate systems and I have 32 coordinates of points in the real world for each coordinate system.

I already know that I have to calculate the translation and the rotation and I (think) that I also understand what the calculation is. Because some smart people already had solve this problem I just want to use openCV for this and I asked the aiChatBot of how to do this calculation without and with openCV.

But I think using "cv2.estimateAffine3D" looks right.

Maybe some can just give me an example how to use it correctly?
At the moment the code with example I have from the aiChatBot looks like this:

import cv2
import numpy as np

# Define the coordinates of the three points in the first coordinate system
p1 = np.array([[1, 2, 3]], dtype=np.float32)
p2 = np.array([[4, 5, 6]], dtype=np.float32)
p3 = np.array([[7, 8, 9]], dtype=np.float32)

# Define the coordinates of the three points in the second coordinate system
q1 = np.array([[1, 2, 3]], dtype=np.float32)
q2 = np.array([[5, 6, 7]], dtype=np.float32)
q3 = np.array([[9, 10, 11]], dtype=np.float32)

# Calculate the affine transformation that aligns the two coordinate systems
T = cv2.estimateAffine3D(p1, p2, p3)

# Reshape the point arrays to 2D or 3D
q1_reshaped = q1.reshape(1, -1, 3)
q2_reshaped = q2.reshape(1, -1, 3)
q3_reshaped = q3.reshape(1, -1, 3)

# Apply the transformation to the second coordinate system
q1_aligned = cv2.transform(q1_reshaped, T)
q2_aligned = cv2.transform(q2_reshaped, T)
q3_aligned = cv2.transform(q3_reshaped, T)

# Print the transformed points
print(q1_aligned)
print(q2_aligned)
print(q3_aligned)

the error I get is :

error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'transform'

Overload resolution failed:

m is not a numerical tuple

Expected Ptr<cv::UMat> for argument 'm

the answer form the aiChatBot to solve this is:
"It looks like the error you are experiencing is caused by passing an incorrect argument to the cv2.transform function. The cv2.transform function expects a 2D or 3D point array as the first argument and a 3x3 or 3x4 transformation matrix as the second argument, but you are passing a 1D point array and a 3x3 or 3x4 transformation matrix as arguments.

To fix this error, you need to pass a 2D or 3D point array as the first argument to the cv2.transform function. You can do this by reshaping the 1D point arrays q1, q2, and q3 using the np.reshape function, as follows:"

but there we come in a loop because this "solution" is already in the code.

So I do not really find any information about that. Can anybody help me with this?

cheers!

I want to align two coordinate systems.


问:
Unable to connect to MongoDB using URL mongodb://localhost:27017 using docker and monstache
So I have 1 docker container named elastic which has 2 images, one for elastic search and one for kibana. This is the yml file that creates them

```<code>version: '3.1'

services:
  elasticsearch:
    container_name: els
    image: docker.elastic.co/elasticsearch/elasticsearch:7.16.1
    ports:
      - 9200:9200
    volumes:
      - elasticsearch-data:/usr/share/elasticsearch/datafile
    environment:
      - xpack.monitoring.enabled=true
      - xpack.watcher.enabled=false
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - discovery.type=single-node
    networks:
      - elasticnetwork

  kibana:
    container_name: kibana
    image: docker.elastic.co/kibana/kibana:7.16.1
    ports:
      - 5601:4601
    depends_on:
      - elasticsearch
    environment:
      - ELASTICSEARCH_URL=http://localhost:9200
    networks:
      - elasticnetwork

networks:
  elasticnetwork:
    driver: bridge

volumes:
  elasticsearch-data:

</code>```

As you can see I'm working with localhost and default ports. Then I run a mongo DB that I only use inside MongoDB Compass to connect via localhost:27017 without an image and without using a docker container.

The issue is the following: I configured a monstache file that synchs data from a collection named Concerts to an index in elasticsearh. It works fine when I execute the command inside the console. This is the monstache file:

```<code>mongo-url = "mongodb://localhost:27017"

elasticsearch-urls = ["http://localhost:9200"]

elasticsearch-max-conns = 10
replay = false
resume = true
enable-oplog = true
resume-name = "default"
namespace-regex = '^.Test\.Concert$' # my namespace which I want to sync
direct-read-namespaces = ["Test.Concert"] # directly copy entire data to es from this name space
index-as-update = true # upsert docs
verbose = true # logs enabled
exit-after-direct-reads = false # don’t exit after copying from db to es

[[mapping]]
namespace = "Test.Concert" # my db collection from where I want to sync
index = "Concert" # my index where I want to sync data.
</code>```

This is how I create the image

```<code># Build monstahce plugin
FROM rwynn/monstache-builder-cache-rel6:1.0.3 AS builder

RUN git clone https://github.com/rwynn/monstache.git/app && \
    cd /app && \
    git checkout v6.4.3 && \
    go mod download

WORKDIR /app/docker/plugin

RUN go mod download

# Main container

FROM rwynn/monstache:6.4.3

WORKDIR /app

COPY monstache.toml monstache.config.toml

ENTRYPOINT [ "/bin/monstache", "-f", "monstache.config.toml" ]
</code>```

So I tried to create an image inside docker that executes that command continuously but it throws the error Unable to connect to MongoDB using URL mongodb://localhost:27017: server selection error: server selection timeout, current topology: { Type: Unknown, Servers: [{ Addr: localhost:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : dial tcp 127.0.0.1:27017: connect: connection refused }, ] }

This confuses me since the command and configuration work fine and the data gets synched. However, when I create the image it stops running after a few seconds because it can't connect to MongoDB. Is there a missing configuration so that the localhost can be reached? Or are there other alternatives to run the monstache command without an image and actively listen to my changes in one collection?

Body:
So I have 1 docker container named elastic which has 2 images, one for elastic search and one for kibana. This is the yml file that creates them

version: '3.1'

services:
  elasticsearch:
    container_name: els
    image: docker.elastic.co/elasticsearch/elasticsearch:7.16.1
    ports:
      - 9200:9200
    volumes:
      - elasticsearch-data:/usr/share/elasticsearch/datafile
    environment:
      - xpack.monitoring.enabled=true
      - xpack.watcher.enabled=false
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - discovery.type=single-node
    networks:
      - elasticnetwork

  kibana:
    container_name: kibana
    image: docker.elastic.co/kibana/kibana:7.16.1
    ports:
      - 5601:4601
    depends_on:
      - elasticsearch
    environment:
      - ELASTICSEARCH_URL=http://localhost:9200
    networks:
      - elasticnetwork

networks:
  elasticnetwork:
    driver: bridge

volumes:
  elasticsearch-data:

As you can see I'm working with localhost and default ports. Then I run a mongo DB that I only use inside MongoDB Compass to connect via localhost:27017 without an image and without using a docker container.

The issue is the following: I configured a monstache file that synchs data from a collection named Concerts to an index in elasticsearh. It works fine when I execute the command inside the console. This is the monstache file:

mongo-url = "mongodb://localhost:27017"

elasticsearch-urls = ["http://localhost:9200"]

elasticsearch-max-conns = 10
replay = false
resume = true
enable-oplog = true
resume-name = "default"
namespace-regex = '^.Test\.Concert$' # my namespace which I want to sync
direct-read-namespaces = ["Test.Concert"] # directly copy entire data to es from this name space
index-as-update = true # upsert docs
verbose = true # logs enabled
exit-after-direct-reads = false # don’t exit after copying from db to es

[[mapping]]
namespace = "Test.Concert" # my db collection from where I want to sync
index = "Concert" # my index where I want to sync data.

This is how I create the image

# Build monstahce plugin
FROM rwynn/monstache-builder-cache-rel6:1.0.3 AS builder

RUN git clone https://github.com/rwynn/monstache.git/app && \
    cd /app && \
    git checkout v6.4.3 && \
    go mod download

WORKDIR /app/docker/plugin

RUN go mod download

# Main container

FROM rwynn/monstache:6.4.3

WORKDIR /app

COPY monstache.toml monstache.config.toml

ENTRYPOINT [ "/bin/monstache", "-f", "monstache.config.toml" ]

So I tried to create an image inside docker that executes that command continuously but it throws the error Unable to connect to MongoDB using URL mongodb://localhost:27017: server selection error: server selection timeout, current topology: { Type: Unknown, Servers: [{ Addr: localhost:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : dial tcp 127.0.0.1:27017: connect: connection refused }, ] }

This confuses me since the command and configuration work fine and the data gets synched. However, when I create the image it stops running after a few seconds because it can't connect to MongoDB. Is there a missing configuration so that the localhost can be reached? Or are there other alternatives to run the monstache command without an image and actively listen to my changes in one collection?


问:
reading values through the usartread function
```<code>if (val == 3) {
           //USARTWriteChar(USARTReadChar());
        char point = USARTReadChar(); //USARTReadChar
        buff[y] = point;

       if (point == 0x0D) {

            buff[y] = '\0';
            buff[y] = END_STR;
            int c = atoi(buff);
            itoa(aux, c, 10);
</code>```

I need to communicate with the PIC through the serial port and the moment I write a whole number with two or more digits on the computer keyboard, it should return the table of that same number

Body:
if (val == 3) {
           //USARTWriteChar(USARTReadChar());
        char point = USARTReadChar(); //USARTReadChar
        buff[y] = point;

       if (point == 0x0D) {

            buff[y] = '\0';
            buff[y] = END_STR;
            int c = atoi(buff);
            itoa(aux, c, 10);

I need to communicate with the PIC through the serial port and the moment I write a whole number with two or more digits on the computer keyboard, it should return the table of that same number


问:
Ngnix Load Balancer unable to find if plus or open source
Hi I have recently joined a firm using ngnix. However, the old team and I are unsure if they are using ngnix plus or ngnix open source. Can anyone guide how to check if the ngnix load balancer we are using is plus or open source ?
Are there different versions or is there some other method.
Any help or suggestion would mean a lot.</p>


问:
PAYG tokens - error messages (on both Disco and Stable Diffusion)
I signed up for some pay as you go credit - and to my dismay now receive this error both on Disco AND Stable Diffusion:

```<code>FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-191981527364> in <module>
     38 import py3d_tools as p3d
     39
---> 40 from helpers import DepthModel, sampler_fn
     41 from k_diffusion.external import CompVisDenoiser
     42 from ldm.util import instantiate_from_config

4 frames
/content/MiDaS/midas/backbones/next_vit.py in <module>
      6 from .utils import activations, forward_default, get_activation
      7
----> 8 file = open("./externals/Next_ViT/classification/nextvit.py", "r")
      9 source_code = file.read().replace(" utils", " externals.Next_ViT.classification.utils")
     10 exec(source_code)

FileNotFoundError: [Errno 2] No such file or directory: './externals/Next_ViT/classification/nextvit.py'
</code>```

I also receive this error on Stable:

```<code>NameError                                 Traceback (most recent call last)
<ipython-input-5-d64464a7a6a5> in <module>
    154 if load_on_run_all and ckpt_valid:
    155     local_config = OmegaConf.load(f"{ckpt_config_path}")
--> 156     model = load_model_from_config(local_config, f"{ckpt_path}", half_precision=half_precision)
    157     device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
    158     model = model.to(device)

<ipython-input-5-d64464a7a6a5> in load_model_from_config(config, ckpt, verbose, device, half_precision)
    136         print(f"Global Step: {pl_sd['global_step']}")
    137     sd = pl_sd["state_dict"]
--> 138     model = instantiate_from_config(config.model)
    139     m, u = model.load_state_dict(sd, strict=False)
    140     if len(m) > 0 and verbose:

</code>```

Despite clearing my Google Drive and reloading Disco and Stable Diffusion, (including the .ckpt file, placed correctly as before in the models folder) the same errors occur.

Body:
I signed up for some pay as you go credit - and to my dismay now receive this error both on Disco AND Stable Diffusion:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-191981527364> in <module>
     38 import py3d_tools as p3d
     39
---> 40 from helpers import DepthModel, sampler_fn
     41 from k_diffusion.external import CompVisDenoiser
     42 from ldm.util import instantiate_from_config

4 frames
/content/MiDaS/midas/backbones/next_vit.py in <module>
      6 from .utils import activations, forward_default, get_activation
      7
----> 8 file = open("./externals/Next_ViT/classification/nextvit.py", "r")
      9 source_code = file.read().replace(" utils", " externals.Next_ViT.classification.utils")
     10 exec(source_code)

FileNotFoundError: [Errno 2] No such file or directory: './externals/Next_ViT/classification/nextvit.py'

I also receive this error on Stable:

NameError                                 Traceback (most recent call last)
<ipython-input-5-d64464a7a6a5> in <module>
    154 if load_on_run_all and ckpt_valid:
    155     local_config = OmegaConf.load(f"{ckpt_config_path}")
--> 156     model = load_model_from_config(local_config, f"{ckpt_path}", half_precision=half_precision)
    157     device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
    158     model = model.to(device)

<ipython-input-5-d64464a7a6a5> in load_model_from_config(config, ckpt, verbose, device, half_precision)
    136         print(f"Global Step: {pl_sd['global_step']}")
    137     sd = pl_sd["state_dict"]
--> 138     model = instantiate_from_config(config.model)
    139     m, u = model.load_state_dict(sd, strict=False)
    140     if len(m) > 0 and verbose:

Despite clearing my Google Drive and reloading Disco and Stable Diffusion, (including the .ckpt file, placed correctly as before in the models folder) the same errors occur.


问:
Resolving services for the IoC DI framework using source generation in opposed to System.Reflection
I like the idea of resolving services in the IoC using attributes. I wanted to replace System.Reflection with source generation, so it improves startup time.

The code snippet below is also on GitHub.

#1 System.Reflection

[Service(typeof(IListenerService), ServiceLifetime.Scoped)]
public class ListenerService : IListenerService
{
    ...
}
```
<pre class="lang-cs prettyprint-override"><code>public static class Bootstrapper
{
    public static void ConfigureServices(IServiceCollection serviceCollection)
    {
        IEnumerable<Assembly> assemblies = GetAssemblies();

        List<KeyValuePair<Type, ServiceAttribute>> serviceAttributes = assemblies
            .SelectMany(x => x.DefinedTypes)
            .SelectMany(x =>
                x.GetCustomAttributes<ServiceAttribute>(false)
                    .Select(y => new KeyValuePair<Type, ServiceAttribute>(x, y)))
            .ToList();

        foreach ((Type type, ServiceAttribute serviceAttribute) in serviceAttributes)
        {
            serviceCollection.Add(new ServiceDescriptor(serviceAttribute.Type, type,
                serviceAttribute.ServiceLifetime));
        }
    }

    private static IEnumerable<Assembly> GetAssemblies()
    {
        List<Assembly> assemblies = GetAssemblies(Assembly.GetEntryAssembly()).Distinct().ToList();

        return assemblies;
    }

    private static IEnumerable<Assembly> GetAssemblies(Assembly assembly)
    {
        string namespacePrefix = typeof(Bootstrapper).Namespace?.Split(".")[0];

        foreach (Assembly referencedAssembly in assembly.GetReferencedAssemblies()
                     .Where(x => x.Name != null && x.Name.StartsWith(namespacePrefix ?? Empty)).Select(Assembly.Load)
                     .SelectMany(GetAssemblies))
        {
            yield return referencedAssembly;
        }

        yield return assembly;
    }
}

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ServiceAttribute : Attribute
{
    public ServiceAttribute(Type type)
    {
        Type = type;
        ServiceLifetime = ServiceLifetime.Scoped;
    }

    public ServiceAttribute(Type type, ServiceLifetime serviceLifetime)
    {
        Type = type;
        ServiceLifetime = serviceLifetime;
    }

    public Type Type { get; }
    public ServiceLifetime ServiceLifetime { get; }
}
</code>```

#2 Source Generation

I made a Class Library called Enliven.SourceGenerator and put the following classes:

using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Enliven.SourceGenerator;

[Generator]
public class ServiceRegistrationGenerator : ISourceGenerator
{
    public void Execute(GeneratorExecutionContext context)
    {
        var serviceTypes = context.Compilation.SyntaxTrees
            .SelectMany(tree => tree.GetRoot().DescendantNodes())
            .OfType<ClassDeclarationSyntax>()
            .Where(classDecl => classDecl.AttributeLists
                .SelectMany(al => al.Attributes)
                .Any(a => a.Name.ToString() == nameof(ServiceAttribute)))
            .ToList();

        if (serviceTypes.Count == 0)
        {
            return;
        }

        var code = new StringBuilder();
        code.AppendLine("using Microsoft.Extensions.DependencyInjection;");
        code.AppendLine("public static class Bootstrapper {");
        code.AppendLine("    public static void ConfigureServices(IServiceCollection serviceCollection) {");

        foreach (var serviceType in serviceTypes)
        {
            var serviceAttribute = serviceType.AttributeLists
                .SelectMany(al => al.Attributes)
                .First(a => a.Name.ToString() == nameof(ServiceAttribute));

            var serviceTypeName = serviceType.Identifier.Text;
            var serviceLifetime = serviceAttribute.ArgumentList!.Arguments[1].Expression.ToString();

            code.AppendLine($"        serviceCollection.Add(new ServiceDescriptor({serviceAttribute.ArgumentList.Arguments[0].Expression}, typeof({serviceTypeName}), ServiceLifetime.{serviceLifetime}));");
        }

        code.AppendLine("    }");
        code.AppendLine("}");

        context.AddSource("Bootstrapper", SourceText.From(code.ToString(), Encoding.UTF8));
    }

    public void Initialize(GeneratorInitializationContext context)
    {
    }
}
```
<pre class="lang-cs prettyprint-override"><code>using Microsoft.Extensions.DependencyInjection;

namespace Enliven.SourceGenerator;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ServiceAttribute : Attribute
{
    public ServiceAttribute(Type type, ServiceLifetime serviceLifetime)
    {
        Type = type;
        ServiceLifetime = serviceLifetime;
    }

    public Type Type { get; }
    public ServiceLifetime ServiceLifetime { get; }
}
</code>```

The issue

I referenced the library in the Enliven.Host and did the following. The issue is it doesn't find the generated class Bootstrapper. Why?

using Enliven.Observability;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";

var host = new HostBuilder()
    .ConfigureAppConfiguration(c => c
        .AddEnvironmentVariables()
        .AddJsonFile($"appsettings.{environment}.json"))
    .ConfigureServices((context, services) =>
    {
        // Configure services
        Bootstrapper.ConfigureServices(services);
    })
    .AddEnlivenLogging()
    .UseConsoleLifetime()
    .Build();

await host.RunAsync();
```

Body:
I like the idea of resolving services in the IoC using attributes. I wanted to replace System.Reflection with source generation, so it improves startup time.

The code snippet below is also on GitHub.

#1 System.Reflection

[Service(typeof(IListenerService), ServiceLifetime.Scoped)]
public class ListenerService : IListenerService
{
    ...
}

public static class Bootstrapper
{
    public static void ConfigureServices(IServiceCollection serviceCollection)
    {
        IEnumerable<Assembly> assemblies = GetAssemblies();

        List<KeyValuePair<Type, ServiceAttribute>> serviceAttributes = assemblies
            .SelectMany(x => x.DefinedTypes)
            .SelectMany(x =>
                x.GetCustomAttributes<ServiceAttribute>(false)
                    .Select(y => new KeyValuePair<Type, ServiceAttribute>(x, y)))
            .ToList();

        foreach ((Type type, ServiceAttribute serviceAttribute) in serviceAttributes)
        {
            serviceCollection.Add(new ServiceDescriptor(serviceAttribute.Type, type,
                serviceAttribute.ServiceLifetime));
        }
    }

    private static IEnumerable<Assembly> GetAssemblies()
    {
        List<Assembly> assemblies = GetAssemblies(Assembly.GetEntryAssembly()).Distinct().ToList();

        return assemblies;
    }

    private static IEnumerable<Assembly> GetAssemblies(Assembly assembly)
    {
        string namespacePrefix = typeof(Bootstrapper).Namespace?.Split(".")[0];

        foreach (Assembly referencedAssembly in assembly.GetReferencedAssemblies()
                     .Where(x => x.Name != null && x.Name.StartsWith(namespacePrefix ?? Empty)).Select(Assembly.Load)
                     .SelectMany(GetAssemblies))
        {
            yield return referencedAssembly;
        }

        yield return assembly;
    }
}

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ServiceAttribute : Attribute
{
    public ServiceAttribute(Type type)
    {
        Type = type;
        ServiceLifetime = ServiceLifetime.Scoped;
    }

    public ServiceAttribute(Type type, ServiceLifetime serviceLifetime)
    {
        Type = type;
        ServiceLifetime = serviceLifetime;
    }

    public Type Type { get; }
    public ServiceLifetime ServiceLifetime { get; }
}

#2 Source Generation

I made a Class Library called Enliven.SourceGenerator and put the following classes:

using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Enliven.SourceGenerator;

[Generator]
public class ServiceRegistrationGenerator : ISourceGenerator
{
    public void Execute(GeneratorExecutionContext context)
    {
        var serviceTypes = context.Compilation.SyntaxTrees
            .SelectMany(tree => tree.GetRoot().DescendantNodes())
            .OfType<ClassDeclarationSyntax>()
            .Where(classDecl => classDecl.AttributeLists
                .SelectMany(al => al.Attributes)
                .Any(a => a.Name.ToString() == nameof(ServiceAttribute)))
            .ToList();

        if (serviceTypes.Count == 0)
        {
            return;
        }

        var code = new StringBuilder();
        code.AppendLine("using Microsoft.Extensions.DependencyInjection;");
        code.AppendLine("public static class Bootstrapper {");
        code.AppendLine("    public static void ConfigureServices(IServiceCollection serviceCollection) {");

        foreach (var serviceType in serviceTypes)
        {
            var serviceAttribute = serviceType.AttributeLists
                .SelectMany(al => al.Attributes)
                .First(a => a.Name.ToString() == nameof(ServiceAttribute));

            var serviceTypeName = serviceType.Identifier.Text;
            var serviceLifetime = serviceAttribute.ArgumentList!.Arguments[1].Expression.ToString();

            code.AppendLine($"        serviceCollection.Add(new ServiceDescriptor({serviceAttribute.ArgumentList.Arguments[0].Expression}, typeof({serviceTypeName}), ServiceLifetime.{serviceLifetime}));");
        }

        code.AppendLine("    }");
        code.AppendLine("}");

        context.AddSource("Bootstrapper", SourceText.From(code.ToString(), Encoding.UTF8));
    }

    public void Initialize(GeneratorInitializationContext context)
    {
    }
}

using Microsoft.Extensions.DependencyInjection;

namespace Enliven.SourceGenerator;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ServiceAttribute : Attribute
{
    public ServiceAttribute(Type type, ServiceLifetime serviceLifetime)
    {
        Type = type;
        ServiceLifetime = serviceLifetime;
    }

    public Type Type { get; }
    public ServiceLifetime ServiceLifetime { get; }
}

The issue

I referenced the library in the Enliven.Host and did the following. The issue is it doesn't find the generated class Bootstrapper. Why?

using Enliven.Observability;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";

var host = new HostBuilder()
    .ConfigureAppConfiguration(c => c
        .AddEnvironmentVariables()
        .AddJsonFile($"appsettings.{environment}.json"))
    .ConfigureServices((context, services) =>
    {
        // Configure services
        Bootstrapper.ConfigureServices(services);
    })
    .AddEnlivenLogging()
    .UseConsoleLifetime()
    .Build();

await host.RunAsync();


问:
NoClassDefFoundError for exoplayer classes when using aar library
I am creating player library which uses exoplayer internally. When I build it and deploy it to the Android application,  during runtime I get NoClassDefFoundError for exoplayer dependency from the library. I copied the source code from library directly to the application and it works perfectly fine.

Also the size of the library that I built is pretty small(160kB). Mostly I am creating the library which serves just for compilation not for deployment. I an mot sure what I am missing in the gradle while building the library.


问:
Apache2 https forward proxy with ProxyRemote
I'm currently trying to set up an Apache2 that (as a temp solution) hands out a .pac file and (kinda) serves as a proxy on the same port.
I say kinda acts as a proxy as it only needs to redirect traffic to the real proxy server.
Here is my virtual host config:

```<code><VirtualHost *:8001>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        ProxyRequests On
        ProxyVia On
        SSLProxyEngine On
        <If "req('Host') == '192.168.122.95:8001'">
            DirectoryIndex pacfile1.pac
        </If>
        ProxyRemote "*" "http://xx.xx.xx.xx:3128"
</VirtualHost>
</code>```

This works for http connections but not for https. I don't need to do any SSL termination on the Apache, just forward everything to the real proxy.
Can anyone help me out why this is not working for https?

Body:
I'm currently trying to set up an Apache2 that (as a temp solution) hands out a .pac file and (kinda) serves as a proxy on the same port.
I say kinda acts as a proxy as it only needs to redirect traffic to the real proxy server.
Here is my virtual host config:

<VirtualHost *:8001>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        ProxyRequests On
        ProxyVia On
        SSLProxyEngine On
        <If "req('Host') == '192.168.122.95:8001'">
            DirectoryIndex pacfile1.pac
        </If>
        ProxyRemote "*" "http://xx.xx.xx.xx:3128"
</VirtualHost>

This works for http connections but not for https. I don't need to do any SSL termination on the Apache, just forward everything to the real proxy.
Can anyone help me out why this is not working for https?


问:
Error building APK react native skia libreactskia.so No such file or directory
Hello everyone i'm not sure if this question is already answered, but i can't find a solution anywhere...

So I want to build my .apk from my bare react native project but when i do: .\gradlew assembleRelease i get the following error:

```<code>> Task :shopify_react-native-skia:buildCMakeRelWithDebInfo[arm64-v8a] FAILED
C/C++: ninja: Entering directory `C:\Users\jpizaf\Desktop\uoc\assignatures\semestre-actual\tfg\projecte-react-native\emage\node_modules\@shopify\react-native-skia\android\.cxx\RelWithDebInfo\2c3m102b\arm64-v8a'
C/C++: clang++: error: linker command failed with exit code 1 (use -v to see invocation)

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':shopify_react-native-skia:buildCMakeRelWithDebInfo[arm64-v8a]'.
> Build command failed.
  Error while executing process C:\Users\jpizaf\AppData\Local\Android\Sdk\cmake\3.18.1\bin\ninja.exe with arguments {-C C:\Users\jpizaf\Desktop\uoc\assignatures\semestre-actual\tfg\projecte-react-native\emage\node_modules\@shopify\react-native-skia\android\.cxx\RelWithDebInfo\2c3m102b\arm64-v8a reactskia}
  ninja: Entering directory `C:\Users\jpizaf\Desktop\uoc\assignatures\semestre-actual\tfg\projecte-react-native\emage\node_modules\@shopify\react-native-skia\android\.cxx\RelWithDebInfo\2c3m102b\arm64-v8a'
  [1/6] Building CXX object CMakeFiles/reactskia.dir/cpp/rnskia-android/SkiaOpenGLRenderer.cpp.o
  [2/6] Building CXX object CMakeFiles/reactskia.dir/cpp/jni/JniPlatformContext.cpp.o
  [3/6] Building CXX object CMakeFiles/reactskia.dir/cpp/rnskia-android/RNSkOpenGLCanvasProvider.cpp.o
  [4/6] Building CXX object CMakeFiles/reactskia.dir/cpp/jni/JniSkiaManager.cpp.o
  [5/6] Building CXX object CMakeFiles/reactskia.dir/cpp/jni/JniLoad.cpp.o
  [6/6] Linking CXX shared library ..\..\..\..\build\intermediates\cxx\RelWithDebInfo\2c3m102b\obj\arm64-v8a\libreactskia.so
  FAILED: ../../../../build/intermediates/cxx/RelWithDebInfo/2c3m102b/obj/arm64-v8a/libreactskia.so
  cmd.exe /C "cd . && C:\Users\jpizaf\AppData\Local\Android\Sdk\ndk\21.4.7075529\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe --target=aarch64-none-linux-android21 --gcc-toolchain=C:/Users/jpizaf/AppData/Local/Android/Sdk/ndk/21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64 --sysroot=C:/Users/jpizaf/AppData/Local/Android/Sdk/ndk/21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64/sysroot -fPIC -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security  -fexceptions -frtti -std=c++1y -DONANDROID -DSK_GL -DSK_BUILD_FOR_ANDROID -DFOLLY_NO_CONFIG=1 -DFOLLY_HAVE_CLOCK_GETTIME=1 -DFOLLY_HAVE_MEMRCHR=1 -DFOLLY_USE_LIBCPP=1 -DFOLLY_MOBILE=1 -DON_ANDROID -DONANDROID -O2 -g -DNDEBUG  -Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libgcc_real.a -Wl,--exclude-libs,libatomic.a -Wl,--build-id -Wl,--fatal-warnings -Wl,--no-undefined -Qunused-arguments -shared -Wl,-soname,libreactskia.so -o ..\..\..\..\build\intermediates\cxx\RelWithDebInfo\2c3m102b\obj\arm64-v8a\libreactskia.so CMakeFiles/reactskia.dir/cpp/jni/JniLoad.cpp.o CMakeFiles/reactskia.dir/cpp/jni/JniSkiaManager.cpp.o CMakeFiles/reactskia.dir/cpp/jni/JniPlatformContext.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia-android/RNSkOpenGLCanvasProvider.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia-android/SkiaOpenGLRenderer.cpp.o CMakeFiles/reactskia.dir/cpp/jsi/JsiHostObject.cpp.o CMakeFiles/reactskia.dir/cpp/jsi/JsiValue.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/RNSkManager.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/RNSkJsView.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/RNSkDomView.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/RNSkDispatchQueue.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/dom/base/DrawingContext.cpp.o CMakeFiles/reactskia.dir/cpp/api/third_party/CSSColorParser.cpp.o -LC:/Users/jpizaf/Desktop/uoc/assignatures/semestre-actual/tfg/projecte-react-native/emage/node_modules/@shopify/react-native-skia/android/../libs/android/arm64-v8a   -LC:/Users/jpizaf/Desktop/uoc/assignatures/semestre-actual/tfg/projecte-react-native/emage/node_modules/@shopify/react-native-skia/android/build/fbjni-0.2.2.aar/jni/arm64-v8a   -LC:/Users/jpizaf/Desktop/uoc/assignatures/semestre-actual/tfg/projecte-react-native/emage/node_modules/@shopify/react-native-skia/android/build/react-native-0.70.6-release.aar/jni/arm64-v8a -llog  -lfbjni  -lreact_nativemodule_core  -ljsi  -lturbomodulejsijni  ../../../../../libs/android/arm64-v8a/libsvg.a  ../../../../../libs/android/arm64-v8a/libskshaper.a  ../../../../../libs/android/arm64-v8a/libskia.a  -ljnigraphics  -lGLESv2  -lEGL  -landroid  -latomic -lm && cd ."
  C:/Users/jpizaf/AppData/Local/Android/Sdk/ndk/21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64/lib/gcc/aarch64-linux-android/4.9.x/../../../../aarch64-linux-android/bin\ld: cannot open output file ..\..\..\..\build\intermediates\cxx\RelWithDebInfo\2c3m102b\obj\arm64-v8a\libreactskia.so: No such file or directory
  clang++: error: linker command failed with exit code 1 (use -v to see invocation)
  ninja: build stopped: subcommand failed.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
java.lang.StackOverflowError (no error message)

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings

Execution optimizations have been disabled for 11 invalid unit(s) of work during this build to ensure correctness.
Please consult deprecation warnings for more details.

BUILD FAILED in 25s
120 actionable tasks: 16 executed, 104 up-to-date
</code>```

I'll show my package.json:

```<code>{
  "name": "emage",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@eva-design/eva": "^2.1.1",
    "@klarna/react-native-vector-drawable": "^0.1.2",
    "@miblanchard/react-native-slider": "^2.1.0",
    "@react-native-async-storage/async-storage": "^1.17.11",
    "@react-native-camera-roll/camera-roll": "^5.2.0",
    "@react-navigation/native": "^6.1.0",
    "@react-navigation/native-stack": "^6.9.5",
    "@shopify/react-native-skia": "^0.1.167",
    "@ui-kitten/components": "^5.1.2",
    "@ui-kitten/eva-icons": "^5.1.2",
    "clamp": "^1.0.1",
    "react": "18.1.0",
    "react-native": "0.70.6",
    "react-native-fs": "^2.20.0",
    "react-native-gesture-handler": "^2.8.0",
    "react-native-image-picker": "^4.10.2",
    "react-native-reanimated": "^2.13.0",
    "react-native-safe-area-context": "^4.4.1",
    "react-native-screens": "^3.18.2",
    "react-native-svg": "^13.6.0",
    "react-native-vector-image": "^0.3.3"
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "0.72.3",
    "react-test-renderer": "18.1.0"
  }
}
</code>```

I've tryed creating a new project with just react native skia and it built the apk without a problem, but I have no idea what's wrong...

If anyone needs more info let me know.

Thanks ahead! <3

Body:
Hello everyone i'm not sure if this question is already answered, but i can't find a solution anywhere...

So I want to build my .apk from my bare react native project but when i do: .\gradlew assembleRelease i get the following error:

> Task :shopify_react-native-skia:buildCMakeRelWithDebInfo[arm64-v8a] FAILED
C/C++: ninja: Entering directory `C:\Users\jpizaf\Desktop\uoc\assignatures\semestre-actual\tfg\projecte-react-native\emage\node_modules\@shopify\react-native-skia\android\.cxx\RelWithDebInfo\2c3m102b\arm64-v8a'
C/C++: clang++: error: linker command failed with exit code 1 (use -v to see invocation)

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':shopify_react-native-skia:buildCMakeRelWithDebInfo[arm64-v8a]'.
> Build command failed.
  Error while executing process C:\Users\jpizaf\AppData\Local\Android\Sdk\cmake\3.18.1\bin\ninja.exe with arguments {-C C:\Users\jpizaf\Desktop\uoc\assignatures\semestre-actual\tfg\projecte-react-native\emage\node_modules\@shopify\react-native-skia\android\.cxx\RelWithDebInfo\2c3m102b\arm64-v8a reactskia}
  ninja: Entering directory `C:\Users\jpizaf\Desktop\uoc\assignatures\semestre-actual\tfg\projecte-react-native\emage\node_modules\@shopify\react-native-skia\android\.cxx\RelWithDebInfo\2c3m102b\arm64-v8a'
  [1/6] Building CXX object CMakeFiles/reactskia.dir/cpp/rnskia-android/SkiaOpenGLRenderer.cpp.o
  [2/6] Building CXX object CMakeFiles/reactskia.dir/cpp/jni/JniPlatformContext.cpp.o
  [3/6] Building CXX object CMakeFiles/reactskia.dir/cpp/rnskia-android/RNSkOpenGLCanvasProvider.cpp.o
  [4/6] Building CXX object CMakeFiles/reactskia.dir/cpp/jni/JniSkiaManager.cpp.o
  [5/6] Building CXX object CMakeFiles/reactskia.dir/cpp/jni/JniLoad.cpp.o
  [6/6] Linking CXX shared library ..\..\..\..\build\intermediates\cxx\RelWithDebInfo\2c3m102b\obj\arm64-v8a\libreactskia.so
  FAILED: ../../../../build/intermediates/cxx/RelWithDebInfo/2c3m102b/obj/arm64-v8a/libreactskia.so
  cmd.exe /C "cd . && C:\Users\jpizaf\AppData\Local\Android\Sdk\ndk\21.4.7075529\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe --target=aarch64-none-linux-android21 --gcc-toolchain=C:/Users/jpizaf/AppData/Local/Android/Sdk/ndk/21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64 --sysroot=C:/Users/jpizaf/AppData/Local/Android/Sdk/ndk/21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64/sysroot -fPIC -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security  -fexceptions -frtti -std=c++1y -DONANDROID -DSK_GL -DSK_BUILD_FOR_ANDROID -DFOLLY_NO_CONFIG=1 -DFOLLY_HAVE_CLOCK_GETTIME=1 -DFOLLY_HAVE_MEMRCHR=1 -DFOLLY_USE_LIBCPP=1 -DFOLLY_MOBILE=1 -DON_ANDROID -DONANDROID -O2 -g -DNDEBUG  -Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libgcc_real.a -Wl,--exclude-libs,libatomic.a -Wl,--build-id -Wl,--fatal-warnings -Wl,--no-undefined -Qunused-arguments -shared -Wl,-soname,libreactskia.so -o ..\..\..\..\build\intermediates\cxx\RelWithDebInfo\2c3m102b\obj\arm64-v8a\libreactskia.so CMakeFiles/reactskia.dir/cpp/jni/JniLoad.cpp.o CMakeFiles/reactskia.dir/cpp/jni/JniSkiaManager.cpp.o CMakeFiles/reactskia.dir/cpp/jni/JniPlatformContext.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia-android/RNSkOpenGLCanvasProvider.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia-android/SkiaOpenGLRenderer.cpp.o CMakeFiles/reactskia.dir/cpp/jsi/JsiHostObject.cpp.o CMakeFiles/reactskia.dir/cpp/jsi/JsiValue.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/RNSkManager.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/RNSkJsView.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/RNSkDomView.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/RNSkDispatchQueue.cpp.o CMakeFiles/reactskia.dir/cpp/rnskia/dom/base/DrawingContext.cpp.o CMakeFiles/reactskia.dir/cpp/api/third_party/CSSColorParser.cpp.o -LC:/Users/jpizaf/Desktop/uoc/assignatures/semestre-actual/tfg/projecte-react-native/emage/node_modules/@shopify/react-native-skia/android/../libs/android/arm64-v8a   -LC:/Users/jpizaf/Desktop/uoc/assignatures/semestre-actual/tfg/projecte-react-native/emage/node_modules/@shopify/react-native-skia/android/build/fbjni-0.2.2.aar/jni/arm64-v8a   -LC:/Users/jpizaf/Desktop/uoc/assignatures/semestre-actual/tfg/projecte-react-native/emage/node_modules/@shopify/react-native-skia/android/build/react-native-0.70.6-release.aar/jni/arm64-v8a -llog  -lfbjni  -lreact_nativemodule_core  -ljsi  -lturbomodulejsijni  ../../../../../libs/android/arm64-v8a/libsvg.a  ../../../../../libs/android/arm64-v8a/libskshaper.a  ../../../../../libs/android/arm64-v8a/libskia.a  -ljnigraphics  -lGLESv2  -lEGL  -landroid  -latomic -lm && cd ."
  C:/Users/jpizaf/AppData/Local/Android/Sdk/ndk/21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64/lib/gcc/aarch64-linux-android/4.9.x/../../../../aarch64-linux-android/bin\ld: cannot open output file ..\..\..\..\build\intermediates\cxx\RelWithDebInfo\2c3m102b\obj\arm64-v8a\libreactskia.so: No such file or directory
  clang++: error: linker command failed with exit code 1 (use -v to see invocation)
  ninja: build stopped: subcommand failed.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
java.lang.StackOverflowError (no error message)

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings

Execution optimizations have been disabled for 11 invalid unit(s) of work during this build to ensure correctness.
Please consult deprecation warnings for more details.

BUILD FAILED in 25s
120 actionable tasks: 16 executed, 104 up-to-date

I'll show my package.json:

{
  "name": "emage",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@eva-design/eva": "^2.1.1",
    "@klarna/react-native-vector-drawable": "^0.1.2",
    "@miblanchard/react-native-slider": "^2.1.0",
    "@react-native-async-storage/async-storage": "^1.17.11",
    "@react-native-camera-roll/camera-roll": "^5.2.0",
    "@react-navigation/native": "^6.1.0",
    "@react-navigation/native-stack": "^6.9.5",
    "@shopify/react-native-skia": "^0.1.167",
    "@ui-kitten/components": "^5.1.2",
    "@ui-kitten/eva-icons": "^5.1.2",
    "clamp": "^1.0.1",
    "react": "18.1.0",
    "react-native": "0.70.6",
    "react-native-fs": "^2.20.0",
    "react-native-gesture-handler": "^2.8.0",
    "react-native-image-picker": "^4.10.2",
    "react-native-reanimated": "^2.13.0",
    "react-native-safe-area-context": "^4.4.1",
    "react-native-screens": "^3.18.2",
    "react-native-svg": "^13.6.0",
    "react-native-vector-image": "^0.3.3"
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "0.72.3",
    "react-test-renderer": "18.1.0"
  }
}

I've tryed creating a new project with just react native skia and it built the apk without a problem, but I have no idea what's wrong...

If anyone needs more info let me know.

Thanks ahead! <3


问:
Error in code for finding an element in an array using java
```<code>import java.io.*;
import java.util.*;

public class Main{

public static void main(String[] args) throws Exception {
    Scanner scn = new Scanner (System.in);
    int n = scn.nextInt();
    int[] arr= new int[n];

    for(int i=0; i<arr.length; i++){
        arr[i]= scn.nextInt(n);
    }
    int j =  scn.nextInt();

       int idx = -1;
       for(int i=0; i<arr.length ; i++){
        if(j==arr[i]){
            idx =i;
            System.out.print(idx);
            break;
        }

 }
 System.out.print(idx);

}
}
</code>```

OUTPUT:-

```<code>Exception in thread "main" java.util.InputMismatchException: For input string: "9" under radix 6
    at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
    at Main.main(Main.java:13)
</code>```

//
HOW TO SOLVE THIS ERROR??

```<code>1.You are given a number n, representing the size of array a.
2.You are given n distinct numbers, representing elements of array a.
3. You are given another number d.
4. You are required to check if d number exists in the array a and at what index (0 based). If found print the index, otherwise print -1.
</code>```

Input Format
A number n
n1
n2
.. n number of elements
A number d

Output Format
A number representing index at which d is found in array a and -1 if not found

```<code>Sample Input
6
15
30
40
4
11
9
40

Sample Output
2
</code>```

Body:
import java.io.*;
import java.util.*;

public class Main{

public static void main(String[] args) throws Exception {
    Scanner scn = new Scanner (System.in);
    int n = scn.nextInt();
    int[] arr= new int[n];

    for(int i=0; i<arr.length; i++){
        arr[i]= scn.nextInt(n);
    }
    int j =  scn.nextInt();

       int idx = -1;
       for(int i=0; i<arr.length ; i++){
        if(j==arr[i]){
            idx =i;
            System.out.print(idx);
            break;
        }

 }
 System.out.print(idx);

}
}

OUTPUT:-

Exception in thread "main" java.util.InputMismatchException: For input string: "9" under radix 6
    at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
    at Main.main(Main.java:13)

//
HOW TO SOLVE THIS ERROR??

1.You are given a number n, representing the size of array a.
2.You are given n distinct numbers, representing elements of array a.
3. You are given another number d.
4. You are required to check if d number exists in the array a and at what index (0 based). If found print the index, otherwise print -1.

Input Format
A number n
n1
n2
.. n number of elements
A number d

Output Format
A number representing index at which d is found in array a and -1 if not found

Sample Input
6
15
30
40
4
11
9
40

Sample Output
2