问:
Why does Firebase Admin SDK have a starting app length of 1?
I have a NextJS app that uses getStaticProps to pre-fetch data from firebase storage and firestore. Since getStaticProps never runs on the client, I decided to use Firebase Admin SDK to fetch my data. I initialize the app by using a seperate js file that initializes the app if the length of the initialized apps is 0, like so:

```<code>import * as admin from "firebase-admin"

if (!admin.app.length) {
    try {
        admin.initializeApp({
            credential: admin.credential.cert({
                clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
                privateKey: process.env.FIREBASE_PRIVATE_KEY,
                projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
            }),
            storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
        })
    } catch (e) {
        console.error("Unable to initialize app!");
        console.log(e)
    }
}

export default admin;
</code>```

For some reason, when importing this module and using the admin variable, the app crashes, telling me that I haven't Initialized an app. Doing a console log before the if check shows the the length of admin.app is 1, even though it says that I haven't initialized it.

Why is this the case? I can fix the bug by just using admin.app.length <= 1 as the if check, but I am confused on why an app is initialized before I called initializeApp.

Body:
I have a NextJS app that uses getStaticProps to pre-fetch data from firebase storage and firestore. Since getStaticProps never runs on the client, I decided to use Firebase Admin SDK to fetch my data. I initialize the app by using a seperate js file that initializes the app if the length of the initialized apps is 0, like so:

import * as admin from "firebase-admin"

if (!admin.app.length) {
    try {
        admin.initializeApp({
            credential: admin.credential.cert({
                clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
                privateKey: process.env.FIREBASE_PRIVATE_KEY,
                projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
            }),
            storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
        })
    } catch (e) {
        console.error("Unable to initialize app!");
        console.log(e)
    }
}

export default admin;

For some reason, when importing this module and using the admin variable, the app crashes, telling me that I haven't Initialized an app. Doing a console log before the if check shows the the length of admin.app is 1, even though it says that I haven't initialized it.

Why is this the case? I can fix the bug by just using admin.app.length <= 1 as the if check, but I am confused on why an app is initialized before I called initializeApp.


来源: stackexchange

问:
Hoisted JavaScript variables undefined or not?
I am trying to understand in a more deep way hoisting, creation phase and execution phase in JavaScript. To the best of my knowledge variables declared with var keyword are hoisted to the top of their scope. But I am running into this problem.

```<code>console.log(name); // Output -> 'any name'
console.log(age); // Output -> undefined

var name = 'any name';
var age = 30
</code>```

I know at the moment when console.log statements are executed bot variables should be undefined because they are declared but values have not been assigned to them (they got undefined in the creation phase). However browsers keep giving me one of the values as undefined (as I expect it to be), but with name variable it is reading the string. Any ideas as to why is this happening?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to understand in a more deep way hoisting, creation phase and execution phase in JavaScript. To the best of my knowledge variables declared with var keyword are hoisted to the top of their scope. But I am running into this problem.

console.log(name); // Output -> 'any name'
console.log(age); // Output -> undefined

var name = 'any name';
var age = 30

I know at the moment when console.log statements are executed bot variables should be undefined because they are declared but values have not been assigned to them (they got undefined in the creation phase). However browsers keep giving me one of the values as undefined (as I expect it to be), but with name variable it is reading the string. Any ideas as to why is this happening?


问:
interrupts not working in KVM x86 16-bit guest
I'm writing a Linux KVM hypervisor for x86 16-bit guests running in real mode. When doing interrupt calls (int ... instruction), I've encountered the KVM_INTERNAL_ERROR_SIMUL_EX error on Linux kernel 3.13.0. The same code is running fine on Linux kernel 3.16.0. Am I missing something? Is there a workaround I can add to my code to make it work with Linux kernel 3.13.0 (and possibly earlier)?

The test guest calls int 0x18 ... int 0x4f, all of which is handled in the hypervisor (C code after KVM_RUN has returned). When it's working correctly, all of the interrupt calls work. On Linux kernel 3.13.0, int 0x21 starts failing (and then int 0x22, int 0x23 and int 0x24 would also fail).

I was trying to write the shortest example C code to demonstrate the problem, here it is:

```<code>/* Based on: https://gist.github.com/zserge/d68683f17c68709818f8baab0ded2d15
 * Based on: https://gist.githubusercontent.com/zserge/d68683f17c68709818f8baab0ded2d15/raw/b79033254b092ec9121bb891938b27dd128030d7/kvm-host-simple.c
 *
 * Compile: gcc -ansi -pedantic -s -O2 -W -Wall -o kvm16 kvm16.c && ./kvm16
 *
 * Expected correct output (e.g. on Linux 3.16.0 compiled for i386 (i686)):
 *
 *   ...
 *   info: int 0x4f iret to: ...
 *   info: success, exiting
 *
 * Failure output (e.g. on Linux 3.13.0 compiled for amd64 (x86_64)):
 *
 *   info: int 0x20 iret to: cs=0x0070 ip=0x0013
 *   fatal: KVM internal error suberror=2
 *
 * // Encounter unexpected simultaneous exceptions.
 * #define KVM_INTERNAL_ERROR_SIMUL_EX 2
 */
#define _GNU_SOURCE
#include <fcntl.h>
#include <linux/kvm.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>

#define INT_NUM 0x21 /* Also works for INT_NUM == 0x20. */

int main(int argc, char *argv[]) {
  int kvm_fd, vm_fd, vcpu_fd;
  void *mem;
  struct kvm_userspace_memory_region region;
  struct kvm_run *run;
  struct kvm_regs regs;
  struct kvm_sregs sregs;
  (void)argc; (void)argv;

  if ((kvm_fd = open("/dev/kvm", O_RDWR)) < 0) {
    perror("failed to open /dev/kvm");
    return 1;
  }
  if ((vm_fd = ioctl(kvm_fd, KVM_CREATE_VM, 0)) < 0) {
    perror("failed to create vm");
    return 1;
  }
  if ((mem = mmap(NULL, 0x1000, PROT_READ | PROT_WRITE,
          MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0)) == NULL) {
    perror("mmap");
    return 1;
  }
  memset(&region, 0, sizeof(region));
  region.slot = 0;
  region.guest_phys_addr = 0;
  region.memory_size = 0x1000;
  region.userspace_addr = (uintptr_t)mem;
  if (ioctl(vm_fd, KVM_SET_USER_MEMORY_REGION, &region) < 0) {
    perror("KVM_SET_USER_MEMORY_REGION");
    return 1;
  }
  {  /* 8086 real mode machine code. */
    char *p = (char*)mem + 0x700;
    unsigned int_num;
    for (int_num = 0; int_num < 0x100; ++int_num) {
      *(unsigned short*)((char*)mem + int_num * 4) = int_num;  /* Interrupt vector INT_NUM offset := INT_NUM. */
      *(unsigned short*)((char*)mem + int_num * 4 + 2) = 0x54;  /* Interrupt vector INT_NUM segment := 0x54. */
    }
    *p++ = (char)0xf4;  /* hlt. */
    for (int_num = 0x18; int_num < 0x50; ++int_num) {
      *p++ = (char)0xcd;  /* int int_num. */
      *p++ = (char)int_num;
    }
    *p++ = (char)0xf4;
  }
  memset((char*)mem + 0x540, '\xf4', 0x100);  /* 256 times hlt. Interrupt vectors point here. */

  if ((vcpu_fd = ioctl(vm_fd, KVM_CREATE_VCPU, 0)) < 0) {
    perror("KVM_CREATE_VCPU");
    return 1;
  }
  {
    int kvm_run_mmap_size = ioctl(kvm_fd, KVM_GET_VCPU_MMAP_SIZE, 0);
    if (kvm_run_mmap_size < 0) {
      perror("KVM_GET_VCPU_MMAP_SIZE");
      return 1;
    }
    run = (struct kvm_run *)mmap(
        NULL, kvm_run_mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, vcpu_fd, 0);
    if (run == NULL) {
      perror("mmap kvm_run");
      return 1;
    }
  }
  memset(&regs, '\0', sizeof(regs));
  if (ioctl(vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {
    perror("KVM_GET_SREGS");
    return 1;
  }
  {
    int fd = open("kvm16.sregs", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    if (fd < 0) {
      perror("open");
      return 1;
    }
    if (write(fd, &sregs, sizeof(sregs)) != sizeof(sregs)) {
      perror("write");
      return 1;
    }
    if (close(fd) != 0) {
      perror("close");
      return 1;
    }
  }
  sregs.cs.base = (sregs.cs.selector = 0x70) << 4;
  sregs.ds.base = (sregs.ds.selector = sregs.cs.selector) << 4;
  sregs.es.base = (sregs.es.selector = sregs.cs.selector) << 4;
  sregs.ss.base = (sregs.ss.selector = sregs.cs.selector) << 4;
  if (ioctl(vcpu_fd, KVM_GET_REGS, &regs) < 0) {
    perror("KVM_GET_REGS");
    return 1;
  }
  regs.rflags = 1 << 1;  /* Reserved bit in EFLAGS. Even needed after KVM_GET_REGS. */
  regs.rip = 0;
  regs.rsp = 0x1000 - 0x700;
  if (ioctl(vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {
    perror("KVM_SET_SREGS");
    return 1;
  }
  if (ioctl(vcpu_fd, KVM_SET_REGS, &regs) < 0) {
    perror("KVM_SET_REGS");
    return 1;
  }
  for (;;) {
    int ret = ioctl(vcpu_fd, KVM_RUN, 0);
    unsigned short cs, ip;
    if (ret < 0) {
      perror("KVM_RUN");
      return 1;
    }
    if (ioctl(vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {
      perror("KVM_GET_SREGS");
      return 1;
    }
    if (ioctl(vcpu_fd, KVM_GET_REGS, &regs) < 0) {
      perror("KVM_GET_REGS");
      return 1;
    }
    cs = sregs.cs.selector;
    ip = regs.rip;
    if (run->exit_reason == KVM_EXIT_HLT) {
      fprintf(stderr, "info: hlt: cs=0x%04x ip=0x%04x\n", cs, ip - 1);
      if (cs == 0x70) {
        if (ip != 0 + 1) {
          fprintf(stderr, "info: success, exiting\n");
          return 0;  /* EXIT_SUCCESS after the second `hlt' in the code. */
        }
      } else if (cs == 0x54) {  /* Simulate iret. */
        const char *csip_ptr = (const char*)mem + ((unsigned short)sregs.ss.selector << 4) + (unsigned short)regs.rsp;
        const unsigned short int_ip = ((const unsigned short*)csip_ptr)[0];
        const unsigned short int_cs = ((const unsigned short*)csip_ptr)[1];
        const unsigned short int_flags = ((const unsigned short*)csip_ptr)[2];
        fprintf(stderr, "info: int 0x%02x iret to: cs=0x%04x ip=0x%04x\n", ip - 1, int_cs, int_ip);
        sregs.cs.base = (sregs.cs.selector = int_cs) << 4;
        regs.rip = int_ip;
        if (int_flags & (1 << 9)) regs.rflags |= (1 << 9);  /* Set IF back to 1 if it was 1. */
        regs.rsp += 6;  /* pop ip, pop cs, popfw . */
        if (ioctl(vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {
          perror("KVM_SET_SREGS");
          return 1;
        }
        if (ioctl(vcpu_fd, KVM_SET_REGS, &regs) < 0) {
          perror("KVM_SET_REGS");
          return 1;
        }
      } else {
        fprintf(stderr, "fatal: unexpected hlt: cs=0x%04x ip=0x%04x\n", cs, ip - 1);
        return 5;
      }
    } else if (run->exit_reason == KVM_EXIT_INTERNAL_ERROR) {
      fprintf(stderr, "fatal: KVM internal error suberror=%d\n", (unsigned)run->internal.suberror);
      return 4;
    } else {
      fprintf(stderr, "fatal: unexpected KVM exit: exit_reason=%d cs=0x%04x ip=0x%04x\n", run->exit_reason, cs, ip);
      return 2;
    }
  }
}
</code>```

Body:
I'm writing a Linux KVM hypervisor for x86 16-bit guests running in real mode. When doing interrupt calls (int ... instruction), I've encountered the KVM_INTERNAL_ERROR_SIMUL_EX error on Linux kernel 3.13.0. The same code is running fine on Linux kernel 3.16.0. Am I missing something? Is there a workaround I can add to my code to make it work with Linux kernel 3.13.0 (and possibly earlier)?

The test guest calls int 0x18 ... int 0x4f, all of which is handled in the hypervisor (C code after KVM_RUN has returned). When it's working correctly, all of the interrupt calls work. On Linux kernel 3.13.0, int 0x21 starts failing (and then int 0x22, int 0x23 and int 0x24 would also fail).

I was trying to write the shortest example C code to demonstrate the problem, here it is:

/* Based on: https://gist.github.com/zserge/d68683f17c68709818f8baab0ded2d15
 * Based on: https://gist.githubusercontent.com/zserge/d68683f17c68709818f8baab0ded2d15/raw/b79033254b092ec9121bb891938b27dd128030d7/kvm-host-simple.c
 *
 * Compile: gcc -ansi -pedantic -s -O2 -W -Wall -o kvm16 kvm16.c && ./kvm16
 *
 * Expected correct output (e.g. on Linux 3.16.0 compiled for i386 (i686)):
 *
 *   ...
 *   info: int 0x4f iret to: ...
 *   info: success, exiting
 *
 * Failure output (e.g. on Linux 3.13.0 compiled for amd64 (x86_64)):
 *
 *   info: int 0x20 iret to: cs=0x0070 ip=0x0013
 *   fatal: KVM internal error suberror=2
 *
 * // Encounter unexpected simultaneous exceptions.
 * #define KVM_INTERNAL_ERROR_SIMUL_EX 2
 */
#define _GNU_SOURCE
#include <fcntl.h>
#include <linux/kvm.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>

#define INT_NUM 0x21 /* Also works for INT_NUM == 0x20. */

int main(int argc, char *argv[]) {
  int kvm_fd, vm_fd, vcpu_fd;
  void *mem;
  struct kvm_userspace_memory_region region;
  struct kvm_run *run;
  struct kvm_regs regs;
  struct kvm_sregs sregs;
  (void)argc; (void)argv;

  if ((kvm_fd = open("/dev/kvm", O_RDWR)) < 0) {
    perror("failed to open /dev/kvm");
    return 1;
  }
  if ((vm_fd = ioctl(kvm_fd, KVM_CREATE_VM, 0)) < 0) {
    perror("failed to create vm");
    return 1;
  }
  if ((mem = mmap(NULL, 0x1000, PROT_READ | PROT_WRITE,
          MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0)) == NULL) {
    perror("mmap");
    return 1;
  }
  memset(&region, 0, sizeof(region));
  region.slot = 0;
  region.guest_phys_addr = 0;
  region.memory_size = 0x1000;
  region.userspace_addr = (uintptr_t)mem;
  if (ioctl(vm_fd, KVM_SET_USER_MEMORY_REGION, &region) < 0) {
    perror("KVM_SET_USER_MEMORY_REGION");
    return 1;
  }
  {  /* 8086 real mode machine code. */
    char *p = (char*)mem + 0x700;
    unsigned int_num;
    for (int_num = 0; int_num < 0x100; ++int_num) {
      *(unsigned short*)((char*)mem + int_num * 4) = int_num;  /* Interrupt vector INT_NUM offset := INT_NUM. */
      *(unsigned short*)((char*)mem + int_num * 4 + 2) = 0x54;  /* Interrupt vector INT_NUM segment := 0x54. */
    }
    *p++ = (char)0xf4;  /* hlt. */
    for (int_num = 0x18; int_num < 0x50; ++int_num) {
      *p++ = (char)0xcd;  /* int int_num. */
      *p++ = (char)int_num;
    }
    *p++ = (char)0xf4;
  }
  memset((char*)mem + 0x540, '\xf4', 0x100);  /* 256 times hlt. Interrupt vectors point here. */

  if ((vcpu_fd = ioctl(vm_fd, KVM_CREATE_VCPU, 0)) < 0) {
    perror("KVM_CREATE_VCPU");
    return 1;
  }
  {
    int kvm_run_mmap_size = ioctl(kvm_fd, KVM_GET_VCPU_MMAP_SIZE, 0);
    if (kvm_run_mmap_size < 0) {
      perror("KVM_GET_VCPU_MMAP_SIZE");
      return 1;
    }
    run = (struct kvm_run *)mmap(
        NULL, kvm_run_mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, vcpu_fd, 0);
    if (run == NULL) {
      perror("mmap kvm_run");
      return 1;
    }
  }
  memset(&regs, '\0', sizeof(regs));
  if (ioctl(vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {
    perror("KVM_GET_SREGS");
    return 1;
  }
  {
    int fd = open("kvm16.sregs", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    if (fd < 0) {
      perror("open");
      return 1;
    }
    if (write(fd, &sregs, sizeof(sregs)) != sizeof(sregs)) {
      perror("write");
      return 1;
    }
    if (close(fd) != 0) {
      perror("close");
      return 1;
    }
  }
  sregs.cs.base = (sregs.cs.selector = 0x70) << 4;
  sregs.ds.base = (sregs.ds.selector = sregs.cs.selector) << 4;
  sregs.es.base = (sregs.es.selector = sregs.cs.selector) << 4;
  sregs.ss.base = (sregs.ss.selector = sregs.cs.selector) << 4;
  if (ioctl(vcpu_fd, KVM_GET_REGS, &regs) < 0) {
    perror("KVM_GET_REGS");
    return 1;
  }
  regs.rflags = 1 << 1;  /* Reserved bit in EFLAGS. Even needed after KVM_GET_REGS. */
  regs.rip = 0;
  regs.rsp = 0x1000 - 0x700;
  if (ioctl(vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {
    perror("KVM_SET_SREGS");
    return 1;
  }
  if (ioctl(vcpu_fd, KVM_SET_REGS, &regs) < 0) {
    perror("KVM_SET_REGS");
    return 1;
  }
  for (;;) {
    int ret = ioctl(vcpu_fd, KVM_RUN, 0);
    unsigned short cs, ip;
    if (ret < 0) {
      perror("KVM_RUN");
      return 1;
    }
    if (ioctl(vcpu_fd, KVM_GET_SREGS, &sregs) < 0) {
      perror("KVM_GET_SREGS");
      return 1;
    }
    if (ioctl(vcpu_fd, KVM_GET_REGS, &regs) < 0) {
      perror("KVM_GET_REGS");
      return 1;
    }
    cs = sregs.cs.selector;
    ip = regs.rip;
    if (run->exit_reason == KVM_EXIT_HLT) {
      fprintf(stderr, "info: hlt: cs=0x%04x ip=0x%04x\n", cs, ip - 1);
      if (cs == 0x70) {
        if (ip != 0 + 1) {
          fprintf(stderr, "info: success, exiting\n");
          return 0;  /* EXIT_SUCCESS after the second `hlt' in the code. */
        }
      } else if (cs == 0x54) {  /* Simulate iret. */
        const char *csip_ptr = (const char*)mem + ((unsigned short)sregs.ss.selector << 4) + (unsigned short)regs.rsp;
        const unsigned short int_ip = ((const unsigned short*)csip_ptr)[0];
        const unsigned short int_cs = ((const unsigned short*)csip_ptr)[1];
        const unsigned short int_flags = ((const unsigned short*)csip_ptr)[2];
        fprintf(stderr, "info: int 0x%02x iret to: cs=0x%04x ip=0x%04x\n", ip - 1, int_cs, int_ip);
        sregs.cs.base = (sregs.cs.selector = int_cs) << 4;
        regs.rip = int_ip;
        if (int_flags & (1 << 9)) regs.rflags |= (1 << 9);  /* Set IF back to 1 if it was 1. */
        regs.rsp += 6;  /* pop ip, pop cs, popfw . */
        if (ioctl(vcpu_fd, KVM_SET_SREGS, &sregs) < 0) {
          perror("KVM_SET_SREGS");
          return 1;
        }
        if (ioctl(vcpu_fd, KVM_SET_REGS, &regs) < 0) {
          perror("KVM_SET_REGS");
          return 1;
        }
      } else {
        fprintf(stderr, "fatal: unexpected hlt: cs=0x%04x ip=0x%04x\n", cs, ip - 1);
        return 5;
      }
    } else if (run->exit_reason == KVM_EXIT_INTERNAL_ERROR) {
      fprintf(stderr, "fatal: KVM internal error suberror=%d\n", (unsigned)run->internal.suberror);
      return 4;
    } else {
      fprintf(stderr, "fatal: unexpected KVM exit: exit_reason=%d cs=0x%04x ip=0x%04x\n", run->exit_reason, cs, ip);
      return 2;
    }
  }
}


问:
Is there a way to hook into DRF ListAPIView to make additional queries for all instances at once?
I am using the Django REST Framework ListAPIView class to represent a collection of model instances and handle pagination automatically.

It's great when you have all the data in the queryset or can grab related data with select_related/prefetch_related to add to the same queryset but when you need to gather more data for each model instance in a different way because there is no direct db relationship, you end up making queries for each instance in the serializer, resulting in a n+1 queries problem.

Is there a way to hook into ListAPIView at a point where all the instances of the current page being returned are known so that more processing/queries can be done at once to fetch the additional data for all instances and add it to the response?

I was thinking of overriding the list method but it sounds a bit hacky.

class Gift(models.Models):
    ...

class SearchList(ListAPIView):
    serializer_class = SearchGiftSerializer
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        return Gift.objects.all()
```


问:
How to write Classes and functions in Leet code solutions
Leet code problems provide an answer section that looks like this:

```<code>class Solution(object):

    def minimumSum(self, num):
        # Answer here
</code>```

I'm used to writing funcitons as

```<code>def somefunction(parameter):
    variable = some_code
</code>```

or classes as:

```<code>class SomeClass():
    def ___init__(self):
        # self.variable1 = Some code

    def some_method(self, parameter):
        # self.variable2 = Some code
</code>```

But somehow, to get my answers to get accepted, I  write my answers as a mixture of both, like this example:

```<code>class Solution(object):

    def minimumSum(self, num):
        # Make string
        n_str = str(num)

        # Create list from digits
        n_list = []
        for x in n_str:
            n_list.append(x)

        # Sort list
        n_list.sort()

        # Create number pairs
        pair_1 = int(n_list[0]+n_list[2])
        pair_2 = int(n_list[1]+n_list[3])

        # Add Numbers
        return(pair_1 + pair_2)
</code>```

I'm writing a class, but the functions don't use 'self' in the function or an init section. I'm wondering why this works or if I'm writing my solutions in an incorrect way.

Body:
Leet code problems provide an answer section that looks like this:

class Solution(object):

    def minimumSum(self, num):
        # Answer here

I'm used to writing funcitons as

def somefunction(parameter):
    variable = some_code

or classes as:

class SomeClass():
    def ___init__(self):
        # self.variable1 = Some code

    def some_method(self, parameter):
        # self.variable2 = Some code

But somehow, to get my answers to get accepted, I  write my answers as a mixture of both, like this example:

class Solution(object):

    def minimumSum(self, num):
        # Make string
        n_str = str(num)

        # Create list from digits
        n_list = []
        for x in n_str:
            n_list.append(x)

        # Sort list
        n_list.sort()

        # Create number pairs
        pair_1 = int(n_list[0]+n_list[2])
        pair_2 = int(n_list[1]+n_list[3])

        # Add Numbers
        return(pair_1 + pair_2)

I'm writing a class, but the functions don't use 'self' in the function or an init section. I'm wondering why this works or if I'm writing my solutions in an incorrect way.


问:
Winzip command line - Include full path information
How do I use winzip command line with include full path information ? I know I can do this under Winzip GUI but how to do it using cmd ? Also, is there a way to zip selected specific folders only ? Thanks

Tried GUI and it is working very slow

Winzip command line doesnt seem to zip selected folders - either parent folders or specific subfolders

I am using winzip 27 command line and this is the syntax I am using:

```<code>wzzip -a -e0 -k -P -r -yx "C:\Users\source\to\save\zipfile.zip" "C:\example"
</code>```

This stores files and folder timestamps underneath C:\example. But since I have enabled -P -r, I want to store the timestamps of the upper folder, C:\example folder. How can I do that ? Does anyone have suggestions?

Also, how do I specify the path for a mapped network drive? Thanks!

Body:
How do I use winzip command line with include full path information ? I know I can do this under Winzip GUI but how to do it using cmd ? Also, is there a way to zip selected specific folders only ? Thanks

Tried GUI and it is working very slow

Winzip command line doesnt seem to zip selected folders - either parent folders or specific subfolders

I am using winzip 27 command line and this is the syntax I am using:

wzzip -a -e0 -k -P -r -yx "C:\Users\source\to\save\zipfile.zip" "C:\example"

This stores files and folder timestamps underneath C:\example. But since I have enabled -P -r, I want to store the timestamps of the upper folder, C:\example folder. How can I do that ? Does anyone have suggestions?

Also, how do I specify the path for a mapped network drive? Thanks!


问:
Mailgun message in Golang not send under cronjob
I have created a go application that at a certain point send a email via Mailgun. If I run my application under Linux with ./testApp it works fine.

But if I run exact the same application under a cronjob it does not work, it is not sending any emails.
*/1 * * * * /home/bin/testApp

In the application i use the standard sending code, see below:

```<code>mg := mailgun.NewMailgun(yourMarketingDomain, privateAPIKey)
mg.SetAPIBase(mailgun.APIBaseEU)
message := mg.NewMessage(email)
message.SetHtml(body.String())
message.SetReplyTo(email)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
_, trackcode, _ := mg.Send(ctx, message)
</code>```

It is not send, and no trackcode is returned.

Any idee's?

Body:
I have created a go application that at a certain point send a email via Mailgun. If I run my application under Linux with ./testApp it works fine.

But if I run exact the same application under a cronjob it does not work, it is not sending any emails.
*/1 * * * * /home/bin/testApp

In the application i use the standard sending code, see below:

mg := mailgun.NewMailgun(yourMarketingDomain, privateAPIKey)
mg.SetAPIBase(mailgun.APIBaseEU)
message := mg.NewMessage(email)
message.SetHtml(body.String())
message.SetReplyTo(email)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
_, trackcode, _ := mg.Send(ctx, message)

It is not send, and no trackcode is returned.

Any idee's?


问:
How to pass a listview control items(itemNumber, itemName, Item Quantity, ItemPrice) vb.net into a database orderItems field
```<code>Private Sub cmdplaceOrder_Click(sender As Object, e As EventArgs) Handles cmdPlaceOrder.Click
    ' Declare variables for the item details
    Dim orderDate As Date = Date.Now
    ' Get the item details from the listview control
    Using connection As New OleDbConnection(myConnectionString)
      ' Open the connection
      connection.Open()
      Dim orderList As New StringBuilder()
      ' Create a command object
      Dim command As New OleDbCommand("INSERT INTO Orders (orderDate,CustomerID,OrderItems, GrossTotalPrice, Discount, NetTotalPrice, Payments, Balance) VALUES (?, ?, ?, ?, ?, ?,?,?)", connection)
      Dim product As ListViewItem = lvOrderItems.Items(0)

      ' Set the command parameters
      command.Parameters.AddWithValue("orderDate", orderDate.ToString("d"))
      command.Parameters.AddWithValue("CustomerID", CustomerID)
      Dim orderItems As New StringBuilder
      For Each item As ListViewItem In lvOrderItems.Items
        orderItems.Append(item.SubItems(0).ToString & "-" & item.SubItems(1).ToString & "-" & item.SubItems(2).ToString & item.SubItems(3).ToString & ",")
      Next
      command.Parameters.AddWithValue("@OrderItems", orderItems)
      command.Parameters.AddWithValue("@GrossTotalPrice", GrandTotal)
      command.Parameters.AddWithValue("@Discount", Discount)
      command.Parameters.AddWithValue("@NetTotalPrice", NetTotal)
      command.Parameters.AddWithValue("@Payments", payments)
      command.Parameters.AddWithValue("@Balance", Balance)

      ' Execute the command
      Dim affectedRows As Integer = command.ExecuteNonQuery()
      If affectedRows > 0 Then
        MessageBox.Show("OrderSaved successfully", "Order Confirmation")
      Else
        MessageBox.Show("Failed To Place Order", "Order Confirmation!!")
      End If
    End Using
  End Sub
</code>```

My database table "Orders" have fields orderID, OrderDate, CustomerID,orderItems,GrossTotal, Discount, NetTotalPrice, Payments, Balance
I need help on how to pass the listview control items(itemNumber, itemName, Item Quantity, ItemPrice) into the database orderItems field. if there is any other alternative to manage this, do suggest.

Body:
Private Sub cmdplaceOrder_Click(sender As Object, e As EventArgs) Handles cmdPlaceOrder.Click
    ' Declare variables for the item details
    Dim orderDate As Date = Date.Now
    ' Get the item details from the listview control
    Using connection As New OleDbConnection(myConnectionString)
      ' Open the connection
      connection.Open()
      Dim orderList As New StringBuilder()
      ' Create a command object
      Dim command As New OleDbCommand("INSERT INTO Orders (orderDate,CustomerID,OrderItems, GrossTotalPrice, Discount, NetTotalPrice, Payments, Balance) VALUES (?, ?, ?, ?, ?, ?,?,?)", connection)
      Dim product As ListViewItem = lvOrderItems.Items(0)

      ' Set the command parameters
      command.Parameters.AddWithValue("orderDate", orderDate.ToString("d"))
      command.Parameters.AddWithValue("CustomerID", CustomerID)
      Dim orderItems As New StringBuilder
      For Each item As ListViewItem In lvOrderItems.Items
        orderItems.Append(item.SubItems(0).ToString & "-" & item.SubItems(1).ToString & "-" & item.SubItems(2).ToString & item.SubItems(3).ToString & ",")
      Next
      command.Parameters.AddWithValue("@OrderItems", orderItems)
      command.Parameters.AddWithValue("@GrossTotalPrice", GrandTotal)
      command.Parameters.AddWithValue("@Discount", Discount)
      command.Parameters.AddWithValue("@NetTotalPrice", NetTotal)
      command.Parameters.AddWithValue("@Payments", payments)
      command.Parameters.AddWithValue("@Balance", Balance)

      ' Execute the command
      Dim affectedRows As Integer = command.ExecuteNonQuery()
      If affectedRows > 0 Then
        MessageBox.Show("OrderSaved successfully", "Order Confirmation")
      Else
        MessageBox.Show("Failed To Place Order", "Order Confirmation!!")
      End If
    End Using
  End Sub

My database table "Orders" have fields orderID, OrderDate, CustomerID,orderItems,GrossTotal, Discount, NetTotalPrice, Payments, Balance
I need help on how to pass the listview control items(itemNumber, itemName, Item Quantity, ItemPrice) into the database orderItems field. if there is any other alternative to manage this, do suggest.


问:
Trouble getting XML converted into variable in C#
I am trying to get an XML from Swagger. Let's just say the XML is this:

```<code><note>
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend!</body>
</note>
</code>```

(HOwever, in reality my XML is MUCH larger). So if the above is being returned from swagger, how would I store these exact results in a variable in C#? Let me know if you need more detail. In theory. I would love to just be able to capture all this data and store it in a string variable or XMLDocument variable. Thanks!

I have tried doing storing it in a XML document and even a string, but the part I am having trouble with is capturing the XML from Swagger.

Body:
I am trying to get an XML from Swagger. Let's just say the XML is this:

<note>
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 Don't forget me this weekend!
</note>

(HOwever, in reality my XML is MUCH larger). So if the above is being returned from swagger, how would I store these exact results in a variable in C#? Let me know if you need more detail. In theory. I would love to just be able to capture all this data and store it in a string variable or XMLDocument variable. Thanks!

I have tried doing storing it in a XML document and even a string, but the part I am having trouble with is capturing the XML from Swagger.


问:
Should I keep python installation if I am switching to pyenv?
Should I remove the preexisting python reference from my PATH environment variable (and/or remove it entirely) if I am starting to use pyenv to manage my python versions?

That is, should I have python3 accessible if I'm using pyenv and have pyenv global set? Why or why not?

```<code>$ which python3
/usr/bin/python3
</code>```
```<code>$ which pyenv
/home/<username>/.pyenv/bin/pyenv

$ pyenv global
3.9.0a5
</code>```

Body:
Should I remove the preexisting python reference from my PATH environment variable (and/or remove it entirely) if I am starting to use pyenv to manage my python versions?

That is, should I have python3 accessible if I'm using pyenv and have pyenv global set? Why or why not?

$ which python3
/usr/bin/python3

$ which pyenv
/home/<username>/.pyenv/bin/pyenv

$ pyenv global
3.9.0a5


问:
Access outdoor controls from classes - VB.NET
Hi and I'm sorry for askin' dummy questions. I have a class which it has to invalidate my workspace(PictureBox) to perform some motion. But I can't do it because it totally doesn't run.

My class:

```<code>Public Class clsLayoutObject
    Private tmrAnimation As New Timer

    Public oID As UInteger
    Public oName As String
    Public oGraphic As New List(Of Image)
    Public oMaxFrame As UInteger
    Public oActiveFrame As UInteger
    Public oFrameRate As UInteger = 100
    Public oX As Integer, oY As Integer
    Public oWidth As Integer, oHeight As Integer
    Public oDepth As UInteger
    Public oLocked As Boolean
    Public oVisible As Boolean

    Private tempActiveFrame As UInteger

    Private Sub playAnimation()
        AddHandler tmrAnimation.Elapsed, New ElapsedEventHandler(AddressOf animationPlayback)
        tmrAnimation.Interval = oFrameRate
        tmrAnimation.Start()
        tempActiveFrame = oActiveFrame
    End Sub

    Private Sub animationPlayback()
        --> frmmain.Workspace.Invalidate()
        If oActiveFrame < oMaxFrame Then
            oActiveFrame += 1
        Else
            oActiveFrame = 0
        End If
    End Sub

    Private Sub animationPause()
        tmrAnimation.Stop()
        frmmain.Workspace.Invalidate()
    End Sub

    Private Sub animationStop()
        oActiveFrame = tempActiveFrame
        tmrAnimation.Stop()
        frmmain.Workspace.Invalidate()
    End Sub
End Class
</code>```

I'm not familiar with OO programming too much and I'm still improving. Thanks.

ContentLicense: CC BY-SA 3.0

Body:
Hi and I'm sorry for askin' dummy questions. I have a class which it has to invalidate my workspace(PictureBox) to perform some motion. But I can't do it because it totally doesn't run.

My class:

Public Class clsLayoutObject
    Private tmrAnimation As New Timer

    Public oID As UInteger
    Public oName As String
    Public oGraphic As New List(Of Image)
    Public oMaxFrame As UInteger
    Public oActiveFrame As UInteger
    Public oFrameRate As UInteger = 100
    Public oX As Integer, oY As Integer
    Public oWidth As Integer, oHeight As Integer
    Public oDepth As UInteger
    Public oLocked As Boolean
    Public oVisible As Boolean

    Private tempActiveFrame As UInteger

    Private Sub playAnimation()
        AddHandler tmrAnimation.Elapsed, New ElapsedEventHandler(AddressOf animationPlayback)
        tmrAnimation.Interval = oFrameRate
        tmrAnimation.Start()
        tempActiveFrame = oActiveFrame
    End Sub

    Private Sub animationPlayback()
        --> frmmain.Workspace.Invalidate()
        If oActiveFrame < oMaxFrame Then
            oActiveFrame += 1
        Else
            oActiveFrame = 0
        End If
    End Sub

    Private Sub animationPause()
        tmrAnimation.Stop()
        frmmain.Workspace.Invalidate()
    End Sub

    Private Sub animationStop()
        oActiveFrame = tempActiveFrame
        tmrAnimation.Stop()
        frmmain.Workspace.Invalidate()
    End Sub
End Class

I'm not familiar with OO programming too much and I'm still improving. Thanks.


问:
How to automatically increment the assembly version number in C#
How to automatically increment the assembly version number in C# .

NET6 no longer has AssemblyInfo.cs, as we all know

And i try the answer at
How to auto increment the version (eg. “1.0.*”) of a .NET Core project?

it doesn't work


问:
Swift CABasicAnimation
Every time I click on the label, I want 1 in 100 progress, how do I do it?</p>
```<code>@objc func labelTapped(_ sender: UITapGestureRecognizer) {
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.toValue = 1
    animation.duration = 100
    animation.isRemovedOnCompletion = true
    shape.add(animation, forKey: "animation")
}

func setupLabelTap() {
    let labelTap = UITapGestureRecognizer(target: self, action: #selector(self.labelTapped(_:)))
    self.label.isUserInteractionEnabled = true
    self.label.addGestureRecognizer(labelTap)
}
</code>```

Title: Swift CABasicAnimation

Body:
Every time I click on the label, I want 1 in 100 progress, how do I do it?

@objc func labelTapped(_ sender: UITapGestureRecognizer) {
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.toValue = 1
    animation.duration = 100
    animation.isRemovedOnCompletion = true
    shape.add(animation, forKey: "animation")
}

func setupLabelTap() {
    let labelTap = UITapGestureRecognizer(target: self, action: #selector(self.labelTapped(_:)))
    self.label.isUserInteractionEnabled = true
    self.label.addGestureRecognizer(labelTap)
}


问:
I want to save a string of 0's and 1's as bits to a file in Python, so it'll take less space
I have a string of 0's and 1's, e.g. [011101110] I want to write each one as a bit to a file, so the space of the file will be 1 byte. instead of 8 bytes as each digit is written as it's own character.

I'm currently using this method but it can't seem to work.

```<code>with open(input_file.name + ".chris", "wb") as output_file:
    binary = bytearray(compressed.encode())
    output_file.write(binary)
    output_file.close()

</code>```

compressed variable is the string of 0's and 1's

Body:
I have a string of 0's and 1's, e.g. [011101110] I want to write each one as a bit to a file, so the space of the file will be 1 byte. instead of 8 bytes as each digit is written as it's own character.

I'm currently using this method but it can't seem to work.

with open(input_file.name + ".chris", "wb") as output_file:
    binary = bytearray(compressed.encode())
    output_file.write(binary)
    output_file.close()

compressed variable is the string of 0's and 1's


问:
Flutter-web no context menu on text selection
I'm developing a web application with Flutter version 3.3.8. I ran the application on my mobile web-browser and there are no context menu upon selecting a text. Therefore, I'm unable to copy the selected text from the web-browser. I've used the SelectionArea Widget to enable the text selection in my application.

Expectations:

Reality:

However, running as an app provides those options:

Here is my impl:

```<code>class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SelectionArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            SizedBox(height: 40.00,),
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Is there flutter way that I'm missing or any workaround that I could use to see the context menu options.

Body:
I'm developing a web application with Flutter version 3.3.8. I ran the application on my mobile web-browser and there are no context menu upon selecting a text. Therefore, I'm unable to copy the selected text from the web-browser. I've used the SelectionArea Widget to enable the text selection in my application.

Expectations:

Reality:

However, running as an app provides those options:

Here is my impl:

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SelectionArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            SizedBox(height: 40.00,),
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
    );
  }
}

Is there flutter way that I'm missing or any workaround that I could use to see the context menu options.


问:
Apollo server accessing all datasources within resolvers before API request is sent
In a graphql query with multiple resolvers, I'm looking for a way to count how many times datasources are called before the first datasource API request is sent. The project that I am working on requires me to either allow or stop all the requests if the number of the datasources called within resolvers in a graphql query exceeds a certain number.

I am using an instance of the RESTDataSource to make API calls and each one of the resolvers call one or more datasources from the RESTDataSource class. I've been looking into this and far as I know, the RESTDataSource class doesn't have a method that shows me all the datasources requested because it is only called by the resolver and per request.

My problem is, I'm not finding a place where I can have access to all the datasources that will be called before the request is sent. I found that in the Apollo server instantiation, the only thing that I have access to are the resolvers, and not the datasources within each resolver, and as far as I know, not before the request is made so I can't stop it if the number of datasources calls exceed a certain threshold. I was hoping I could access that in the willSendRequest method inside the RESTDataSource class since from what I know, this is the only method that intercepts the request before being sent, but I don't think it's possible.

I'm pretty new to Apollo and I've been reading about this but didn't find a solution. I'd really appreciate any help.

Here's a simplified snippet of my code (not the original code):

resolvers.ts

```<code>export const resolvers: Resolvers = {
  Query: {
    getCompanies: (_, __, { dataSources }) => {
      return dataSources.companyDatasource.getCompanies();
    },
    getCompany: (_, { name }, { dataSources }) => {
      return dataSources.companyDatasource.getCompanyByName(name);
    },
    getCompanyCEOs: async (_, { name }, { dataSources }) => {
      const company = await dataSources.companyDatasource.getCompanyByName(name);
      return dataSources.companyDatasource.getCEOs(company.id);
    },
....
</code>```

company.datasource.ts

```<code>export default class CompanyDatasource extends RESTDataSource {
  async willSendRequest(request) {
    // some logic
  }

  async getCompanies() {
    return this.get(`some_api_url`);
  }

  async getCompanyByName(name) {
    return this.get(`some_api_url?companyName=name`);
  }
  //other external API endpoints
...
}
</code>```

main.ts

```<code>  const server = new ApolloServer({
    typeDefs: schema,
    schema,
    resolvers,
    dataSources,
    cache: 'bounded',
  });
  await server.start();
</code>```

Edit: I'm limiting the number of unique datasource API calls because the API I'm hitting has a limit. I tried instantiating a counter in the RESTDataSource class and using it in the willSendRequest to count how many datasource calls there are, but the problem is this is counting request by request and has no access to all the API requests that are coming from the resolver. For instance, if the getCompanies API can be called only once and I have 2 upcoming requests, I'll have to let one of them pass and only stop the second, because at that point I don't know there's a second request coming. My team has agreed to stop both requests in case the number of upcoming requests exceeds the available limit for the endpoint (this is specified in our database), so this is why I need to know beforehand how many API requests are there before even allowing the first request.

Body:
In a graphql query with multiple resolvers, I'm looking for a way to count how many times datasources are called before the first datasource API request is sent. The project that I am working on requires me to either allow or stop all the requests if the number of the datasources called within resolvers in a graphql query exceeds a certain number.

I am using an instance of the RESTDataSource to make API calls and each one of the resolvers call one or more datasources from the RESTDataSource class. I've been looking into this and far as I know, the RESTDataSource class doesn't have a method that shows me all the datasources requested because it is only called by the resolver and per request.

My problem is, I'm not finding a place where I can have access to all the datasources that will be called before the request is sent. I found that in the Apollo server instantiation, the only thing that I have access to are the resolvers, and not the datasources within each resolver, and as far as I know, not before the request is made so I can't stop it if the number of datasources calls exceed a certain threshold. I was hoping I could access that in the willSendRequest method inside the RESTDataSource class since from what I know, this is the only method that intercepts the request before being sent, but I don't think it's possible.

I'm pretty new to Apollo and I've been reading about this but didn't find a solution. I'd really appreciate any help.

Here's a simplified snippet of my code (not the original code):

resolvers.ts

export const resolvers: Resolvers = {
  Query: {
    getCompanies: (_, __, { dataSources }) => {
      return dataSources.companyDatasource.getCompanies();
    },
    getCompany: (_, { name }, { dataSources }) => {
      return dataSources.companyDatasource.getCompanyByName(name);
    },
    getCompanyCEOs: async (_, { name }, { dataSources }) => {
      const company = await dataSources.companyDatasource.getCompanyByName(name);
      return dataSources.companyDatasource.getCEOs(company.id);
    },
....

company.datasource.ts

export default class CompanyDatasource extends RESTDataSource {
  async willSendRequest(request) {
    // some logic
  }

  async getCompanies() {
    return this.get(`some_api_url`);
  }

  async getCompanyByName(name) {
    return this.get(`some_api_url?companyName=name`);
  }
  //other external API endpoints
...
}

main.ts

  const server = new ApolloServer({
    typeDefs: schema,
    schema,
    resolvers,
    dataSources,
    cache: 'bounded',
  });
  await server.start();

Edit: I'm limiting the number of unique datasource API calls because the API I'm hitting has a limit. I tried instantiating a counter in the RESTDataSource class and using it in the willSendRequest to count how many datasource calls there are, but the problem is this is counting request by request and has no access to all the API requests that are coming from the resolver. For instance, if the getCompanies API can be called only once and I have 2 upcoming requests, I'll have to let one of them pass and only stop the second, because at that point I don't know there's a second request coming. My team has agreed to stop both requests in case the number of upcoming requests exceeds the available limit for the endpoint (this is specified in our database), so this is why I need to know beforehand how many API requests are there before even allowing the first request.


问:
Firebase messaging (web) - get topics results in 401
I'm trying to get a list of topics subscribed to via the firebase API.

My firebase project has an api-key, which is known to the client. The client has also generated a messaging-token (which I guess is really a google iid). So both are public information.

I am attempting a GET to the following url (based on these google iid instructions)

https://iid.googleapis.com/iid/info/<messaging-token>?details=true&Authorization:key=<api-key>

I also have a header Authorization:key=<api-key> as the instructions are little ambiguous

I am getting 401 responses.

I have done this a few months ago but then I had to provide a secret server key, which the firebase UI described as legacy then, and which is now not available. There is a private key in the UI but that also results in 401s.

What do I need to do?


问:
How to listen to audio stream in flutter web
I'm working on an app that works with audio in real time measuring things such as intensity. I need it to run on Android, IOS and web. I already covered Android and IOS using flutter_sound package, which allows me to access the byte stream and do stuff from there. However this is not possible for web, since the codec used by flutter_sound that gives access to stream is not supported by web browsers.

Is there any package for web that allows byte handling or any workaround to this?

I've been searching with no success. So far all packages that I found that support web only allow to access data through files


问:
TradingView Pine - How to anchor VWAP to the highest high of the last n bars? Or to the previous trading session?
Just a beginner here.

If I'm not wrong, the 'highest high' (or lowest low; or highest volume; ...) is known only after the anchor time / date has passed, because only after all bars are analyzed Pine knows where it is. So, if this is true, how can I anchor a VWAP (just an example) to the specific bar? Can I request a 'chart re-drawing' after the anchor time / date is known?

Similar problem: how to anchor a VWAP to the beginning of the previous trading session without providing the date of that session but having Pine calculating it dinamically? For example, today I would anchor a VWAP to the trading session before today (that is 2022-12-23) and tomorrow this anchoring should 'move' to today ...

Thanks for any help. Best wishes of a happy New Year. LP

Read Pine documentation, tried many solution and searched StackOverflow, without finding anything.


问:
JS expressions in After Effects -- Undefined value error
I'm having an issue using JS expression inside After Effects.

My comp is set up so there is a null with a dropdown controller. I am wanting to use this in the expression for a bulge effect where I am experiencing my issue.

If option 1 is picked, set the bulge value to 0.5, if option 2 -0.5, and option 3, 0. You can see this from the code snippet below:

```<code>var controller = thisComp.layer("Null 1").effect("Bulge direction")("Menu");
if(controller == 1){0.5};
if(controller == 2){-0.5};
if(controller == 3){0};
</code>```

Please also refer to this image:

and help me with an error stating that an undefined expression was used on line 1. Thanks a lot.

Body:
I'm having an issue using JS expression inside After Effects.

My comp is set up so there is a null with a dropdown controller. I am wanting to use this in the expression for a bulge effect where I am experiencing my issue.

If option 1 is picked, set the bulge value to 0.5, if option 2 -0.5, and option 3, 0. You can see this from the code snippet below:

var controller = thisComp.layer("Null 1").effect("Bulge direction")("Menu");
if(controller == 1){0.5};
if(controller == 2){-0.5};
if(controller == 3){0};

Please also refer to this image:

and help me with an error stating that an undefined expression was used on line 1. Thanks a lot.


问:
Stuck on returning a object that references local function value error
I have been experimenting with Rust, and am quite happy with it.
Unfortunately I have been banging my head against a wall now, and don't get why the below code would give an error.

I would expect that it's ok to have a reference to a Category in the item, but somehow it won't let me do that and return the Data object without complaining.
It says that I return a value referencing data owned by the current function, but I would think that all data and references are moved/put in the resulting Data object, so there is no problem. But apparently I'm too much of a newbie in Rust. Took me a few hours, but every time I get to the same error in the end. Anybody a clue?

```<code>struct Data<'a> {
    categories:Vec<Category>,
    items:Vec<Item<'a>>
}
struct Category
{
    id:String,
}
struct Item<'a>
{
    id:String,
    category:&'a Category,

}

struct Mapper {}

impl Mapper {
    pub fn map() -> Data<'static>
    {
        let mut categories = Vec::<Category>::new();
        categories.push(Category{ id:"cat1".to_string()});
        categories.push(Category{ id:"cat2".to_string()});

        let mut items = Vec::<Item>::new();
        items.push(Item{ id:"item1".to_string(), category:categories.first().unwrap()});
        items.push(Item{ id:"item2".to_string(), category:categories.last().unwrap()});

        return Data { items, categories};
    }
}
</code>```

Error:

```<code>error[E0515]: cannot return value referencing local variable `categories`
  --> src/SimpleTest.rs:30:16
   |
27 |         items.push(Item{ id:"item1".to_string(), category:categories.first().unwrap()});
   |                                                           ------------------ `categories` is borrowed here
...
30 |         return Data { items, categories};
   |                ^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
</code>```

Body:
I have been experimenting with Rust, and am quite happy with it.
Unfortunately I have been banging my head against a wall now, and don't get why the below code would give an error.

I would expect that it's ok to have a reference to a Category in the item, but somehow it won't let me do that and return the Data object without complaining.
It says that I return a value referencing data owned by the current function, but I would think that all data and references are moved/put in the resulting Data object, so there is no problem. But apparently I'm too much of a newbie in Rust. Took me a few hours, but every time I get to the same error in the end. Anybody a clue?

struct Data<'a> {
    categories:Vec<Category>,
    items:Vec<Item<'a>>
}
struct Category
{
    id:String,
}
struct Item<'a>
{
    id:String,
    category:&'a Category,

}

struct Mapper {}

impl Mapper {
    pub fn map() -> Data<'static>
    {
        let mut categories = Vec::<Category>::new();
        categories.push(Category{ id:"cat1".to_string()});
        categories.push(Category{ id:"cat2".to_string()});

        let mut items = Vec::<Item>::new();
        items.push(Item{ id:"item1".to_string(), category:categories.first().unwrap()});
        items.push(Item{ id:"item2".to_string(), category:categories.last().unwrap()});

        return Data { items, categories};
    }
}

Error:

error[E0515]: cannot return value referencing local variable `categories`
  --> src/SimpleTest.rs:30:16
   |
27 |         items.push(Item{ id:"item1".to_string(), category:categories.first().unwrap()});
   |                                                           ------------------ `categories` is borrowed here
...
30 |         return Data { items, categories};
   |                ^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function


问:
Django_Quill not showing css in Django template
Here is output of my admin panel where the input of django quill field is visible
admin image

but in my html file no styling is seen
html image

Here is my model.py

```<code>
from django.db import models
from django_quill.fields import QuillField

class Blog(models.Model):
    title = models.CharField(max_length=200)
    date = models.DateTimeField(auto_now_add=True)
    body = QuillField()

    def __str__(self):
        return self.title

    def summary(self):
        return self.body[:100]

    def pub_date_pretty(self):
        return self.date.strftime('%b %e %Y')

</code>```

Here is my views.py

```<code>
from django.shortcuts import render, get_object_or_404
from .models import Blog

def all_blogs(request):
    blogs = Blog.objects.order_by('-date')
    return render(request, 'blog/all_blogs.html', {'blogs': blogs})

def detail(request, blog_id):
    blog = get_object_or_404(Blog, pk=blog_id)
    return render(request, 'blog/detail.html', {'blog': blog})

</code>```

Here is my template html code

```<code>
{% extends 'base.html' %} {% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>{% block title %} Detailed Blog {% endblock %}</title>
  </head>
  <body>
    {% block content %}
    <h1 class="text-center mt-5" id="blogdetailtitle" style="font-size: 3rem">{{ blog.title }}</h1>
    <h5 class="text-center text-muted mt-2 mb-5">{{ blog.date|date:'F jS Y' }}</h5>
    <div class="container">{{ blog.body.html | safe }}</div>
    {% endblock %}
  </body>
</html>

</code>```

I tried all the solutions given in github and here also about .html | safe
This isn't issue here I think.
What's wrong here...

Body:
Here is output of my admin panel where the input of django quill field is visible
admin image

but in my html file no styling is seen
html image

Here is my model.py

from django.db import models
from django_quill.fields import QuillField

class Blog(models.Model):
    title = models.CharField(max_length=200)
    date = models.DateTimeField(auto_now_add=True)
    body = QuillField()

    def __str__(self):
        return self.title

    def summary(self):
        return self.body[:100]

    def pub_date_pretty(self):
        return self.date.strftime('%b %e %Y')

Here is my views.py

from django.shortcuts import render, get_object_or_404
from .models import Blog

def all_blogs(request):
    blogs = Blog.objects.order_by('-date')
    return render(request, 'blog/all_blogs.html', {'blogs': blogs})

def detail(request, blog_id):
    blog = get_object_or_404(Blog, pk=blog_id)
    return render(request, 'blog/detail.html', {'blog': blog})

Here is my template html code

{% extends 'base.html' %} {% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>{% block title %} Detailed Blog {% endblock %}</title>

    {% block content %}

{{ blog.title }}

{{ blog.date|date:'F jS Y' }}

{{ blog.body.html | safe }}

    {% endblock %}

I tried all the solutions given in github and here also about .html | safe
This isn't issue here I think.
What's wrong here...


问:
How do I listen for keyPress event on list elements in react js
I have tried this way but it doesn't work. It doesn't even log a simple text in the console. How do I listen for a keyPress event on the list element?

```<code><MotionUL variants={dropUlAnimVariant}>
                  {category.map((item, i, arr) => {
                    return (
                      <MotionLI
                        key={i}
                        className={`cursor-pointer list-none ${
                          i === state.selectIndex
                            ? 'text-white'
                            : 'text-gray-400'
                        }  hover:text-white ${
                          item === arr.slice(-1).join('')
                            ? 'border-none'
                            : 'border-b border-[#2d2d2d]'
                        } py-2`}
                        role="button"
                        ariaPressed={i === state.selectIndex}
                        tabIndex={0}
                        onClick={() => {
                          setCurrentCatItem(item);
                          dispatch({ type: 'select', payload: i });
                        }}
                        onKeyPress={(e) => {
                          console.log(item); //NOT WORKING
                        }}
                      >
                        {item}
                      </MotionLI>
                    );
                  })}
                </MotionUL>
</code>```

Motion.LI is a component that returns an element from the framer motion library called motion.li. It's just a parent component that wrapped up its children.

Motion.LI.jsx

```<code>import React from 'react';
import { dropdownLiAnimVariant } from '../assets/constants';
import { motion } from 'framer-motion';
const MotionLI = ({
  children,
  className,
  onClick,
  key,
  role,
  ariaPressed,
  tabIndex,
  onKeyPress,
}) => {
  return (
    <motion.li
      className={className}
      onClick={onClick}
      variants={dropdownLiAnimVariant}
      whileTap={{ scale: 0.9 }}
      key={key}
      role={role}
      aria-pressed={ariaPressed}
      tabIndex={tabIndex}
      onKeyPress={onKeyPress}
    >
      {children}
    </motion.li>
  );
};

export default MotionLI;
</code>```

Body:
I have tried this way but it doesn't work. It doesn't even log a simple text in the console. How do I listen for a keyPress event on the list element?

<MotionUL variants={dropUlAnimVariant}>
                  {category.map((item, i, arr) => {
                    return (
                      <MotionLI
                        key={i}
                        className={`cursor-pointer list-none ${
                          i === state.selectIndex
                            ? 'text-white'
                            : 'text-gray-400'
                        }  hover:text-white ${
                          item === arr.slice(-1).join('')
                            ? 'border-none'
                            : 'border-b border-[#2d2d2d]'
                        } py-2`}
                        role="button"
                        ariaPressed={i === state.selectIndex}
                        tabIndex={0}
                        onClick={() => {
                          setCurrentCatItem(item);
                          dispatch({ type: 'select', payload: i });
                        }}
                        onKeyPress={(e) => {
                          console.log(item); //NOT WORKING
                        }}
                      >
                        {item}
                      </MotionLI>
                    );
                  })}
                </MotionUL>

Motion.LI is a component that returns an element from the framer motion library called motion.li. It's just a parent component that wrapped up its children.

Motion.LI.jsx

import React from 'react';
import { dropdownLiAnimVariant } from '../assets/constants';
import { motion } from 'framer-motion';
const MotionLI = ({
  children,
  className,
  onClick,
  key,
  role,
  ariaPressed,
  tabIndex,
  onKeyPress,
}) => {
  return (
    <motion.li
      className={className}
      onClick={onClick}
      variants={dropdownLiAnimVariant}
      whileTap={{ scale: 0.9 }}
      key={key}
      role={role}
      aria-pressed={ariaPressed}
      tabIndex={tabIndex}
      onKeyPress={onKeyPress}
    >
      {children}
    </motion.li>
  );
};

export default MotionLI;


问:
pub get failed on pubspec.yaml
```<code>dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  quickalert: ^1.0.1
</code>```

I tried to run pub get, but it failed (i live in Syria; I don't know if the location is the problem)

This is the link to the package I want to use https://pub.dev/packages/quickalert/install

so please help

```<code>flutter pub get
Running "flutter pub get" in puzzel...
Authentication error (403)
package:pub/src/authentication/client.dart 95:5    _AuthenticatedClient._throwAuthException
package:pub/src/authentication/client.dart 60:9    _AuthenticatedClient.send
===== asynchronous gap ===========================
package:pub/src/authentication/client.dart 133:12  withAuthenticatedClient
===== asynchronous gap ===========================
package:pub/src/source/hosted.dart 862:22          HostedSource._download.<fn>
===== asynchronous gap ===========================
package:pub/src/io.dart 886:12                     withTempDir
===== asynchronous gap ===========================
package:pub/src/source/hosted.dart 859:5           HostedSource._download
===== asynchronous gap ===========================
package:pub/src/source/hosted.dart 669:7           HostedSource.downloadToSystemCache
===== asynchronous gap ===========================
package:pub/src/solver/result.dart 86:9            SolveResult.downloadCachedPackages.<fn>.<fn>
===== asynchronous gap ===========================
package:pub/src/solver/result.dart 85:14           SolveResult.downloadCachedPackages.<fn>
===== asynchronous gap ===========================
package:pub/src/solver/result.dart 82:5            SolveResult.downloadCachedPackages
===== asynchronous gap ===========================
package:pub/src/entrypoint.dart 332:7              Entrypoint.acquireDependencies
===== asynchronous gap ===========================
package:pub/src/command/get.dart 55:5              GetCommand.runProtected
This is an unexpected error. The full log and other details are collected in:

    C:\src\flutter\.pub-cache\log\pub_log.txt

Consider creating an issue on https://github.com/dart-lang/pub/issues/new
and attaching the relevant parts of that log file.
pub get failed (1; and attaching the relevant parts of that log file.)
exit code 1
</code>```

Title: pub get failed on pubspec.yaml

Body:
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  quickalert: ^1.0.1

I tried to run pub get, but it failed (i live in Syria; I don't know if the location is the problem)

This is the link to the package I want to use https://pub.dev/packages/quickalert/install

so please help

flutter pub get
Running "flutter pub get" in puzzel...
Authentication error (403)
package:pub/src/authentication/client.dart 95:5    _AuthenticatedClient._throwAuthException
package:pub/src/authentication/client.dart 60:9    _AuthenticatedClient.send
===== asynchronous gap ===========================
package:pub/src/authentication/client.dart 133:12  withAuthenticatedClient
===== asynchronous gap ===========================
package:pub/src/source/hosted.dart 862:22          HostedSource._download.<fn>
===== asynchronous gap ===========================
package:pub/src/io.dart 886:12                     withTempDir
===== asynchronous gap ===========================
package:pub/src/source/hosted.dart 859:5           HostedSource._download
===== asynchronous gap ===========================
package:pub/src/source/hosted.dart 669:7           HostedSource.downloadToSystemCache
===== asynchronous gap ===========================
package:pub/src/solver/result.dart 86:9            SolveResult.downloadCachedPackages.<fn>.<fn>
===== asynchronous gap ===========================
package:pub/src/solver/result.dart 85:14           SolveResult.downloadCachedPackages.<fn>
===== asynchronous gap ===========================
package:pub/src/solver/result.dart 82:5            SolveResult.downloadCachedPackages
===== asynchronous gap ===========================
package:pub/src/entrypoint.dart 332:7              Entrypoint.acquireDependencies
===== asynchronous gap ===========================
package:pub/src/command/get.dart 55:5              GetCommand.runProtected
This is an unexpected error. The full log and other details are collected in:

    C:\src\flutter\.pub-cache\log\pub_log.txt

Consider creating an issue on https://github.com/dart-lang/pub/issues/new
and attaching the relevant parts of that log file.
pub get failed (1; and attaching the relevant parts of that log file.)
exit code 1


问:
How to store RealityKit types like ModelEntity, Entity or Materials on the device?
I have a class that looks like this:

```<code>enum EntityState {
    case unselected
    case selected
    case colored
}

class AREntity {
    var entity: ModelEntity
    var state: EntityState
    var notes: String
    var originalMaterial: PhysicallyBasedMaterial
    var isHidden: Bool
    var isFaded: Bool
    var isFadedOthers: Bool
    var isolated: Bool
    var isIsolated: Bool
    ...
}
</code>```

So this class has properties with types like ModelEntity, enum, PhysicallyBasedMaterial and the user can change the entitys material, opacity and so on. But I want the device to store the modified entity so when the user opens the application again and uses the same entity, the modifications would remain. I was thinking of UserDefaults but it only allows a short list of types to store and ModelEntity or Materials are not among them.

Body:
I have a class that looks like this:

enum EntityState {
    case unselected
    case selected
    case colored
}

class AREntity {
    var entity: ModelEntity
    var state: EntityState
    var notes: String
    var originalMaterial: PhysicallyBasedMaterial
    var isHidden: Bool
    var isFaded: Bool
    var isFadedOthers: Bool
    var isolated: Bool
    var isIsolated: Bool
    ...
}

So this class has properties with types like ModelEntity, enum, PhysicallyBasedMaterial and the user can change the entitys material, opacity and so on. But I want the device to store the modified entity so when the user opens the application again and uses the same entity, the modifications would remain. I was thinking of UserDefaults but it only allows a short list of types to store and ModelEntity or Materials are not among them.


问:
Angular: How to change the style of ng-bootstrap pagination component
I'm using an ng-bootstrap pagination component but I need to change his style from this:
ng-bootstrap pagination to this: enter image description here (or something like that). I don't know if it's possible and how to do that, but if it's can someone help me, please?!

Site of ng-bootstrap pagination component: https://ng-bootstrap.github.io/#/components/pagination/examples

component.html

```<code><ngb-pagination [collectionSize]="collectionSize" [(page)]="page" [boundaryLinks]="true" [pageSize]="pageSize" (pageChange)="refreshContent()">
      <ng-template ngbPaginationPages let-page let-pages="pages">
        <li class="ngb-custom-pages-item" *ngIf="pages.length > 0">
          <div class="mb-3 d-flex flex-nowrap px-2">
            <label id="paginationInputLabel" for="paginationInput" class="col-form-label me-2 ms-1">Page</label>
            <input
              #i
              type="text"
              inputmode="numeric"
              pattern="[0-9]*"
              class="form-control custom-pages-input"
              id="paginationInput"
              [value]="page"
              (keyup.enter)="selectPage(i.value)"
              (blur)="selectPage(i.value)"
              (input)="formatInput($any($event).target)"
              aria-labelledby="paginationInputLabel paginationDescription"
              style="width: 2.5rem"
            />
            <span id="paginationDescription" class="col-form-label text-nowrap px-2"> of {{pages.length}}</span>
          </div>
        </li>
      </ng-template>
    </ngb-pagination>
</code>```

Body:
I'm using an ng-bootstrap pagination component but I need to change his style from this:
ng-bootstrap pagination to this: enter image description here (or something like that). I don't know if it's possible and how to do that, but if it's can someone help me, please?!

Site of ng-bootstrap pagination component: https://ng-bootstrap.github.io/#/components/pagination/examples

component.html

<ngb-pagination [collectionSize]="collectionSize" [(page)]="page" [boundaryLinks]="true" [pageSize]="pageSize" (pageChange)="refreshContent()">
      <ng-template ngbPaginationPages let-page let-pages="pages">

 0">

            Page
            <input
              #i
              type="text"
              inputmode="numeric"
              pattern="[0-9]*"
              class="form-control custom-pages-input"
              id="paginationInput"
              [value]="page"
              (keyup.enter)="selectPage(i.value)"
              (blur)="selectPage(i.value)"
              (input)="formatInput($any($event).target)"
              aria-labelledby="paginationInputLabel paginationDescription"
              style="width: 2.5rem"
            />
             of {{pages.length}}

      </ng-template>
    </ngb-pagination>


问:
Casting column value during update operation
I have one table (ABC) which has one column of type uuid (city), now I want to convert it in array of uuid which is _uuid. To achieve this I have created one temporary column(temp_cities) with data type of _uuid.

When I try to update newly created column with exiting one I am getting following error:

SQL Error [42804]: ERROR: column "temp_cities" is of type uuid[] but expression is of type uuid

Can someone tell me how to cast this thing. I was able to get the solution for datatype text but not for uuid.


问:
What is the std::filesystem counterpart of stat.st_rdev for block devices and character devices?
The std::filesystem library provides nice portable bindings for directory tree traversal and all kinds of filetypes and almost all the features I know of a typical UNIX/POSIX system are there (hardlink count etc.).

Problem: I fail to find the stat.st_rdev information in std::filesystem::status. I know that the st_rdev field is highly OS dependent and even filesystem specific. It contains the major/minor numbers of block and character devices on UNIX-like systems (Linux, macOS etc).

Question: Do I have to revert to using the C APIs for these (stat() for reading and mknod() for creating) or am I overlooking something in std::filesystem?


问:
Import Error: No Module Name filter error in Anaconda
I'm facing the following problem while running the code. Please help me I am doing this in Anaconda and I have installed all essential libraries.

File "C:\Users\Hanzala Iqbal\Desktop\LSTM-RNN-for-Traffic-Prediction-in-Cellular-Networks-master\ntpa.py", line 36, in
import filters

ModuleNotFoundError: No module named 'filters'

```<code>

I am trying to run the code but "No modul name filter" is occuring
</code>```

Body:
I'm facing the following problem while running the code. Please help me I am doing this in Anaconda and I have installed all essential libraries.

File "C:\Users\Hanzala Iqbal\Desktop\LSTM-RNN-for-Traffic-Prediction-in-Cellular-Networks-master\ntpa.py", line 36, in
import filters

ModuleNotFoundError: No module named 'filters'

I am trying to run the code but "No modul name filter" is occuring


问:
Which standard freedesktop icon should I use as a fallback to represent my application on Linux?
I would like to use one of the standard icons defined in the FreeDesktop Icon Naming Specification to represent my application on Linux desktops.

Is there any generic application icon I should use, or do I pick whatever I believe best represents my app? (i.e. utilities-terminal for terminal utilities, applications-utilities for generic GUI utilities, and so on)

I am not looking for a way to install or use my own custom icons.


问:
How do I add the option to use a P4 switch in Miniedit?
I've been trying to use a P4 switch in mininet/miniedit for quite some time but I haven't been able to do so.
I have p4c, the behaviour-model install and p4-utils installed and I still can't get mininet to recognize the P4 switches as valid switches.

Has anyone stumbled into this problem and knows a solution?

I've tried executing multiple commands, tried multiple examples and I just can't get it to work


问:
How to develop using OpenVSCode and a remote container
I would like to use OpenVSCode for cloud development in a microservices-orianted environment.

I was thinking on the following architecture/setup:

Use K8s as the runtime environment.

OVSC & Dev pods to run using dedicated/separated pods (Not sidecars).

Code sharing is done via NFS, syncthing, etc

The documentation are showcasing a setup of OVSC that operate/run as the Dev pod itself. While running as described above (IDE & Dev pods running on a separated pod), I noticed that dev-related libraries/missing (e.g. Golang packages) are not available as they are installed on the dev pod, etc:

Q:

What is needed in order to support such a setup?

Is it possible to init OVSC in such a way that it will execute commands/open the terminal on a remote container as default?

Thanks!


问:
Date and Time in URL - not working in FireFox
I am using the following datetime format for an URL with DateTime:
...?projectid=10&starttime=2022-12-01t14:10:00z&endtime=2022-12-02t18:10:00z

works fine in every Browser, but FireFox. In FF the time portion is ignored.
Any idea whta might be wrong?

Thanks


问:
Android Focus allows GPS data to upload with picture, Chrome does not
Picture contrasting uploads from different browsers

I'm using the website https://gowomple.com to document a trip I just took. This website extracts the GPS data of the pic you upload, and place a globe at the corner of the frame that you can click to see the spot the pic was taken on google maps. The attached photo has an arrow pointing to the globe, The circle shows the missing globe.

I have a Pixel 6A.

When I use Anderid firefox focus this works fine. When I use Android Chrome it does not. If I use desktop chrome it works. Is there a security setting for Android chrome that sanitizes your picture at upload?

I uploaded a picture using Android chrome and got no globe showing where the pic was taken at. I expected to see a globe. Android Focus worked fine


问:
In Visual Studio Code how do you 'Configure default editor for...' so it's available for 'Select editor for...'?
I have the same question as reddit post "Adding a 'default editor'?" The question surfaces in multiple contexts where Visual Studio Code (VS Code) prompts Select editor for... Perhaps the easiest illustration is when, in the VS Code Explorer, you right click a file and choose Open With... VS Code responds with a dialog that prompts Select editor for... and below that text is a list of editors to choose from. Question is, how do you add editors to that list?

Searching for answers is difficult because the associated terms result in many 'hits' that have nothing to do with this specific question.


问:
M1 Mac g++ use GMP Library error Undefined symbols for architecture arm64 "__ZlsRSoPK12__mpz_struct"
I use gcc with brew on my M1 Mac, But these code can run successfully with clang, but can not linked with g++(Homebrew).

$ g++-12 -v
Using built-in specs.
COLLECT_GCC=g++-12
COLLECT_LTO_WRAPPER=/opt/homebrew/Cellar/gcc/12.2.0/bin/../libexec/gcc/aarch64-apple-darwin21/12/lto-wrapper
Target: aarch64-apple-darwin21
Configured with: ../configure --prefix=/opt/homebrew/opt/gcc --libdir=/opt/homebrew/opt/gcc/lib/gcc/current --disable-nls --enable-checking=release --with-gcc-major-version-only --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-12 --with-gmp=/opt/homebrew/opt/gmp --with-mpfr=/opt/homebrew/opt/mpfr --with-mpc=/opt/homebrew/opt/libmpc --with-isl=/opt/homebrew/opt/isl --with-zstd=/opt/homebrew/opt/zstd --with-pkgversion='Homebrew GCC 12.2.0' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --with-system-zlib --build=aarch64-apple-darwin21 --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 12.2.0 (Homebrew GCC 12.2.0)
```
<p>And My code for GMP:</p>
<pre class="lang-cpp prettyprint-override"><code>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include "gmp.h"
#include "gmpxx.h"

using namespace std;
int main() { // Declare two arbitrary-precision integers
    mpz_t x, y;

    // Initialize the integers
    mpz_init(x);
    mpz_init(y);

    // Set the value of x to 1234567890
    mpz_set_str(x, "1234567890", 10);

    // Set the value of y to 9876543210
    mpz_set_str(y, "9876543210", 10);

    // Declare a third arbitrary-precision integer to store the result
    mpz_t result;
    mpz_init(result);

    // Perform the multiplication
    mpz_mul(result, x, y);

    // Print the result
    std::cout << "Result: " << result << std::endl;

    // Clear the variables to free memory
    mpz_clear(x);
    mpz_clear(y);
    mpz_clear(result);
    return 0;
}

</code>```

Error:

$ g++-12 gmp_test.cpp -lgmpxx -lgmp
Undefined symbols for architecture arm64:
  "__ZlsRSoPK12__mpz_struct", referenced from:
      __Z2t1v in cceShKq0.o
      __ZlsIA1_12__mpz_struct17__gmp_binary_exprI10__gmp_exprIS1_S1_ES4_23__gmp_binary_multipliesEERSoS7_RKS3_IT_T0_E in cceShKq0.o
ld: symbol(s) not found for architecture arm64
collect2: error: ld returned 1 exit status

```

I can run the above code with both llvm clang(with brew) and /usr/bin/clang(with xcode), but cannot run with g++, and I don't not why!

Body:
I use gcc with brew on my M1 Mac, But these code can run successfully with clang, but can not linked with g++(Homebrew).

$ g++-12 -v
Using built-in specs.
COLLECT_GCC=g++-12
COLLECT_LTO_WRAPPER=/opt/homebrew/Cellar/gcc/12.2.0/bin/../libexec/gcc/aarch64-apple-darwin21/12/lto-wrapper
Target: aarch64-apple-darwin21
Configured with: ../configure --prefix=/opt/homebrew/opt/gcc --libdir=/opt/homebrew/opt/gcc/lib/gcc/current --disable-nls --enable-checking=release --with-gcc-major-version-only --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-12 --with-gmp=/opt/homebrew/opt/gmp --with-mpfr=/opt/homebrew/opt/mpfr --with-mpc=/opt/homebrew/opt/libmpc --with-isl=/opt/homebrew/opt/isl --with-zstd=/opt/homebrew/opt/zstd --with-pkgversion='Homebrew GCC 12.2.0' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --with-system-zlib --build=aarch64-apple-darwin21 --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 12.2.0 (Homebrew GCC 12.2.0)

And My code for GMP:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include "gmp.h"
#include "gmpxx.h"

using namespace std;
int main() { // Declare two arbitrary-precision integers
    mpz_t x, y;

    // Initialize the integers
    mpz_init(x);
    mpz_init(y);

    // Set the value of x to 1234567890
    mpz_set_str(x, "1234567890", 10);

    // Set the value of y to 9876543210
    mpz_set_str(y, "9876543210", 10);

    // Declare a third arbitrary-precision integer to store the result
    mpz_t result;
    mpz_init(result);

    // Perform the multiplication
    mpz_mul(result, x, y);

    // Print the result
    std::cout << "Result: " << result << std::endl;

    // Clear the variables to free memory
    mpz_clear(x);
    mpz_clear(y);
    mpz_clear(result);
    return 0;
}

Error:

$ g++-12 gmp_test.cpp -lgmpxx -lgmp
Undefined symbols for architecture arm64:
  "__ZlsRSoPK12__mpz_struct", referenced from:
      __Z2t1v in cceShKq0.o
      __ZlsIA1_12__mpz_struct17__gmp_binary_exprI10__gmp_exprIS1_S1_ES4_23__gmp_binary_multipliesEERSoS7_RKS3_IT_T0_E in cceShKq0.o
ld: symbol(s) not found for architecture arm64
collect2: error: ld returned 1 exit status

I can run the above code with both llvm clang(with brew) and /usr/bin/clang(with xcode), but cannot run with g++, and I don't not why!


问:
python dataframe conver to json and more info
Please help me to solve my issue..I am trying to convert my dataframe to json and adding outer json.

```<code>technologies = {
    'rid':[1000208,1000209,11111],
    'num' :[1,2,3],
    'cid':[10002,10003,10000]
              }
df = pd.DataFrame(technologies)
print(df)
json_res=df.to_json(orient="records")
print(json_res)
</code>```

[{"rid":1000208,"num":1,"cid":10002},{"rid":1000209,"num":2,"cid":10003},{"rid":11111,"num":3,"cid":10000}]

...
Just want to add keyword
key_word = "report_result"
expect result
[{"report_result" : [{"rid":1000208,"num":1,"cid":10002},{"rid":1000209,"num":2,"cid":10003},{"rid":11111,"num":3,"cid":10000}]}]

Body:
Please help me to solve my issue..I am trying to convert my dataframe to json and adding outer json.

technologies = {
    'rid':[1000208,1000209,11111],
    'num' :[1,2,3],
    'cid':[10002,10003,10000]
              }
df = pd.DataFrame(technologies)
print(df)
json_res=df.to_json(orient="records")
print(json_res)

[{"rid":1000208,"num":1,"cid":10002},{"rid":1000209,"num":2,"cid":10003},{"rid":11111,"num":3,"cid":10000}]

...
Just want to add keyword
key_word = "report_result"
expect result
[{"report_result" : [{"rid":1000208,"num":1,"cid":10002},{"rid":1000209,"num":2,"cid":10003},{"rid":11111,"num":3,"cid":10000}]}]


问:
Reading temperature of CPU cores using C++ on linux
I'm working on an application that can print the usage of each CPU core using C++ by reading proc/stat and parsing it, but I'm having problem with getting temperature, the problem is that different applications show we different amount of CPU cores. when I launch system monitor it shows me 12 cores, btop also shows me 12 cores same as my stat/proc. but when I'm using something like sensors to get temperature it shows temperature for only 6 cores, same thing for /sys/devices/platform/coretemp.0/hwmon/hwmon2/ it shows me temperature only for 6 cores. I don't know where's the problem, how am I supposed to get temperature of all 12 cores? I tried looking at btop source code because it displays temperature for all 12 cores, the problem is that I am terrible at reading source code so I weren't able to find anything useful :(.


问:
Karate drag and drop UI challange
a part of my Karate UI test is to select date range on calendar element. I was trying all possible ways, but unfortunatelly I'm failing with that.
The calendar is pretty the same solution as on this site: https://automationintesting.online/ (you need to select "Book this room" and then the calendar shows up).

This is a scenario I wrote:

```<code>Scenario: Calendar drag&drop
Given driver 'https://automationintesting.online/'
And click("//button[text()='Book this room']")
And input("//input[@name='firstname']", "John")
And input("//input[@name='lastname']", "Doe")
And input("//input[@name='email']", "john@email.com")
And input("//input[@name='phone']", "00123456789")
And click("//button[text()='Next']")
And mouse().move("//button[text()='04']").down().move("//button[text()='05']").up()
Then click("//button[text()='Book']")
</code>```

I also tried the solution suggested in this thread Karate UI drag and drop
so for example:

```<code>* script("var myDragEvent = new Event('dragstart'); myDragEvent.dataTransfer = new DataTransfer()")
* waitFor("//button[text()='08']").script("_.dispatchEvent(myDragEvent)")
* script("var myDropEvent = new Event('drop'); myDropEvent.dataTransfer = myDragEvent.dataTransfer")
* script("//button[text()='09']", "_.dispatchEvent(myDropEvent)")
</code>```

but it also didn't work.

Could anybody help me here?

Title: Karate drag and drop UI challange

Body:
a part of my Karate UI test is to select date range on calendar element. I was trying all possible ways, but unfortunatelly I'm failing with that.
The calendar is pretty the same solution as on this site: https://automationintesting.online/ (you need to select "Book this room" and then the calendar shows up).

This is a scenario I wrote:

Scenario: Calendar drag&drop
Given driver 'https://automationintesting.online/'
And click("//button[text()='Book this room']")
And input("//input[@name='firstname']", "John")
And input("//input[@name='lastname']", "Doe")
And input("//input[@name='email']", "john@email.com")
And input("//input[@name='phone']", "00123456789")
And click("//button[text()='Next']")
And mouse().move("//button[text()='04']").down().move("//button[text()='05']").up()
Then click("//button[text()='Book']")

I also tried the solution suggested in this thread Karate UI drag and drop
so for example:

* script("var myDragEvent = new Event('dragstart'); myDragEvent.dataTransfer = new DataTransfer()")
* waitFor("//button[text()='08']").script("_.dispatchEvent(myDragEvent)")
* script("var myDropEvent = new Event('drop'); myDropEvent.dataTransfer = myDragEvent.dataTransfer")
* script("//button[text()='09']", "_.dispatchEvent(myDropEvent)")

but it also didn't work.

Could anybody help me here?


问:
Return a Calculated Field from a Cross-Join Query
I am using sp_addlinkedsrvlogin to execute a cross-join query on two different SQL Servers (our payroll server and our production server).  The first query returns how many hours each employee logged on the time clock (payroll server).  The second query returns how many hours that same employee was logged into work orders.

I would like to create a calculated column called Employee_Utilization that divides WO_Hours by Payroll_Hours.  Any tips on how to do this in this Cross Join query would be great.

```<code>EXEC sp_addlinkedsrvlogin 'PAYROLLSERVER', 'false', NULL, '**', '**********'
SELECT * FROM
(
    SELECT
        C.EMPLOYEE AS [Employee ID]
        ,E.FIRSTNAME
        ,E.LASTNAME
        ,C.[PEREND]
        ,C.[CATEGORY]
        ,C.[AUDTORG]
        ,C.[EARDEDTYPE]
        ,C.[EARDEDDATE]
        ,SUM(DISTINCT C.[HOURS]) AS [Payroll_Hours]
    FROM [PAYROLLSERVER].[SagePayroll].[dbo].[UPCHKD] C JOIN [PAYROLLSERVER01].[SagePayroll_SUD].[dbo].[UPHHAU] E ON C.EMPLOYEE = E.EMPLOYEE
    WHERE C.CATEGORY = '2' AND C.PEREND = '20221210'
    GROUP BY
        C.EMPLOYEE
        ,E.FIRSTNAME
        ,E.LASTNAME
        ,C.[PEREND]
        ,C.[CATEGORY]
        ,C.[AUDTORG]
        ,C.[EARDEDTYPE]
        ,C.[EARDEDDATE]
) A
CROSS JOIN
(
     SELECT [Employee ID],SUM([Labor Run Hours]) AS [WO_Hours]
     FROM [********].[*********].[dbo].[WorkOrders_Labor]
     WHERE [Date Worked] > '11/26/22' AND [Date Worked] < '12/11/22'
     GROUP BY [Employee ID]
) B
WHERE A.[Employee ID] = B.[Employee ID]
</code>```

``

Body:
I am using sp_addlinkedsrvlogin to execute a cross-join query on two different SQL Servers (our payroll server and our production server).  The first query returns how many hours each employee logged on the time clock (payroll server).  The second query returns how many hours that same employee was logged into work orders.

I would like to create a calculated column called Employee_Utilization that divides WO_Hours by Payroll_Hours.  Any tips on how to do this in this Cross Join query would be great.

EXEC sp_addlinkedsrvlogin 'PAYROLLSERVER', 'false', NULL, '**', '**********'
SELECT * FROM
(
    SELECT
        C.EMPLOYEE AS [Employee ID]
        ,E.FIRSTNAME
        ,E.LASTNAME
        ,C.[PEREND]
        ,C.[CATEGORY]
        ,C.[AUDTORG]
        ,C.[EARDEDTYPE]
        ,C.[EARDEDDATE]
        ,SUM(DISTINCT C.[HOURS]) AS [Payroll_Hours]
    FROM [PAYROLLSERVER].[SagePayroll].[dbo].[UPCHKD] C JOIN [PAYROLLSERVER01].[SagePayroll_SUD].[dbo].[UPHHAU] E ON C.EMPLOYEE = E.EMPLOYEE
    WHERE C.CATEGORY = '2' AND C.PEREND = '20221210'
    GROUP BY
        C.EMPLOYEE
        ,E.FIRSTNAME
        ,E.LASTNAME
        ,C.[PEREND]
        ,C.[CATEGORY]
        ,C.[AUDTORG]
        ,C.[EARDEDTYPE]
        ,C.[EARDEDDATE]
) A
CROSS JOIN
(
     SELECT [Employee ID],SUM([Labor Run Hours]) AS [WO_Hours]
     FROM [********].[*********].[dbo].[WorkOrders_Labor]
     WHERE [Date Worked] > '11/26/22' AND [Date Worked] < '12/11/22'
     GROUP BY [Employee ID]
) B
WHERE A.[Employee ID] = B.[Employee ID]

``


问:
i had the error Py4JJavaError: An error occurred while calling o65.showString in pyspark
i am trying to implement this code using:

python 3.9

spark-3.3.1-bin-hadoop3 included pyspark

java 1.8.0_171

the paths is alright and i am running other codes on jupyter but i didn't find any answer related to the error Py4JJavaError: An error occurred while calling o65.showString

note: my spark contains spark-sql_2.12-3.3.1 and graphframes-0.8.2-spark3.2-s_2.12 jar files and thats mean the same version of scala 2.12

```<code>from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark import SparkContext

sc = SparkContext()
sc.addPyFile('C:\Program Files\spark-3.3.1-bin-hadoop3\jars\graphframes-0.8.2-spark3.2-s_2.12.jar')
sqlc = SQLContext(sc)
# Create a Vertex DataFrame with unique ID column "id"
v = sqlc.createDataFrame([
  ("a", "Alice", 34),
  ("b", "Bob", 36),
  ("c", "Charlie", 30),
], ["id", "name", "age"])
# Create an Edge DataFrame with "src" and "dst" columns
e = sqlc.createDataFrame([
  ("a", "b", "friend"),
  ("b", "c", "follow"),
  ("c", "b", "follow"),
], ["src", "dst", "relationship"])
# Create a GraphFrame
from graphframes import *
g = GraphFrame(v, e)

# Query: Get in-degree of each vertex.
g.inDegrees.show()

# Query: Count the number of "follow" connections in the graph.
g.edges.filter("relationship = 'follow'").count()

# Run PageRank algorithm, and show results.
results = g.pageRank(resetProbability=0.01, maxIter=20)
results.vertices.select("id", "pagerank").show()
</code>```

i hope some one help to fix the error

Body:
i am trying to implement this code using:

python 3.9

spark-3.3.1-bin-hadoop3 included pyspark

java 1.8.0_171

the paths is alright and i am running other codes on jupyter but i didn't find any answer related to the error Py4JJavaError: An error occurred while calling o65.showString

note: my spark contains spark-sql_2.12-3.3.1 and graphframes-0.8.2-spark3.2-s_2.12 jar files and thats mean the same version of scala 2.12

from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark import SparkContext

sc = SparkContext()
sc.addPyFile('C:\Program Files\spark-3.3.1-bin-hadoop3\jars\graphframes-0.8.2-spark3.2-s_2.12.jar')
sqlc = SQLContext(sc)
# Create a Vertex DataFrame with unique ID column "id"
v = sqlc.createDataFrame([
  ("a", "Alice", 34),
  ("b", "Bob", 36),
  ("c", "Charlie", 30),
], ["id", "name", "age"])
# Create an Edge DataFrame with "src" and "dst" columns
e = sqlc.createDataFrame([
  ("a", "b", "friend"),
  ("b", "c", "follow"),
  ("c", "b", "follow"),
], ["src", "dst", "relationship"])
# Create a GraphFrame
from graphframes import *
g = GraphFrame(v, e)

# Query: Get in-degree of each vertex.
g.inDegrees.show()

# Query: Count the number of "follow" connections in the graph.
g.edges.filter("relationship = 'follow'").count()

# Run PageRank algorithm, and show results.
results = g.pageRank(resetProbability=0.01, maxIter=20)
results.vertices.select("id", "pagerank").show()

i hope some one help to fix the error


问:
Unable to return DOM nodes from evaluate with querySelectorAll() in Puppeteer
When I execute the same querySelectorAll() on the same page but in diff envs:

Chrome Dev Tools

Puppeteer on NodeJS

then I get different objects.

On Chrome Dev Tools I call:

```<code>var elems = document.querySelectorAll("#someId > tr > td")
</code>```

then I get a NodeList object like here:

```<code>NodeList(4) [td.tcat, td.trow, td.trow, td.trow]
</code>```

And it's OK.

On NodeJS with Puppeteer I call:

```<code>...
await page.goto("http://localhost:8080/")
const elems = await page.evaluate(() => {
  return document.querySelectorAll("#someId > tr > td")
})
...
</code>```

then I get a bad object with 4x empty objects inside, like this:

```<code>console.log(JSON.stringify(elems))
{"0":{},"1":{},"2":{},"3":{}}
</code>```

Any idea what I did wrong?

Body:
When I execute the same querySelectorAll() on the same page but in diff envs:

Chrome Dev Tools

Puppeteer on NodeJS

then I get different objects.

On Chrome Dev Tools I call:

var elems = document.querySelectorAll("#someId > tr > td")

then I get a NodeList object like here:

NodeList(4) [td.tcat, td.trow, td.trow, td.trow]

And it's OK.

On NodeJS with Puppeteer I call:

...
await page.goto("http://localhost:8080/")
const elems = await page.evaluate(() => {
  return document.querySelectorAll("#someId > tr > td")
})
...

then I get a bad object with 4x empty objects inside, like this:

console.log(JSON.stringify(elems))
{"0":{},"1":{},"2":{},"3":{}}

Any idea what I did wrong?


问:
When should I put a `requires` clause in a template function's signature instead of before it?
In C++20 you can add a requires clause (1) after a template parameter list as well as (2) after a function declaration (like a specifier). In the following snippet foo is an example of (1) and bar is an example of (2).

```<code>#include <type_traits>

template <typename T>
  requires std::is_integral_v<T>
bool foo(T x) {
  return x > 0;
}

template <typename T>
bool foo(T x) {
  return false;
}

template <typename T>
bool bar(T x)
  requires std::is_integral_v<T>
{
  return x > 0;
}

template <typename T>
bool bar(T x) {
  return false;
}
</code>```

How is overload resolution going to differ between functions like foo and functions like bar? Is there any difference?

Body:
In C++20 you can add a requires clause (1) after a template parameter list as well as (2) after a function declaration (like a specifier). In the following snippet foo is an example of (1) and bar is an example of (2).

#include <type_traits>

template <typename T>
  requires std::is_integral_v<T>
bool foo(T x) {
  return x > 0;
}

template <typename T>
bool foo(T x) {
  return false;
}

template <typename T>
bool bar(T x)
  requires std::is_integral_v<T>
{
  return x > 0;
}

template <typename T>
bool bar(T x) {
  return false;
}

How is overload resolution going to differ between functions like foo and functions like bar? Is there any difference?