问:
Firebase. getDocs returns an empty array and an infinite loop occurs
I want to create a document search string from firebase. When I enter values that are not in the Firebase collection, getDocs always returns an empty array and an infinite loop occurs.

The place where the endless cycle happens:

```<code>  export async function get() {
    const query = query(collectionRef, orderBy("title"), startAt("Abbb"), endAt("Abbb\uf8ff"));
    const snapshot = await getDocs(query);
  }
</code>```

I don't understand why there is an infinite loop. I just want my snapshot to be empty so nothing is displayed

Here is my collection:

```<code>const collectionRef = getCollectionRef<Model>("collectionName") // CollectionReference<Model>
</code>```
```<code>  /**
   * Getting typed collectionReference.
   * @param collectionName - Collection name.
   */
  function getCollectionRef<T = DocumentData>(collectionName):CollectionReference<T> {
    return collection(database, collectionName) as CollectionReference<T>;
  }
</code>```

I realized that the problem occurs in this line. It is after it that the function starts executing again.

```<code>    const snapshot = await getDocs(query);
</code>```

Body:
I want to create a document search string from firebase. When I enter values that are not in the Firebase collection, getDocs always returns an empty array and an infinite loop occurs.

The place where the endless cycle happens:

  export async function get() {
    const query = query(collectionRef, orderBy("title"), startAt("Abbb"), endAt("Abbb\uf8ff"));
    const snapshot = await getDocs(query);
  }

I don't understand why there is an infinite loop. I just want my snapshot to be empty so nothing is displayed

Here is my collection:

const collectionRef = getCollectionRef<Model>("collectionName") // CollectionReference<Model>

  /**
   * Getting typed collectionReference.
   * @param collectionName - Collection name.
   */
  function getCollectionRef<T = DocumentData>(collectionName):CollectionReference<T> {
    return collection(database, collectionName) as CollectionReference<T>;
  }

I realized that the problem occurs in this line. It is after it that the function starts executing again.

    const snapshot = await getDocs(query);


来源: stackexchange

问:
Postgres's deployment to EKS causing error
I have been working on a project with Postgres. I want to add this to EKS. my deployment is giving me an error as:

Warning  FailedScheduling  29s   default-scheduler  0/2 nodes are available: 2 pod has unbound immediate PersistentVolumeClaims. preemption: 0/2 nodes are available: 2 Preemption is not helpful for scheduling.

I have tried changing the storage capacity but nothing worked.
Various components of the YAML file are below:

```<code>apiVersion: v1
kind: Secret
metadata:
  name: xdb-secret
  namespace: default
type: Opaque
data:
  django-secret-key: xxx
  django_database_name: xxx
  django_database_username: xxx
  django_database_password: xxx
  email_host_user: xxx
  email_host_password: xxx

# ---

# apiVersion: v1
# kind: PersistentVolume
# metadata:
#   name: xdb-pv
#   labels:
#     type: local
# spec:
#   capacity:
#     storage: 10Gi
#   volumeMode: Filesystem
#   accessModes:
#     - ReadWriteOnce
#   storageClassName: standard

---

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: xdb-pvc
  namespace: default
  labels:
    app: local
spec:
  storageClassName: standard
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  # volumeName: xdb-pv

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name:  xdb-deployment
  namespace: default
  labels:
    app:  xdb

spec:
  selector:
    matchLabels:
      app: xdb

  replicas: 1

  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate

  template:
    metadata:
      labels:
        app:  xdb

    spec:
      # initContainers:
        # Init containers are exactly like regular containers, except:
          # - Init containers always run to completion.
          # - Each init container must complete successfully before the next one starts.
      containers:
      - name:  xdb-cont
        image:  postgres:latest

        env:
        - name: DJANGO_SECRET_KEY
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: django-secret-key
        - name: DJANGO_DATABASE_NAME
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: django_database_name
        - name: DJANGO_DATABASE_USERNAME
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: django_database_username
        - name: DJANGO_DATABASE_PASSWORD
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: django_database_password
        - name: EMAIL_HOST_USER
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: email_host_user
        - name: EMAIL_HOST_PASSWORD
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: email_host_password
        - name: DJANGO_DATABASE_PORT
          value: "5432"
        - name: DJANGO_DATABASE_HOST
          value: xdb-service

        ports:
        - containerPort:  5432
          name:  xdb-cont
        volumeMounts:
        - name: xdb-volume-mount
          mountPath: /var/lib/postgresql/data

      volumes:
        - name: xdb-volume-mount
          persistentVolumeClaim:
            claimName: xdb-pvc

      restartPolicy: Always

---

apiVersion: v1
kind: Service
metadata:
  name: xdb-service
  namespace: default
spec:
  selector:
    app: xdb
  ports:
  - protocol: TCP
    port: 5432
    targetPort: 5432

</code>```

Details:

replica: 1

node: 2

each node capacity: 20Gi

Capacity type: Spot

Desired size: 2 nodes

Minimum size: 2 nodes

Maximum size: 5 nodes

I am not sure what's going wrong in this.

ContentLicense: CC BY-SA 4.0

Body:
I have been working on a project with Postgres. I want to add this to EKS. my deployment is giving me an error as:

Warning  FailedScheduling  29s   default-scheduler  0/2 nodes are available: 2 pod has unbound immediate PersistentVolumeClaims. preemption: 0/2 nodes are available: 2 Preemption is not helpful for scheduling.

I have tried changing the storage capacity but nothing worked.
Various components of the YAML file are below:

apiVersion: v1
kind: Secret
metadata:
  name: xdb-secret
  namespace: default
type: Opaque
data:
  django-secret-key: xxx
  django_database_name: xxx
  django_database_username: xxx
  django_database_password: xxx
  email_host_user: xxx
  email_host_password: xxx

# ---

# apiVersion: v1
# kind: PersistentVolume
# metadata:
#   name: xdb-pv
#   labels:
#     type: local
# spec:
#   capacity:
#     storage: 10Gi
#   volumeMode: Filesystem
#   accessModes:
#     - ReadWriteOnce
#   storageClassName: standard

---

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: xdb-pvc
  namespace: default
  labels:
    app: local
spec:
  storageClassName: standard
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  # volumeName: xdb-pv

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name:  xdb-deployment
  namespace: default
  labels:
    app:  xdb

spec:
  selector:
    matchLabels:
      app: xdb

  replicas: 1

  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate

  template:
    metadata:
      labels:
        app:  xdb

    spec:
      # initContainers:
        # Init containers are exactly like regular containers, except:
          # - Init containers always run to completion.
          # - Each init container must complete successfully before the next one starts.
      containers:
      - name:  xdb-cont
        image:  postgres:latest

        env:
        - name: DJANGO_SECRET_KEY
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: django-secret-key
        - name: DJANGO_DATABASE_NAME
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: django_database_name
        - name: DJANGO_DATABASE_USERNAME
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: django_database_username
        - name: DJANGO_DATABASE_PASSWORD
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: django_database_password
        - name: EMAIL_HOST_USER
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: email_host_user
        - name: EMAIL_HOST_PASSWORD
          valueFrom:
            secretKeyRef:
              name: xdb-secret
              key: email_host_password
        - name: DJANGO_DATABASE_PORT
          value: "5432"
        - name: DJANGO_DATABASE_HOST
          value: xdb-service

        ports:
        - containerPort:  5432
          name:  xdb-cont
        volumeMounts:
        - name: xdb-volume-mount
          mountPath: /var/lib/postgresql/data

      volumes:
        - name: xdb-volume-mount
          persistentVolumeClaim:
            claimName: xdb-pvc

      restartPolicy: Always

---

apiVersion: v1
kind: Service
metadata:
  name: xdb-service
  namespace: default
spec:
  selector:
    app: xdb
  ports:
  - protocol: TCP
    port: 5432
    targetPort: 5432

Details:

replica: 1

node: 2

each node capacity: 20Gi

Capacity type: Spot

Desired size: 2 nodes

Minimum size: 2 nodes

Maximum size: 5 nodes

I am not sure what's going wrong in this.


问:
How to read a list as an input in Swi-Prolog?
I am writing a function that takes two parameters as inputs:

The first one is a representation of a binary tree that can be in this form:
[bt(integer, binary_tree_node, binary_tree_node)] for example:
[bt(1,[bt(3,[],[])],[bt(3,[],[])])]

or
[] when the tree is empty.

The second parameter is an integer .

```<code>bt([]).
bt(X) :-
            X = [N,L,R],
            integer(N),
            (L == [] ; L = [bt(_nl,_ll,_rl)], bt([_nl,_ll,_rl])),
            (R == []  ; R = [bt(_nr,_lr,_rr)], bt([_nr,_lr,_rr])).

bintree_func(Tree, Int ) :-
                            read(Tree),
                            readint(Int).

                            /*
                            I need the two inputs to finish the function
                            */

</code>```

I am not able to find how to take the representation of the tree as an input. How can I do it correctly ?

Thanks for your help.

I have tried some read options like readln() ... but none of them worked.

Body:
I am writing a function that takes two parameters as inputs:

The first one is a representation of a binary tree that can be in this form:
[bt(integer, binary_tree_node, binary_tree_node)] for example:
[bt(1,[bt(3,[],[])],[bt(3,[],[])])]

or
[] when the tree is empty.

The second parameter is an integer .

bt([]).
bt(X) :-
            X = [N,L,R],
            integer(N),
            (L == [] ; L = [bt(_nl,_ll,_rl)], bt([_nl,_ll,_rl])),
            (R == []  ; R = [bt(_nr,_lr,_rr)], bt([_nr,_lr,_rr])).

bintree_func(Tree, Int ) :-
                            read(Tree),
                            readint(Int).

                            /*
                            I need the two inputs to finish the function
                            */

I am not able to find how to take the representation of the tree as an input. How can I do it correctly ?

Thanks for your help.

I have tried some read options like readln() ... but none of them worked.


问:
When scrolling to next page grid view position not setting to zero
When scrolling to next page grid view position not setting to zero. How to fix that in android kotlin?</p>


问:
Rasa to dialogflow connection in javascript
I need a solution for the Rasa nlu to dialogflow connection. I tried different ways in the code from adding the yml file, tar.gz file and Rasa provided webhooks and API. None of these methods are working and it is not responsing the answers from the domain.yml file but getting the response "Sorry. Something went wrong. Can you say that again?" in the dialogflow and getting different errors in the vs code terminal when I try to enter the inputs from the nlu.yml file for Rasa nlu in the dialogflow.

```<code>async function defaultFallback(agent) {
const yaml = require('js-yaml');
const fs   = require('fs');
const defaultFallback = yaml.load(fs.readFileSync('nlu.yml'));

const dialog = [
  `The following is a conversation with an AI assistant that can have meaningful conversations with users. The assistant is helpful, empathic, and friendly. Its objective is to make the user feel better by feeling heard. With each response, the AI assisstant prompts the user to continue the conversation in a natural way.

  AI: Hello, my name is Debra. I am your personal AI assistant from Orient Telecoms. How are you doing today?`,
];

let query = agent.query;
console.log('querytext ', query)
dialog.push(`User: ${query}`);
dialog.push('AI:');

try{
  var targz = require('targz');
  var tar = require('tar-stream');
  var extract = tar.extract();
//  targz.decompress({src: '20221206-172837-simple-assistant.tar.gz',
//                    dest: '\dialogflow'})
    // const response = yaml.load(fs.readFileSync('domain.yml'));
//  const response = await fetch (extract.on('20221206-172837-simple-assistant.tar.gz'));
  const response = await fetch ('http://0.0.0.0:5005',
  {
    method: "POST",
    body: JSON.stringify(query),
  });
  const botResponse = await response.json();
  console.log('botResponse: ', botResponse)
  agent.add(botResponse[0].generated_text.substring(botResponse[0].generated_text.indexOf('?') + 1).trim());
}catch(err){
  console.log('This is error:', err);
  agent.add('Sorry. Something went wrong. Can you say that again?');
}
</code>```

}

I was able to run with rasa shell, node and ngrok command together but there is no response from the yml file when I'm working on the dialogflow. Is there a solution for these problems?

Body:
I need a solution for the Rasa nlu to dialogflow connection. I tried different ways in the code from adding the yml file, tar.gz file and Rasa provided webhooks and API. None of these methods are working and it is not responsing the answers from the domain.yml file but getting the response "Sorry. Something went wrong. Can you say that again?" in the dialogflow and getting different errors in the vs code terminal when I try to enter the inputs from the nlu.yml file for Rasa nlu in the dialogflow.

async function defaultFallback(agent) {
const yaml = require('js-yaml');
const fs   = require('fs');
const defaultFallback = yaml.load(fs.readFileSync('nlu.yml'));

const dialog = [
  `The following is a conversation with an AI assistant that can have meaningful conversations with users. The assistant is helpful, empathic, and friendly. Its objective is to make the user feel better by feeling heard. With each response, the AI assisstant prompts the user to continue the conversation in a natural way.

  AI: Hello, my name is Debra. I am your personal AI assistant from Orient Telecoms. How are you doing today?`,
];

let query = agent.query;
console.log('querytext ', query)
dialog.push(`User: ${query}`);
dialog.push('AI:');

try{
  var targz = require('targz');
  var tar = require('tar-stream');
  var extract = tar.extract();
//  targz.decompress({src: '20221206-172837-simple-assistant.tar.gz',
//                    dest: '\dialogflow'})
    // const response = yaml.load(fs.readFileSync('domain.yml'));
//  const response = await fetch (extract.on('20221206-172837-simple-assistant.tar.gz'));
  const response = await fetch ('http://0.0.0.0:5005',
  {
    method: "POST",
    body: JSON.stringify(query),
  });
  const botResponse = await response.json();
  console.log('botResponse: ', botResponse)
  agent.add(botResponse[0].generated_text.substring(botResponse[0].generated_text.indexOf('?') + 1).trim());
}catch(err){
  console.log('This is error:', err);
  agent.add('Sorry. Something went wrong. Can you say that again?');
}

}

I was able to run with rasa shell, node and ngrok command together but there is no response from the yml file when I'm working on the dialogflow. Is there a solution for these problems?


问:
showing the the labels/names instead of percentage in javascript PIE CHART
I am working on a pie chart where I want to show the Account names according to account types & balance. But I only saw the tutorials where they show only the percentage. But I want to show the Account Names also.

My code is----

```

In the above code, I have processed the Balance according to the Account Types. The account Names are not showing here.

How do I show the account names inside each Account Types?

Body:
I am working on a pie chart where I want to show the Account names according to account types & balance. But I only saw the tutorials where they show only the percentage. But I want to show the Account Names also.

My code is----

In the above code, I have processed the Balance according to the Account Types. The account Names are not showing here.

How do I show the account names inside each Account Types?


问:
How to "turn" gravity
I was wondering if there is a way to "turn" gravity. Would it possible with say a Rodin coil to "turn" gravity from going down towards the earth and instead turn it horizontal?</p>

Title: How to "turn" gravity


问:
How to construct a ZipArchive on the fly without using the file system
I want to construct a zip and serve it back to the user. I currently use Symfony and so far I have the following which works well:

```<code>// Create zip.
$zip = new \ZipArchive();
$zip->open('/tmp/foo.zip', \ZipArchive::CREATE);
$zip->addFromString("test1.txt", "test 1 content");
$zip->addFromString("test2.txt", "test 2 content");
$zip->close();

// Read zip.
$stream = fopen('/tmp/foo.zip', 'r');
$zipData = fread($stream, 1024);
fclose($stream);
unlink('/tmp/foo.zip');

// Serve zip.
$response = new Response($zipData);
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment; filename=foo.zip');
return $response;
</code>```

My problem is that I want to avoid having to use the file system (/tmp/foo.zip). I tried $zip->open('php://memory', ...) which I thought that would do the job but it didn't work (result file was always 0 bytes). Is there a way to solve this?

Edit: I want to be using vanilla PHP and not directly make use of commands of the underlying O/S.

Body:
I want to construct a zip and serve it back to the user. I currently use Symfony and so far I have the following which works well:

// Create zip.
$zip = new \ZipArchive();
$zip->open('/tmp/foo.zip', \ZipArchive::CREATE);
$zip->addFromString("test1.txt", "test 1 content");
$zip->addFromString("test2.txt", "test 2 content");
$zip->close();

// Read zip.
$stream = fopen('/tmp/foo.zip', 'r');
$zipData = fread($stream, 1024);
fclose($stream);
unlink('/tmp/foo.zip');

// Serve zip.
$response = new Response($zipData);
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment; filename=foo.zip');
return $response;

My problem is that I want to avoid having to use the file system (/tmp/foo.zip). I tried $zip->open('php://memory', ...) which I thought that would do the job but it didn't work (result file was always 0 bytes). Is there a way to solve this?

Edit: I want to be using vanilla PHP and not directly make use of commands of the underlying O/S.


问:
If else condition countdown php code show wrong hour with local time zone
I have used a PHP countdown code from StackOverflow on my website. Countdown everything is okay, but getting the wrong 6 hours with my local time zone.

I think it is a time zone problem with the code. I want to show the exact hours in any local time zone. I know no how to solve the problem.

The code is to check if the date is passed and expired.

Example: if xx-x-xx date then count down else expired days :0, hours:0, minutes: 0, seconds: 0

```<code>    $expire_date = "dec 25";   //you can change this date
    $datetime1 = new DateTime();
    $datetime2 = new DateTime($expire_date);

    $formatted_date = $datetime2->format('Y-m-d'); // we need to pass a well formatted expire date to jQuery

    if($datetime2 >= $datetime1) {
        ?>

        <h2>To Christmas <span id="getting-started"></span></h2> <!-- that is the container of the countdown in your page, jQuery will populate it -->

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- copy this line as it is, it's load jQuery library from google repository -->
        <script src="https://www.xmascountdown.net/old/1/jquery.countdown-2.2.0/jquery.countdown.js"></script> <!-- here you have to load the countdown library, modify your path in case you'll put that library in a subfolder -->

        <!-- that's our jQuery script -->
        <script type="text/javascript">
                var dateVar = "<?php echo $formatted_date;?>";
                var expire_date=new Date(dateVar);

                $('#getting-started').countdown(expire_date, function(event) {
                    $(this).html(event.strftime('%w weeks %D days %H:%M:%S'));
                });
        </script>

<?php
    } else {
        echo 'Time expired';
    };
?>```
```

Body:
I have used a PHP countdown code from StackOverflow on my website. Countdown everything is okay, but getting the wrong 6 hours with my local time zone.

I think it is a time zone problem with the code. I want to show the exact hours in any local time zone. I know no how to solve the problem.

The code is to check if the date is passed and expired.

Example: if xx-x-xx date then count down else expired days :0, hours:0, minutes: 0, seconds: 0

    $expire_date = "dec 25";   //you can change this date
    $datetime1 = new DateTime();
    $datetime2 = new DateTime($expire_date);

    $formatted_date = $datetime2->format('Y-m-d'); // we need to pass a well formatted expire date to jQuery

    if($datetime2 >= $datetime1) {
        ?>

To Christmas

<?php
    } else {
        echo 'Time expired';
    };
?>```


问:
How to create an independent process using python on Windows 10?
Python version: 3.10.8
Windows version: 10

Tried many ways, but all failed, the process was closed when python script exited.

```<code>import subprocess
p = subprocess.Popen(['C:\\Program Files (x86)\\Notepad3\\Notepad3.exe'], creationflags=subprocess.DETACHED_PROCESS, close_fds=True)
print(p.pid)
</code>```
```<code>import multiprocessing
import os

def run_process():
    os.popen('C:\\Program Files (x86)\\Notepad3\\Notepad3.exe')

p = multiprocessing.Process(target=run_process)
p.start()
</code>```
```<code>import os
os.startfile('C:\\Program Files (x86)\\Notepad3\\Notepad3.exe')
</code>```
```<code>import win32api as api, win32process as proc
info = proc.STARTUPINFO()
result = proc.CreateProcess(
    "C:\\Program Files (x86)\\Notepad3\\Notepad3.exe", "", None,
    None, 0, proc.DETACHED_PROCESS, None, None, info)
print(result)
</code>```

By the way, I tried below code in an Windows Console program, it works. Have no idea why win32process is not working. I even let python call this Console program, but when it exits, it still closes notepad3.

```<code>    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    // Start the child process.
    if (!CreateProcess(L"C:\\Program Files (x86)\\Notepad3\\Notepad3.exe",   // No module name (use command line)
        NULL,        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        DETACHED_PROCESS,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi)           // Pointer to PROCESS_INFORMATION structure
        )
    {
        printf("CreateProcess failed (%d).\n", GetLastError());
        return;
    }
</code>```

Body:
Python version: 3.10.8
Windows version: 10

Tried many ways, but all failed, the process was closed when python script exited.

import subprocess
p = subprocess.Popen(['C:\\Program Files (x86)\\Notepad3\\Notepad3.exe'], creationflags=subprocess.DETACHED_PROCESS, close_fds=True)
print(p.pid)

import multiprocessing
import os

def run_process():
    os.popen('C:\\Program Files (x86)\\Notepad3\\Notepad3.exe')

p = multiprocessing.Process(target=run_process)
p.start()

import os
os.startfile('C:\\Program Files (x86)\\Notepad3\\Notepad3.exe')

import win32api as api, win32process as proc
info = proc.STARTUPINFO()
result = proc.CreateProcess(
    "C:\\Program Files (x86)\\Notepad3\\Notepad3.exe", "", None,
    None, 0, proc.DETACHED_PROCESS, None, None, info)
print(result)

By the way, I tried below code in an Windows Console program, it works. Have no idea why win32process is not working. I even let python call this Console program, but when it exits, it still closes notepad3.

    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    // Start the child process.
    if (!CreateProcess(L"C:\\Program Files (x86)\\Notepad3\\Notepad3.exe",   // No module name (use command line)
        NULL,        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        DETACHED_PROCESS,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi)           // Pointer to PROCESS_INFORMATION structure
        )
    {
        printf("CreateProcess failed (%d).\n", GetLastError());
        return;
    }


问:
Clearing all apps data
Can someone help me with an problem please?

I have an A20e (SM-A202F) phone and I try to clear all apps data and cache with adb with this command:

cmd package list packages | cut -d":" -f2 | while read package; do pm clear $package && echo $package; done
```

All working fine but at some point for whatever reason its stuck at one random app... I try again and the same thing, at another app is stuck and is not finishing to clear all apps. I also want to specify that I'm trying to do this on stock firmware, the latest one.

Someone have an ideea please? Thanks a lot and please excuse my English, I'm not native.

UPDATE: I found that when pm clear command stops working on the phone screen appears an message: Security policy restrics clearing of application data....

Title: Clearing all apps data

Body:
Can someone help me with an problem please?

I have an A20e (SM-A202F) phone and I try to clear all apps data and cache with adb with this command:

cmd package list packages | cut -d":" -f2 | while read package; do pm clear $package && echo $package; done

All working fine but at some point for whatever reason its stuck at one random app... I try again and the same thing, at another app is stuck and is not finishing to clear all apps. I also want to specify that I'm trying to do this on stock firmware, the latest one.

Someone have an ideea please? Thanks a lot and please excuse my English, I'm not native.

UPDATE: I found that when pm clear command stops working on the phone screen appears an message: Security policy restrics clearing of application data....


问:
Error while connecting to redis server locally
Has anyone faced this issue while connecting to redis server locally ?

`

```<code>[ioredis] Unhandled error event: Error: connect ETIMEDOUT
    at Socket.<anonymous> (/Users/PB/Desktop/Projects/PTS/node_modules/ioredis/lib/redis.js:289:21)
    at Object.onceWrapper (events.js:519:28)
    at Socket.emit (events.js:400:28)
    at Socket.emit (domain.js:470:12)
    at Socket._onTimeout (net.js:484:8)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)
</code>```

`

I wanted to connect to redis server locally.
My client application is in nodejs.

Body:
Has anyone faced this issue while connecting to redis server locally ?

`

[ioredis] Unhandled error event: Error: connect ETIMEDOUT
    at Socket.<anonymous> (/Users/PB/Desktop/Projects/PTS/node_modules/ioredis/lib/redis.js:289:21)
    at Object.onceWrapper (events.js:519:28)
    at Socket.emit (events.js:400:28)
    at Socket.emit (domain.js:470:12)
    at Socket._onTimeout (net.js:484:8)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)

`

I wanted to connect to redis server locally.
My client application is in nodejs.


问:
Where are the DOMProperty and EventPluginRegistry after upgrade react 15 to 17?
I lost DOMProperty and EventPluginRegistry.Both of them are in "react/lib". Now it 's disappear.I think maybe is because it's to old,so react 17 abandon it.What should I do now?My boss told me that This project needs a new react version.So I can't back to react 15. Here is the dependencies in my package.json:

```<code>"devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/plugin-proposal-class-properties": "^7.0.0",
    "@babel/plugin-proposal-decorators": "^7.0.0",
    "@babel/plugin-proposal-do-expressions": "^7.0.0",
    "@babel/plugin-proposal-export-default-from": "^7.0.0",
    "@babel/plugin-proposal-export-namespace-from": "^7.0.0",
    "@babel/plugin-proposal-function-bind": "^7.0.0",
    "@babel/plugin-proposal-function-sent": "^7.0.0",
    "@babel/plugin-proposal-json-strings": "^7.0.0",
    "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0",
    "@babel/plugin-proposal-numeric-separator": "^7.0.0",
    "@babel/plugin-proposal-optional-chaining": "^7.0.0",
    "@babel/plugin-proposal-pipeline-operator": "^7.0.0",
    "@babel/plugin-proposal-throw-expressions": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/plugin-syntax-import-meta": "^7.0.0",
    "@babel/plugin-transform-arrow-functions": "^7.0.0",
    "@babel/plugin-transform-react-jsx": "^7.0.0",
    "@babel/plugin-transform-runtime": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "@babel/runtime-corejs2": "^7.0.0",
    "antd": "^1.11.1",
    "babel-loader": "^8.0.0",
    "babel-plugin-antd": "^0.5.1",
    "babel-plugin-import": "^1.7.0",
    "css-loader": "^0.28.4",
    "eslint": "^3.3.0",
    "eslint-config-airbnb": "^10.0.1",
    "eslint-plugin-import": "^1.13.0",
    "eslint-plugin-jsx-a11y": "^2.1.0",
    "eslint-plugin-react": "^6.1.0",
    "jquery": "^3.1.0",
    "path": "^0.12.7",
    "react-hot-loader": "1.3.0",
    "react-mixin": "3.0.3",
    "react-router": "^2.6.1",
    "reflux": "^0.4.1",
    "select2": "^4.0.13",
    "shallow-equal-fuzzy": "^0.0.2",
    "style-loader": "0.18.2",
    "superagent": "^2.1.0",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^1.14.1"
  },
  "dependencies": {
    "@babel/core": "^7.0.0",
    "@babel/plugin-transform-react-constant-elements": "^7.0.0",
    "@babel/plugin-transform-react-inline-elements": "^7.0.0",
    "@babel/polyfill": "^7.0.0",
    "babel-plugin-transform-react-pure-class-to-function": "^1.0.1",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.13",
    "bundle-loader": "0.5.4",
    "echarts": "^3.8.5",
    "moment": "^2.18.1",
    "prop-types": "^15.8.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-loadable": "^5.4.0",
    "yarn": "^1.22.19"
  }
}
</code>```

Here is the code about import DOMProperty and EventPluginRegistry in my project:

```<code>import React, { Component } from 'react';
import PropTypes from "prop-types";
import DOMProperty from 'react/lib/DOMProperty';
import EventPluginRegistry from 'react/lib/EventPluginRegistry';
import shallowEqualFuzzy from 'shallow-equal-fuzzy';
import $ from 'jquery';
import 'select2';
import './select2.css;
</code>```

I search DOMProperty and EventPluginRegistry in google and I think both of them are too
old to run on react 17.So react 17 abandoned them and get the new one.But I didn't get it.What is it?

Body:
I lost DOMProperty and EventPluginRegistry.Both of them are in "react/lib". Now it 's disappear.I think maybe is because it's to old,so react 17 abandon it.What should I do now?My boss told me that This project needs a new react version.So I can't back to react 15. Here is the dependencies in my package.json:

"devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/plugin-proposal-class-properties": "^7.0.0",
    "@babel/plugin-proposal-decorators": "^7.0.0",
    "@babel/plugin-proposal-do-expressions": "^7.0.0",
    "@babel/plugin-proposal-export-default-from": "^7.0.0",
    "@babel/plugin-proposal-export-namespace-from": "^7.0.0",
    "@babel/plugin-proposal-function-bind": "^7.0.0",
    "@babel/plugin-proposal-function-sent": "^7.0.0",
    "@babel/plugin-proposal-json-strings": "^7.0.0",
    "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0",
    "@babel/plugin-proposal-numeric-separator": "^7.0.0",
    "@babel/plugin-proposal-optional-chaining": "^7.0.0",
    "@babel/plugin-proposal-pipeline-operator": "^7.0.0",
    "@babel/plugin-proposal-throw-expressions": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/plugin-syntax-import-meta": "^7.0.0",
    "@babel/plugin-transform-arrow-functions": "^7.0.0",
    "@babel/plugin-transform-react-jsx": "^7.0.0",
    "@babel/plugin-transform-runtime": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "@babel/runtime-corejs2": "^7.0.0",
    "antd": "^1.11.1",
    "babel-loader": "^8.0.0",
    "babel-plugin-antd": "^0.5.1",
    "babel-plugin-import": "^1.7.0",
    "css-loader": "^0.28.4",
    "eslint": "^3.3.0",
    "eslint-config-airbnb": "^10.0.1",
    "eslint-plugin-import": "^1.13.0",
    "eslint-plugin-jsx-a11y": "^2.1.0",
    "eslint-plugin-react": "^6.1.0",
    "jquery": "^3.1.0",
    "path": "^0.12.7",
    "react-hot-loader": "1.3.0",
    "react-mixin": "3.0.3",
    "react-router": "^2.6.1",
    "reflux": "^0.4.1",
    "select2": "^4.0.13",
    "shallow-equal-fuzzy": "^0.0.2",
    "style-loader": "0.18.2",
    "superagent": "^2.1.0",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^1.14.1"
  },
  "dependencies": {
    "@babel/core": "^7.0.0",
    "@babel/plugin-transform-react-constant-elements": "^7.0.0",
    "@babel/plugin-transform-react-inline-elements": "^7.0.0",
    "@babel/polyfill": "^7.0.0",
    "babel-plugin-transform-react-pure-class-to-function": "^1.0.1",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.13",
    "bundle-loader": "0.5.4",
    "echarts": "^3.8.5",
    "moment": "^2.18.1",
    "prop-types": "^15.8.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-loadable": "^5.4.0",
    "yarn": "^1.22.19"
  }
}

Here is the code about import DOMProperty and EventPluginRegistry in my project:

import React, { Component } from 'react';
import PropTypes from "prop-types";
import DOMProperty from 'react/lib/DOMProperty';
import EventPluginRegistry from 'react/lib/EventPluginRegistry';
import shallowEqualFuzzy from 'shallow-equal-fuzzy';
import $ from 'jquery';
import 'select2';
import './select2.css;

I search DOMProperty and EventPluginRegistry in google and I think both of them are too
old to run on react 17.So react 17 abandoned them and get the new one.But I didn't get it.What is it?


问:
expected statement in html line
the strBody below will be shown in a html body in an outlook email from excel, but i get an expected statement error and i cant seem to find the fix to the error</p>
```<code>strBody = "<BODY>Cell(s) " & Target.Address(False, False) & _
        " were modified on " & _
        Format$(Now, "mm/dd/yyyy") & " at " & Format$(Now, "hh:mm:ss") & _
        " by " & Environ$("username") &_
        "<br> <br> Select the Invoicing Tab in the <a href="http://www.google.com">Workbook</a></BODY>"
</code>```

Title: expected statement in html line

Body:
the strBody below will be shown in a html body in an outlook email from excel, but i get an expected statement error and i cant seem to find the fix to the error

strBody = "Cell(s) " & Target.Address(False, False) & _
        " were modified on " & _
        Format$(Now, "mm/dd/yyyy") & " at " & Format$(Now, "hh:mm:ss") & _
        " by " & Environ$("username") &_
        "

 Select the Invoicing Tab in the Workbook"


问:
Grey Bar In iPhone Chrome causing problem
Not sure if this is the right platform to ask this question (sorry for that).

I'm working on a web-app using ReactJS (using JS and material UI) that is intend to work on mobile screens. I'm facing a problem while opening it in iPhone's (iPhone 12, iPhone 13) chrome browser.

There's a grey bar at the bottom that is causing the issue. At the bottom of the screen I have "Button" that is being hidden behind grey area (see area pointed out by green arrow in screenshot).

Not just this screen, nearly all of my screens are rendered behind it, as result most of the functionalities are not working properly.

But this problem is not coming if I open it in laptop browser with mobile screen using developer tools.


问:
GA4 configuration tag fields returning undefined values
GA4 Configuration tag: Fields that have been set are returning undefined values when the tag is fired. Below is the dataLayer on the website. Can someone please help?

```<code>dataLayer.push({
  event: "virtualPageview",
  membershipType: "xxxxx",
  pageCategory: "xxxx",
  loginstatus: "logged-in",
  userId: "9330000",
  gtm.uniqueEventId: 14
})
</code>```

[[enter image description here](https://i.stack.imgur.com/Jjfz6.png)](https://i.stack.imgur.com/YRpXo.png)

I tried dataLayer variable in GTM but it is not helping. Can someone please suggest something?

Body:
GA4 Configuration tag: Fields that have been set are returning undefined values when the tag is fired. Below is the dataLayer on the website. Can someone please help?

dataLayer.push({
  event: "virtualPageview",
  membershipType: "xxxxx",
  pageCategory: "xxxx",
  loginstatus: "logged-in",
  userId: "9330000",
  gtm.uniqueEventId: 14
})

[[enter image description here](https://i.stack.imgur.com/Jjfz6.png)](https://i.stack.imgur.com/YRpXo.png)

I tried dataLayer variable in GTM but it is not helping. Can someone please suggest something?


问:
flatlist images flashing when mutating data using SWR
I am fetching an array of posts using SWR in a React native app and then displaying the data using React Native's flatlist.

When a user clicks a like button on an item, a function is called and the data is mutated on the server and the cache is updated to reflect the updated data.

The issue is when the data is mutated and revalidated, it causes the flat list to re-render and the images to flash.

I have tried using useCallback to wrap the function and React.memo to wrap the renderItem, but neither are fixing the issue.

I've also made sure the keyExtractor is using a unique value.

Here is my code:

```<code>export function PostList() {
  const { mutate } = useSWRConfig();

  const { data, error } = useSWR(
    `${process.env.SERVER_API}/posts?userId=1`,
    fetcher
  );

  if (error)
    return (
      <View>
        <Text>failed to load</Text>
      </View>
    );
  if (!data)
    return (
      <View>
        <Text>loading...</Text>
      </View>
    );

  async function likePost(postId) {
    try {
      const response = await fetch(
        `${process.env.SERVER_API}/likePosts`,
        {
          method: "POST",
          body: JSON.stringify({ postId, userId: 1 }),
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      const data = await response.json();
      if (!response.ok) {
        console.log("Something went wrong!");
      }
      console.log("data", data);
    } catch (e) {
      console.log("There was a problem!");
    }
    return data;
  }

  const onClick = useCallback((postId) => {
      const options = {
        rollbackOnError: true,
      };

      mutate(
        `${process.env.SERVER_API}/posts?userId=2`,
        likePost(postId),
        options
      );
  }, []);

  const Item = React.memo(
    ({ id, title, image, categories}) => (
      <>
        <RecipeCard
          id={id}
          title={title}
          image={image}
          onClick={onClick}
        />
      </>
    )
  );

  const renderItem = ({ item, index }: any) => (
    <Item
      index={index}
      id={item.post_id}
      title={item.title}
      image={item.image
      categories={item.categories}
    />
  );

  const keyExtractor = (item) => item.post_id;

  return (
    <>
      <FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={keyExtractor}
      />
    </>
  );
}
</code>```

Body:
I am fetching an array of posts using SWR in a React native app and then displaying the data using React Native's flatlist.

When a user clicks a like button on an item, a function is called and the data is mutated on the server and the cache is updated to reflect the updated data.

The issue is when the data is mutated and revalidated, it causes the flat list to re-render and the images to flash.

I have tried using useCallback to wrap the function and React.memo to wrap the renderItem, but neither are fixing the issue.

I've also made sure the keyExtractor is using a unique value.

Here is my code:

export function PostList() {
  const { mutate } = useSWRConfig();

  const { data, error } = useSWR(
    `${process.env.SERVER_API}/posts?userId=1`,
    fetcher
  );

  if (error)
    return (
      <View>
        <Text>failed to load</Text>
      </View>
    );
  if (!data)
    return (
      <View>
        <Text>loading...</Text>
      </View>
    );

  async function likePost(postId) {
    try {
      const response = await fetch(
        `${process.env.SERVER_API}/likePosts`,
        {
          method: "POST",
          body: JSON.stringify({ postId, userId: 1 }),
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      const data = await response.json();
      if (!response.ok) {
        console.log("Something went wrong!");
      }
      console.log("data", data);
    } catch (e) {
      console.log("There was a problem!");
    }
    return data;
  }

  const onClick = useCallback((postId) => {
      const options = {
        rollbackOnError: true,
      };

      mutate(
        `${process.env.SERVER_API}/posts?userId=2`,
        likePost(postId),
        options
      );
  }, []);

  const Item = React.memo(
    ({ id, title, image, categories}) => (
      <>
        <RecipeCard
          id={id}
          title={title}
          image={image}
          onClick={onClick}
        />
      </>
    )
  );

  const renderItem = ({ item, index }: any) => (
    <Item
      index={index}
      id={item.post_id}
      title={item.title}
      image={item.image
      categories={item.categories}
    />
  );

  const keyExtractor = (item) => item.post_id;

  return (
    <>
      <FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={keyExtractor}
      />
    </>
  );
}


问:
How do I get SSL to work with Google Compute Engine?
I have successfully pushed image to the Google Cloud Artifact Registry and have created a Google Cloud Compute Engine instance with it. I have set it up with http and https and am failing to call it with https. If I switch from https to http  it works as expected but is of course not as secure so I don't want to stick with it. It's set up with a static IP so that I can point my subdomain to it.

I have set up nginx on compute engine . so when I enter the domain name in browser with https it works and displays Welcome to nginx page. I used below docker run command to execute the app

```<code>docker run -d -p 8080:443 -p 8081:80  --name app <artifact registry url>
</code>```

when I hit the URL with port 8080 it gives ERR_CONNECTION_REFUSED. But when I use port 8081 it works
Can anyone help me to solve this issue?

Body:
I have successfully pushed image to the Google Cloud Artifact Registry and have created a Google Cloud Compute Engine instance with it. I have set it up with http and https and am failing to call it with https. If I switch from https to http  it works as expected but is of course not as secure so I don't want to stick with it. It's set up with a static IP so that I can point my subdomain to it.

I have set up nginx on compute engine . so when I enter the domain name in browser with https it works and displays Welcome to nginx page. I used below docker run command to execute the app

docker run -d -p 8080:443 -p 8081:80  --name app <artifact registry url>

when I hit the URL with port 8080 it gives ERR_CONNECTION_REFUSED. But when I use port 8081 it works
Can anyone help me to solve this issue?


问:
Navigating user to his mail box and pre populating search bar using JavaScript (client-side)
We have a requirement in which we want to redirect user from web app to users email client and search for a specific text.

Although this can be achieved if we navigate the user to redirection_url

This might work on gmail, we might have to search for similar URL for different email service provider (outlook, hotmail etc)

The problem is if we use above URL

It might open the default email, where as the user might have registered with us using secondary email.

Search functionality does not work as expected if multiple emails are configured in the device

Is there a way/link to navigate and open a specific email account (instead of default account)
(gmail, outlook, iCloud Mail etc)

Thanks in advance.

Tried navigating to a specific URL but this does not work as expected.

Tried with mailto API of JS but it does not fulfill our requirements : Docs


问:
ViewPager - Disable swiping to previous page
I want to disable swiping into the previous page so its basically one-way ViewPager. How to achieve that?

I can disable it completely like this:

```<code>open var mIsSwipable = true
    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return if (mIsSwipable){
            super.onInterceptTouchEvent(ev)
        } else {
            false
        }
    }

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        return if(mIsSwipable){
            super.onTouchEvent(ev)
        } else {
            false
        }
    }
</code>```

But I don't know how to determine if user is swiping to the previous page or he is in a process of swiping to next page, but he decides to not proceed completely and swipe back to current screen.

What I've tried so far:

```<code>open class IntroViewPager: ViewPager {

    constructor(context: Context): super(context)
    constructor(context: Context, attrs: AttributeSet): super(context, attrs)

    open var mIsSwipable = true
    open var lastPagePos = 0
    open var touchingScreen = false
    open fun setupLastPagePos(lastPage: Int){
        App.log("IntroViewPager: setupLastPagePos:lastPagePos: $lastPage")
        lastPagePos = lastPage
    }

    open fun swipingValidation(swipingTo: Int, offset: Float){
        val swipingToPos = if (swipingTo == lastPagePos) swipingTo+1 else swipingTo
        App.log("IntroViewPager: swipingValidation: swipingTo: $swipingToPos, lastPagePos: $lastPagePos, offset: $offset")
        val canSwipe = if (swipingToPos > lastPagePos) true else if (touchingScreen) offset == 0f else true
        App.log("IntroViewPager: swipingValidation: canSwipe: $canSwipe")
        isEnabled = canSwipe
        mIsSwipable = canSwipe
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        App.log("IntroViewPager: swipingValidation: onInterceptTouchEvent: ${ev?.action?:"null"}")
        return if (mIsSwipable){
            super.onInterceptTouchEvent(ev)
        } else {
            false
        }
    }

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        App.log("IntroViewPager: swipingValidation: onTouchEvent: ${ev?.action?:"null"}")
        return if(mIsSwipable){
            super.onTouchEvent(ev)
        } else {
            false
        }
    }
}
</code>```

ViewPager:

```<code> override fun onPageScrollStateChanged(state: Int) {
                if (!scrollStarted && state == ViewPager.SCROLL_STATE_DRAGGING) {
                    App.log("IntroViewPager: swipingValidation: swipeStarting")
                    viewPager.touchingScreen = true
                    scrollStarted = true
                } else {
                    App.log("IntroViewPager: swipingValidation: swipeEnded")
                    viewPager.touchingScreen = false
                    scrollStarted = false
                }
            }
</code>```

I can setup lastPage which was successfully swiped from onPageSelected. swipingValidation is called from onPageScrolled. But its not working as expected. If you swipe to next page and back, its working, but as soon as I'm at current page and want to swipe back, it will disable swipe (canSwipe == false) and even if I stop scrolling (release my finger from screen) it will be disabled indefinitely and I cant swipe to next page anymore.

For those who want to see adapter I'm using:

```<code>class IntroViewPagerAdapter(private var pageList: List<IntroScreenDefinition>): PagerAdapter() {

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    override fun getCount(): Int {
        return pageList.size
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View)
    }

    override fun instantiateItem(container: ViewGroup, position: Int): View {
        val layout = pageList[position].getIntroScreen(container)
        container.addView(layout)
        return layout
    }
}
</code>```

Body:
I want to disable swiping into the previous page so its basically one-way ViewPager. How to achieve that?

I can disable it completely like this:

open var mIsSwipable = true
    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return if (mIsSwipable){
            super.onInterceptTouchEvent(ev)
        } else {
            false
        }
    }

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        return if(mIsSwipable){
            super.onTouchEvent(ev)
        } else {
            false
        }
    }

But I don't know how to determine if user is swiping to the previous page or he is in a process of swiping to next page, but he decides to not proceed completely and swipe back to current screen.

What I've tried so far:

open class IntroViewPager: ViewPager {

    constructor(context: Context): super(context)
    constructor(context: Context, attrs: AttributeSet): super(context, attrs)

    open var mIsSwipable = true
    open var lastPagePos = 0
    open var touchingScreen = false
    open fun setupLastPagePos(lastPage: Int){
        App.log("IntroViewPager: setupLastPagePos:lastPagePos: $lastPage")
        lastPagePos = lastPage
    }

    open fun swipingValidation(swipingTo: Int, offset: Float){
        val swipingToPos = if (swipingTo == lastPagePos) swipingTo+1 else swipingTo
        App.log("IntroViewPager: swipingValidation: swipingTo: $swipingToPos, lastPagePos: $lastPagePos, offset: $offset")
        val canSwipe = if (swipingToPos > lastPagePos) true else if (touchingScreen) offset == 0f else true
        App.log("IntroViewPager: swipingValidation: canSwipe: $canSwipe")
        isEnabled = canSwipe
        mIsSwipable = canSwipe
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        App.log("IntroViewPager: swipingValidation: onInterceptTouchEvent: ${ev?.action?:"null"}")
        return if (mIsSwipable){
            super.onInterceptTouchEvent(ev)
        } else {
            false
        }
    }

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        App.log("IntroViewPager: swipingValidation: onTouchEvent: ${ev?.action?:"null"}")
        return if(mIsSwipable){
            super.onTouchEvent(ev)
        } else {
            false
        }
    }
}

ViewPager:

 override fun onPageScrollStateChanged(state: Int) {
                if (!scrollStarted && state == ViewPager.SCROLL_STATE_DRAGGING) {
                    App.log("IntroViewPager: swipingValidation: swipeStarting")
                    viewPager.touchingScreen = true
                    scrollStarted = true
                } else {
                    App.log("IntroViewPager: swipingValidation: swipeEnded")
                    viewPager.touchingScreen = false
                    scrollStarted = false
                }
            }

I can setup lastPage which was successfully swiped from onPageSelected. swipingValidation is called from onPageScrolled. But its not working as expected. If you swipe to next page and back, its working, but as soon as I'm at current page and want to swipe back, it will disable swipe (canSwipe == false) and even if I stop scrolling (release my finger from screen) it will be disabled indefinitely and I cant swipe to next page anymore.

For those who want to see adapter I'm using:

class IntroViewPagerAdapter(private var pageList: List<IntroScreenDefinition>): PagerAdapter() {

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    override fun getCount(): Int {
        return pageList.size
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View)
    }

    override fun instantiateItem(container: ViewGroup, position: Int): View {
        val layout = pageList[position].getIntroScreen(container)
        container.addView(layout)
        return layout
    }
}


问:
How can ChangeNotifierProvider be disposed in a healthy way?
Note: Due to the structure we have set up, the ChangeNotifierProvider object needs to be generated more than once.
Object will be generated while generating the page, and disposed when the page is disposed.

```<code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
 runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({super.key});

 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: 'Flutter Demo',
     debugShowCheckedModeBanner: false,
     theme: ThemeData(
       primarySwatch: Colors.blue,
     ),
     home: const MyHomePage(),
   );
 }
}

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

 @override
 State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 @override
 void dispose() {
   // TODO: implement dispose
   super.dispose();

 }
 @override
 Widget build(BuildContext context) {
   return ChangeNotifierProvider(
     create: (context) => ViewModel(),
     child: SonrakiSayfa(),
   );
 }
}

class SonrakiSayfa extends StatelessWidget {
 const SonrakiSayfa({Key? key}) : super(key: key);

 @override
 Widget build(BuildContext context) {
   var provider = Provider.of<ViewModel>(context);
   return Scaffold(
     appBar: AppBar(
       actions: [
         IconButton(
           onPressed: () {
             /*When My Home Page is generated a few times with this button and the floating action button is pressed and returned immediately, I expect apiresponse to stop in the viewmodel.
*/
             Navigator.push(
               context,
               MaterialPageRoute(
                 builder: (context) => MyHomePage(),
               ),
             );
           },
           icon: Icon(Icons.arrow_forward_ios_outlined),
         ),
       ],
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: () {
         provider.fonksiyon();
       },
     ),
     body: Center(
       child: provider.apiResponse.status==Status.completed?Text(provider.apiResponse.data):CircularProgressIndicator(),
     ),
   );
 }
}

class ViewModel with ChangeNotifier {
 ApiResponse<String> _apiResponse = ApiResponse.initial("initial");

 ApiResponse<String> get apiResponse => _apiResponse;

 set apiResponse(ApiResponse<String> value) {
   _apiResponse = value;
   notifyListeners();
 }

 Future<void> fonksiyon() async {
   Future.delayed(
     const Duration(seconds: 5),
     () {
       apiResponse = ApiResponse.completed("Tamamlandı");
     },
   );
 }
}

class ApiResponse<T> {
 late Status status;
 late T data;
 late String message;

 ApiResponse.initial(this.message) : status = Status.initial;

 ApiResponse.loading(this.message) : status = Status.loading;

 ApiResponse.completed(this.data) : status = Status.completed;

 ApiResponse.error(this.message) : status = Status.error;

 @override
 String toString() {
   return "Status : $status \n Message : $message \n Data : $data";
 }
}

enum Status { loading, completed, error, initial }
</code>```

The error I get is below

E/flutter (11012): \[ERROR:flutter/runtime/dart_vm_initializer.cc(41)\] Unhandled Exception: A ViewModel was used after being disposed.
E/flutter (11012): Once you have called dispose() on a ViewModel, it can no longer be used.
E/flutter (11012): #0      ChangeNotifier.debugAssertNotDisposed.\<anonymous closure\> (package:flutter/src/foundation/change_notifier.dart:147:9)
E/flutter (11012): #1      ChangeNotifier.debugAssertNotDisposed (package:flutter/src/foundation/change_notifier.dart:154:6)
E/flutter (11012): #2      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:330:27)
E/flutter (11012): #3      ViewModel.apiResponse= (package:untitled2/main.dart:92:5)
E/flutter (11012): #4      ViewModel.fonksiyon.\<anonymous closure\> (package:untitled2/main.dart:99:9)
E/flutter (11012): #5      new Future.delayed.\<anonymous closure\> (dart:async/future.dart:424:39)
E/flutter (11012): #6      Timer.\_createTimer.\<anonymous closure\> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (11012): #7      \_Timer.\_runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (11012): #8      \_Timer.\_handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (11012): #9      \_RawReceivePortImpl.\_handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter (11012):
```

Body:
Note: Due to the structure we have set up, the ChangeNotifierProvider object needs to be generated more than once.
Object will be generated while generating the page, and disposed when the page is disposed.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
 runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({super.key});

 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: 'Flutter Demo',
     debugShowCheckedModeBanner: false,
     theme: ThemeData(
       primarySwatch: Colors.blue,
     ),
     home: const MyHomePage(),
   );
 }
}

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

 @override
 State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 @override
 void dispose() {
   // TODO: implement dispose
   super.dispose();

 }
 @override
 Widget build(BuildContext context) {
   return ChangeNotifierProvider(
     create: (context) => ViewModel(),
     child: SonrakiSayfa(),
   );
 }
}

class SonrakiSayfa extends StatelessWidget {
 const SonrakiSayfa({Key? key}) : super(key: key);

 @override
 Widget build(BuildContext context) {
   var provider = Provider.of<ViewModel>(context);
   return Scaffold(
     appBar: AppBar(
       actions: [
         IconButton(
           onPressed: () {
             /*When My Home Page is generated a few times with this button and the floating action button is pressed and returned immediately, I expect apiresponse to stop in the viewmodel.
*/
             Navigator.push(
               context,
               MaterialPageRoute(
                 builder: (context) => MyHomePage(),
               ),
             );
           },
           icon: Icon(Icons.arrow_forward_ios_outlined),
         ),
       ],
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: () {
         provider.fonksiyon();
       },
     ),
     body: Center(
       child: provider.apiResponse.status==Status.completed?Text(provider.apiResponse.data):CircularProgressIndicator(),
     ),
   );
 }
}

class ViewModel with ChangeNotifier {
 ApiResponse<String> _apiResponse = ApiResponse.initial("initial");

 ApiResponse<String> get apiResponse => _apiResponse;

 set apiResponse(ApiResponse<String> value) {
   _apiResponse = value;
   notifyListeners();
 }

 Future<void> fonksiyon() async {
   Future.delayed(
     const Duration(seconds: 5),
     () {
       apiResponse = ApiResponse.completed("Tamamlandı");
     },
   );
 }
}

class ApiResponse<T> {
 late Status status;
 late T data;
 late String message;

 ApiResponse.initial(this.message) : status = Status.initial;

 ApiResponse.loading(this.message) : status = Status.loading;

 ApiResponse.completed(this.data) : status = Status.completed;

 ApiResponse.error(this.message) : status = Status.error;

 @override
 String toString() {
   return "Status : $status \n Message : $message \n Data : $data";
 }
}

enum Status { loading, completed, error, initial }

The error I get is below

E/flutter (11012): \[ERROR:flutter/runtime/dart_vm_initializer.cc(41)\] Unhandled Exception: A ViewModel was used after being disposed.
E/flutter (11012): Once you have called dispose() on a ViewModel, it can no longer be used.
E/flutter (11012): #0      ChangeNotifier.debugAssertNotDisposed.\<anonymous closure\> (package:flutter/src/foundation/change_notifier.dart:147:9)
E/flutter (11012): #1      ChangeNotifier.debugAssertNotDisposed (package:flutter/src/foundation/change_notifier.dart:154:6)
E/flutter (11012): #2      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:330:27)
E/flutter (11012): #3      ViewModel.apiResponse= (package:untitled2/main.dart:92:5)
E/flutter (11012): #4      ViewModel.fonksiyon.\<anonymous closure\> (package:untitled2/main.dart:99:9)
E/flutter (11012): #5      new Future.delayed.\<anonymous closure\> (dart:async/future.dart:424:39)
E/flutter (11012): #6      Timer.\_createTimer.\<anonymous closure\> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (11012): #7      \_Timer.\_runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (11012): #8      \_Timer.\_handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (11012): #9      \_RawReceivePortImpl.\_handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter (11012):


问:
Error thrown while decrypting AES encrypted string using NodeJS Crypto
This is my encrypting function:-

```<code>        const key = '3f29658160528447';
        const cipher = Crypto.createCipheriv('aes-128-ecb', key, null);
        const encryptedQueryParams = Buffer.concat([cipher.update(stringToEncrypt), cipher.final()]).toString('base64');
        return encryptedQueryParams;
</code>```

When I try to decrypt this using the following function:-

```<code>    const key = '3f29658160528447';
    const cipher = Crypto.createDecipheriv('aes-128-ecb', key, null);
    const decryptedQueryParams = Buffer.concat([cipher.update(encryptedText, 'base64'), cipher.final()]).toString();
    return decryptedQueryParams;
</code>```

I get an error:-
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

I've gone through quite a few threads, but can't seem to fix this. My Node version is 14.17.1.

Body:
This is my encrypting function:-

        const key = '3f29658160528447';
        const cipher = Crypto.createCipheriv('aes-128-ecb', key, null);
        const encryptedQueryParams = Buffer.concat([cipher.update(stringToEncrypt), cipher.final()]).toString('base64');
        return encryptedQueryParams;

When I try to decrypt this using the following function:-

    const key = '3f29658160528447';
    const cipher = Crypto.createDecipheriv('aes-128-ecb', key, null);
    const decryptedQueryParams = Buffer.concat([cipher.update(encryptedText, 'base64'), cipher.final()]).toString();
    return decryptedQueryParams;

I get an error:-
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

I've gone through quite a few threads, but can't seem to fix this. My Node version is 14.17.1.


问:
Jetpack compose deeplink does not save previous composable's state
I am navigating to a deep-level screen via the deep link in my app. However, as there is no controller navigation through the previous screen to my deep link, the state of the last screen is ignored. I don't want to navigate to the deep link as the screen manually I want to navigate to can be accessed from anywhere and I don't want to put that logic everywhere. Any suggestions?

I am using jetpack compose navigation.


问:
Android Google Billing Client Connection Issues
We're receiving thousands of analytics events due to failed connection to the google billing client and our users are affected. We're retrying the connection two times onBillingServiceDisconnected but still seeing a lot of events. How can we improve the stability, any idea? Or maybe, any idea why the issues are hitting us so hard? Thanks

v4.1.0

Retrying the connection onBillingServiceDisconnected, there were some improvements but still seeing lots of issues.


问:
How to start an immediate transaction of Sqlite in Qt?
Got troubles with using QSqlDatabase::transaction().
I want to start a transaction of Sqlite in Qt and I know this function : bool QSqlDatabase::transaction():

```<code>if(db.transaction())
{
    QSqlQuery query(db);
    // do stuff

   if(!db.commit())
   {
        qDebug() << "Failed to commit";
        db.rollback();
   }
}
</code>```

My problem is that I want to start an immediate transaction as follows:

```<code>> begin immediate;
> ...(operation)
> commit;
</code>```

This function bool QSqlDatabase::transaction() will start a default transaction.
There will be several users using this program to access sqlite database so I need to control their access orders. If one user is writing, others can't read or write. It seems that I need to start an immediate transaction.

So how to start an immediate transaction by QSqlDatabase::transaction() ?
Is there way to specify transaction type in QSqlDatabase::transaction() ?

I use this to start an immediate transaction:

```<code>QsqlQuery query(myDatabase);
query.exec("begin immediate;");
query.exec(...) // read or write database.
query.exec("commit;");
</code>```

It didn't work. There is still wrong data caused by multiple user access in database.

Body:
Got troubles with using QSqlDatabase::transaction().
I want to start a transaction of Sqlite in Qt and I know this function : bool QSqlDatabase::transaction():

if(db.transaction())
{
    QSqlQuery query(db);
    // do stuff

   if(!db.commit())
   {
        qDebug() << "Failed to commit";
        db.rollback();
   }
}

My problem is that I want to start an immediate transaction as follows:

> begin immediate;
> ...(operation)
> commit;

This function bool QSqlDatabase::transaction() will start a default transaction.
There will be several users using this program to access sqlite database so I need to control their access orders. If one user is writing, others can't read or write. It seems that I need to start an immediate transaction.

So how to start an immediate transaction by QSqlDatabase::transaction() ?
Is there way to specify transaction type in QSqlDatabase::transaction() ?

I use this to start an immediate transaction:

QsqlQuery query(myDatabase);
query.exec("begin immediate;");
query.exec(...) // read or write database.
query.exec("commit;");

It didn't work. There is still wrong data caused by multiple user access in database.


问:
How to generate certificates with Java
i am currently working on an API endpoint with Spring Boot for creating Secretkeys / keypairs.

This is my code for generating a keypair:

```<code>public static KeyPair createKeyPair(final String algorithm, final String cryptoProvider, final int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
    checkCryptoProvider(cryptoProvider);
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm, cryptoProvider);
    keyPairGenerator.initialize(keySize);
    keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}
</code>```

Now if i want to save the private key into a keystore, I need a certificate for that, but i don't know how to get that.
I saw an example with BouncyCastle which might work, but i wonder if there is a possibility to do so with Sun provider? In the documentation I only found methods for reading and validating some existing certificates from the file system etc.

OwnerDisplayName: Sinnedkid

Title: How to generate certificates with Java

Body:
i am currently working on an API endpoint with Spring Boot for creating Secretkeys / keypairs.

This is my code for generating a keypair:

public static KeyPair createKeyPair(final String algorithm, final String cryptoProvider, final int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
    checkCryptoProvider(cryptoProvider);
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm, cryptoProvider);
    keyPairGenerator.initialize(keySize);
    keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}

Now if i want to save the private key into a keystore, I need a certificate for that, but i don't know how to get that.
I saw an example with BouncyCastle which might work, but i wonder if there is a possibility to do so with Sun provider? In the documentation I only found methods for reading and validating some existing certificates from the file system etc.


问:
Installation of Pycairo for Manim on Mac OSX
I have installed all dependencies expect the final library, that is, manim. The only solutions offered so far are for linux and windows users, not sure for mac. When I try to install it I get this:

```<code>Haydens-Air:~ hmyers$ pip3 install manim
Collecting manim
  Using cached manim-0.17.0-py3-none-any.whl (523 kB)
Collecting Pillow<10.0,>=9.1
  Using cached Pillow-9.3.0-cp311-cp311-macosx_10_10_x86_64.whl (3.3 MB)
Collecting Pygments<3.0.0,>=2.10.0
  Using cached Pygments-2.13.0-py3-none-any.whl (1.1 MB)
Collecting click<=9.0,>=7.2
  Using cached click-8.1.3-py3-none-any.whl (96 kB)
Collecting click-default-group<2.0.0,>=1.2.2
  Using cached click-default-group-1.2.2.tar.gz (3.3 kB)
  Preparing metadata (setup.py) ... done
Collecting cloup<0.14.0,>=0.13.0
  Using cached cloup-0.13.1-py2.py3-none-any.whl (51 kB)
Collecting colour<0.2.0,>=0.1.5
  Using cached colour-0.1.5-py2.py3-none-any.whl (23 kB)
Collecting decorator<6.0.0,>=5.0.7
  Using cached decorator-5.1.1-py3-none-any.whl (9.1 kB)
Collecting isosurfaces==0.1.0
  Using cached isosurfaces-0.1.0-py3-none-any.whl (10 kB)
Collecting manimpango<0.5.0,>=0.4.0.post0
  Using cached ManimPango-0.4.3-cp311-cp311-macosx_10_9_x86_64.whl (4.1 MB)
Collecting mapbox-earcut<2.0.0,>=1.0.0
  Using cached mapbox_earcut-1.0.1-cp311-cp311-macosx_10_9_x86_64.whl (75 kB)
Collecting moderngl<6.0.0,>=5.6.3
  Using cached moderngl-5.7.3-cp311-cp311-macosx_10_9_x86_64.whl (121 kB)
Collecting moderngl-window<3.0.0,>=2.3.0
  Using cached moderngl_window-2.4.2-py3-none-any.whl (368 kB)
Collecting networkx<3.0,>=2.5
  Using cached networkx-2.8.8-py3-none-any.whl (2.0 MB)
Collecting numpy<2.0,>=1.19
  Using cached numpy-1.23.5-cp311-cp311-macosx_10_9_x86_64.whl (18.1 MB)
Collecting pycairo<2.0,>=1.21
  Using cached pycairo-1.23.0.tar.gz (344 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... done
Collecting pydub<0.26.0,>=0.25.1
  Using cached pydub-0.25.1-py2.py3-none-any.whl (32 kB)
Collecting requests<3.0.0,>=2.26.0
  Using cached requests-2.28.1-py3-none-any.whl (62 kB)
Collecting rich!=12.0.0,>=6.0
  Using cached rich-12.6.0-py3-none-any.whl (237 kB)
Collecting scipy<2.0.0,>=1.7.3
  Using cached scipy-1.9.3-cp311-cp311-macosx_10_9_x86_64.whl (34.2 MB)
Collecting screeninfo<0.9,>=0.8
  Using cached screeninfo-0.8.1-py3-none-any.whl (12 kB)
Collecting skia-pathops<0.8.0,>=0.7.0
  Using cached skia_pathops-0.7.4-cp311-cp311-macosx_10_9_x86_64.whl (1.6 MB)
Collecting srt<4.0.0,>=3.5.0
  Using cached srt-3.5.2.tar.gz (24 kB)
  Preparing metadata (setup.py) ... done
Collecting svgelements<2.0.0,>=1.7.2
  Using cached svgelements-1.8.4-py2.py3-none-any.whl (125 kB)
Collecting tqdm<5.0.0,>=4.62.3
  Using cached tqdm-4.64.1-py2.py3-none-any.whl (78 kB)
Collecting watchdog<3.0.0,>=2.1.6
  Using cached watchdog-2.2.0-cp311-cp311-macosx_10_9_x86_64.whl (87 kB)
Collecting glcontext<3,>=2.3.6
  Using cached glcontext-2.3.7-cp311-cp311-macosx_10_9_x86_64.whl (9.2 kB)
Collecting pyglet>=2.0dev23
  Using cached pyglet-2.0.1-py3-none-any.whl (964 kB)
Collecting pyrr<1,>=0.10.3
  Using cached pyrr-0.10.3-py3-none-any.whl (46 kB)
Collecting charset-normalizer<3,>=2
  Using cached charset_normalizer-2.1.1-py3-none-any.whl (39 kB)
Collecting idna<4,>=2.5
  Using cached idna-3.4-py3-none-any.whl (61 kB)
Collecting urllib3<1.27,>=1.21.1
  Using cached urllib3-1.26.13-py2.py3-none-any.whl (140 kB)
Collecting certifi>=2017.4.17
  Using cached certifi-2022.12.7-py3-none-any.whl (155 kB)
Collecting commonmark<0.10.0,>=0.9.0
  Using cached commonmark-0.9.1-py2.py3-none-any.whl (51 kB)
Collecting Cython
  Using cached Cython-0.29.32-py2.py3-none-any.whl (986 kB)
Collecting pyobjc-framework-Cocoa
  Using cached pyobjc_framework_Cocoa-9.0-cp311-cp311-macosx_10_9_universal2.whl (388 kB)
Collecting multipledispatch
  Using cached multipledispatch-0.6.0-py3-none-any.whl (11 kB)
Collecting pyobjc-core>=9.0
  Using cached pyobjc_core-9.0-cp311-cp311-macosx_10_9_universal2.whl (725 kB)
Collecting six
  Using cached six-1.16.0-py2.py3-none-any.whl (11 kB)
Building wheels for collected packages: click-default-group, pycairo, srt
  Building wheel for click-default-group (setup.py) ... done
  Created wheel for click-default-group: filename=click_default_group-1.2.2-py3-none-any.whl size=3383 sha256=ca6f0efc6ff844f0b37b529152ef0236e37a61f384ef9f0c3e21ba12a8eb2ebb
  Stored in directory: /Users/hmyers/Library/Caches/pip/wheels/25/86/2b/70a16a4dfc8c3ddfbee8b54dd199345d04f91a25eb95aa6a8e
  Building wheel for pycairo (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for pycairo (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [12 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build/lib.macosx-10.9-universal2-cpython-311
      creating build/lib.macosx-10.9-universal2-cpython-311/cairo
      copying cairo/__init__.py -> build/lib.macosx-10.9-universal2-cpython-311/cairo
      copying cairo/__init__.pyi -> build/lib.macosx-10.9-universal2-cpython-311/cairo
      copying cairo/py.typed -> build/lib.macosx-10.9-universal2-cpython-311/cairo
      running build_ext
      Package 'gobject-2.0' requires 'libffi >= 3.0.0' but version of libffi is 2.1
      Command '['pkg-config', '--print-errors', '--exists', 'cairo >= 1.15.10']' returned non-zero exit status 1.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for pycairo
  Building wheel for srt (setup.py) ... done
  Created wheel for srt: filename=srt-3.5.2-py3-none-any.whl size=22467 sha256=a981a4c7f278c337814fb2c6bd04fc9a0f77d757969d1973932db664f21569f6
  Stored in directory: /Users/hmyers/Library/Caches/pip/wheels/09/02/ac/16294d67d2b6ae081c2e0777a308baff081c59a8f35c34451c
Successfully built click-default-group srt
Failed to build pycairo
ERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based projects

[notice] A new release of pip available: 22.3 -> 22.3.1
[notice] To update, run: pip3 install --upgrade pip
</code>```

Any way to fix this and get pycairo to install? I'm  not sure how to install pycairo on its own, and am  wondering if there is a simpler solution to this.

Body:
I have installed all dependencies expect the final library, that is, manim. The only solutions offered so far are for linux and windows users, not sure for mac. When I try to install it I get this:

Haydens-Air:~ hmyers$ pip3 install manim
Collecting manim
  Using cached manim-0.17.0-py3-none-any.whl (523 kB)
Collecting Pillow<10.0,>=9.1
  Using cached Pillow-9.3.0-cp311-cp311-macosx_10_10_x86_64.whl (3.3 MB)
Collecting Pygments<3.0.0,>=2.10.0
  Using cached Pygments-2.13.0-py3-none-any.whl (1.1 MB)
Collecting click<=9.0,>=7.2
  Using cached click-8.1.3-py3-none-any.whl (96 kB)
Collecting click-default-group<2.0.0,>=1.2.2
  Using cached click-default-group-1.2.2.tar.gz (3.3 kB)
  Preparing metadata (setup.py) ... done
Collecting cloup<0.14.0,>=0.13.0
  Using cached cloup-0.13.1-py2.py3-none-any.whl (51 kB)
Collecting colour<0.2.0,>=0.1.5
  Using cached colour-0.1.5-py2.py3-none-any.whl (23 kB)
Collecting decorator<6.0.0,>=5.0.7
  Using cached decorator-5.1.1-py3-none-any.whl (9.1 kB)
Collecting isosurfaces==0.1.0
  Using cached isosurfaces-0.1.0-py3-none-any.whl (10 kB)
Collecting manimpango<0.5.0,>=0.4.0.post0
  Using cached ManimPango-0.4.3-cp311-cp311-macosx_10_9_x86_64.whl (4.1 MB)
Collecting mapbox-earcut<2.0.0,>=1.0.0
  Using cached mapbox_earcut-1.0.1-cp311-cp311-macosx_10_9_x86_64.whl (75 kB)
Collecting moderngl<6.0.0,>=5.6.3
  Using cached moderngl-5.7.3-cp311-cp311-macosx_10_9_x86_64.whl (121 kB)
Collecting moderngl-window<3.0.0,>=2.3.0
  Using cached moderngl_window-2.4.2-py3-none-any.whl (368 kB)
Collecting networkx<3.0,>=2.5
  Using cached networkx-2.8.8-py3-none-any.whl (2.0 MB)
Collecting numpy<2.0,>=1.19
  Using cached numpy-1.23.5-cp311-cp311-macosx_10_9_x86_64.whl (18.1 MB)
Collecting pycairo<2.0,>=1.21
  Using cached pycairo-1.23.0.tar.gz (344 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... done
Collecting pydub<0.26.0,>=0.25.1
  Using cached pydub-0.25.1-py2.py3-none-any.whl (32 kB)
Collecting requests<3.0.0,>=2.26.0
  Using cached requests-2.28.1-py3-none-any.whl (62 kB)
Collecting rich!=12.0.0,>=6.0
  Using cached rich-12.6.0-py3-none-any.whl (237 kB)
Collecting scipy<2.0.0,>=1.7.3
  Using cached scipy-1.9.3-cp311-cp311-macosx_10_9_x86_64.whl (34.2 MB)
Collecting screeninfo<0.9,>=0.8
  Using cached screeninfo-0.8.1-py3-none-any.whl (12 kB)
Collecting skia-pathops<0.8.0,>=0.7.0
  Using cached skia_pathops-0.7.4-cp311-cp311-macosx_10_9_x86_64.whl (1.6 MB)
Collecting srt<4.0.0,>=3.5.0
  Using cached srt-3.5.2.tar.gz (24 kB)
  Preparing metadata (setup.py) ... done
Collecting svgelements<2.0.0,>=1.7.2
  Using cached svgelements-1.8.4-py2.py3-none-any.whl (125 kB)
Collecting tqdm<5.0.0,>=4.62.3
  Using cached tqdm-4.64.1-py2.py3-none-any.whl (78 kB)
Collecting watchdog<3.0.0,>=2.1.6
  Using cached watchdog-2.2.0-cp311-cp311-macosx_10_9_x86_64.whl (87 kB)
Collecting glcontext<3,>=2.3.6
  Using cached glcontext-2.3.7-cp311-cp311-macosx_10_9_x86_64.whl (9.2 kB)
Collecting pyglet>=2.0dev23
  Using cached pyglet-2.0.1-py3-none-any.whl (964 kB)
Collecting pyrr<1,>=0.10.3
  Using cached pyrr-0.10.3-py3-none-any.whl (46 kB)
Collecting charset-normalizer<3,>=2
  Using cached charset_normalizer-2.1.1-py3-none-any.whl (39 kB)
Collecting idna<4,>=2.5
  Using cached idna-3.4-py3-none-any.whl (61 kB)
Collecting urllib3<1.27,>=1.21.1
  Using cached urllib3-1.26.13-py2.py3-none-any.whl (140 kB)
Collecting certifi>=2017.4.17
  Using cached certifi-2022.12.7-py3-none-any.whl (155 kB)
Collecting commonmark<0.10.0,>=0.9.0
  Using cached commonmark-0.9.1-py2.py3-none-any.whl (51 kB)
Collecting Cython
  Using cached Cython-0.29.32-py2.py3-none-any.whl (986 kB)
Collecting pyobjc-framework-Cocoa
  Using cached pyobjc_framework_Cocoa-9.0-cp311-cp311-macosx_10_9_universal2.whl (388 kB)
Collecting multipledispatch
  Using cached multipledispatch-0.6.0-py3-none-any.whl (11 kB)
Collecting pyobjc-core>=9.0
  Using cached pyobjc_core-9.0-cp311-cp311-macosx_10_9_universal2.whl (725 kB)
Collecting six
  Using cached six-1.16.0-py2.py3-none-any.whl (11 kB)
Building wheels for collected packages: click-default-group, pycairo, srt
  Building wheel for click-default-group (setup.py) ... done
  Created wheel for click-default-group: filename=click_default_group-1.2.2-py3-none-any.whl size=3383 sha256=ca6f0efc6ff844f0b37b529152ef0236e37a61f384ef9f0c3e21ba12a8eb2ebb
  Stored in directory: /Users/hmyers/Library/Caches/pip/wheels/25/86/2b/70a16a4dfc8c3ddfbee8b54dd199345d04f91a25eb95aa6a8e
  Building wheel for pycairo (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for pycairo (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [12 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build/lib.macosx-10.9-universal2-cpython-311
      creating build/lib.macosx-10.9-universal2-cpython-311/cairo
      copying cairo/__init__.py -> build/lib.macosx-10.9-universal2-cpython-311/cairo
      copying cairo/__init__.pyi -> build/lib.macosx-10.9-universal2-cpython-311/cairo
      copying cairo/py.typed -> build/lib.macosx-10.9-universal2-cpython-311/cairo
      running build_ext
      Package 'gobject-2.0' requires 'libffi >= 3.0.0' but version of libffi is 2.1
      Command '['pkg-config', '--print-errors', '--exists', 'cairo >= 1.15.10']' returned non-zero exit status 1.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for pycairo
  Building wheel for srt (setup.py) ... done
  Created wheel for srt: filename=srt-3.5.2-py3-none-any.whl size=22467 sha256=a981a4c7f278c337814fb2c6bd04fc9a0f77d757969d1973932db664f21569f6
  Stored in directory: /Users/hmyers/Library/Caches/pip/wheels/09/02/ac/16294d67d2b6ae081c2e0777a308baff081c59a8f35c34451c
Successfully built click-default-group srt
Failed to build pycairo
ERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based projects

[notice] A new release of pip available: 22.3 -> 22.3.1
[notice] To update, run: pip3 install --upgrade pip

Any way to fix this and get pycairo to install? I'm  not sure how to install pycairo on its own, and am  wondering if there is a simpler solution to this.


问:
Thalhammer JWT CPP latest update breaks Docker Compose
The JWT CPP Above has been updated to v0.7.0-rc.0 and with the update they changed the use of get_payload_claims() to get_payload_json(). I wish it was as simple as to just use the later in the code but it isn't. So I am trying to clone it through a docker file but I would like to use the previous version (v0.6.0) as the program worked with that version.

This was the original line of code in the docker file:

```<code>RUN git clone https://github.com/Thalhammer/jwt-cpp.git
</code>```

But that causes it to use the latest version of the repo. I did some googling and found the following methods of doing it:

```<code>RUN git clone --depth 1 --branch v0.6.0 https://github.com/Thalhammer/jwt-cpp.git
RUN git checkout v0.6.0
</code>```

I also tried clearing the cache and running docker fresh with this:

```<code>docker system prune -a
</code>```

However, none of these have worked. When I try to compose in Docker I still get the get_payload_claims() doesn't exist meaning it's still the newer version. How do I use the previous version of the repo?

Body:
The JWT CPP Above has been updated to v0.7.0-rc.0 and with the update they changed the use of get_payload_claims() to get_payload_json(). I wish it was as simple as to just use the later in the code but it isn't. So I am trying to clone it through a docker file but I would like to use the previous version (v0.6.0) as the program worked with that version.

This was the original line of code in the docker file:

RUN git clone https://github.com/Thalhammer/jwt-cpp.git

But that causes it to use the latest version of the repo. I did some googling and found the following methods of doing it:

RUN git clone --depth 1 --branch v0.6.0 https://github.com/Thalhammer/jwt-cpp.git
RUN git checkout v0.6.0

I also tried clearing the cache and running docker fresh with this:

docker system prune -a

However, none of these have worked. When I try to compose in Docker I still get the get_payload_claims() doesn't exist meaning it's still the newer version. How do I use the previous version of the repo?


问:
How to update excel cell by adding data to new line of the existing cell data using apache poi?
I need to update existing cell value by adding new lines to it during testing through selenium. I am not able to figure out code to update exising data using POI. When I tried to add using New Line Character, it is overwriting existing data. Please provide solution to add value to existing cell data on new line.
Below is the code what I have for new Line comment</p>
```<code>try (OutputStream fileOut = new FileOutputStream("MyFile.xls")) {
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("Sheet");
    Row row     = sheet.createRow(1);
    Cell cell   = row.createCell(1);
    cell.setCellValue("This is first line and \n this is second line");
    CellStyle cs = wb.createCellStyle();
    cs.setWrapText(true);
    cell.setCellStyle(cs);
    row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
    sheet.autoSizeColumn(2);
    wb.write(fileOut);
    Cell cell2   = row.getCell(1);
    cell2.setCellValue(" \n this is third line");
    CellStyle cs2 = wb.createCellStyle();
    cs2.setWrapText(true);
    cell2.setCellStyle(cs2);
    row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
    sheet.autoSizeColumn(2);
    wb.write(fileOut);

}catch(Exception e) {
    System.out.println(e.getMessage());
}
</code>```

Body:
I need to update existing cell value by adding new lines to it during testing through selenium. I am not able to figure out code to update exising data using POI. When I tried to add using New Line Character, it is overwriting existing data. Please provide solution to add value to existing cell data on new line.
Below is the code what I have for new Line comment

try (OutputStream fileOut = new FileOutputStream("MyFile.xls")) {
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("Sheet");
    Row row     = sheet.createRow(1);
    Cell cell   = row.createCell(1);
    cell.setCellValue("This is first line and \n this is second line");
    CellStyle cs = wb.createCellStyle();
    cs.setWrapText(true);
    cell.setCellStyle(cs);
    row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
    sheet.autoSizeColumn(2);
    wb.write(fileOut);
    Cell cell2   = row.getCell(1);
    cell2.setCellValue(" \n this is third line");
    CellStyle cs2 = wb.createCellStyle();
    cs2.setWrapText(true);
    cell2.setCellStyle(cs2);
    row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
    sheet.autoSizeColumn(2);
    wb.write(fileOut);

}catch(Exception e) {
    System.out.println(e.getMessage());
}


问:
SequenceClassifierOutput has generator as loss instead of a tensor
I'm doing Distillation from a Roberta with an Adapter, I'm following this tutorial

and in the function distill_roberta_weights() I just change teacher_model.config.to_dict()
to student.load_state_dict(teacher.state_dict(), strict=False), so the student model has the adapter too.

But when I am training the distillation using the

```<code>DistillationTrainer
</code>```

from here
I get the following error

Do you have any idea of what is the problem?
The student_output has a loss generator instead the tensor, the part of the cross entropy does not have any problem as it uses the logits from the outputs.

EDIT:

I am adding more information

def distill_weights(teacher, student):
   """
   Recursively copies the weights of the (teacher) to the (student).
   This function is meant to be first called on a RobertaFor... model, but is then called on every children of that model recursively.
   The only part that's not fully copied is the encoder, of which only half is copied.
   """
   # If the part is an entire RoBERTa model or a RobertaFor..., unpack and iterate
   if isinstance(teacher, RobertaModel) or type(teacher).__name__.startswith('RobertaFor'):
       for teacher_part, student_part in zip(teacher.children(), student.children()):
           distill_weights(teacher_part, student_part)
   # Else if the part is an encoder, copy one out of every layer
   elif isinstance(teacher, RobertaEncoder):
           teacher_encoding_layers = [layer for layer in next(teacher.children())]
           student_encoding_layers = [layer for layer in next(student.children())]
           for i in range(len(student_encoding_layers)):
               student_encoding_layers[i].load_state_dict(teacher_encoding_layers[2*i].state_dict())
   # Else the part is a head or something else, copy the state_dict
   else:
       student.load_state_dict(teacher.state_dict(), strict=False)

def distill_roberta_based(teacher_model):
   """
   Distilates a RoBERTa (teacher_model) like would DistilBERT for a BERT model.
   The student model has the same configuration, except for the number of hidden layers, which is // by 2.
   The student layers are initilized by copying one out of two layers of the teacher, starting with layer 0.
   The head of the teacher is also copied.
   """
   # Set student configuration
   configuration = teacher_model.config.to_dict()
   configuration['num_hidden_layers'] //= 2
   configuration = RobertaConfig.from_dict(configuration)

   # create student model
   student_model = type(teacher_model)(configuration)
   distill_weights(teacher=teacher_model, student=student_model)

   return student_model
#function for train the Distillated model
class DistillationTrainer(Trainer):
   def __init__(self, *args, teacher_model=None, **kwargs):
       super().__init__(*args, **kwargs)

       self.teacher = teacher_model
       # place teacher on same device as student
       self._move_model_to_device(self.teacher,self.model.device)
       self.teacher.eval()

   def compute_loss(self, model, inputs, return_outputs = False)  :
       """
       The distillation loss for distilating a BERT-like model.
       The loss takes the (teacher_logits), (student_logits) and (labels) for various losses.
       The (temperature) can be given, otherwise it's set to 1 by default.
       """
       outputs_student =  model(**inputs)
       print(outputs_student)
       student_loss    = outputs_student.loss

       # compute teacher output
       with torch.no_grad():
         outputs_teacher = self.teacher(**inputs)

       # assert size
       assert outputs_student.logits.size() == outputs_teacher.logits.size()

       # Classification loss (problem-specific loss)
       loss_function = CrossEntropyLoss()

       # Temperature and sotfmax
       student_logits = F.softmax (outputs_student.logits / self.args.temperature, dim=-1)
       teacher_logits = F.softmax (outputs_teacher.logits / self.args.temperature, dim=-1)
       loss_logits = loss_function(student_logits, teacher_logits)

       # Return weighted student loss
       loss = self.args.alpha * student_loss + (1. - self.args.alpha) * loss_logits
       return (loss, outputs_student) if return_outputs else loss

#create the student
student_model_adapter = distill_roberta_based(teacher_model)
#activate adapter
student_model_adapter.set_active_adapters('parallel')
student_model_adapter.train_adapter('parallel')

trainer = DistillationTrainer(
   student_model_adapter,
   training_args,
   teacher_model=teacher_model,
   train_dataset=tokenized_datasets["train"],
   eval_dataset=tokenized_datasets["validation"],
   data_collator=data_collator,
   tokenizer=tokenizer,
   compute_metrics=compute_metrics,
)
trainer.args._n_gpu = 4
```
<p>So, the desired output of <code>outputs_student</code> should be like</p>
```SequenceClassifierOutput(loss=tensor([0.6899, 0.6902, 0.6926, 0.6913, 0.6906, 0.6904, 0.6922, 0.6917],
       device='cuda:0', grad_fn=<GatherBackward>), logits=tensor([[-1.2512e-03, -9.7885e-03],
        [ 6.2714e-03, -5.7755e-03],.....])
```
<p>But instead the output is</p>
```SequenceClassifierOutput(loss=<generator object gather.<locals>.gather_map.<locals>.<genexpr> at 0x7f5bb4fbe9d0>, logits=tensor([[-0.0150,  0.0075],
        [-0.0122,  0.0181],...
```

Body:
I'm doing Distillation from a Roberta with an Adapter, I'm following this tutorial

and in the function distill_roberta_weights() I just change teacher_model.config.to_dict()
to student.load_state_dict(teacher.state_dict(), strict=False), so the student model has the adapter too.

But when I am training the distillation using the

DistillationTrainer

from here
I get the following error

Do you have any idea of what is the problem?
The student_output has a loss generator instead the tensor, the part of the cross entropy does not have any problem as it uses the logits from the outputs.

EDIT:

I am adding more information

def distill_weights(teacher, student):
   """
   Recursively copies the weights of the (teacher) to the (student).
   This function is meant to be first called on a RobertaFor... model, but is then called on every children of that model recursively.
   The only part that's not fully copied is the encoder, of which only half is copied.
   """
   # If the part is an entire RoBERTa model or a RobertaFor..., unpack and iterate
   if isinstance(teacher, RobertaModel) or type(teacher).__name__.startswith('RobertaFor'):
       for teacher_part, student_part in zip(teacher.children(), student.children()):
           distill_weights(teacher_part, student_part)
   # Else if the part is an encoder, copy one out of every layer
   elif isinstance(teacher, RobertaEncoder):
           teacher_encoding_layers = [layer for layer in next(teacher.children())]
           student_encoding_layers = [layer for layer in next(student.children())]
           for i in range(len(student_encoding_layers)):
               student_encoding_layers[i].load_state_dict(teacher_encoding_layers[2*i].state_dict())
   # Else the part is a head or something else, copy the state_dict
   else:
       student.load_state_dict(teacher.state_dict(), strict=False)

def distill_roberta_based(teacher_model):
   """
   Distilates a RoBERTa (teacher_model) like would DistilBERT for a BERT model.
   The student model has the same configuration, except for the number of hidden layers, which is // by 2.
   The student layers are initilized by copying one out of two layers of the teacher, starting with layer 0.
   The head of the teacher is also copied.
   """
   # Set student configuration
   configuration = teacher_model.config.to_dict()
   configuration['num_hidden_layers'] //= 2
   configuration = RobertaConfig.from_dict(configuration)

   # create student model
   student_model = type(teacher_model)(configuration)
   distill_weights(teacher=teacher_model, student=student_model)

   return student_model
#function for train the Distillated model
class DistillationTrainer(Trainer):
   def __init__(self, *args, teacher_model=None, **kwargs):
       super().__init__(*args, **kwargs)

       self.teacher = teacher_model
       # place teacher on same device as student
       self._move_model_to_device(self.teacher,self.model.device)
       self.teacher.eval()

   def compute_loss(self, model, inputs, return_outputs = False)  :
       """
       The distillation loss for distilating a BERT-like model.
       The loss takes the (teacher_logits), (student_logits) and (labels) for various losses.
       The (temperature) can be given, otherwise it's set to 1 by default.
       """
       outputs_student =  model(**inputs)
       print(outputs_student)
       student_loss    = outputs_student.loss

       # compute teacher output
       with torch.no_grad():
         outputs_teacher = self.teacher(**inputs)

       # assert size
       assert outputs_student.logits.size() == outputs_teacher.logits.size()

       # Classification loss (problem-specific loss)
       loss_function = CrossEntropyLoss()

       # Temperature and sotfmax
       student_logits = F.softmax (outputs_student.logits / self.args.temperature, dim=-1)
       teacher_logits = F.softmax (outputs_teacher.logits / self.args.temperature, dim=-1)
       loss_logits = loss_function(student_logits, teacher_logits)

       # Return weighted student loss
       loss = self.args.alpha * student_loss + (1. - self.args.alpha) * loss_logits
       return (loss, outputs_student) if return_outputs else loss

#create the student
student_model_adapter = distill_roberta_based(teacher_model)
#activate adapter
student_model_adapter.set_active_adapters('parallel')
student_model_adapter.train_adapter('parallel')

trainer = DistillationTrainer(
   student_model_adapter,
   training_args,
   teacher_model=teacher_model,
   train_dataset=tokenized_datasets["train"],
   eval_dataset=tokenized_datasets["validation"],
   data_collator=data_collator,
   tokenizer=tokenizer,
   compute_metrics=compute_metrics,
)
trainer.args._n_gpu = 4

So, the desired output of outputs_student should be like

SequenceClassifierOutput(loss=tensor([0.6899, 0.6902, 0.6926, 0.6913, 0.6906, 0.6904, 0.6922, 0.6917],
       device='cuda:0', grad_fn=<GatherBackward>), logits=tensor([[-1.2512e-03, -9.7885e-03],
        [ 6.2714e-03, -5.7755e-03],.....])

But instead the output is

SequenceClassifierOutput(loss=<generator object gather.<locals>.gather_map.<locals>.<genexpr> at 0x7f5bb4fbe9d0>, logits=tensor([[-0.0150,  0.0075],
        [-0.0122,  0.0181],...