问:
Compiling kernel for Android (Moto E3 Power) fails with "output directory .../tools/tools/ does not exist"
I want my phone kernel to support the CH341 driver, so I made changes in the configuration as CONFIG_USB_SERIAL=y and CONFIG_USB_SERIAL_CH341=y. Then I followed this guide
to compile the kernel, but I'm getting the following issue:

```<code>ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ export ARCH=arm
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ SUBARCH=arm
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ export CROSS_COMPILE=/home/ercin/Downloads/arm-eabi-4.8-toolchain-master/bin/arm-eabi-
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ make clean && make mrproper
drivers/misc/mediatek/ext_disp/common/test/Makefile:46: "lwlwlw"
*MTK_GPU_VERSION 1 =
$CONFIG_MTK_GPU_COMMON_DVFS_SUPPORT is []
drivers/misc/mediatek/secwidevine/classicdrm/Makefile:6: "custom build secwidevine"
"custom build secwidevinemdw"
"CONFIG_MICROTRUST_TEE_SUPPORT="
"CONFIG_MICROTRUST_TZ_DRIVER="
"CONFIG_MICROTRUST_VFS_DRIVER="
"CONFIG_MICROTRUST_FP_DRIVER="
drivers/misc/mediatek/ext_disp/common/test/Makefile:46: "lwlwlw"
*MTK_GPU_VERSION 1 =
$CONFIG_MTK_GPU_COMMON_DVFS_SUPPORT is []
drivers/misc/mediatek/secwidevine/classicdrm/Makefile:6: "custom build secwidevine"
"custom build secwidevinemdw"
"CONFIG_MICROTRUST_TEE_SUPPORT="
"CONFIG_MICROTRUST_TZ_DRIVER="
"CONFIG_MICROTRUST_VFS_DRIVER="
"CONFIG_MICROTRUST_FP_DRIVER="
  CLEAN   scripts/basic
  CLEAN   scripts/kconfig
  CLEAN   include/config include/generated
  CLEAN   .config
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ make lineageos_taido_defconfig
  HOSTCC  scripts/basic/fixdep
  HOSTCC  scripts/kconfig/conf.o
  SHIPPED scripts/kconfig/zconf.tab.c
  SHIPPED scripts/kconfig/zconf.lex.c
  SHIPPED scripts/kconfig/zconf.hash.c
  HOSTCC  scripts/kconfig/zconf.tab.o
  HOSTLD  scripts/kconfig/conf
warning: (ARCH_REQUIRE_GPIOLIB && PINCTRL_AT91 && PINCTRL_MTK_COMMON && PINCTRL_NOMADIK && MFD_TC6393XB && FB_VIA) selects GPIOLIB which has unmet direct dependencies (ARCH_WANT_OPTIONAL_GPIOLIB || ARCH_REQUIRE_GPIOLIB)
warning: (ARCH_REQUIRE_GPIOLIB && PINCTRL_AT91 && PINCTRL_MTK_COMMON && PINCTRL_NOMADIK && MFD_TC6393XB && FB_VIA) selects GPIOLIB which has unmet direct dependencies (ARCH_WANT_OPTIONAL_GPIOLIB || ARCH_REQUIRE_GPIOLIB)
#
# configuration written to .config
#
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ make -j$(nproc --all)
scripts/kconfig/conf --silentoldconfig Kconfig
warning: (ARCH_REQUIRE_GPIOLIB && PINCTRL_AT91 && PINCTRL_MTK_COMMON && PINCTRL_NOMADIK && MFD_TC6393XB && FB_VIA) selects GPIOLIB which has unmet direct dependencies (ARCH_WANT_OPTIONAL_GPIOLIB || ARCH_REQUIRE_GPIOLIB)
warning: (ARCH_REQUIRE_GPIOLIB && PINCTRL_AT91 && PINCTRL_MTK_COMMON && PINCTRL_NOMADIK && MFD_TC6393XB && FB_VIA) selects GPIOLIB which has unmet direct dependencies (ARCH_WANT_OPTIONAL_GPIOLIB || ARCH_REQUIRE_GPIOLIB)
  CHK     include/config/kernel.release
  UPD     include/config/kernel.release
/bin/sh: 1: cd: can't cd to /home/ercin/Downloads/android_kernel_motorola_mt6735-cm-14.1/tools/tools/
scripts/Makefile.include:16: *** output directory "/home/ercin/Downloads/android_kernel_motorola_mt6735-cm-14.1/tools/tools/" does not exist.  Stop.
  WRAP    arch/arm/include/generated/asm/auxvec.h
  WRAP    arch/arm/include/generated/asm/bitsperlong.h
make: *** [Makefile:1511: tools/dct/DrvGen] Error 2
make: *** Waiting for unfinished jobs....
  WRAP    arch/arm/include/generated/asm/cputime.h
  WRAP    arch/arm/include/generated/asm/current.h
  WRAP    arch/arm/include/generated/asm/emergency-restart.h
  WRAP    arch/arm/include/generated/asm/errno.h
  WRAP    arch/arm/include/generated/asm/exec.h
  WRAP    arch/arm/include/generated/asm/ioctl.h
  WRAP    arch/arm/include/generated/asm/hash.h
  WRAP    arch/arm/include/generated/asm/ipcbuf.h
  WRAP    arch/arm/include/generated/asm/irq_regs.h
  WRAP    arch/arm/include/generated/asm/local.h
  WRAP    arch/arm/include/generated/asm/local64.h
  WRAP    arch/arm/include/generated/asm/kdebug.h
  WRAP    arch/arm/include/generated/asm/mcs_spinlock.h
  WRAP    arch/arm/include/generated/asm/param.h
  WRAP    arch/arm/include/generated/asm/msgbuf.h
  WRAP    arch/arm/include/generated/asm/parport.h
  WRAP    arch/arm/include/generated/asm/poll.h
  WRAP    arch/arm/include/generated/asm/preempt.h
  WRAP
arch/arm/include/generated/asm/resource.h
  WRAP    arch/arm/include/generated/asm/scatterlist.h
  WRAP    arch/arm/include/generated/asm/sections.h
  WRAP    arch/arm/include/generated/asm/rwsem.h
  WRAP    arch/arm/include/generated/asm/segment.h
  WRAP    arch/arm/include/generated/asm/serial.h
  WRAP    arch/arm/include/generated/asm/shmbuf.h
  WRAP    arch/arm/include/generated/asm/siginfo.h
  WRAP    arch/arm/include/generated/asm/sembuf.h
  WRAP    arch/arm/include/generated/asm/simd.h
  WRAP    arch/arm/include/generated/asm/sizes.h
  WRAP    arch/arm/include/generated/asm/socket.h
  WRAP    arch/arm/include/generated/asm/sockios.h
  WRAP    arch/arm/include/generated/asm/termbits.h
  WRAP    arch/arm/include/generated/asm/termios.h
  WRAP    arch/arm/include/generated/asm/timex.h
  WRAP    arch/arm/include/generated/asm/unaligned.h
  WRAP    arch/arm/include/generated/asm/trace_clock.h
  ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$

</code>```

So how to fix this error?

I tried the 4.8 and 4.9 compilers, but that didn't work.

Body:
I want my phone kernel to support the CH341 driver, so I made changes in the configuration as CONFIG_USB_SERIAL=y and CONFIG_USB_SERIAL_CH341=y. Then I followed this guide
to compile the kernel, but I'm getting the following issue:

ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ export ARCH=arm
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ SUBARCH=arm
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ export CROSS_COMPILE=/home/ercin/Downloads/arm-eabi-4.8-toolchain-master/bin/arm-eabi-
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ make clean && make mrproper
drivers/misc/mediatek/ext_disp/common/test/Makefile:46: "lwlwlw"
*MTK_GPU_VERSION 1 =
$CONFIG_MTK_GPU_COMMON_DVFS_SUPPORT is []
drivers/misc/mediatek/secwidevine/classicdrm/Makefile:6: "custom build secwidevine"
"custom build secwidevinemdw"
"CONFIG_MICROTRUST_TEE_SUPPORT="
"CONFIG_MICROTRUST_TZ_DRIVER="
"CONFIG_MICROTRUST_VFS_DRIVER="
"CONFIG_MICROTRUST_FP_DRIVER="
drivers/misc/mediatek/ext_disp/common/test/Makefile:46: "lwlwlw"
*MTK_GPU_VERSION 1 =
$CONFIG_MTK_GPU_COMMON_DVFS_SUPPORT is []
drivers/misc/mediatek/secwidevine/classicdrm/Makefile:6: "custom build secwidevine"
"custom build secwidevinemdw"
"CONFIG_MICROTRUST_TEE_SUPPORT="
"CONFIG_MICROTRUST_TZ_DRIVER="
"CONFIG_MICROTRUST_VFS_DRIVER="
"CONFIG_MICROTRUST_FP_DRIVER="
  CLEAN   scripts/basic
  CLEAN   scripts/kconfig
  CLEAN   include/config include/generated
  CLEAN   .config
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ make lineageos_taido_defconfig
  HOSTCC  scripts/basic/fixdep
  HOSTCC  scripts/kconfig/conf.o
  SHIPPED scripts/kconfig/zconf.tab.c
  SHIPPED scripts/kconfig/zconf.lex.c
  SHIPPED scripts/kconfig/zconf.hash.c
  HOSTCC  scripts/kconfig/zconf.tab.o
  HOSTLD  scripts/kconfig/conf
warning: (ARCH_REQUIRE_GPIOLIB && PINCTRL_AT91 && PINCTRL_MTK_COMMON && PINCTRL_NOMADIK && MFD_TC6393XB && FB_VIA) selects GPIOLIB which has unmet direct dependencies (ARCH_WANT_OPTIONAL_GPIOLIB || ARCH_REQUIRE_GPIOLIB)
warning: (ARCH_REQUIRE_GPIOLIB && PINCTRL_AT91 && PINCTRL_MTK_COMMON && PINCTRL_NOMADIK && MFD_TC6393XB && FB_VIA) selects GPIOLIB which has unmet direct dependencies (ARCH_WANT_OPTIONAL_GPIOLIB || ARCH_REQUIRE_GPIOLIB)
#
# configuration written to .config
#
ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$ make -j$(nproc --all)
scripts/kconfig/conf --silentoldconfig Kconfig
warning: (ARCH_REQUIRE_GPIOLIB && PINCTRL_AT91 && PINCTRL_MTK_COMMON && PINCTRL_NOMADIK && MFD_TC6393XB && FB_VIA) selects GPIOLIB which has unmet direct dependencies (ARCH_WANT_OPTIONAL_GPIOLIB || ARCH_REQUIRE_GPIOLIB)
warning: (ARCH_REQUIRE_GPIOLIB && PINCTRL_AT91 && PINCTRL_MTK_COMMON && PINCTRL_NOMADIK && MFD_TC6393XB && FB_VIA) selects GPIOLIB which has unmet direct dependencies (ARCH_WANT_OPTIONAL_GPIOLIB || ARCH_REQUIRE_GPIOLIB)
  CHK     include/config/kernel.release
  UPD     include/config/kernel.release
/bin/sh: 1: cd: can't cd to /home/ercin/Downloads/android_kernel_motorola_mt6735-cm-14.1/tools/tools/
scripts/Makefile.include:16: *** output directory "/home/ercin/Downloads/android_kernel_motorola_mt6735-cm-14.1/tools/tools/" does not exist.  Stop.
  WRAP    arch/arm/include/generated/asm/auxvec.h
  WRAP    arch/arm/include/generated/asm/bitsperlong.h
make: *** [Makefile:1511: tools/dct/DrvGen] Error 2
make: *** Waiting for unfinished jobs....
  WRAP    arch/arm/include/generated/asm/cputime.h
  WRAP    arch/arm/include/generated/asm/current.h
  WRAP    arch/arm/include/generated/asm/emergency-restart.h
  WRAP    arch/arm/include/generated/asm/errno.h
  WRAP    arch/arm/include/generated/asm/exec.h
  WRAP    arch/arm/include/generated/asm/ioctl.h
  WRAP    arch/arm/include/generated/asm/hash.h
  WRAP    arch/arm/include/generated/asm/ipcbuf.h
  WRAP    arch/arm/include/generated/asm/irq_regs.h
  WRAP    arch/arm/include/generated/asm/local.h
  WRAP    arch/arm/include/generated/asm/local64.h
  WRAP    arch/arm/include/generated/asm/kdebug.h
  WRAP    arch/arm/include/generated/asm/mcs_spinlock.h
  WRAP    arch/arm/include/generated/asm/param.h
  WRAP    arch/arm/include/generated/asm/msgbuf.h
  WRAP    arch/arm/include/generated/asm/parport.h
  WRAP    arch/arm/include/generated/asm/poll.h
  WRAP    arch/arm/include/generated/asm/preempt.h
  WRAP
arch/arm/include/generated/asm/resource.h
  WRAP    arch/arm/include/generated/asm/scatterlist.h
  WRAP    arch/arm/include/generated/asm/sections.h
  WRAP    arch/arm/include/generated/asm/rwsem.h
  WRAP    arch/arm/include/generated/asm/segment.h
  WRAP    arch/arm/include/generated/asm/serial.h
  WRAP    arch/arm/include/generated/asm/shmbuf.h
  WRAP    arch/arm/include/generated/asm/siginfo.h
  WRAP    arch/arm/include/generated/asm/sembuf.h
  WRAP    arch/arm/include/generated/asm/simd.h
  WRAP    arch/arm/include/generated/asm/sizes.h
  WRAP    arch/arm/include/generated/asm/socket.h
  WRAP    arch/arm/include/generated/asm/sockios.h
  WRAP    arch/arm/include/generated/asm/termbits.h
  WRAP    arch/arm/include/generated/asm/termios.h
  WRAP    arch/arm/include/generated/asm/timex.h
  WRAP    arch/arm/include/generated/asm/unaligned.h
  WRAP    arch/arm/include/generated/asm/trace_clock.h
  ercin@ercin:~/Downloads/android_kernel_motorola_mt6735-cm-14.1$

So how to fix this error?

I tried the 4.8 and 4.9 compilers, but that didn't work.


来源: stackexchange

问:
Powershell slow because of fancy script
I had installed a fancy script from the internet to make my Powershell cool like iterm.
Not only I am unhappy with the user interface now but also PowerShell is too slow now.

How do I configure powershell to not to load this script on load? Where do I find this script on m computer?

ContentLicense: CC BY-SA 4.0

Title: Powershell slow because of fancy script


问:
How to sort and filter the record together in react?
I am using redux to filter the record and usememo for sorting.
Sorting and FIlter are working but separately. Either filter or sorting.

How to filter the record and sort together ?

```<code>const ProductItem = ({ sortDir }) => {
const productData = useSelector((state) => state.appData.value.data);

const sortedRecords = useMemo(
    () =>
      [...productData].sort((a, b) => {

        return sortDir === "lowtohigh" ? a.price - b.price : b.price - a.price;

      }),
    [sortDir]
  );

console.log(Pdata);
const dispatch = useDispatch();
return (
    <>
        <div className="container left-content-border">
            <div className="right-content">
                {
                 productData.map((value, index) => {
                 const { id, pname, product, category, imgscr, price, visible } = value;

                        var linkto = "/details/"+id;
   })
                }
</code>```

if Now filter is working but if I put "sortedRecords" at the place of productData.map then only sorting works. How to perform both operation together?

Body:
I am using redux to filter the record and usememo for sorting.
Sorting and FIlter are working but separately. Either filter or sorting.

How to filter the record and sort together ?

const ProductItem = ({ sortDir }) => {
const productData = useSelector((state) => state.appData.value.data);

const sortedRecords = useMemo(
    () =>
      [...productData].sort((a, b) => {

        return sortDir === "lowtohigh" ? a.price - b.price : b.price - a.price;

      }),
    [sortDir]
  );

console.log(Pdata);
const dispatch = useDispatch();
return (
    <>

                {
                 productData.map((value, index) => {
                 const { id, pname, product, category, imgscr, price, visible } = value;

                        var linkto = "/details/"+id;
   })
                }

if Now filter is working but if I put "sortedRecords" at the place of productData.map then only sorting works. How to perform both operation together?


问:
How to get the file id of uploaded file in telegram bot?
I tried to use the following url to get updates but it only returns all message id.

https://api.telegram.org/bot{token}/getUpdates

I would like to get the file id of all uploaded (existing in Bot chat) files....

Thanks.


问:
Kubernetes Network Policy within Istio Service Mesh
I have my workloads running within a kubernetes cluster (GKE) with Istio Service Mesh. I am trying to isolate my workload  from other namespaces. I just want to allow traffic from same namespace and the istio ingressgateway deployed in istio-system namespace. Here's what I have tried using kubernetes network policy:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-same-ns-network-policy
  namespace: my-app-namespace
spec:
  podSelector: {}
  policyTypes:
    - Ingress
  ingress:
  - from:
    # Allow from all pods from same namespace
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: "my-app-namespace"
      podSelector: {}
    # Allow from all pods from kube-system, may not be required, did this for experiementation
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: "kube-system"
      podSelector: {}
    # Allow from all pods from istio-system, for istio ingressgateway
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: "istio-system"
      podSelector: {}
```

After applying this, connections between my workload and via ingress start timing out.

Initially I was looking at Istio's Authorization Policy to achieve this but it requires strict mtls to support the above and my workloads don't work well with strict mtls atm.

Please help.

Thanks !

Body:
I have my workloads running within a kubernetes cluster (GKE) with Istio Service Mesh. I am trying to isolate my workload  from other namespaces. I just want to allow traffic from same namespace and the istio ingressgateway deployed in istio-system namespace. Here's what I have tried using kubernetes network policy:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-same-ns-network-policy
  namespace: my-app-namespace
spec:
  podSelector: {}
  policyTypes:
    - Ingress
  ingress:
  - from:
    # Allow from all pods from same namespace
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: "my-app-namespace"
      podSelector: {}
    # Allow from all pods from kube-system, may not be required, did this for experiementation
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: "kube-system"
      podSelector: {}
    # Allow from all pods from istio-system, for istio ingressgateway
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: "istio-system"
      podSelector: {}

After applying this, connections between my workload and via ingress start timing out.

Initially I was looking at Istio's Authorization Policy to achieve this but it requires strict mtls to support the above and my workloads don't work well with strict mtls atm.

Please help.

Thanks !


问:
Line chart in Google Sheet does not allow to select a range for Series
I have 3 columns:

A - time

B - temperature

C - temperature

I want a simple Line chart where axis X (horizontal) has the time and vertical one has two lines for each column (B and C)

How to specify data ranges for each line as vertical axis and time as horizontal axis?

Similar question but not answered - How to create a data ranged chart in Google Sheets

The spreadsheet - https://docs.google.com/spreadsheets/d/1ddg0prPHZVQf896bG7OA89lgSLBRXThPNVJNWeMd8Zk/edit?usp=sharing


问:
Bootstrap 5 card group with tiny-slider-2, Card width changing
Im trying to use Bootstrap 5 card group with tiny slider.
Tiny slider changing Bootstrap Card width.
Tiny slider autoWidth and fixedWidth not fixing Card Width.

HTML Code

```<code><div class="card-group" id="slider">
    <div class="card m-3" >
        <img src="image/card1.png" alt="">
        <div class="body">
            <h6 class="card-title text-center m-0">Lorem, ipsum dolor.</h6>
            <p class="card-text text-muted text-center"><small class="">Rs 99999</small></p>
        </div>
    </div>
    <div class="card m-3" >
        <img src="image/card1.png" alt="">
        <div class="body">
            <h6 class="card-title text-center m-0">Lorem, ipsum dolor.</h6>
            <p class="card-text text-muted text-center"><small class="">Rs 99999</small></p>
        </div>
    </div>
    <div class="card m-3" >
        <img src="image/card1.png" alt="">
        <div class="body">
            <h6 class="card-title text-center m-0">Lorem, ipsum dolor.</h6>
            <p class="card-text text-muted text-center"><small class="">Rs 99999</small></p>
        </div>
    </div>
    <div class="card m-3" >
        <img src="image/card1.png" alt="">
        <div class="body">
            <h6 class="card-title text-center m-0">Lorem, ipsum dolor.</h6>
            <p class="card-text text-muted text-center"><small class="">Rs 99999</small></p>
        </div>
    </div>
</div>
</code>```

Tiny Slider

```<code>slider = tns({
  "container": "#slider",
  "nav": false,
  "items": 4,
  "gutter": 10,
  "swipeAngle": false,
  "speed": 400,
});
</code>```

Body:
Im trying to use Bootstrap 5 card group with tiny slider.
Tiny slider changing Bootstrap Card width.
Tiny slider autoWidth and fixedWidth not fixing Card Width.

HTML Code

Lorem, ipsum dolor.

Rs 99999

Lorem, ipsum dolor.

Rs 99999

Lorem, ipsum dolor.

Rs 99999

Lorem, ipsum dolor.

Rs 99999

Tiny Slider

slider = tns({
  "container": "#slider",
  "nav": false,
  "items": 4,
  "gutter": 10,
  "swipeAngle": false,
  "speed": 400,
});


问:
Mocking an async function to return same response more than once during test
I am trying to write a unit test case using xUnit.
I want to test a function (F1) which internally calls 2 functions (F2 & F3) which further calls the same function (F4).

F4 is an async function which I am mocking using Moq. I need to return true from F4 both times its called internally.

```<code>cP.Setup(x => x.F4()).ReturnsAsync(true);
</code>```

I checked with Verify() method, its being called only once.

What can be the solution here...

Body:
I am trying to write a unit test case using xUnit.
I want to test a function (F1) which internally calls 2 functions (F2 & F3) which further calls the same function (F4).

F4 is an async function which I am mocking using Moq. I need to return true from F4 both times its called internally.

cP.Setup(x => x.F4()).ReturnsAsync(true);

I checked with Verify() method, its being called only once.

What can be the solution here...


问:
how would i write a HTML/CSS/JS code that generates a 3d spinning cube?
I've been recently making my own website, and I decided that I want to have a 3d cube effect that would spin around clockwise; I wrote some of the basic codes down but when I am getting to the CSS part the whole construction decides to give up on me and do stuff I did not mean for it to do.

I am fairly new to HTML and CSS, so I don't know everything about this. This is the code I've written so far, a bit of a warning to this is that I do not know how to code in JavaScript.

body {
  background-color: black;
  color: lime;
  font-family: "Courier New";
}

.cube {
  perspective: 800px;
  transform-style: preserve-3d;
  text-align: center;
}

.face {
  position: absolute;
  width: 200px;
  height: 200px;
  border: 2px solid lime;
  box-sizing: border-box;
  font-size: 32px;
  font-weight: bold;
  text-align: center;
  line-height: 200px;
}

.front {
  transform: rotateY(0deg) translateZ(100px);
}

.back {
  transform: rotateY(180deg) translateZ(100px);
}

.top {
  transform: rotateX(90deg) translateZ(100px);
}

.bottom {
  transform: rotateX(-90deg) translateZ(100px);
}

.left {
  transform: rotateY(-90deg) translateZ(100px);
}

.right {
  transform: rotateY(90deg) translateZ(100px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cube">
  <div class="face front">1</div>
  <div class="face back">2</div>
  <div class="face top">3</div>
  <div class="face bottom">4</div>
  <div class="face left">5</div>
  <div class="face right">6</div>
</div></code>```

The biggest problem for me was actually centering the cube, I tried margins and flexbox but I really am not sure what I'm doing wrong. If anyone would be okay with helping me, I would be grateful.

Body:
I've been recently making my own website, and I decided that I want to have a 3d cube effect that would spin around clockwise; I wrote some of the basic codes down but when I am getting to the CSS part the whole construction decides to give up on me and do stuff I did not mean for it to do.

I am fairly new to HTML and CSS, so I don't know everything about this. This is the code I've written so far, a bit of a warning to this is that I do not know how to code in JavaScript.

body {
  background-color: black;
  color: lime;
  font-family: "Courier New";
}

.cube {
  perspective: 800px;
  transform-style: preserve-3d;
  text-align: center;
}

.face {
  position: absolute;
  width: 200px;
  height: 200px;
  border: 2px solid lime;
  box-sizing: border-box;
  font-size: 32px;
  font-weight: bold;
  text-align: center;
  line-height: 200px;
}

.front {
  transform: rotateY(0deg) translateZ(100px);
}

.back {
  transform: rotateY(180deg) translateZ(100px);
}

.top {
  transform: rotateX(90deg) translateZ(100px);
}

.bottom {
  transform: rotateX(-90deg) translateZ(100px);
}

.left {
  transform: rotateY(-90deg) translateZ(100px);
}

.right {
  transform: rotateY(90deg) translateZ(100px);
}

1

2

3

4

5

6

The biggest problem for me was actually centering the cube, I tried margins and flexbox but I really am not sure what I'm doing wrong. If anyone would be okay with helping me, I would be grateful.


问:
magento shipping collectRates method $request->getDestRegionId() is empty value on estimate-shipping-methods-by-address-id
shipping collectRates method RateRequest class method of $request->getDestRegionId() is returning an empty value on estimate-shipping-methods-by-address-id, but same working well on estimate-shipping-methods

/V1/carts/mine/estimate-shipping-methods-by-address-id

from above API call in checkout $request->getDestRegionId() or $request->getDestRegionCode() is not working as expected.

```<code>public function collectRates(RateRequest $request)
 {
 if (!$this->getConfigFlag('active')) {
 return false;
     }

     /** @var Magento\Shipping\Model\Rate\Result $result */
     $result = $this->_rateResultFactory-create();

     /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
     $method = $this->_rateMethodFactory-create();

     $method->setCarrier($this->_code);
     $method->setCarrierTitle($this-getConfigData('title'));

     $method->setMethod($this->_code);
     $method->setMethodTitle($this-getConfigData('name'));

     $amount = $this->getShippingPrice();

     $method->setPrice($amount);
     $method->setCost($amount);

     $region     = ($request->getDestRegionId() !== null) ? $this-getStateNameByRegionID($request-getDestRegionId()) : $request-getDestRegionCode();

     $result->append($method);

 return $result;
 }
</code>```

Expecting same result like estimate-shipping-methods

Body:
shipping collectRates method RateRequest class method of $request->getDestRegionId() is returning an empty value on estimate-shipping-methods-by-address-id, but same working well on estimate-shipping-methods

/V1/carts/mine/estimate-shipping-methods-by-address-id

from above API call in checkout $request->getDestRegionId() or $request->getDestRegionCode() is not working as expected.

public function collectRates(RateRequest $request)
 {
 if (!$this->getConfigFlag('active')) {
 return false;
     }

     /** @var Magento\Shipping\Model\Rate\Result $result */
     $result = $this->_rateResultFactory-create();

     /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
     $method = $this->_rateMethodFactory-create();

     $method->setCarrier($this->_code);
     $method->setCarrierTitle($this-getConfigData('title'));

     $method->setMethod($this->_code);
     $method->setMethodTitle($this-getConfigData('name'));

     $amount = $this->getShippingPrice();

     $method->setPrice($amount);
     $method->setCost($amount);

     $region     = ($request->getDestRegionId() !== null) ? $this-getStateNameByRegionID($request-getDestRegionId()) : $request-getDestRegionCode();

     $result->append($method);

 return $result;
 }

Expecting same result like estimate-shipping-methods


问:
Ping external service using Grafana ( Loki, Prometheus)
I have two questions about Grafana, Loki, Prometheus:

Is it possible to ping an external services and have a visual preview for it?

How I can check if FTP from APP to FTP is established and active?


问:
What is this S.android.intent.extra.TEXT in the application schema
can anyone help me understand this S.android.intent.extra.TEXT What is this S.android.intent.extra.TEXT where are they?

intent:#Intent;action=android.intent.action.SEND;type=text/plain;S.android.intent.extra.TEXT={Share%20Text};S.android.intent.extra.SUBJECT=Amazing;S.browser_fallback_url=;end

I spent hours and still can't find this S.android.intent.extra.TEXT explanation

What is this S.android.intent why do they use the 'S' character


问:
In VS 2022 settings for sending e-mail with php
In VS 2022, I have built a simple html contact form linking to a php file to send an e-mail. There is no error returned by “mail($to,$subject,$message,$headers);”  but the mail does not get dispatchted. I have devsense PHP tools installed and the php.ini file is C:\Program Files\IIS Express\PHP\v8.1\php.ini.

Windows 11 pro, 22H2, IIS 10.0.22621

Principally I am confident that the code with input from previous stackoverflow contributions is fine. The code runs successfully on notepad++ with the Apache Xampp server and my google account. In php.ini I have set

```<code>smtp_server = smtp.gmail.com
smt_port = 587
sendmail_from = me@example.com
sendmail_path ="\"C:\xampp\sendmail\sendmail.exe\" -t"
</code>```

Accordingly, I have used these settings also in C:\Program Files\IIS Express\PHP\v8.1\php.ini. This ini file is now diverting to the sendmail.exe in my xampp/sendmail folder, but this seems not be correct for VS 2022. Any idea which settings to be made under VS 2022 and where to get the e-mail function working?

Body:
In VS 2022, I have built a simple html contact form linking to a php file to send an e-mail. There is no error returned by “mail($to,$subject,$message,$headers);”  but the mail does not get dispatchted. I have devsense PHP tools installed and the php.ini file is C:\Program Files\IIS Express\PHP\v8.1\php.ini.

Windows 11 pro, 22H2, IIS 10.0.22621

Principally I am confident that the code with input from previous stackoverflow contributions is fine. The code runs successfully on notepad++ with the Apache Xampp server and my google account. In php.ini I have set

smtp_server = smtp.gmail.com
smt_port = 587
sendmail_from = me@example.com
sendmail_path ="\"C:\xampp\sendmail\sendmail.exe\" -t"

Accordingly, I have used these settings also in C:\Program Files\IIS Express\PHP\v8.1\php.ini. This ini file is now diverting to the sendmail.exe in my xampp/sendmail folder, but this seems not be correct for VS 2022. Any idea which settings to be made under VS 2022 and where to get the e-mail function working?


问:
Configure Simple-Peer for better streaming quality
I'm using simple-peer to send a 1080 video stream from one tab to another tab on the same computer. And the receiver's video quality is not as good as sender's and the resolution is also bad.

How can I improve the quality of webrtc video stream and make it consistent all the time?

One option I know is to edit the SDP (Session Description Protocol). I would be helpful if someone can give example of a good SDP to always keep the video quality good and consistent


问:
Plotting columns of "yes" and "no" data in R
I am trying to learn R from a textbook and the data I am using is called College.csv, and it is found here.

The question from the textbook is

use the plot function to produce side-by-side boxplots of Outside versus Private.

I have tried

```<code>plot(college[,1], college[,9])
</code>```

but I get a blank window along with some messages:

1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion

2: In min(x) : no non-missing arguments to min; returning Inf

3: In max(x) : no non-missing arguments to max; returning -Inf

Body:
I am trying to learn R from a textbook and the data I am using is called College.csv, and it is found here.

The question from the textbook is

use the plot function to produce side-by-side boxplots of Outside versus Private.

I have tried

plot(college[,1], college[,9])

but I get a blank window along with some messages:

1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion

2: In min(x) : no non-missing arguments to min; returning Inf

3: In max(x) : no non-missing arguments to max; returning -Inf


问:
Load and save GIF file by Glide in Jetpack Compose
Hi everyone I'm trying to save gif file locally in my storage from a Uri by glide.

I've been tried some code like below one but it didn't work,

And all I get is class com.bumptech.glide.load.engine.GlideException: Failed to load resource

...

fun saveGifLocally(ctx: Context, gifUri: Uri, path: String) {
    viewModelScope.launch(Dispatchers.IO) {

        val bytes = Glide.with(ctx)
            .load(gifUri)
            .into(250, 250)
            .get()
            .toBitmap()
            .byteCount

        val file = File(path)

        FileOutputStream(file).use {
            it.write(bytes)
            it.flush()
        }
    }
}

...
```
<pre class="lang-kotlin prettyprint-override"><code>...

val ctx = LocalContext.current

saveGifLocally(ctx,Uri.parse("https://media.giphy.com/media/26tn6t51nYZDwNIqI/giphy.gif"),"internalPath/test.gif")

...
</code>```

Body:
Hi everyone I'm trying to save gif file locally in my storage from a Uri by glide.

I've been tried some code like below one but it didn't work,

And all I get is class com.bumptech.glide.load.engine.GlideException: Failed to load resource

...

fun saveGifLocally(ctx: Context, gifUri: Uri, path: String) {
    viewModelScope.launch(Dispatchers.IO) {

        val bytes = Glide.with(ctx)
            .load(gifUri)
            .into(250, 250)
            .get()
            .toBitmap()
            .byteCount

        val file = File(path)

        FileOutputStream(file).use {
            it.write(bytes)
            it.flush()
        }
    }
}

...

...

val ctx = LocalContext.current

saveGifLocally(ctx,Uri.parse("https://media.giphy.com/media/26tn6t51nYZDwNIqI/giphy.gif"),"internalPath/test.gif")

...


问:
Automatic Duplicate file created .~db.json, Inserted contacts not fetching
I've setup JSON server in root folder, while adding a new contact JSON server automatically creating .~db.json file, once closing server and restarting inserted contacts are not showing.

to communicate with json server ( GET / POST )

```<code>import axios from "axios";

export class ContactService {
  static ServerUrl = "http://localhost:2999";

  static getAllContacts() {
    let dataUrl = `${this.ServerUrl}/contacts`;

    return axios.get(dataUrl);
  }

  static getContact(_id) {
    let dataUrl = `${this.ServerUrl}/contacts/${_id}`;
    return axios.get(dataUrl);
  }

  static getGroups() {
    let dataUrl = `${this.ServerUrl}/groups`;
    return axios.get(dataUrl);
  }

  static getGroup(contact) {
    // console.log(contact)
    let dataUrl = `${this.ServerUrl}/groups/${contact.groupId}`;
    return axios.get(dataUrl);
  }

  static createContact (contact) {
    let dataUrl = `${this.ServerUrl}/contacts`;
    return axios.post(dataUrl, contact);
  }
}

```

After restarting json server old data fetching into project.

I've Deleted .~db.json, once new content inserted it was automatically creating.
```

Body:
I've setup JSON server in root folder, while adding a new contact JSON server automatically creating .~db.json file, once closing server and restarting inserted contacts are not showing.

to communicate with json server ( GET / POST )

import axios from "axios";

export class ContactService {
  static ServerUrl = "http://localhost:2999";

  static getAllContacts() {
    let dataUrl = `${this.ServerUrl}/contacts`;

    return axios.get(dataUrl);
  }

  static getContact(_id) {
    let dataUrl = `${this.ServerUrl}/contacts/${_id}`;
    return axios.get(dataUrl);
  }

  static getGroups() {
    let dataUrl = `${this.ServerUrl}/groups`;
    return axios.get(dataUrl);
  }

  static getGroup(contact) {
    // console.log(contact)
    let dataUrl = `${this.ServerUrl}/groups/${contact.groupId}`;
    return axios.get(dataUrl);
  }

  static createContact (contact) {
    let dataUrl = `${this.ServerUrl}/contacts`;
    return axios.post(dataUrl, contact);
  }
}

```

After restarting json server old data fetching into project.

I've Deleted .~db.json, once new content inserted it was automatically creating.


问:
same shared memory zone not working for multiple upstream in nginx-plus
while doing nginx plus upstream configuration, we are seeing one issue where we configured same shared memory zone under multiple upstream with different hosts in state file.
One thing we observed that, if zone is same for different upstream  having different hosts, its not working and right away we are seeing 404 page not found error.

Upstream config as below:

Location tab as below:

If I configure same zone shared memory for group3 as "shared_memory_zone" , our application is throwing 404 error and if we change it to some other value, we see 200 response coming from backend with valid response.

can someone please assist how can we use same shared memory zone in all stream? Any help guidance will be appreciated.


问:
Iterator (index) in VUE each function
How can I modify this function, so I will have index (iterator) in there?

```<code>attach: function (context, settings) {
  $(document, context).once('vue__comparison_training').each(() => {
    Vue.component('training', {
      template: this.template,
      props: ['item', 'user_count'],
      data() {
        return {
          details: false,
          participants: false,
          productId: false,
          variant: false,
          prices: false,
          inComparison: false,
        }
      },
</code>```

I tried for example this modification, it doesn't work, but it doesn't give any errors either:

```<code>attach: function (context, settings) {
  $(document, context).once('vue__comparison_training').each((index) => {
    Vue.component('training', {
      template: this.template,
      props: ['item', 'user_count', 'index'],
      data() {
        return {
          details: false,
          participants: false,
          productId: false,
          variant: false,
          prices: false,
          inComparison: false,
        }
      },
</code>```

Title: Iterator (index) in VUE each function

Body:
How can I modify this function, so I will have index (iterator) in there?

attach: function (context, settings) {
  $(document, context).once('vue__comparison_training').each(() => {
    Vue.component('training', {
      template: this.template,
      props: ['item', 'user_count'],
      data() {
        return {
          details: false,
          participants: false,
          productId: false,
          variant: false,
          prices: false,
          inComparison: false,
        }
      },

I tried for example this modification, it doesn't work, but it doesn't give any errors either:

attach: function (context, settings) {
  $(document, context).once('vue__comparison_training').each((index) => {
    Vue.component('training', {
      template: this.template,
      props: ['item', 'user_count', 'index'],
      data() {
        return {
          details: false,
          participants: false,
          productId: false,
          variant: false,
          prices: false,
          inComparison: false,
        }
      },


问:
Output data to abuffersrc and pull from abuffersink with multiple inputs using FFMPEG afir filter
I want to understand why av_buffersink_get_frame() always return AVERROR(EAGAIN).
I use this algorithm:

Open input file input.mp3, create decoder for input file

Open signal file signal.wav, create decoder for signal file

Create filter graph and inputs/outputs with function avfilter_graph_parse2("[in0][in1]afir[out], &inputs, &outputs")

Create abuffersrc for every inputs with names "in0", "in1"

Create one abuffersink for one outputs with name "out"

Read and decode samples with methods av_read_frame(), avcodec_send_packet(), avcodec_receive_frame(), put samples to abuffersrc with av_buffersrc_add_frame() and trying to read samples from abuffersink with av_buffersink_get_frame() - HERE I get AVERROR(EAGAIN) for every call

Please, help!

I've tried to read all samples and push its to abuffersrc for input and signal pipes in first step and and call av_buffersink_get_frame one time in second step. I got AVERROR(EGAIN) again.

I've tried to config two outputs with names "in0" and "in1" and one input with name "out" and call avfilter_graph_parse_ptr() as done in here:

```<code>static AVFilterContext *init_buffersrc(AVCodecContext *decoder, AVFilterGraph *filter_graph, const char *pad_name) {
    AVFilterContext *buffersrc = NULL;
    uint8_t args[1024];

    snprintf(args, sizeof(args),
        "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64"",
        decoder->time_base.num, decoder->time_base.den, decoder->sample_rate, av_get_sample_fmt_name(decoder->sample_fmt), decoder->channel_layout);

    CHECK_AV(avfilter_graph_create_filter(&buffersrc, avfilter_get_by_name("abuffer"), pad_name, args, NULL, filter_graph));
    return buffersrc;
}

static AVFilterContext *init_buffersink(AVFilterGraph *filter_graph) {
    AVFilterContext *buffersink = NULL;

    CHECK_AV(avfilter_graph_create_filter(&buffersink, avfilter_get_by_name("abuffersink"), "out", NULL, NULL, filter_graph));
    return buffersink;
}

static void init_complex_graph(const char *desc, Context *ctx) {

    AVFilterGraph *filter_graph;
    AVFilterInOut *inputs = avfilter_inout_alloc();
    AVFilterInOut **outputs = (AVFilterInOut**) av_malloc(ctx->nb_input_files*sizeof(AVFilterInOut *));
    char *dump;
    uint8_t pad_name[64];

    filter_graph = ctx->filter_graph = avfilter_graph_alloc();
    filter_graph->nb_threads = 1;

    for (int i = 0; i< ctx->nb_input_files; ++i) {
        outputs[i] = avfilter_inout_alloc();
    }

    for (int i = 0; i < ctx->nb_input_files; ++i) {
        AVFilterContext *buffersrc;
        snprintf(pad_name, sizeof(pad_name), "in%d", i);
        buffersrc = init_buffersrc(ctx->input_files[i]->decoder, filter_graph, pad_name);
        ctx->input_files[i]->buffersrc = buffersrc;
        outputs[i]->name = av_strdup(pad_name);
        outputs[i]->filter_ctx = buffersrc;
        outputs[i]->pad_idx = 0;
        if (i == ctx->nb_input_files - 1) {
            outputs[i]->next = NULL;
        }
        else {
            outputs[i]->next = outputs[i + 1];
        }
    }

    ctx->output_file->buffersink = init_buffersink(filter_graph);

    inputs->name = av_strdup("out");
    inputs->filter_ctx = ctx->output_file->buffersink;
    inputs->pad_idx =0;
    inputs->next = NULL;

    CHECK_AV(avfilter_graph_parse_ptr(filter_graph, desc, &inputs, outputs, NULL));

    CHECK_AV(avfilter_graph_config(filter_graph, NULL));
}

// Call init_complex_graph("[in0][in1]afir[out]", SOME_CONTEXT);
</code>```

and still nothing.

Body:
I want to understand why av_buffersink_get_frame() always return AVERROR(EAGAIN).
I use this algorithm:

Open input file input.mp3, create decoder for input file

Open signal file signal.wav, create decoder for signal file

Create filter graph and inputs/outputs with function avfilter_graph_parse2("[in0][in1]afir[out], &inputs, &outputs")

Create abuffersrc for every inputs with names "in0", "in1"

Create one abuffersink for one outputs with name "out"

Read and decode samples with methods av_read_frame(), avcodec_send_packet(), avcodec_receive_frame(), put samples to abuffersrc with av_buffersrc_add_frame() and trying to read samples from abuffersink with av_buffersink_get_frame() - HERE I get AVERROR(EAGAIN) for every call

Please, help!

I've tried to read all samples and push its to abuffersrc for input and signal pipes in first step and and call av_buffersink_get_frame one time in second step. I got AVERROR(EGAIN) again.

I've tried to config two outputs with names "in0" and "in1" and one input with name "out" and call avfilter_graph_parse_ptr() as done in here:

static AVFilterContext *init_buffersrc(AVCodecContext *decoder, AVFilterGraph *filter_graph, const char *pad_name) {
    AVFilterContext *buffersrc = NULL;
    uint8_t args[1024];

    snprintf(args, sizeof(args),
        "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64"",
        decoder->time_base.num, decoder->time_base.den, decoder->sample_rate, av_get_sample_fmt_name(decoder->sample_fmt), decoder->channel_layout);

    CHECK_AV(avfilter_graph_create_filter(&buffersrc, avfilter_get_by_name("abuffer"), pad_name, args, NULL, filter_graph));
    return buffersrc;
}

static AVFilterContext *init_buffersink(AVFilterGraph *filter_graph) {
    AVFilterContext *buffersink = NULL;

    CHECK_AV(avfilter_graph_create_filter(&buffersink, avfilter_get_by_name("abuffersink"), "out", NULL, NULL, filter_graph));
    return buffersink;
}

static void init_complex_graph(const char *desc, Context *ctx) {

    AVFilterGraph *filter_graph;
    AVFilterInOut *inputs = avfilter_inout_alloc();
    AVFilterInOut **outputs = (AVFilterInOut**) av_malloc(ctx->nb_input_files*sizeof(AVFilterInOut *));
    char *dump;
    uint8_t pad_name[64];

    filter_graph = ctx->filter_graph = avfilter_graph_alloc();
    filter_graph->nb_threads = 1;

    for (int i = 0; i< ctx->nb_input_files; ++i) {
        outputs[i] = avfilter_inout_alloc();
    }

    for (int i = 0; i < ctx->nb_input_files; ++i) {
        AVFilterContext *buffersrc;
        snprintf(pad_name, sizeof(pad_name), "in%d", i);
        buffersrc = init_buffersrc(ctx->input_files[i]->decoder, filter_graph, pad_name);
        ctx->input_files[i]->buffersrc = buffersrc;
        outputs[i]->name = av_strdup(pad_name);
        outputs[i]->filter_ctx = buffersrc;
        outputs[i]->pad_idx = 0;
        if (i == ctx->nb_input_files - 1) {
            outputs[i]->next = NULL;
        }
        else {
            outputs[i]->next = outputs[i + 1];
        }
    }

    ctx->output_file->buffersink = init_buffersink(filter_graph);

    inputs->name = av_strdup("out");
    inputs->filter_ctx = ctx->output_file->buffersink;
    inputs->pad_idx =0;
    inputs->next = NULL;

    CHECK_AV(avfilter_graph_parse_ptr(filter_graph, desc, &inputs, outputs, NULL));

    CHECK_AV(avfilter_graph_config(filter_graph, NULL));
}

// Call init_complex_graph("[in0][in1]afir[out]", SOME_CONTEXT);

and still nothing.


问:
Financial information in same ERP database?
I am making a back-end that handles inventory, user data, documentation, & images (basically a custom ERP system) for an application I am developing.

I am deriving some accounting information (payroll, TVM calculations) based on price data and hours logged by users. Is it typical to use the same relational database (MySQL) to store EVERYTHING (but in separate tables of course)? Or do you want to split things into separate databases?


问:
Unable to push container to azure registery from VS Code "aad access token with sp failed client id must be gui"
I'm attempting to use the command palette in VS Code to push a container to Azure repository and I'm receiving the following error: "aad access token with sp failed client id must be gui". I have tried resigning in using the command palette and received the same results.</p>


问:
ClaimsIdentity cant access methods in official OpenIdDict Samples
I have been very frustrated trying to use openiddict. I can't use any of the pre-existing sample since their ClaimsIdentity uses methods that to me aren't available, for example the identity.SetClaims(), identity.SetScopes() and identity.GetScopes() don't work for me.

This is the official sample Zirku.Server:

```<code>var builder = WebApplication.CreateBuilder(args);

// OpenIddict offers native integration with Quartz.NET to perform scheduled tasks
// (like pruning orphaned authorizations/tokens from the database) at regular intervals.
builder.Services.AddQuartz(options =>
{
    options.UseMicrosoftDependencyInjectionJobFactory();
    options.UseSimpleTypeLoader();
    options.UseInMemoryStore();
});

// Register the Quartz.NET service and configure it to block shutdown until jobs are complete.
builder.Services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);

builder.Services.AddDbContext<DbContext>(options =>
{
    // Configure the context to use Microsoft SQL Server.
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));

    // Register the entity sets needed by OpenIddict.
    // Note: use the generic overload if you need
    // to replace the default OpenIddict entities.
    options.UseOpenIddict();
});

builder.Services.AddOpenIddict()

    // Register the OpenIddict core components.
    .AddCore(options =>
    {
        options.UseEntityFrameworkCore()
               .UseDbContext<DbContext>();
    })

    // Register the OpenIddict server components.
    .AddServer(options =>
    {
        // Enable the authorization, introspection and token endpoints.
        options.SetAuthorizationEndpointUris("/authorize")
               .SetIntrospectionEndpointUris("/introspect")
               .SetTokenEndpointUris("/token");

        // Note: this sample only uses the authorization code flow but you can enable
        // the other flows if you need to support implicit, password or client credentials.
        options.AllowAuthorizationCodeFlow();

        // Register the signing credentials.
        options.AddDevelopmentSigningCertificate();

        // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
        //
        // Note: unlike other samples, this sample doesn't use token endpoint pass-through
        // to handle token requests in a custom MVC action. As such, the token requests
        // will be automatically handled by OpenIddict, that will reuse the identity
        // resolved from the authorization code to produce access and identity tokens.
        //
        options.UseAspNetCore()
               .EnableAuthorizationEndpointPassthrough();
    })

    // Register the OpenIddict validation components.
    .AddValidation(options =>
    {
        // Import the configuration from the local OpenIddict server instance.
        options.UseLocalServer();

        // Register the ASP.NET Core host.
        options.UseAspNetCore();
    });

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseHttpsRedirection();

// Create new application registrations matching the values configured in Zirku.Client and Zirku.Api1.
// Note: in a real world application, this step should be part of a setup script.
await using (var scope = app.Services.CreateAsyncScope())
{
    var context = scope.ServiceProvider.GetRequiredService<DbContext>();
    await context.Database.EnsureCreatedAsync();

    await CreateApplicationsAsync();
    await CreateScopesAsync();

    async Task CreateApplicationsAsync()
    {
        var manager = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();

        if (await manager.FindByClientIdAsync("console_app") is null)
        {
            await manager.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId = "console_app",
                RedirectUris =
                {
                    new Uri("http://localhost:8739/")
                },
                Permissions =
                {
                    Permissions.Endpoints.Authorization,
                    Permissions.Endpoints.Token,
                    Permissions.GrantTypes.AuthorizationCode,
                    Permissions.ResponseTypes.Code,
                    Permissions.Scopes.Email,
                    Permissions.Scopes.Profile,
                    Permissions.Scopes.Roles,
                    Permissions.Prefixes.Scope + "api1",
                    Permissions.Prefixes.Scope + "api2"
                }
            });
        }

        if (await manager.FindByClientIdAsync("resource_server_1") is null)
        {
            await manager.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId = "resource_server_1",
                ClientSecret = "846B62D0-DEF9-4215-A99D-86E6B8DAB342",
                Permissions =
                {
                    Permissions.Endpoints.Introspection
                }
            });
        }

        // Note: no client registration is created for resource_server_2
        // as it uses local token validation instead of introspection.
    }

    async Task CreateScopesAsync()
    {
        var manager = scope.ServiceProvider.GetRequiredService<IOpenIddictScopeManager>();

        if (await manager.FindByNameAsync("api1") is null)
        {
            await manager.CreateAsync(new OpenIddictScopeDescriptor
            {
                Name = "api1",
                Resources =
                {
                    "resource_server_1"
                }
            });
        }

        if (await manager.FindByNameAsync("api2") is null)
        {
            await manager.CreateAsync(new OpenIddictScopeDescriptor
            {
                Name = "api2",
                Resources =
                {
                    "resource_server_2"
                }
            });
        }
    }
}

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/api", [Authorize(AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)]
(ClaimsPrincipal user) => user.Identity!.Name);

app.MapGet("/authorize", async (HttpContext context, IOpenIddictScopeManager manager) =>
{
    // Retrieve the OpenIddict server request from the HTTP context.
    var request = context.GetOpenIddictServerRequest();

    var identifier = (int?)request["hardcoded_identity_id"];
    if (identifier is not (1 or 2))
    {
        return Results.Challenge(
            authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme },
            properties: new AuthenticationProperties(new Dictionary<string, string>
            {
                [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidRequest,
                [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The specified hardcoded identity is invalid."
            }));
    }

    // Create the claims-based identity that will be used by OpenIddict to generate tokens.
    var identity = new ClaimsIdentity(
        authenticationType: TokenValidationParameters.DefaultAuthenticationType,
        nameType: Claims.Name,
        roleType: Claims.Role);

    // Add the claims that will be persisted in the tokens.
    identity.AddClaim(new Claim(Claims.Subject, identifier.Value.ToString(CultureInfo.InvariantCulture)));
    identity.AddClaim(new Claim(Claims.Name, identifier switch
    {
        1 => "Alice",
        2 => "Bob",
        _ => throw new InvalidOperationException()
    }));

    // Note: in this sample, the client is granted all the requested scopes for the first identity (Alice)
    // but for the second one (Bob), only the "api1" scope can be granted, which will cause requests sent
    // to Zirku.Api2 on behalf of Bob to be automatically rejected by the OpenIddict validation handler,
    // as the access token representing Bob won't contain the "resource_server_2" audience required by Api2.
    identity.SetScopes(identifier switch
    {
        1 => request.GetScopes(),
        2 => new[] { "api1" }.Intersect(request.GetScopes()),
        _ => throw new InvalidOperationException()
    });

    identity.SetResources(await manager.ListResourcesAsync(identity.GetScopes()).ToListAsync());

    // Allow all claims to be added in the access tokens.
    identity.SetDestinations(claim => new[] { Destinations.AccessToken });

    return Results.SignIn(new ClaimsPrincipal(identity), properties: null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
});

app.Run();
</code>```

I have been trying to convert the samples to identity.AddClaim(), but I am not sure that it works as expected.

Please tell me what I am doing wrong. I am new to authorization and authentication so, as you can imagine, I am not good enough to figure out what is going wrong.

PS If you have any good up-to-date sources so that I can read up on the subject, that would be great.

PS 2 Excuse my english, it is not my first language

Body:
I have been very frustrated trying to use openiddict. I can't use any of the pre-existing sample since their ClaimsIdentity uses methods that to me aren't available, for example the identity.SetClaims(), identity.SetScopes() and identity.GetScopes() don't work for me.

This is the official sample Zirku.Server:

var builder = WebApplication.CreateBuilder(args);

// OpenIddict offers native integration with Quartz.NET to perform scheduled tasks
// (like pruning orphaned authorizations/tokens from the database) at regular intervals.
builder.Services.AddQuartz(options =>
{
    options.UseMicrosoftDependencyInjectionJobFactory();
    options.UseSimpleTypeLoader();
    options.UseInMemoryStore();
});

// Register the Quartz.NET service and configure it to block shutdown until jobs are complete.
builder.Services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);

builder.Services.AddDbContext<DbContext>(options =>
{
    // Configure the context to use Microsoft SQL Server.
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));

    // Register the entity sets needed by OpenIddict.
    // Note: use the generic overload if you need
    // to replace the default OpenIddict entities.
    options.UseOpenIddict();
});

builder.Services.AddOpenIddict()

    // Register the OpenIddict core components.
    .AddCore(options =>
    {
        options.UseEntityFrameworkCore()
               .UseDbContext<DbContext>();
    })

    // Register the OpenIddict server components.
    .AddServer(options =>
    {
        // Enable the authorization, introspection and token endpoints.
        options.SetAuthorizationEndpointUris("/authorize")
               .SetIntrospectionEndpointUris("/introspect")
               .SetTokenEndpointUris("/token");

        // Note: this sample only uses the authorization code flow but you can enable
        // the other flows if you need to support implicit, password or client credentials.
        options.AllowAuthorizationCodeFlow();

        // Register the signing credentials.
        options.AddDevelopmentSigningCertificate();

        // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
        //
        // Note: unlike other samples, this sample doesn't use token endpoint pass-through
        // to handle token requests in a custom MVC action. As such, the token requests
        // will be automatically handled by OpenIddict, that will reuse the identity
        // resolved from the authorization code to produce access and identity tokens.
        //
        options.UseAspNetCore()
               .EnableAuthorizationEndpointPassthrough();
    })

    // Register the OpenIddict validation components.
    .AddValidation(options =>
    {
        // Import the configuration from the local OpenIddict server instance.
        options.UseLocalServer();

        // Register the ASP.NET Core host.
        options.UseAspNetCore();
    });

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseHttpsRedirection();

// Create new application registrations matching the values configured in Zirku.Client and Zirku.Api1.
// Note: in a real world application, this step should be part of a setup script.
await using (var scope = app.Services.CreateAsyncScope())
{
    var context = scope.ServiceProvider.GetRequiredService<DbContext>();
    await context.Database.EnsureCreatedAsync();

    await CreateApplicationsAsync();
    await CreateScopesAsync();

    async Task CreateApplicationsAsync()
    {
        var manager = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();

        if (await manager.FindByClientIdAsync("console_app") is null)
        {
            await manager.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId = "console_app",
                RedirectUris =
                {
                    new Uri("http://localhost:8739/")
                },
                Permissions =
                {
                    Permissions.Endpoints.Authorization,
                    Permissions.Endpoints.Token,
                    Permissions.GrantTypes.AuthorizationCode,
                    Permissions.ResponseTypes.Code,
                    Permissions.Scopes.Email,
                    Permissions.Scopes.Profile,
                    Permissions.Scopes.Roles,
                    Permissions.Prefixes.Scope + "api1",
                    Permissions.Prefixes.Scope + "api2"
                }
            });
        }

        if (await manager.FindByClientIdAsync("resource_server_1") is null)
        {
            await manager.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId = "resource_server_1",
                ClientSecret = "846B62D0-DEF9-4215-A99D-86E6B8DAB342",
                Permissions =
                {
                    Permissions.Endpoints.Introspection
                }
            });
        }

        // Note: no client registration is created for resource_server_2
        // as it uses local token validation instead of introspection.
    }

    async Task CreateScopesAsync()
    {
        var manager = scope.ServiceProvider.GetRequiredService<IOpenIddictScopeManager>();

        if (await manager.FindByNameAsync("api1") is null)
        {
            await manager.CreateAsync(new OpenIddictScopeDescriptor
            {
                Name = "api1",
                Resources =
                {
                    "resource_server_1"
                }
            });
        }

        if (await manager.FindByNameAsync("api2") is null)
        {
            await manager.CreateAsync(new OpenIddictScopeDescriptor
            {
                Name = "api2",
                Resources =
                {
                    "resource_server_2"
                }
            });
        }
    }
}

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/api", [Authorize(AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)]
(ClaimsPrincipal user) => user.Identity!.Name);

app.MapGet("/authorize", async (HttpContext context, IOpenIddictScopeManager manager) =>
{
    // Retrieve the OpenIddict server request from the HTTP context.
    var request = context.GetOpenIddictServerRequest();

    var identifier = (int?)request["hardcoded_identity_id"];
    if (identifier is not (1 or 2))
    {
        return Results.Challenge(
            authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme },
            properties: new AuthenticationProperties(new Dictionary<string, string>
            {
                [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidRequest,
                [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The specified hardcoded identity is invalid."
            }));
    }

    // Create the claims-based identity that will be used by OpenIddict to generate tokens.
    var identity = new ClaimsIdentity(
        authenticationType: TokenValidationParameters.DefaultAuthenticationType,
        nameType: Claims.Name,
        roleType: Claims.Role);

    // Add the claims that will be persisted in the tokens.
    identity.AddClaim(new Claim(Claims.Subject, identifier.Value.ToString(CultureInfo.InvariantCulture)));
    identity.AddClaim(new Claim(Claims.Name, identifier switch
    {
        1 => "Alice",
        2 => "Bob",
        _ => throw new InvalidOperationException()
    }));

    // Note: in this sample, the client is granted all the requested scopes for the first identity (Alice)
    // but for the second one (Bob), only the "api1" scope can be granted, which will cause requests sent
    // to Zirku.Api2 on behalf of Bob to be automatically rejected by the OpenIddict validation handler,
    // as the access token representing Bob won't contain the "resource_server_2" audience required by Api2.
    identity.SetScopes(identifier switch
    {
        1 => request.GetScopes(),
        2 => new[] { "api1" }.Intersect(request.GetScopes()),
        _ => throw new InvalidOperationException()
    });

    identity.SetResources(await manager.ListResourcesAsync(identity.GetScopes()).ToListAsync());

    // Allow all claims to be added in the access tokens.
    identity.SetDestinations(claim => new[] { Destinations.AccessToken });

    return Results.SignIn(new ClaimsPrincipal(identity), properties: null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
});

app.Run();

I have been trying to convert the samples to identity.AddClaim(), but I am not sure that it works as expected.

Please tell me what I am doing wrong. I am new to authorization and authentication so, as you can imagine, I am not good enough to figure out what is going wrong.

PS If you have any good up-to-date sources so that I can read up on the subject, that would be great.

PS 2 Excuse my english, it is not my first language


问:
Were 90s compilers not able to perform constant int-to-float typecasting at compile-time?
In the book "Black art of 3D game programming", the author talks about an optimization related to int/floating point constants.

Referring to a 2d matrix of floats:

// multiple statements like this
a[0][1] = a[0][2] = a[0][3] = 0;
```

he writes:

As I was trying to optimize the 3D engine and performing code profiling, I found that simple floating point assignments were slow
[...] the compiler uses the floating point processor to convert the 0’s into temporary reals and then assigns them to the array elements, which is slow. A better way to do this would be to simply fill the array memory with 0’s.

There is an existing answer to this topic here:

It is not an optimization. Turning off optimization won't make the compiler include the int-to-float conversion in the executable code, unless it's a very poor-quality implementation.

however, the answer refers to modern compilers.

Was this an atypical optimization for compilers in the 90s? AFAIK the author uses the Watcom compiler, and I find it odd that such widespread compiler didn't implement this optimization.

Body:
In the book "Black art of 3D game programming", the author talks about an optimization related to int/floating point constants.

Referring to a 2d matrix of floats:

// multiple statements like this
a[0][1] = a[0][2] = a[0][3] = 0;

he writes:

As I was trying to optimize the 3D engine and performing code profiling, I found that simple floating point assignments were slow
[...] the compiler uses the floating point processor to convert the 0’s into temporary reals and then assigns them to the array elements, which is slow. A better way to do this would be to simply fill the array memory with 0’s.

There is an existing answer to this topic here:

It is not an optimization. Turning off optimization won't make the compiler include the int-to-float conversion in the executable code, unless it's a very poor-quality implementation.

however, the answer refers to modern compilers.

Was this an atypical optimization for compilers in the 90s? AFAIK the author uses the Watcom compiler, and I find it odd that such widespread compiler didn't implement this optimization.


问:
ReactJS getting state variable from Context returns undefined
I have array of objects which I am getting from my Context. The problem is, if I am trying to use it, it is undefined. In the code, which I am showcasing, I am mapping over this variable, but I have also tried setting it to new state first. But it had the same result. The only time the code doesn't break is if I use optional chaining. But then it doesn't render mapped content. Can somebody explain my mistake here, as it is not the first time I am seeing it.

P.S. Setting new state to some defined value and then setting it on render to variable from Context doesn't work here.

```<code>const BacklogDropdown = ({setTask}) => {
    const { tasks } = useContext(UserContext)

    const handleChoose = (e) => {
        const { value } = e.target
        setTask(value)
    }

    return (
        <div className="">
            <p className='text-lg pl-1 font-medium'>Select from Backlog</p>
            <Listbox value={tasks?.backlog} onChange={(e) => handleChoose(e)}>
                <Listbox.Button className='h-10 w-full z-30 bg-background text-lg rounded-md px-2 py-1 border-2 border-grayDark'>{tasks?.backlog[0].name}</Listbox.Button>
                <Listbox.Options className='z-50 h-max w-full'>
                    {tasks?.backlog?.map(task => (
                        <Listbox.Option key={task.id} value={task} className='ui-active:bg-primaryDark ui-active:text-white'>
                            {task.priority}
                            {task.name}
                            <CheckIcon className="hidden ui-selected:block" />
                        </Listbox.Option>
                    ))}
                </Listbox.Options>
            </Listbox>
        </div>
    )
}

export default BacklogDropdown
</code>```

Body:
I have array of objects which I am getting from my Context. The problem is, if I am trying to use it, it is undefined. In the code, which I am showcasing, I am mapping over this variable, but I have also tried setting it to new state first. But it had the same result. The only time the code doesn't break is if I use optional chaining. But then it doesn't render mapped content. Can somebody explain my mistake here, as it is not the first time I am seeing it.

P.S. Setting new state to some defined value and then setting it on render to variable from Context doesn't work here.

const BacklogDropdown = ({setTask}) => {
    const { tasks } = useContext(UserContext)

    const handleChoose = (e) => {
        const { value } = e.target
        setTask(value)
    }

    return (

Select from Backlog

            <Listbox value={tasks?.backlog} onChange={(e) => handleChoose(e)}>
                <Listbox.Button className='h-10 w-full z-30 bg-background text-lg rounded-md px-2 py-1 border-2 border-grayDark'>{tasks?.backlog[0].name}</Listbox.Button>
                <Listbox.Options className='z-50 h-max w-full'>
                    {tasks?.backlog?.map(task => (
                        <Listbox.Option key={task.id} value={task} className='ui-active:bg-primaryDark ui-active:text-white'>
                            {task.priority}
                            {task.name}
                            <CheckIcon className="hidden ui-selected:block" />
                        </Listbox.Option>
                    ))}
                </Listbox.Options>
            </Listbox>

    )
}

export default BacklogDropdown


问:
Wrong caret position in TEdit (Android, RADStudio 11.2)
When I'm using TEdit with ControlType = Styled in Android, while typing text I have wrong Edit.Caret.Pos (always at begning, not changing) so caret also stays in one position on scren. By the way Edit.CarePosition is correct and changing.

If I change ConrolType to = Platform, everything flies...but I need styling..anybody faced this issue?


问:
using .net to a wrap a glass cylinder/tube around a 2d image
I need find a way (in .net code) to create the effect of wrapping glass tube around a 2d image.  More or less like viewing a picture of a ship inside a glass bottle.

I've done a lot of searching for examples, and have even tried chatgpt to give me some ideas but have come up empty.

The 2d image I have, the glass tube around it is the challenge.

Any help/examples would be appreciated.


问:
How to send data to a WebApp opening with either menu or inline buttons with Telebot Go API
I understand that it is possible to initialise a WebApp opened from Telegram using a menu or inline button. Ideally I want to provide the Telegram client's contact list to the WebApp. If anyone can provide an example of how to do that I would be very grateful.

```<code>var (
    webapp   = &tele.ReplyMarkup{}
    app      = &tele.WebApp{URL: "SomeURL"}
    helloMsg    = &tele.Message{Text: "SomeMessage"}

    // Inline buttons.
    btnGo = webapp.WebApp("Start inviting friends", app)
)

func main() {
    webapp.Inline(
        webapp.Row(btnGo),
    )

    log.Println("Starting Noah_HQ_bot")
    pref := tele.Settings{
        Token:  os.Getenv("TOKEN"),
        Poller: &tele.LongPoller{Timeout: 5 * time.Second},
    }

    b, err := tele.NewBot(pref)
    if err != nil {
        log.Fatal(err)
        return
    }

    b.Handle("/start", func(c tele.Context) error {
        log.Println("Detected Start")
        b.Send(c.Message().Sender, helloMsg.Text, &tele.SendOptions{
            ParseMode: "MARKDOWN",
        }, webapp)
        return nil
    })

    b.Start()
}
</code>```

Body:
I understand that it is possible to initialise a WebApp opened from Telegram using a menu or inline button. Ideally I want to provide the Telegram client's contact list to the WebApp. If anyone can provide an example of how to do that I would be very grateful.

var (
    webapp   = &tele.ReplyMarkup{}
    app      = &tele.WebApp{URL: "SomeURL"}
    helloMsg    = &tele.Message{Text: "SomeMessage"}

    // Inline buttons.
    btnGo = webapp.WebApp("Start inviting friends", app)
)

func main() {
    webapp.Inline(
        webapp.Row(btnGo),
    )

    log.Println("Starting Noah_HQ_bot")
    pref := tele.Settings{
        Token:  os.Getenv("TOKEN"),
        Poller: &tele.LongPoller{Timeout: 5 * time.Second},
    }

    b, err := tele.NewBot(pref)
    if err != nil {
        log.Fatal(err)
        return
    }

    b.Handle("/start", func(c tele.Context) error {
        log.Println("Detected Start")
        b.Send(c.Message().Sender, helloMsg.Text, &tele.SendOptions{
            ParseMode: "MARKDOWN",
        }, webapp)
        return nil
    })

    b.Start()
}


问:
Vitejs. Running a script for a specific task
I'm using Vite. I installed the npm plugin called 'vite-plugin-zip-file' in order to archive the dist folder. How can I run a separate from 'build' script in package.json specifically for this task?

vite.config.js below

```<code>import { defineConfig } from 'vite';
import { resolve } from 'path';
import { viteZip } from 'vite-plugin-zip-file';

export default defineConfig({
build: {
    outDir: 'build',
},
plugins: [
    viteZip({
      folderPath: resolve(__dirname, 'build'),
      outPath: resolve(__dirname),
      zipName: 'Test.zip',
    }),
],
});
</code>```

package.json 'scripts' (I don't know what to write in 'zip' here)

```<code>  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
    "zip": ?
  },
</code>```

I tried adding the environmental variable, but I don't know exactly how to do it. So, there's probably another better way.

Body:
I'm using Vite. I installed the npm plugin called 'vite-plugin-zip-file' in order to archive the dist folder. How can I run a separate from 'build' script in package.json specifically for this task?

vite.config.js below

import { defineConfig } from 'vite';
import { resolve } from 'path';
import { viteZip } from 'vite-plugin-zip-file';

export default defineConfig({
build: {
    outDir: 'build',
},
plugins: [
    viteZip({
      folderPath: resolve(__dirname, 'build'),
      outPath: resolve(__dirname),
      zipName: 'Test.zip',
    }),
],
});

package.json 'scripts' (I don't know what to write in 'zip' here)

  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
    "zip": ?
  },

I tried adding the environmental variable, but I don't know exactly how to do it. So, there's probably another better way.


问:
How to set Maven home path Bundled Maven as default [IntelliJ]
In settings Maven home path is always "Use Maven wapper" even if I set "Bundled (Maven 3)" in previous project.
How to set Maven home path Bundled Maven as default in IntelliJ?</p>


问:
Populate Search MongoDB Objects
Can you please tell me how to search for a nested object (only _id appears in it and is expanded via .populate() )?
I need to search by title and album.title, how can I do this?

    async getAll(searchTerm?: string) {
        let options = {}

        if (searchTerm) {
            options = {
                $or: [
                    {
                        title: new RegExp(searchTerm.trim(), 'gi'),
                    },
                ],
            }
        }

        return this.TrackModel.find(options)
            .select('-updatedAt -__v')
            .sort({ createdAt: 'desc' })
            .populate('album author')
            .exec()
    }

```
<p>image of JSON below</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "_id": "638cec330c055283f3eeb227",
    "poster": "/uploads/tracks/Coolio/Coolio-cover.jpg",
    "title": "Gangsta's Paradise",
    "slug": "gangstasparadise",
    "duration": 240,
    "countPlays": 7269322,
    "trackUrl": "/uploads/tracks/Coolio/Coolio - Gangstas Paradise.mp3",
    "album": [
      {
        "_id": "638ceb960c055283f3eeb225",
        "title": "Gangsta's Paradise",
        "slug": "gangstasparadise",
        "poster": "/uploads/tracks/Coolio/Coolio-cover.jpg",
        "author": [
          "638ce9f50c055283f3eeb223"
        ],
        "createdAt": "2022-12-04T18:48:54.306Z",
        "updatedAt": "2022-12-04T18:48:54.306Z",
        "_v": 0
      }
    ]
  }
]
</code>```

I tried to search using $or, but I ran into a problem that at the time of the search, only _id is stored in the album array.

Title: Populate Search MongoDB Objects

Body:
Can you please tell me how to search for a nested object (only _id appears in it and is expanded via .populate() )?
I need to search by title and album.title, how can I do this?

    async getAll(searchTerm?: string) {
        let options = {}

        if (searchTerm) {
            options = {
                $or: [
                    {
                        title: new RegExp(searchTerm.trim(), 'gi'),
                    },
                ],
            }
        }

        return this.TrackModel.find(options)
            .select('-updatedAt -__v')
            .sort({ createdAt: 'desc' })
            .populate('album author')
            .exec()
    }

image of JSON below

[
  {
    "_id": "638cec330c055283f3eeb227",
    "poster": "/uploads/tracks/Coolio/Coolio-cover.jpg",
    "title": "Gangsta's Paradise",
    "slug": "gangstasparadise",
    "duration": 240,
    "countPlays": 7269322,
    "trackUrl": "/uploads/tracks/Coolio/Coolio - Gangstas Paradise.mp3",
    "album": [
      {
        "_id": "638ceb960c055283f3eeb225",
        "title": "Gangsta's Paradise",
        "slug": "gangstasparadise",
        "poster": "/uploads/tracks/Coolio/Coolio-cover.jpg",
        "author": [
          "638ce9f50c055283f3eeb223"
        ],
        "createdAt": "2022-12-04T18:48:54.306Z",
        "updatedAt": "2022-12-04T18:48:54.306Z",
        "_v": 0
      }
    ]
  }
]

I tried to search using $or, but I ran into a problem that at the time of the search, only _id is stored in the album array.


问:
How to solve "pg_dump server version mismatch error" when you find 4 different pg_dump binaries?
Attempting to get the Postgresql database on my local machine, but I am getting this error:

```<code>pg_dump: error: server version: 14.5; pg_dump version: 12.8
pg_dump: error: aborting because of server version mismatch
</code>```

Running this command:

```<code>find / -name pg_dump -type f 2>/dev/null
</code>```

I found 4 different pg_dump versions on my end:

```<code>/usr/local/Cellar/postgresql@15/15.1/bin/pg_dump
/System/Volumes/Data/usr/local/Cellar/postgresql@15/15.1/bin/pg_dump
/System/Volumes/Data/Applications/Postgres.app/Contents/Versions/12/bin/pg_dump
/Applications/Postgres.app/Contents/Versions/12/bin/pg_dump
</code>```

How can I change my pg_dump to the correct version?

I've tried to use ln -s to link the files to the correct version, and generally understanding what to do with little luck. An explanation to this problem would be greatly appreciated

Body:
Attempting to get the Postgresql database on my local machine, but I am getting this error:

pg_dump: error: server version: 14.5; pg_dump version: 12.8
pg_dump: error: aborting because of server version mismatch

Running this command:

find / -name pg_dump -type f 2>/dev/null

I found 4 different pg_dump versions on my end:

/usr/local/Cellar/postgresql@15/15.1/bin/pg_dump
/System/Volumes/Data/usr/local/Cellar/postgresql@15/15.1/bin/pg_dump
/System/Volumes/Data/Applications/Postgres.app/Contents/Versions/12/bin/pg_dump
/Applications/Postgres.app/Contents/Versions/12/bin/pg_dump

How can I change my pg_dump to the correct version?

I've tried to use ln -s to link the files to the correct version, and generally understanding what to do with little luck. An explanation to this problem would be greatly appreciated


问:
Hostname/IP does not match certificate's altnames Nextjs with S3 Bucket
I get this error in my Nextjs Application where I use an image with next/image from my s3 bucket:

```<code>FetchError: request to https://bucketname.s3.us-west-1.amazonaws.com/1671375836114 failed, reason: Hostname/IP does not match certificate's altnames: Host: bucketname.s3.us-west-1.amazonaws.com. is not in the cert's altnames: DNS:s3-us-west-1.amazonaws.com, DNS:*.s3-us-west-1.amazonaws.com, DNS:s3.us-west-1.amazonaws.com, DNS:*.s3.us-west-1.amazonaws.com, DNS:s3.dualstack.us-west-1.amazonaws.com, DNS:*.s3.dualstack.us-west-1.amazonaws.com, DNS:*.s3.amazonaws.com, DNS:*.s3-control.us-west-1.amazonaws.com, DNS:s3-control.us-west-1.amazonaws.com, DNS:*.s3-control.dualstack.us-west-1.amazonaws.com, DNS:s3-control.dualstack.us-west-1.amazonaws.com, DNS:*.s3-accesspoint.us-west-1.amazonaws.com, DNS:*.s3-accesspoint.dualstack.us-west-1.amazonaws.com
</code>```

Any idea how to fix this issue?

Body:
I get this error in my Nextjs Application where I use an image with next/image from my s3 bucket:

FetchError: request to https://bucketname.s3.us-west-1.amazonaws.com/1671375836114 failed, reason: Hostname/IP does not match certificate's altnames: Host: bucketname.s3.us-west-1.amazonaws.com. is not in the cert's altnames: DNS:s3-us-west-1.amazonaws.com, DNS:*.s3-us-west-1.amazonaws.com, DNS:s3.us-west-1.amazonaws.com, DNS:*.s3.us-west-1.amazonaws.com, DNS:s3.dualstack.us-west-1.amazonaws.com, DNS:*.s3.dualstack.us-west-1.amazonaws.com, DNS:*.s3.amazonaws.com, DNS:*.s3-control.us-west-1.amazonaws.com, DNS:s3-control.us-west-1.amazonaws.com, DNS:*.s3-control.dualstack.us-west-1.amazonaws.com, DNS:s3-control.dualstack.us-west-1.amazonaws.com, DNS:*.s3-accesspoint.us-west-1.amazonaws.com, DNS:*.s3-accesspoint.dualstack.us-west-1.amazonaws.com

Any idea how to fix this issue?


问:
"non finite transformation detected" when reprojecting a SpatialPointsDataFrame from longlat to Mollweide
I want to calculate the distance of some points from the nearest polygon. In order to use gDistance, I read that the input data should not be lat-lon. I have a tibble with the coordinates of the points (global extent, this is a subset of the original data, which has 2 million rows):

```<code>myCoords <- structure(list(decimallatitude = c(54.17786, 50.161934, 48.245286,
                                               37.701389, 38.444489, 44.526939, 43.172417, 36.508221, 38.85,
                                               37.64389, 41.771111, 39.52127, 38.938053, 38.879131, 43.112221
), decimallongitude = c(12.104702, 8.651218, -114.295816, -97.279716,
                        -98.6848, -95.756943, -101.593178, -91.618217, -97.76, -98.737221,
                        -81.050003, -98.36738, -99.523003, -99.419502, -101.537498)), row.names = c(NA,
                                                                                -15L), class = c("tbl_df", "tbl", "data.frame"), type = "single")
</code>```

I convert them to a SpatialPointsDataFrame object:

```<code>mySpdf <- SpatialPointsDataFrame(coords = myCoords,
                                 data = myCoords,
                                 proj4string = CRS(as.character("+proj=longlat +datum=WGS84 +no_defs")))
</code>```

And, as the original projection is longlat, I want to reproject them to Mollweide.

```<code>mySpdf_moll <- spTransform(mySpdf, CRS("+proj=moll +lon_0=0 +x_0=0 +y_0=0"))
</code>```

This doesn't work and gives this error:

```<code>Error in spTransform(xSP, CRSobj, ...) :
  failure in points 3:4:5:6:7:8:9:10:12:13:14:15
In addition: Warning message:
In spTransform(xSP, CRSobj, ...) : 12 projected point(s) not finite
</code>```

No point (in the original dataset as well) has coordinates outside +/- 180. Is this not working because the points have longitude negative values? What is the rationale behind that? Is there a better projection I should use?

When the points will be in a correct projection, I will proceed to load the shapefile and transform it into a SpatialPolygonsDataFrame object:

```<code>myShp <- read_sf("path/myShp.shp") # a .shp with crs: +proj=longlat +datum=WGS84 +no_defs
myShp <- as(myShp, "Spatial")
</code>```

Then reproject it (this should work):

```<code>myShp_moll <- spTransform(myShp, CRS("+proj=moll +lon_0=0 +x_0=0 +y_0=0"))
</code>```

And lastly calculating the distances of the points from the polygon(s):

```<code>dist <- gDistance(mySpdf_moll, myShp_moll)
</code>```

Lastly, is there a better framework to use?

Body:
I want to calculate the distance of some points from the nearest polygon. In order to use gDistance, I read that the input data should not be lat-lon. I have a tibble with the coordinates of the points (global extent, this is a subset of the original data, which has 2 million rows):

myCoords <- structure(list(decimallatitude = c(54.17786, 50.161934, 48.245286,
                                               37.701389, 38.444489, 44.526939, 43.172417, 36.508221, 38.85,
                                               37.64389, 41.771111, 39.52127, 38.938053, 38.879131, 43.112221
), decimallongitude = c(12.104702, 8.651218, -114.295816, -97.279716,
                        -98.6848, -95.756943, -101.593178, -91.618217, -97.76, -98.737221,
                        -81.050003, -98.36738, -99.523003, -99.419502, -101.537498)), row.names = c(NA,
                                                                                -15L), class = c("tbl_df", "tbl", "data.frame"), type = "single")

I convert them to a SpatialPointsDataFrame object:

mySpdf <- SpatialPointsDataFrame(coords = myCoords,
                                 data = myCoords,
                                 proj4string = CRS(as.character("+proj=longlat +datum=WGS84 +no_defs")))

And, as the original projection is longlat, I want to reproject them to Mollweide.

mySpdf_moll <- spTransform(mySpdf, CRS("+proj=moll +lon_0=0 +x_0=0 +y_0=0"))

This doesn't work and gives this error:

Error in spTransform(xSP, CRSobj, ...) :
  failure in points 3:4:5:6:7:8:9:10:12:13:14:15
In addition: Warning message:
In spTransform(xSP, CRSobj, ...) : 12 projected point(s) not finite

No point (in the original dataset as well) has coordinates outside +/- 180. Is this not working because the points have longitude negative values? What is the rationale behind that? Is there a better projection I should use?

When the points will be in a correct projection, I will proceed to load the shapefile and transform it into a SpatialPolygonsDataFrame object:

myShp <- read_sf("path/myShp.shp") # a .shp with crs: +proj=longlat +datum=WGS84 +no_defs
myShp <- as(myShp, "Spatial")

Then reproject it (this should work):

myShp_moll <- spTransform(myShp, CRS("+proj=moll +lon_0=0 +x_0=0 +y_0=0"))

And lastly calculating the distances of the points from the polygon(s):

dist <- gDistance(mySpdf_moll, myShp_moll)

Lastly, is there a better framework to use?


问:
Redux not running on page load
I am currently working on a react app with redux. When I attempt to navigate to the ticket page, nothing will load and I get a 'Cannot read properties of null'error Console error I receive when coming from a different page because redux will not run and the page is dependent on redux running so I can get the state of the ticket. However, when I click the reload button in the browser, redux will then run and everything works like it should. Redux state after refreshing the page in the browser</p>
```<code>function Ticket() {
  const { ticket } = useSelector((state) => state.tickets);
  const dispatch = useDispatch();
  const { ticketId } = useParams();

  useEffect(() => {
    dispatch(getTicket(ticketId)).unwrap().catch(toast.error);
  }, [dispatch, ticketId]);

  return (
    <>
      <BackButton />
      <div className='container flex '>
        <h1>{ticket.subject}</h1>
        <h1 className='capitalize'>Ticket Status: {ticket.status}</h1>
      </div>
</code>```
```<code>// Get user ticket
export const getTicket = createAsyncThunk(
  'tickets/getSingleTicket',
  async (ticketId, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await ticketService.getTicket(ticketId, token);
    } catch (error) {
      return thunkAPI.rejectWithValue(extractErrorMessage(error));
    }
  }
);
</code>```

Title: Redux not running on page load

Body:
I am currently working on a react app with redux. When I attempt to navigate to the ticket page, nothing will load and I get a 'Cannot read properties of null'error Console error I receive when coming from a different page because redux will not run and the page is dependent on redux running so I can get the state of the ticket. However, when I click the reload button in the browser, redux will then run and everything works like it should. Redux state after refreshing the page in the browser

function Ticket() {
  const { ticket } = useSelector((state) => state.tickets);
  const dispatch = useDispatch();
  const { ticketId } = useParams();

  useEffect(() => {
    dispatch(getTicket(ticketId)).unwrap().catch(toast.error);
  }, [dispatch, ticketId]);

  return (
    <>
      <BackButton />

{ticket.subject}

Ticket Status: {ticket.status}

// Get user ticket
export const getTicket = createAsyncThunk(
  'tickets/getSingleTicket',
  async (ticketId, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await ticketService.getTicket(ticketId, token);
    } catch (error) {
      return thunkAPI.rejectWithValue(extractErrorMessage(error));
    }
  }
);


问:
Issues with areal interpolation function from sf package
I got the following warnings when I was performing an areal interpolation with sf package areal_int <- st_interpolate_aw(poly, grid, extensive = T):

Warning messages: 1: In st_interpolate_aw.sf(poly, grid, extensive = T) : st_interpolate_aw assumes attributes are constant or uniform over areas of x 2: In NextMethod() : number of items to replace is not a multiple of replacement length

First warning of course it's not a problem as it simply reminds us what is the assumption that drives the estimations of the data from source zones to source zones.

The second one (2: In NextMethod() :..... and so on) is concerning me as I really don't know why this happens and mostly I'm not sure if I can ignore it or if it affects the results.

Any suggestions would be appreciated!


问:
pdftk multi pdf merge via input params
I'm attempting to merge set groups of pdfs, the pdf filenames being dictated elsewhere and passed to ps via input parameter, I've added defaults below to hopefully give a complete picture.

The error raised by pdftk is a failure to open the input files, if I was to run this manually without parameters it works fine so I'm a little stumped as to where I'm going wrong???

```<code>param($UniRow="144",$CC="1142033",$Pdfs="EP3058513_A.pdf EP3058512_A.pdf EP2981932_A.pdf EP2981931_A.pdf EP3100208_A.pdf")
Set-Location -Path "E:\pdfs\"
pdftk $Pdfs cat output "E:\OptedOut\pdfs\${UniRow}_${CC}.pdf"
</code>```

Edit - To clarify, when I say run the above manually I mean....

```<code>Set-Location -Path "E:\pdfs\"

pdftk "EP3058513_A.pdf EP3058512_A.pdf EP2981932_A.pdf EP2981931_A.pdf EP3100208_A.pdf" cat output "E:\Reports\UPC\OptedOut\pdfs\144_1142033.pdf"
</code>```

Title: pdftk multi pdf merge via input params

Body:
I'm attempting to merge set groups of pdfs, the pdf filenames being dictated elsewhere and passed to ps via input parameter, I've added defaults below to hopefully give a complete picture.

The error raised by pdftk is a failure to open the input files, if I was to run this manually without parameters it works fine so I'm a little stumped as to where I'm going wrong???

param($UniRow="144",$CC="1142033",$Pdfs="EP3058513_A.pdf EP3058512_A.pdf EP2981932_A.pdf EP2981931_A.pdf EP3100208_A.pdf")
Set-Location -Path "E:\pdfs\"
pdftk $Pdfs cat output "E:\OptedOut\pdfs\${UniRow}_${CC}.pdf"

Edit - To clarify, when I say run the above manually I mean....

Set-Location -Path "E:\pdfs\"

pdftk "EP3058513_A.pdf EP3058512_A.pdf EP2981932_A.pdf EP2981931_A.pdf EP3100208_A.pdf" cat output "E:\Reports\UPC\OptedOut\pdfs\144_1142033.pdf"


问:
What does the compiler do when you make a function template?
I was learning about function templates and the tutorial said:

"Once a template is defined, the compiler can use the template to generate as many overloaded functions (or classes) as needed, each using different actual types!".

Is this true? Does that mean that a function template is just the compiler generating overloaded functions for different types? Does the compiler scan through your code checking if you made any user-defined types and then generates overloaded functions for those user-defined types?

Is that all there is to function templates or does the compiler do additional things?


问:
CSV open>edit>save from Webserver using HTML/JS/PHP
I am using jquery.datatable.editable and I want this datatable to get the main data from a simple CSV-file stored on the webserver. This is shown possible with CSV to HTML Table.

When I edit a cell inside jquery.datatable.editable I want it to update the CSV-file stored on my webserver. How can I do this?

I also checked vscode-edit-csv and love the layout as an editing interface but it only seams that it opens the file from a local stored file and not from the server...

(Some people use mySQL but I want to use a flat file (CSV) instead for syncing reasons.)