问:
dbclick fullscreen mode issue with Sliding Image Track
I have an issue with project images sliding since the sliding works fine but the issue with dbclick when click on image to display it in fullscreen mode it display the image in specific position in page not actual fullscreen Also when display in fullscreen mode black background color does not work so I want someone to explain to me what the issue here and how I can fix it properly...?!

const track = document.getElementById("image-track");

const handleOnDown = e => track.dataset.mouseDownAt = e.clientX;

const handleOnUp = () => {
  track.dataset.mouseDownAt = "0";
  track.dataset.prevPercentage = track.dataset.percentage;
}

const handleOnMove = e => {
  if (track.dataset.mouseDownAt === "0") return;

  const mouseDelta = parseFloat(track.dataset.mouseDownAt) - e.clientX,
    maxDelta = window.innerWidth / 2;

  const percentage = (mouseDelta / maxDelta) * -100,
    nextPercentageUnconstrained = parseFloat(track.dataset.prevPercentage) + percentage,
    nextPercentage = Math.max(Math.min(nextPercentageUnconstrained, 0), -100);

  track.dataset.percentage = nextPercentage;

  track.animate({
    transform: `translate(${nextPercentage}%, -50%)`
  }, {
    duration: 1200,
    fill: "forwards"
  });

  for (const image of track.getElementsByClassName("image")) {
    image.animate({
      objectPosition: `${100 + nextPercentage}% center`
    }, {
      duration: 1200,
      fill: "forwards"
    });
  }
}

/* -- Had to add extra lines for touch events -- */

window.onmousedown = e => handleOnDown(e);

window.ontouchstart = e => handleOnDown(e.touches[0]);

window.onmouseup = e => handleOnUp(e);

window.ontouchend = e => handleOnUp(e.touches[0]);

window.onmousemove = e => handleOnMove(e);

window.ontouchmove = e => handleOnMove(e.touches[0]);

/* -- Fullscreen Mode -- */
function FullView(ImageLink) {
  document.getElementById("FullImage").src = ImageLink;
  document.getElementById("FullImageView").style.display = "block";
}

function CloseFullView() {
  document.getElementById("FullImageView").style.display = "none";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>image-body {
  height: 100vh;
  width: 100vw;
  background-color: black;
  margin: 0rem;
  overflow: hidden;
}

#image-track {
  display: flex;
  gap: 4vmin;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(0%, -50%);
  user-select: none;
  /* -- Prevent image highlighting -- */
}

#image-track>.image {
  width: 40vmin;
  height: 56vmin;
  object-fit: cover;
  object-position: 100% center;
}

/* -- YouTube Link Styles -- */

body.menu-toggled>.meta-link>span {
  color: rgb(30, 30, 30);
}

#source-link {
  bottom: 60px;
}

#source-link>i {
  color: rgb(94, 106, 210);
}

#yt-link>i {
  color: rgb(239, 83, 80);
}

.meta-link {
  align-items: center;
  backdrop-filter: blur(3px);
  background-color: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  bottom: 10px;
  box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  display: inline-flex;
  gap: 5px;
  left: 10px;
  padding: 10px 20px;
  position: fixed;
  text-decoration: none;
  transition: background-color 400ms, border-color 400ms;
  z-index: 10000;
}

.meta-link:hover {
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.meta-link>i,
.meta-link>span {
  height: 20px;
  line-height: 20px;
}

.meta-link>span {
  color: white;
  font-family: "Rubik", sans-serif;
  font-weight: 500;
}

/* -- Fullscreen Mode -- */

#FullImageView {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: (0, 0, 0, 0.9);
  text-align: center;
}

#FullImage {
  padding: 24px;
  max-width: 98%;
  max-height: 98%;
}

#CloseButton {
  position: absolute;
  top: 12px;
  right: 12px;
  font-size: 2rem;
  color: white;
  cursor: pointer;
}</code>```

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" />

Project

first

Personal Info

              full name

              gander

              nationality

              stay address

              phone number

              social media id

              email

              civil id

              avatar

cv

partispate

              category

              job title

              certificate

              edu_level

              school_name

              school_admin_name

              edu_area_name

              governorate

              certificate_concern

achivments

project details

              project_title

              project_shorts

              word file

                  Perview

              project images.

                ×

              project voice.

              project video

              project powerpoint

              proprietorship certificate

            </form>

```

Body:
I have an issue with project images sliding since the sliding works fine but the issue with dbclick when click on image to display it in fullscreen mode it display the image in specific position in page not actual fullscreen Also when display in fullscreen mode black background color does not work so I want someone to explain to me what the issue here and how I can fix it properly...?!

const track = document.getElementById("image-track");

const handleOnDown = e => track.dataset.mouseDownAt = e.clientX;

const handleOnUp = () => {
  track.dataset.mouseDownAt = "0";
  track.dataset.prevPercentage = track.dataset.percentage;
}

const handleOnMove = e => {
  if (track.dataset.mouseDownAt === "0") return;

  const mouseDelta = parseFloat(track.dataset.mouseDownAt) - e.clientX,
    maxDelta = window.innerWidth / 2;

  const percentage = (mouseDelta / maxDelta) * -100,
    nextPercentageUnconstrained = parseFloat(track.dataset.prevPercentage) + percentage,
    nextPercentage = Math.max(Math.min(nextPercentageUnconstrained, 0), -100);

  track.dataset.percentage = nextPercentage;

  track.animate({
    transform: `translate(${nextPercentage}%, -50%)`
  }, {
    duration: 1200,
    fill: "forwards"
  });

  for (const image of track.getElementsByClassName("image")) {
    image.animate({
      objectPosition: `${100 + nextPercentage}% center`
    }, {
      duration: 1200,
      fill: "forwards"
    });
  }
}

/* -- Had to add extra lines for touch events -- */

window.onmousedown = e => handleOnDown(e);

window.ontouchstart = e => handleOnDown(e.touches[0]);

window.onmouseup = e => handleOnUp(e);

window.ontouchend = e => handleOnUp(e.touches[0]);

window.onmousemove = e => handleOnMove(e);

window.ontouchmove = e => handleOnMove(e.touches[0]);

/* -- Fullscreen Mode -- */
function FullView(ImageLink) {
  document.getElementById("FullImage").src = ImageLink;
  document.getElementById("FullImageView").style.display = "block";
}

function CloseFullView() {
  document.getElementById("FullImageView").style.display = "none";
}

image-body {
  height: 100vh;
  width: 100vw;
  background-color: black;
  margin: 0rem;
  overflow: hidden;
}

#image-track {
  display: flex;
  gap: 4vmin;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(0%, -50%);
  user-select: none;
  /* -- Prevent image highlighting -- */
}

#image-track>.image {
  width: 40vmin;
  height: 56vmin;
  object-fit: cover;
  object-position: 100% center;
}

/* -- YouTube Link Styles -- */

body.menu-toggled>.meta-link>span {
  color: rgb(30, 30, 30);
}

#source-link {
  bottom: 60px;
}

#source-link>i {
  color: rgb(94, 106, 210);
}

#yt-link>i {
  color: rgb(239, 83, 80);
}

.meta-link {
  align-items: center;
  backdrop-filter: blur(3px);
  background-color: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  bottom: 10px;
  box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  display: inline-flex;
  gap: 5px;
  left: 10px;
  padding: 10px 20px;
  position: fixed;
  text-decoration: none;
  transition: background-color 400ms, border-color 400ms;
  z-index: 10000;
}

.meta-link:hover {
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.meta-link>i,
.meta-link>span {
  height: 20px;
  line-height: 20px;
}

.meta-link>span {
  color: white;
  font-family: "Rubik", sans-serif;
  font-weight: 500;
}

/* -- Fullscreen Mode -- */

#FullImageView {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: (0, 0, 0, 0.9);
  text-align: center;
}

#FullImage {
  padding: 24px;
  max-width: 98%;
  max-height: 98%;
}

#CloseButton {
  position: absolute;
  top: 12px;
  right: 12px;
  font-size: 2rem;
  color: white;
  cursor: pointer;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" />

Project

first

Personal Info

              full name

              gander

              nationality

              stay address

              phone number

              social media id

              email

              civil id

              avatar

cv

partispate

              category

              job title

              certificate

              edu_level

              school_name

              school_admin_name

              edu_area_name

              governorate

              certificate_concern

achivments

project details

              project_title

              project_shorts

              word file

                  Perview

              project images.

                ×

              project voice.

              project video

              project powerpoint

              proprietorship certificate

            </form>


来源: stackexchange

问:
python celery Redis: how to disable exception raise for one exception
I am using all default settings in Celery 4.4.

```<code>Celery(__name__, backend='redis://redis_url.cache.amazonaws.com', broker='amqp://user@localhost:5672/app')
......

@app.task(bind=True, name='devices')
def _(self):
    try:
        execute(update_devices, self)
    except ConnectionResetError as e:
        logging.warning("exception {}".format(type(e).__name__))
</code>```

now everything works fine except there are exceptions throwing once in a while like this:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/redis/connection.py", line 697, in send_packed_command
    sendall(self._sock, item)
  File "/usr/local/lib/python3.8/site-packages/redis/_compat.py", line 9, in sendall
    return sock.sendall(*args, **kwargs)
ConnectionResetError: [Errno 104] Connection reset by peer
</code>```

It seems the exception catch doesn't work. my question is how to just simply disable/catch all the "ConnectionResetError" exceptions.

ContentLicense: CC BY-SA 4.0

Body:
I am using all default settings in Celery 4.4.

Celery(__name__, backend='redis://redis_url.cache.amazonaws.com', broker='amqp://user@localhost:5672/app')
......

@app.task(bind=True, name='devices')
def _(self):
    try:
        execute(update_devices, self)
    except ConnectionResetError as e:
        logging.warning("exception {}".format(type(e).__name__))

now everything works fine except there are exceptions throwing once in a while like this:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/redis/connection.py", line 697, in send_packed_command
    sendall(self._sock, item)
  File "/usr/local/lib/python3.8/site-packages/redis/_compat.py", line 9, in sendall
    return sock.sendall(*args, **kwargs)
ConnectionResetError: [Errno 104] Connection reset by peer

It seems the exception catch doesn't work. my question is how to just simply disable/catch all the "ConnectionResetError" exceptions.


问:
removeObserver doesn't remove an observer attached to an AVPlayer.currentItem object
Essentially I have a scrolling list of videos (think TikTok). I want each video to play while it's on the screen. The functionality is all there, but when you swipe to the next video, I want to remove the observer attached to the last video that caused it to loop. For some reason, calling .removeObserver with the previous AVPlayer's currentItem does not remove the AVPlayer from the NotificationCenter (I know this because I still see the old observer in the debugDescription).

```<code>@State var players: [AVPlayer] = [myAVPlayers]
@State var selectedIndex: Int = 0

VStack {
    // ForEach players makes a PlayerView that takes in an AVPlayer for the specific video
}.gesture(
    DragGesture()
        .onEnded { _ in

            // here, I know I need to somehow remove the observer for the previous video
            // I've tried NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: players[i].currentItem)
            // Also tried storing the players[selectedIndex].currentItem object in a @State var right before the .addObserver() is called and then passing that into the object parameter for both the add and remove functions.

            // selectedIndex is updated to new value

            NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: players[selectedIndex].currentItem, queue: .main) { (_) in
                print(NotificationCenter.default.debugDescription)
                let playerItem = players[selectedIndex]
                playerItem.seek(to: .zero)
                playerItem.play()
            }
        }
)
</code>```

Any help is much appreciated!

Body:
Essentially I have a scrolling list of videos (think TikTok). I want each video to play while it's on the screen. The functionality is all there, but when you swipe to the next video, I want to remove the observer attached to the last video that caused it to loop. For some reason, calling .removeObserver with the previous AVPlayer's currentItem does not remove the AVPlayer from the NotificationCenter (I know this because I still see the old observer in the debugDescription).

@State var players: [AVPlayer] = [myAVPlayers]
@State var selectedIndex: Int = 0

VStack {
    // ForEach players makes a PlayerView that takes in an AVPlayer for the specific video
}.gesture(
    DragGesture()
        .onEnded { _ in

            // here, I know I need to somehow remove the observer for the previous video
            // I've tried NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: players[i].currentItem)
            // Also tried storing the players[selectedIndex].currentItem object in a @State var right before the .addObserver() is called and then passing that into the object parameter for both the add and remove functions.

            // selectedIndex is updated to new value

            NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: players[selectedIndex].currentItem, queue: .main) { (_) in
                print(NotificationCenter.default.debugDescription)
                let playerItem = players[selectedIndex]
                playerItem.seek(to: .zero)
                playerItem.play()
            }
        }
)

Any help is much appreciated!


问:
MapboxGL access token with URL restriction returning 403 Forbidden
We use mapboxGL JS v1.8 for a simple single page store locator that loads a mapbox map and markers for various locations. Until yesterday 12/20 , I used an access token created over on the mapbox account with URL restriction to limit access to just our domain. This was working  just fine until yesterday when  it suddenly started returning a 403 forbidden error. The only way to "fix" it has been to remove the URL restrictions on the access token after which it works fine.
There have been  no changes to the app or the domain or to the access tokens for many months but for some reason  the URL restriction on the access token prevents access to even  the restricted domain. I've inspected the request headers sent to mapbox for the "origin" and "Referrer" headers and they are the same domain as they were previously when they were working fine.
Just curious if anyone else has experienced this issue and how it was resolved. I've sent a support ticket to mapbox but we're not a premium customer so , not sure if there will be any response.
(We've not exceeded any mapbox usage limits and our account is not overdue or anything like that)

The following mapbox-gl libraries are used in the app:
https://api.tiles.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.js
https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.2.0/mapbox-gl-geocoder.min.js
https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.2.0/mapbox-gl-geocoder.css
https://api.tiles.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.css

The code snippet used to load the map is :

```<code>mapboxgl.accessToken = config.accessToken; // accesstoken created on the account
    var map = new mapboxgl.Map({
        container: 'mapContainer',
        style: config.mapStyle,
        center: validCoordinates,
        zoom: 5
    });
</code>```

Body:
We use mapboxGL JS v1.8 for a simple single page store locator that loads a mapbox map and markers for various locations. Until yesterday 12/20 , I used an access token created over on the mapbox account with URL restriction to limit access to just our domain. This was working  just fine until yesterday when  it suddenly started returning a 403 forbidden error. The only way to "fix" it has been to remove the URL restrictions on the access token after which it works fine.
There have been  no changes to the app or the domain or to the access tokens for many months but for some reason  the URL restriction on the access token prevents access to even  the restricted domain. I've inspected the request headers sent to mapbox for the "origin" and "Referrer" headers and they are the same domain as they were previously when they were working fine.
Just curious if anyone else has experienced this issue and how it was resolved. I've sent a support ticket to mapbox but we're not a premium customer so , not sure if there will be any response.
(We've not exceeded any mapbox usage limits and our account is not overdue or anything like that)

The following mapbox-gl libraries are used in the app:
https://api.tiles.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.js
https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.2.0/mapbox-gl-geocoder.min.js
https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.2.0/mapbox-gl-geocoder.css
https://api.tiles.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.css

The code snippet used to load the map is :

mapboxgl.accessToken = config.accessToken; // accesstoken created on the account
    var map = new mapboxgl.Map({
        container: 'mapContainer',
        style: config.mapStyle,
        center: validCoordinates,
        zoom: 5
    });


问:
How to stop making window.open watch the tab?
When I click a button, it's supposed to essentially open a random website. When I press the button, it makes me view the opened tab.

I made a JSFiddle
https://jsfiddle.net/fL9rpox6/

```<code>  <button onclick="
    const random = Math.random();
    var idk = random
    window.open('https://www.bing.com/search?q=scp+agent+'+ idk + '+cool&qs=n&form=QBRE&sp=-1&pq=scp+agent+'+ idk +'+cool&sc=10-3&sk&cvid=3A6D4119FA794E4294E48112AB40166D&ghsh=0&ghacc=0&ghpl&safesearch=strict&adlt=strict', '_blank');
    ">Open</button>
</code>```

and if you click the button, you see that it forces you to see the new website. Can I make it so I can click the button multiple times without it making me change tabs each time?

None of the answers to the "duplicate" work for me, I have tried all of them.

Body:
When I click a button, it's supposed to essentially open a random website. When I press the button, it makes me view the opened tab.

I made a JSFiddle
https://jsfiddle.net/fL9rpox6/

  <button onclick="
    const random = Math.random();
    var idk = random
    window.open('https://www.bing.com/search?q=scp+agent+'+ idk + '+cool&qs=n&form=QBRE&sp=-1&pq=scp+agent+'+ idk +'+cool&sc=10-3&sk&cvid=3A6D4119FA794E4294E48112AB40166D&ghsh=0&ghacc=0&ghpl&safesearch=strict&adlt=strict', '_blank');
    ">Open</button>

and if you click the button, you see that it forces you to see the new website. Can I make it so I can click the button multiple times without it making me change tabs each time?

None of the answers to the "duplicate" work for me, I have tried all of them.


问:
Minified React error #321 on using useEffect in React
I'm having trouble with "Minified React error #321". I only get it when i'm using useEffect. Hopefully someone can help me out, i've been stuck for 3 hours trying to figure something out.

I'm beginning by exporting a .js file (not sure if js/jsx matters)

```<code>
import React, { useState, useEffect, useContext } from "react";

export default function CalDisplayLogic() {

setOccupiedFinalArray(occupiedBy); //occupiedBy is an array.

return occupiedFinalArray;
}
</code>```

Error Img

I don't seem to get this error whenever i remove useEffect, but the component constantly re-renders if i don't. Am wondering if there is any other solution for this.

```<code>import CalDisplayLogic from "./CalDisplayLogic";
export default function CalendarDisplay() {
useEffect(() => {
    CalDisplayLogic();
    console.log("effectRunning");
  }, [selectedDateState]);
</code>```

Body:
I'm having trouble with "Minified React error #321". I only get it when i'm using useEffect. Hopefully someone can help me out, i've been stuck for 3 hours trying to figure something out.

I'm beginning by exporting a .js file (not sure if js/jsx matters)

import React, { useState, useEffect, useContext } from "react";

export default function CalDisplayLogic() {

setOccupiedFinalArray(occupiedBy); //occupiedBy is an array.

return occupiedFinalArray;
}

Error Img

I don't seem to get this error whenever i remove useEffect, but the component constantly re-renders if i don't. Am wondering if there is any other solution for this.

import CalDisplayLogic from "./CalDisplayLogic";
export default function CalendarDisplay() {
useEffect(() => {
    CalDisplayLogic();
    console.log("effectRunning");
  }, [selectedDateState]);


问:
Mongodb aggregation lookup from the same collection
I have the following documents which show specific data of a selected Stock for the selected day.
MOSC, SHL, DDSM values are the signals. So if either of them are greater than 0 this indicates positive signal for that stock.

```<code>{
    "_id" : ObjectId("63a02b76de39412a1ce52d0c"),
    "Date" : ISODate("2022-12-13T00:00:00.000+0000"),
    "Stock" : "ALFAS",
    "Open" : 286.0,
    "High" : 308.3,
    "Low" : 285.0,
    "Price" : 308.3,
    "Change" : 9.99,
    "MOSC" : NumberInt(0),
    "SHL" : NumberInt(0),
    "DDSM" : NumberInt(0),
    "TF" : "D"
}

{
    "_id" : ObjectId("63a02b76de39412a1ce52cf5"),
    "Date" : ISODate("2022-12-13T00:00:00.000+0000"),
    "Stock" : "ACSEL",
    "Open" : 82.2,
    "High" : 84.0,
    "Low" : 81.0,
    "Price" : 82.15,
    "Change" : 0.18,
    "MOSC" : NumberInt(67),
    "SHL" : NumberInt(0),
    "DDSM" : NumberInt(0),
    "TF" : "D"
}
</code>```
```<code>
{ $or : [ { "MOSC" : { $gt : 0.0 } }, { "SHL" : { $gt : 0.0 } }, { "DDSM" : { $gt : 0.0 } } ], "Date" : ISODate("2022-12-12T00:00:00.000+0000") }
</code>```

So this query returns positive stocks for the selected day.
However i need to add new fields showing the changes and the sum of changes for the next days like:

```<code>{
    "_id" : ObjectId("63a02b76de39412a1ce52cf5"),
    "Date" : ISODate("2022-12-13T00:00:00.000+0000"),
    "Stock" : "ACSEL",
    "Open" : 82.2,
    "High" : 84.0,
    "Low" : 81.0,
    "Price" : 82.15,
    "Change" : 0.18,
    "MOSC" : NumberInt(67),
    "SHL" : NumberInt(0),
    "DDSM" : NumberInt(0),
    "TF" : "D",
    "Change 1D" : 3.83,
    "Change 2D" : -2.93,
    "Change 3D" : -1.09,
    "SUM 3D" :   -0.19
}
</code>```

I'm new to mongodb so this is important for me to get an idea on how to build up aggregations that i need.
Thanks in advance.

Body:
I have the following documents which show specific data of a selected Stock for the selected day.
MOSC, SHL, DDSM values are the signals. So if either of them are greater than 0 this indicates positive signal for that stock.

{
    "_id" : ObjectId("63a02b76de39412a1ce52d0c"),
    "Date" : ISODate("2022-12-13T00:00:00.000+0000"),
    "Stock" : "ALFAS",
    "Open" : 286.0,
    "High" : 308.3,
    "Low" : 285.0,
    "Price" : 308.3,
    "Change" : 9.99,
    "MOSC" : NumberInt(0),
    "SHL" : NumberInt(0),
    "DDSM" : NumberInt(0),
    "TF" : "D"
}

{
    "_id" : ObjectId("63a02b76de39412a1ce52cf5"),
    "Date" : ISODate("2022-12-13T00:00:00.000+0000"),
    "Stock" : "ACSEL",
    "Open" : 82.2,
    "High" : 84.0,
    "Low" : 81.0,
    "Price" : 82.15,
    "Change" : 0.18,
    "MOSC" : NumberInt(67),
    "SHL" : NumberInt(0),
    "DDSM" : NumberInt(0),
    "TF" : "D"
}

{ $or : [ { "MOSC" : { $gt : 0.0 } }, { "SHL" : { $gt : 0.0 } }, { "DDSM" : { $gt : 0.0 } } ], "Date" : ISODate("2022-12-12T00:00:00.000+0000") }

So this query returns positive stocks for the selected day.
However i need to add new fields showing the changes and the sum of changes for the next days like:

{
    "_id" : ObjectId("63a02b76de39412a1ce52cf5"),
    "Date" : ISODate("2022-12-13T00:00:00.000+0000"),
    "Stock" : "ACSEL",
    "Open" : 82.2,
    "High" : 84.0,
    "Low" : 81.0,
    "Price" : 82.15,
    "Change" : 0.18,
    "MOSC" : NumberInt(67),
    "SHL" : NumberInt(0),
    "DDSM" : NumberInt(0),
    "TF" : "D",
    "Change 1D" : 3.83,
    "Change 2D" : -2.93,
    "Change 3D" : -1.09,
    "SUM 3D" :   -0.19
}

I'm new to mongodb so this is important for me to get an idea on how to build up aggregations that i need.
Thanks in advance.


问:
I have an error when executing this basic program in JAVA that can obtain Methods, returns inputs and outputs of several .class files ¿Solution?
```<code>

package com.mycompany.dataclass;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class DataClass {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // Obtener la lista de archivos .class de la carpeta
        File folder = new File("E:\\ruta\\arcchivosclass");
        File[] listOfFiles = folder.listFiles();

        for (File file : listOfFiles) {
            if (file.isFile() && file.getName().endsWith(".class")) {
                // Cargar la clase utilizando un ClassLoader
                URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { folder.toURI().toURL() });
                Class<?> cls = classLoader.loadClass(file.getName().replace(".class", ""));

                // Obtener información de los métodos de la clase
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    System.out.println("Nombre del método: " + method.getName());
                    System.out.println("Tipo de retorno: " + method.getReturnType().getName());
                    System.out.println("Entradas: ");
                    for (Class<?> parameterType : method.getParameterTypes()) {
                        System.out.println(" - " + parameterType.getName());
                    }
                    System.out.println("Salidas: ");
                    for (Class<?> exceptionType : method.getExceptionTypes()) {
                        System.out.println(" - " + exceptionType.getName());
                    }
                }
            }
        }
    }
}
</code>```

The problem

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "" is null
at com.mycompany.dataclass.DataClass.main(DataClass.java:19)
Command execution failed.
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)

Body:
package com.mycompany.dataclass;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class DataClass {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // Obtener la lista de archivos .class de la carpeta
        File folder = new File("E:\\ruta\\arcchivosclass");
        File[] listOfFiles = folder.listFiles();

        for (File file : listOfFiles) {
            if (file.isFile() && file.getName().endsWith(".class")) {
                // Cargar la clase utilizando un ClassLoader
                URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { folder.toURI().toURL() });
                Class<?> cls = classLoader.loadClass(file.getName().replace(".class", ""));

                // Obtener información de los métodos de la clase
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    System.out.println("Nombre del método: " + method.getName());
                    System.out.println("Tipo de retorno: " + method.getReturnType().getName());
                    System.out.println("Entradas: ");
                    for (Class<?> parameterType : method.getParameterTypes()) {
                        System.out.println(" - " + parameterType.getName());
                    }
                    System.out.println("Salidas: ");
                    for (Class<?> exceptionType : method.getExceptionTypes()) {
                        System.out.println(" - " + exceptionType.getName());
                    }
                }
            }
        }
    }
}

The problem

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "" is null
at com.mycompany.dataclass.DataClass.main(DataClass.java:19)
Command execution failed.
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)


问:
Using the Microsoft Graph Beta Java SDK, how do I obtain the ReviewSet export operation?
I am working with the Microsoft Graph Beta Java SDK, specifically the 0.61.0-SNAPSHOT at the moment.

I am looking to perform an eDiscovery workflow in which I:

Create a compliance case (doc)

Create an associated SourceCollection (doc)

Create a ReviewSet (doc)

Add the SourceCollection to the ReviewSet(doc)

Begin export of the ReviewSet (doc)

Check status of export until done (?)

Download result of the export (?)

I am having trouble determining how to accomplish the last 2 steps, but seem to have things working up to that point.  To begin an export (having created the associated case, source collection and review set) I do the following:

```<code>ReviewSetExportParameterSet exportParameterSet = ReviewSetExportParameterSet
        .newBuilder()
        .withOutputName(outputName)
        .withDescription(description)
        .withAzureBlobContainer(null)
        .withAzureBlobToken(null)
        .withExportOptions(exportOptions)
        .withExportStructure(exportStructure)
        .build();

graphClient.compliance().ediscovery().cases(caseId).reviewSets(reviewSetId)
        .export(exportParameterSet)
        .buildRequest()
        .post();
</code>```

The call to post() returns no result and therefore it is not clear what the ID of the resulting caseExportOperation would be.  The export endpoint documentation mentions that the response should contain a location header with a URL to the export operation, but I am failing to see a way to get that response/header from the SDK.

Since that does not provide the created export operation, I've tried instead getting a listing of all the export operations associated with the appropriate case.  My intent would then be to filter to the export operation associated to the appropriate review set.  While not ideal, it would be something and for my user case, it would likely be fine for now.

```<code>CaseExportOperationCollectionPage pager = graphClient.compliance().ediscovery()
.cases(caseId).operationsAsCaseExportOperation()
    .buildRequest()
    .get();
</code>```

Unfortunately the actual call fails for me though (note the ID in URL below has been altered by me, real error has appropriate ID):

```<code>Dec 21, 2022 10:33:53 AM com.microsoft.graph.logger.DefaultLogger logError
SEVERE: CoreHttpProvider[sendRequestInternal] - 408Graph service exception
Dec 21, 2022 10:33:53 AM com.microsoft.graph.logger.DefaultLogger logError
SEVERE: Throwable detail: com.microsoft.graph.http.GraphServiceException: Error code: BadRequest
Error message: Specified HTTP method is not allowed for the request target.

[Some information was truncated for brevity, enable debug logging for more details]
com.microsoft.graph.http.GraphServiceException: Error code: BadRequest
Error message: Specified HTTP method is not allowed for the request target.

GET https://graph.microsoft.com/beta/compliance/ediscovery/cases/5f8e12a3-1234-1234-abcd-aed302b94ba5/operations/microsoft.graph.ediscovery.caseExportOperation
SdkVersion : graph-java/v0.61.0

400 : Bad Request

[Some information was truncated for brevity, enable debug logging for more details]
    at app//com.microsoft.graph.http.GraphServiceException.createFromResponse(GraphServiceException.java:419)
    at app//com.microsoft.graph.http.GraphServiceException.createFromResponse(GraphServiceException.java:378)
    at app//com.microsoft.graph.http.CoreHttpProvider.handleErrorResponse(CoreHttpProvider.java:512)
    at app//com.microsoft.graph.http.CoreHttpProvider.processResponse(CoreHttpProvider.java:442)
    at app//com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal(CoreHttpProvider.java:408)
    at app//com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:225)
    at app//com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:202)
    at app//com.microsoft.graph.http.BaseCollectionRequest.send(BaseCollectionRequest.java:103)
    at app//com.microsoft.graph.http.BaseEntityCollectionRequest.get(BaseEntityCollectionRequest.java:78)
</code>```

As the error implies, the endpoint apparently does not support GET, but that seems to be what the SDK will let me do for that call.  This is where I stand, not really sure how to accomplish the last bit of the workflow.  Any advice or suggestions are appreciated.  Thanks!

Follow-up 1

In reply to Brian's comment, I've gone through and modified much of my code to instead use the security endpoints over the compliance ones to run some tests.  I am getting stuck in a similar place unfortunately, monitoring the export progress and obtaining the download URL.

The documentation provides an example like the following for initiating an export:

graphClient.security().cases().ediscoveryCases(caseId).reviewSets(reviewSetId)
    .export(EdiscoveryReviewSetExportParameterSet
        .newBuilder()
        .withOutputName(outputName)
        .withDescription(description)
        .withAzureBlobContainer(null)
        .withAzureBlobToken(null)
        .withExportOptions(exportOptions)
        .withExportStructure(exportStructure)
        .build())
    .buildRequest()
    .post();
```
<p>The call to <code>post()</code> does not return an ID or object that can be used to identify the created export operation.  The documentation for obtaining the download URL for a completed export provides an example like the following:</p>
<pre class="lang-java prettyprint-override"><code>String string = graphClient.security().cases().ediscoveryCases(caseId).operations(operationId).microsoft.graph.security.ediscoveryExportOperation()
    .getDownloadUrl()
    .buildRequest()
    .get()
</code>```

At this point I wouldn't really know what the operationId would be though.  I suppose I could try to find it by getting al list of all the generic operations like so:

CaseOperationCollectionPage operationPager = graphClient.security().cases().ediscoveryCases(eDiscoReviewSet.getOwningCase().getId()).operations()
                .buildRequest().get();
```
<p>having that I could then look for the one that is the export operation that I want, but that seems like it might be error prone.</p>
<p>Also I am wondering if perhaps something went wrong with generation of the example for obtaining the download URL as this bit looks suspicious:</p>
<pre class="lang-java prettyprint-override"><code>.operations(operationId).microsoft.graph.security.ediscoveryExportOperation()
</code>```

If you have any additional questions, please let me know.  Thank you!

Follow-up 2

I am probably going to just piggy-back off the seemingly relevant GitHub issue here: https://github.com/microsoftgraph/msgraph-beta-sdk-java/issues/475

I will try and make an effort to and come back and update with whatever resolution comes to fruition.

Body:
I am working with the Microsoft Graph Beta Java SDK, specifically the 0.61.0-SNAPSHOT at the moment.

I am looking to perform an eDiscovery workflow in which I:

Create a compliance case (doc)

Create an associated SourceCollection (doc)

Create a ReviewSet (doc)

Add the SourceCollection to the ReviewSet(doc)

Begin export of the ReviewSet (doc)

Check status of export until done (?)

Download result of the export (?)

I am having trouble determining how to accomplish the last 2 steps, but seem to have things working up to that point.  To begin an export (having created the associated case, source collection and review set) I do the following:

ReviewSetExportParameterSet exportParameterSet = ReviewSetExportParameterSet
        .newBuilder()
        .withOutputName(outputName)
        .withDescription(description)
        .withAzureBlobContainer(null)
        .withAzureBlobToken(null)
        .withExportOptions(exportOptions)
        .withExportStructure(exportStructure)
        .build();

graphClient.compliance().ediscovery().cases(caseId).reviewSets(reviewSetId)
        .export(exportParameterSet)
        .buildRequest()
        .post();

The call to post() returns no result and therefore it is not clear what the ID of the resulting caseExportOperation would be.  The export endpoint documentation mentions that the response should contain a location header with a URL to the export operation, but I am failing to see a way to get that response/header from the SDK.

Since that does not provide the created export operation, I've tried instead getting a listing of all the export operations associated with the appropriate case.  My intent would then be to filter to the export operation associated to the appropriate review set.  While not ideal, it would be something and for my user case, it would likely be fine for now.

CaseExportOperationCollectionPage pager = graphClient.compliance().ediscovery()
.cases(caseId).operationsAsCaseExportOperation()
    .buildRequest()
    .get();

Unfortunately the actual call fails for me though (note the ID in URL below has been altered by me, real error has appropriate ID):

Dec 21, 2022 10:33:53 AM com.microsoft.graph.logger.DefaultLogger logError
SEVERE: CoreHttpProvider[sendRequestInternal] - 408Graph service exception
Dec 21, 2022 10:33:53 AM com.microsoft.graph.logger.DefaultLogger logError
SEVERE: Throwable detail: com.microsoft.graph.http.GraphServiceException: Error code: BadRequest
Error message: Specified HTTP method is not allowed for the request target.

[Some information was truncated for brevity, enable debug logging for more details]
com.microsoft.graph.http.GraphServiceException: Error code: BadRequest
Error message: Specified HTTP method is not allowed for the request target.

GET https://graph.microsoft.com/beta/compliance/ediscovery/cases/5f8e12a3-1234-1234-abcd-aed302b94ba5/operations/microsoft.graph.ediscovery.caseExportOperation
SdkVersion : graph-java/v0.61.0

400 : Bad Request

[Some information was truncated for brevity, enable debug logging for more details]
    at app//com.microsoft.graph.http.GraphServiceException.createFromResponse(GraphServiceException.java:419)
    at app//com.microsoft.graph.http.GraphServiceException.createFromResponse(GraphServiceException.java:378)
    at app//com.microsoft.graph.http.CoreHttpProvider.handleErrorResponse(CoreHttpProvider.java:512)
    at app//com.microsoft.graph.http.CoreHttpProvider.processResponse(CoreHttpProvider.java:442)
    at app//com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal(CoreHttpProvider.java:408)
    at app//com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:225)
    at app//com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:202)
    at app//com.microsoft.graph.http.BaseCollectionRequest.send(BaseCollectionRequest.java:103)
    at app//com.microsoft.graph.http.BaseEntityCollectionRequest.get(BaseEntityCollectionRequest.java:78)

As the error implies, the endpoint apparently does not support GET, but that seems to be what the SDK will let me do for that call.  This is where I stand, not really sure how to accomplish the last bit of the workflow.  Any advice or suggestions are appreciated.  Thanks!

Follow-up 1

In reply to Brian's comment, I've gone through and modified much of my code to instead use the security endpoints over the compliance ones to run some tests.  I am getting stuck in a similar place unfortunately, monitoring the export progress and obtaining the download URL.

The documentation provides an example like the following for initiating an export:

graphClient.security().cases().ediscoveryCases(caseId).reviewSets(reviewSetId)
    .export(EdiscoveryReviewSetExportParameterSet
        .newBuilder()
        .withOutputName(outputName)
        .withDescription(description)
        .withAzureBlobContainer(null)
        .withAzureBlobToken(null)
        .withExportOptions(exportOptions)
        .withExportStructure(exportStructure)
        .build())
    .buildRequest()
    .post();

The call to post() does not return an ID or object that can be used to identify the created export operation.  The documentation for obtaining the download URL for a completed export provides an example like the following:

String string = graphClient.security().cases().ediscoveryCases(caseId).operations(operationId).microsoft.graph.security.ediscoveryExportOperation()
    .getDownloadUrl()
    .buildRequest()
    .get()

At this point I wouldn't really know what the operationId would be though.  I suppose I could try to find it by getting al list of all the generic operations like so:

CaseOperationCollectionPage operationPager = graphClient.security().cases().ediscoveryCases(eDiscoReviewSet.getOwningCase().getId()).operations()
                .buildRequest().get();

having that I could then look for the one that is the export operation that I want, but that seems like it might be error prone.

Also I am wondering if perhaps something went wrong with generation of the example for obtaining the download URL as this bit looks suspicious:

.operations(operationId).microsoft.graph.security.ediscoveryExportOperation()

If you have any additional questions, please let me know.  Thank you!

Follow-up 2

I am probably going to just piggy-back off the seemingly relevant GitHub issue here: https://github.com/microsoftgraph/msgraph-beta-sdk-java/issues/475

I will try and make an effort to and come back and update with whatever resolution comes to fruition.


问:
Spring Data JPA offset is inject in the database query but limit is not
I am using spring data JPA. I am building a query where I need to limit the query. I am passing the offset and limit value from frontend. When query is executed in the database I see that offset is in the query but limit is not.

It is asking the database to pickup all the  records as offset + limit. It's not similar with raw query limit then. How can I act the limit value as raw query so that the query execution get faster without native query?

My method where I am building the criteria:

```<code>public List<Role> findAllByRoleNameAndUpdatedBy(String roleName, Integer offset, Integer limit) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Role> cq = cb.createQuery(Role.class);
    Root<Role> role = cq.from(Role.class);
    Predicate roleNamePredicate = cb.like(role.get("roleName"), roleName + "%");
    cq.where(roleNamePredicate);
    TypedQuery<Role> query = em.createQuery(cq).setFirstResult(offset) // offset
            .setMaxResults(limit); // limit
    return query.getResultList();
}
</code>```

Edit:

My controller method:

```<code>@GetMapping(value = "/list/{roleName}/{offset}/{limit}")
public List<Role> getListDummy(@PathVariable String roleName, @PathVariable Integer offset, @PathVariable Integer limit) {
    return roleServiceDummy.findAllByRoleNameAndUpdatedBy(roleName, offset, limit);
}
</code>```

My API in postman: localhost:9000/role/list/test_/1000/1

Generated query in console:

```<code>select
    top 1001 role0_.id as id1_13_,
    role0_.created_by_id as created_2_13_,
    role0_.created_date as created_3_13_,
    role0_.modified_date as modified4_13_,
    role0_.updated_by_id as updated_5_13_,
    role0_.role_name as role_nam6_13_
from
    auth_role role0_
where
    role0_.role_name like ?
</code>```

As we can see it is picking all the 1001 rows.

Body:
I am using spring data JPA. I am building a query where I need to limit the query. I am passing the offset and limit value from frontend. When query is executed in the database I see that offset is in the query but limit is not.

It is asking the database to pickup all the  records as offset + limit. It's not similar with raw query limit then. How can I act the limit value as raw query so that the query execution get faster without native query?

My method where I am building the criteria:

public List<Role> findAllByRoleNameAndUpdatedBy(String roleName, Integer offset, Integer limit) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Role> cq = cb.createQuery(Role.class);
    Root<Role> role = cq.from(Role.class);
    Predicate roleNamePredicate = cb.like(role.get("roleName"), roleName + "%");
    cq.where(roleNamePredicate);
    TypedQuery<Role> query = em.createQuery(cq).setFirstResult(offset) // offset
            .setMaxResults(limit); // limit
    return query.getResultList();
}

Edit:

My controller method:

@GetMapping(value = "/list/{roleName}/{offset}/{limit}")
public List<Role> getListDummy(@PathVariable String roleName, @PathVariable Integer offset, @PathVariable Integer limit) {
    return roleServiceDummy.findAllByRoleNameAndUpdatedBy(roleName, offset, limit);
}

My API in postman: localhost:9000/role/list/test_/1000/1

Generated query in console:

select
    top 1001 role0_.id as id1_13_,
    role0_.created_by_id as created_2_13_,
    role0_.created_date as created_3_13_,
    role0_.modified_date as modified4_13_,
    role0_.updated_by_id as updated_5_13_,
    role0_.role_name as role_nam6_13_
from
    auth_role role0_
where
    role0_.role_name like ?

As we can see it is picking all the 1001 rows.


问:
Configuring an Eclipse SourceViewer for Java
I am trying to create a viewer that embeds a Java Editor/Viewer. However, I cannot get the Source Viewer to do the proper Java scanning & coloring. This is the code I have so far.

```<code>ScopedPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE,
        ID);
JavaTextTools tools = new JavaTextTools(store);

Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));

viewer = new SourceViewer(composite, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
viewer.getTextWidget().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
viewer.setEditable(true);
viewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
Document document = new Document();
tools.setupJavaDocumentPartitioner(document);
viewer.setDocument(document);
viewer.configure(new JavaSourceViewerConfiguration(tools.getColorManager(), store, null,
        IJavaPartitions.JAVA_PARTITIONING));
</code>```

Just amazed how hard it seem to just embed a simple Java editor ... Whatever I do, the viewer works but remains without any coloring.

Body:
I am trying to create a viewer that embeds a Java Editor/Viewer. However, I cannot get the Source Viewer to do the proper Java scanning & coloring. This is the code I have so far.

ScopedPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE,
        ID);
JavaTextTools tools = new JavaTextTools(store);

Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));

viewer = new SourceViewer(composite, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
viewer.getTextWidget().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
viewer.setEditable(true);
viewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
Document document = new Document();
tools.setupJavaDocumentPartitioner(document);
viewer.setDocument(document);
viewer.configure(new JavaSourceViewerConfiguration(tools.getColorManager(), store, null,
        IJavaPartitions.JAVA_PARTITIONING));

Just amazed how hard it seem to just embed a simple Java editor ... Whatever I do, the viewer works but remains without any coloring.


问:
how can one make a mongoDB field of type map of map
I am kinda new to mongoose and have an existing schema that looks like this

```<code>const folder = new Schema({
  files: {
    type: Map,
    of: String
  },
})
</code>```

and i want files field to be something like this:

```<code>          files: {
            '054wrtrd': { 'fileName': "hello.js", 'editLink': "none", 'downloadLink': "none" },
            'gdtgeyev5': { 'fileName': "bye.js", 'editLink': "none", 'downloadLink': "none" },
          },
</code>```

however, i am getting this error

```<code> {
        "stringValue": "\"{ fileName: 'none', editLink: 'none', downloadLink: 'none' }\"",
        "valueType": "Object",
        "kind": "string",
        "value": {
            "fileName": "none",
            "editLink": "none",
            "downloadLink": "none"
        },
        "path": "files.$*",
        "reason": null,
        "name": "CastError",
        "message": "Cast to string failed for value \"{ fileName: 'none', editLink: 'none', downloadLink: 'none' }\" (type Object) at path \"files.$*\""
    }
</code>```

Is there a way to set the field type to be like Map:Map or something along those lines?
plus how would i retrieve for instance fileName

Thanks in advance!

Edit:
I found the answer, i needed to declare the files field like this way

```<code>    const folder = new Schema({
      files: {
        type: Map,
        of: {
          fileName: { type: String },
          editLink: { type: String },
          downloadLink: { type: String },
        },
      },
    });
</code>```

Body:
I am kinda new to mongoose and have an existing schema that looks like this

const folder = new Schema({
  files: {
    type: Map,
    of: String
  },
})

and i want files field to be something like this:

          files: {
            '054wrtrd': { 'fileName': "hello.js", 'editLink': "none", 'downloadLink': "none" },
            'gdtgeyev5': { 'fileName': "bye.js", 'editLink': "none", 'downloadLink': "none" },
          },

however, i am getting this error

 {
        "stringValue": "\"{ fileName: 'none', editLink: 'none', downloadLink: 'none' }\"",
        "valueType": "Object",
        "kind": "string",
        "value": {
            "fileName": "none",
            "editLink": "none",
            "downloadLink": "none"
        },
        "path": "files.$*",
        "reason": null,
        "name": "CastError",
        "message": "Cast to string failed for value \"{ fileName: 'none', editLink: 'none', downloadLink: 'none' }\" (type Object) at path \"files.$*\""
    }

Is there a way to set the field type to be like Map:Map or something along those lines?
plus how would i retrieve for instance fileName

Thanks in advance!

Edit:
I found the answer, i needed to declare the files field like this way

    const folder = new Schema({
      files: {
        type: Map,
        of: {
          fileName: { type: String },
          editLink: { type: String },
          downloadLink: { type: String },
        },
      },
    });


问:
Performance cost of DB::listen()
In our Laravel 8 app, we would like to leverage a DB::listen() call in our AppServiceProvider to catch any database query that takes longer than a specified length of time. Once caught, it can be logged, emailed, or sent to any third-party debugging service for investigation. This was found in a recent LaravelDaily video referencing one of the guidelines used at a Dutch software company.

Our concern is whether or not adding this listener would result in a performance hit on our database calls. If so, how much of a hit? We have an extensive database, with some tables reaching millions of records. We've indexed everything the best we can but are still worried that adding such a listener might slow down all of our queries too much.

Does anyone have any experience with DB::listen() and can speak to its performance cost?

Title: Performance cost of DB::listen()


问:
PostgreSQL: Is there a way to represent "one or more tokens" at index time for placeholder text?
I'm currently trying to search message catalog data that may contain placeholder tokens such as "{0}".

As an example, lets use "Your document is titled '{0}'. Is this correct?"  The placeholder is in the middle of the text, and could potentially contain multiple tokens.

I would like to make it possible for a user to search for "Your document is titled 'A Tale of Two Cities'. Is this correct?" and be able to return the above record with the placeholder.

With the default configuration, the placeholder is processed into a token itself (0), but I was wondering if there is any hint that I could put into the record/index to allow the index to recognize "one or more tokens can go here"

PostgreSQL has a proximity operator '<->' that can be used in a query to return results that are close enough based on the distance between two tokens.  The - can be replaced by a number which changes it to "within X tokens".  So I could use the following query to retrieve this record:

SELECT * FROM "Messages" WHERE "tsvec_en" @@ to_tsquery('english', 'Your & document & is & titled <-> Is & this & correct')

However, this only works if I know about the placeholder and can replace it with the proximity operator prior to running the query. I would like to pass the query through plainto_tsquery() as entered and be able to find the placeholder record.

Is there a way where I could replace the "{0}" token at index time (The records are being pushed in from an external application, so I can replace the placeholder with something else before hand), or provide a hint to the index such that a search using plainto_tsquery('english', 'Your document is titled ''A Tale of Two Cities''. Is this correct?') would still be able to find the record?


问:
How do I determine requirements.yml for a given Ansible role?
Beginner alert - I'm using ansible for the first time and trying to figure out some very basic steps here.

I want to make a playbook that installs the gcloud SDK. So far, I've:

installed ansible with sudo apt install ansible after adding an entry in /etc/sources.list.d/ansible.list

copied the example playbook from https://github.com/ansible/role-install-gcloud#example-playbook

tried running the playbook with sudo ansible-playbook playbook.yaml -K

I'm getting ERROR! the role 'role-install-gcloud' was not found in ...

Sounds like I need a requirements.yml file defining role-install-gcloud, and then run ansible-galaxy install -r requirements.yml.

My question is: how do I determine what goes in requirements.yml?

If there's a better way to approach this, I'm very interested in knowing.

Sorry if this is a dupe. I searched for help on this and couldn't find something that assumed more ignorance :)


问:
javax.ws.rs custom BeanParam with Inheritance not working
I have a custom JAX RS BeanParam (XYZ) as defined below.

```<code>@FieldDefaults(level = AccessLevel.PRIVATE)
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class XYZ extends ABC {
  @PathParam("xyz") @Valid String xyz;
}
</code>```
```<code>@FieldDefaults(level = AccessLevel.PRIVATE)
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class ABC {
  @PathParam("abc") @Valid String abc;
}
</code>```

XYZ extends ABC class. I use the above custom BeanParam in the controller / resource class method like this -

```<code>@GET
@CustomAnnotation
public Object test(@Valid @BeanParam XYZ xyz) {
  ...
}
</code>```

When I try to get the method arguments as part of the CustomAnnotation interceptor, it gives me only xyz and not abc for XYZ BeanParam.

Is there something wrong with the Lombok specifications which I have done that is preventing abc to be not included ?

Body:
I have a custom JAX RS BeanParam (XYZ) as defined below.

@FieldDefaults(level = AccessLevel.PRIVATE)
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class XYZ extends ABC {
  @PathParam("xyz") @Valid String xyz;
}

@FieldDefaults(level = AccessLevel.PRIVATE)
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class ABC {
  @PathParam("abc") @Valid String abc;
}

XYZ extends ABC class. I use the above custom BeanParam in the controller / resource class method like this -

@GET
@CustomAnnotation
public Object test(@Valid @BeanParam XYZ xyz) {
  ...
}

When I try to get the method arguments as part of the CustomAnnotation interceptor, it gives me only xyz and not abc for XYZ BeanParam.

Is there something wrong with the Lombok specifications which I have done that is preventing abc to be not included ?


问:
free() function always crash
so, all my work just fine, but only the free function is disable
i'm pretty sure that's the problem is in the way i'm using malloc

```<code>// This is the head

typedef struct Contact {
    char*firstName;
    char* lastName;
    char* phoneNum;
    struct Contact* next
} Contact;

</code>```

//this is how I allocate and create new contact
Just example for how I try to allocate using malloc

```<code>
Contact* createNewCont(char* fName, char* lName, char* phoNum)
{
    Contact* newCont;
    newCont = malloc(sizeof (newCont));

    //allocate and check all the string in the contact
    newCont->firstName = malloc(strlen(fName));
    printf ("%d",strlen(fName));
    if(newCont->firstName == NULL)
        return NULL;
    strcpy(newCont->firstName,fName);

}
</code>```

here the problem happend
I try to free specifc contact

```<code>int freeParam(Contact** head,char* fName, char* lName)
{
    Contact* temp = *head;
    int isExist = FALSE;
    int compVal1, compVal2;

    if (temp == NULL)
    {
        printf("null");
        return FALSE;
    }
    compVal1 = strcmp((*head)->firstName,fName);
    compVal2 = strcmp((*head)->lastName,lName);
    if (compVal1 == 0 && compVal2 == 0)
    {
        if (temp->next == NULL)
        {
            Contact* toRemvoe = *head;
            *head = NULL;
            return TRUE;
        }
        Contact* toRemvoe = *head;
        (*head) = (*head)->next;

        free(toRemvoe->firstName);
        free(toRemvoe->lastName);
        free(toRemvoe->phoneNum);
        free(toRemvoe);
        toRemvoe = NULL;
        return TRUE;
    }

</code>```

I saw some answers but didnt understand much

I try few diffrent ways, to allocate using malloc
but I got the same result

Title: free() function always crash

Body:
so, all my work just fine, but only the free function is disable
i'm pretty sure that's the problem is in the way i'm using malloc

// This is the head

typedef struct Contact {
    char*firstName;
    char* lastName;
    char* phoneNum;
    struct Contact* next
} Contact;

//this is how I allocate and create new contact
Just example for how I try to allocate using malloc

Contact* createNewCont(char* fName, char* lName, char* phoNum)
{
    Contact* newCont;
    newCont = malloc(sizeof (newCont));

    //allocate and check all the string in the contact
    newCont->firstName = malloc(strlen(fName));
    printf ("%d",strlen(fName));
    if(newCont->firstName == NULL)
        return NULL;
    strcpy(newCont->firstName,fName);

}

here the problem happend
I try to free specifc contact

int freeParam(Contact** head,char* fName, char* lName)
{
    Contact* temp = *head;
    int isExist = FALSE;
    int compVal1, compVal2;

    if (temp == NULL)
    {
        printf("null");
        return FALSE;
    }
    compVal1 = strcmp((*head)->firstName,fName);
    compVal2 = strcmp((*head)->lastName,lName);
    if (compVal1 == 0 && compVal2 == 0)
    {
        if (temp->next == NULL)
        {
            Contact* toRemvoe = *head;
            *head = NULL;
            return TRUE;
        }
        Contact* toRemvoe = *head;
        (*head) = (*head)->next;

        free(toRemvoe->firstName);
        free(toRemvoe->lastName);
        free(toRemvoe->phoneNum);
        free(toRemvoe);
        toRemvoe = NULL;
        return TRUE;
    }

I saw some answers but didnt understand much

I try few diffrent ways, to allocate using malloc
but I got the same result


问:
docker compose giving permission denied error on GCP
I'm trying to run my docker compose file and I have a few issues

The first is I can not run docker compose I can only run docker-compose I'm running docker version 20.10.5. When I try and run docker compose I get an error saying docker compose not found. When I try and run my docker compose command using docker-compose I get the below error docker-compose -f docker-compose.prod.yml up --build


问:
Use argv from main.c in another .c file (segmentation error?)
Basically my problem is, that I get a segmentation error when I try to use the passed argv[] from my main.c in another .c file.
I have three files:

main.c

```<code>...
#include "header.h"
int main(int argc, char *argv[]) {

int number;

if(argv[4] == NULL) {
 number = 512;
 } else {
  number = atoi(argv[4]);
}

 if (strcmp(argv[1], "test") == 0) {
   method1(argv[2], argv[3], number);
 }
...

return 0;
}
</code>```

filewithmethods.c

```<code>...
#include "header.h"
void method1(char *a[], char *b[], int c) {
 printf("a contains: %s\n", a[0]);
}
...
</code>```

header.h

```<code>void method1(char *a[], char *b[], int c);
</code>```

When it reaches the printf in filewithmethods.c, I get a segmentation error and I can't access the arguments from my main.c. I'm aware it has something to do with memory allocation and/or pointers, but I still can't figure out how to get it to work, as im very new to C (and programming in general).

Body:
Basically my problem is, that I get a segmentation error when I try to use the passed argv[] from my main.c in another .c file.
I have three files:

main.c

...
#include "header.h"
int main(int argc, char *argv[]) {

int number;

if(argv[4] == NULL) {
 number = 512;
 } else {
  number = atoi(argv[4]);
}

 if (strcmp(argv[1], "test") == 0) {
   method1(argv[2], argv[3], number);
 }
...

return 0;
}

filewithmethods.c

...
#include "header.h"
void method1(char *a[], char *b[], int c) {
 printf("a contains: %s\n", a[0]);
}
...

header.h

void method1(char *a[], char *b[], int c);

When it reaches the printf in filewithmethods.c, I get a segmentation error and I can't access the arguments from my main.c. I'm aware it has something to do with memory allocation and/or pointers, but I still can't figure out how to get it to work, as im very new to C (and programming in general).


问:
Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
I want to see that some data will come from an array through the checkbox. But when I select such an error is showing!

```<code>{groupList && groupList.length > 0 && (
    <div className="form-check form-check-inline">
        {groupList.map((group) => (
          <div>
            <input
              className="form-check-input"
              type="checkbox"
              id={group.id}

              value={group.id}
              onChange={(e) => {
                setGroups(
                  Array.from(
                    e.target.options,
                    (item) => item.value
                  )
                );

              }}
            />
            <label className="form-check-label" htmlFor={group.id}>
              {group.name}
            </label>
          </div>
        ))}
  </div>
)}
</code>```

How to solve?

Thanks in advance.

Body:
I want to see that some data will come from an array through the checkbox. But when I select such an error is showing!

{groupList && groupList.length > 0 && (

        {groupList.map((group) => (

            <input
              className="form-check-input"
              type="checkbox"
              id={group.id}

              value={group.id}
              onChange={(e) => {
                setGroups(
                  Array.from(
                    e.target.options,
                    (item) => item.value
                  )
                );

              }}
            />

              {group.name}

        ))}

)}

How to solve?

Thanks in advance.


问:
How to save history from django-simple-history in different database?
I'm new to Django and currently, I'm trying to implement Django-simple-history in my project, but I found a problem, I want to save my object in the default database and the history in a different database, I found that I can indicate the history model to not use the main database like this:

history = HistoricalRecords(use_base_model_db=False)

But I can't find any information about how to achieve that I know that I can save the object in a specific database like this:

obj.save("database_name")

or select which database to use:

poll = Poll.objects.using('other').create(question='Question 1')

I know that only calling save() will store the object in the default database but I don't know how to save only the historical object in a different database.

Anyone can help me with this?


问:
How to deal with does not contain an msbuild solution or packages.config file to restore
I have created one React app with Node JS Backend and Firebase Services. I want to deploy it on Azure platform. I filled basics fields like name of you app, resource group. In deployment I chooses Github and connect Azure to My github repo where my code exist. After that all It shows me Deployment is completed. But in background process Azure is making Actions with github. After 36 seconds my build task failed. So what should i do now? If I am going wrong process then can you suggest me a step wise process to how to deploy

Here error occurred

In line 20 we can see that content is deleted


问:
Why is ipywidgets interact not providing a menu
Anyone know why i'm not getting a dropdown menu with with?

```<code>@interact
def get_q(x = ['A', 'B']):
    return
    """
    select * from table where x = {}
    """.format(x)
</code>```

it just says interactive(children=(Dropdown(description='x', options=('A', 'B'), value='A'...)

Body:
Anyone know why i'm not getting a dropdown menu with with?

@interact
def get_q(x = ['A', 'B']):
    return
    """
    select * from table where x = {}
    """.format(x)

it just says interactive(children=(Dropdown(description='x', options=('A', 'B'), value='A'...)


问:
How to reverse/use 2d texture or texture atlas to 3d models
So recently I wanted to make mods on some games and I'm already done some digging. All I found are only 2d textures, there's no 3d model or object that can be opened on 3d software like Blender. There are many texture for others like texture on character, weapon, etc. But i chose this one just for example, so I have this book texture like this:

It was in PCT format. There are two of them, one that is only PCT and the other is PCT_Header (i don't know how to open that header) then I convert it to TGA and then convert it again to JPG. So my question is how to use or convert that texture into 3d models? so I can mod it properly in 3d, not in 2d. Because the game seems don't have 3d models, I always found only 2d textures. Thank you.


问:
Variable returns as both boolean and array when assigned
Do you remember that previously when you would use a boolean as an array, php would send a notice, but with php8 that notice is a warning now?

```<code>$obj = false;
var_dump($obj); /* false */
var_dump($obj[1]); /* null (and warning now) */
</code>```

Is there a way to create an object/class that has that same behaviour?
In other words, can you create a class that when assigned directly to a variable behaves as one data type but that class can also be consumed as an array and return a different value/data-type?

Body:
Do you remember that previously when you would use a boolean as an array, php would send a notice, but with php8 that notice is a warning now?

$obj = false;
var_dump($obj); /* false */
var_dump($obj[1]); /* null (and warning now) */

Is there a way to create an object/class that has that same behaviour?
In other words, can you create a class that when assigned directly to a variable behaves as one data type but that class can also be consumed as an array and return a different value/data-type?


问:
PCF react component (tinymce wrapper) fails in Power Apps Studio with "Promise.allSettled is not a function" error
I have constructed a PowerApps PCF react component by wrapping tinyMCE library to get a rich text editor component for canvas apps. It works perfect while testing in Visual Studio Code, but fails to render editor UI being loaded into Power Apps Studio. It writes:

```<code>tinymce.min.js:9 Uncaught TypeError: Promise.allSettled is not a function
at r (tinymce.min.js:9:63402)
at s (tinymce.min.js:9:63751)
at ya.loadScripts (tinymce.min.js:9:63951)
at ya.loadQueue (tinymce.min.js:9:63108)
at MR (tinymce.min.js:9:360088)
at tinymce.min.js:9:395090
at jA.render (tinymce.min.js:9:395106)
at tinymce.min.js:9:403331
at Array.<anonymous> (tinymce.min.js:9:403341)
at Ne (tinymce.min.js:9:5303)
</code>```

It looks like a react-native error: https://stackoverflow.com/questions/66575667/promise-allsettled-is-not-a-function. How to get rid of this?

It works well in test environment, so I think the question is about appropriate intergity between Power Apps environment (react-native in use?) and tinyMCE library (fail-safe Promise.allSettled usage?). I wonder if someone confirm my assumptions and probably look under the hood there )

Body:
I have constructed a PowerApps PCF react component by wrapping tinyMCE library to get a rich text editor component for canvas apps. It works perfect while testing in Visual Studio Code, but fails to render editor UI being loaded into Power Apps Studio. It writes:

tinymce.min.js:9 Uncaught TypeError: Promise.allSettled is not a function
at r (tinymce.min.js:9:63402)
at s (tinymce.min.js:9:63751)
at ya.loadScripts (tinymce.min.js:9:63951)
at ya.loadQueue (tinymce.min.js:9:63108)
at MR (tinymce.min.js:9:360088)
at tinymce.min.js:9:395090
at jA.render (tinymce.min.js:9:395106)
at tinymce.min.js:9:403331
at Array.<anonymous> (tinymce.min.js:9:403341)
at Ne (tinymce.min.js:9:5303)

It looks like a react-native error: https://stackoverflow.com/questions/66575667/promise-allsettled-is-not-a-function. How to get rid of this?

It works well in test environment, so I think the question is about appropriate intergity between Power Apps environment (react-native in use?) and tinyMCE library (fail-safe Promise.allSettled usage?). I wonder if someone confirm my assumptions and probably look under the hood there )


问:
std::ifstream read into vector results in 0 sized vector
I'm aware that there are other ways to accomplish the read of data. But I am confused, why in this code does the size print as 0? file.txt is a random text file with more than 4 characters.

```<code>#include <iostream>
#include <fstream>
#include <vector>

int main() {
  std::ifstream ifs("file.txt");
  std::vector<char> file_vec{};
  file_vec.reserve(4);
  ifs.read(file_vec.data(), 4);
  std::cout << file_vec.size() << std::endl;
  ifs.close();
}
</code>```

Body:
I'm aware that there are other ways to accomplish the read of data. But I am confused, why in this code does the size print as 0? file.txt is a random text file with more than 4 characters.

#include <iostream>
#include <fstream>
#include <vector>

int main() {
  std::ifstream ifs("file.txt");
  std::vector<char> file_vec{};
  file_vec.reserve(4);
  ifs.read(file_vec.data(), 4);
  std::cout << file_vec.size() << std::endl;
  ifs.close();
}


问:
How do i use and manipulate the many-to-many table i've created with EF core code-first made through Icollection?
The following code creates a many-to-many EmployeeTitle table with EmployeesId and TitlesID as it's primary keys

```<code>public class Employee : IEntity
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public double? Salery { get; set; }
        public bool InUnion { get; set; }
        public int? BranchId { get; set; }
        public Branch Branch { get; set; }

        public ICollection<Title> Titles { get; set; }

</code>```

and

```<code>public class Title : IEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public ICollection<Employee> Employees { get; set; }
    }
</code>```

However i don't know how to manipulate the data thorugh an api controller (Trying to get it to work with swagger) with post and delete.
I have been able to add seed data thorugh this code in my DbContext but i don't know if it has any relavence:

```<code>//Seed for EmployeeTitles
            builder.Entity<Employee>().HasMany(e => e.Titles).WithMany(e => e.Employees)
            .UsingEntity(j => j.HasData(
                new {EmployeesId = 1, TitlesId = 1},
                new {EmployeesId = 1, TitlesId = 9},
                new {EmployeesId = 2, TitlesId = 3},
                new {EmployeesId = 2, TitlesId = 4},
                new {EmployeesId = 3, TitlesId = 10},
                new {EmployeesId = 3, TitlesId = 12},
                new {EmployeesId = 4, TitlesId = 11},
                new {EmployeesId = 5, TitlesId = 8}
                ));
</code>```

I tried to use my DbContext defined as db in my controller to get a similair result as the above seed data code, but i've had no luck and haven't found any good answers online related to my specific question. Is there no other way then by creating the connection with fluent api and a entity class for EmployeeTitle?

Body:
The following code creates a many-to-many EmployeeTitle table with EmployeesId and TitlesID as it's primary keys

public class Employee : IEntity
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public double? Salery { get; set; }
        public bool InUnion { get; set; }
        public int? BranchId { get; set; }
        public Branch Branch { get; set; }

        public ICollection<Title> Titles { get; set; }

and

public class Title : IEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public ICollection<Employee> Employees { get; set; }
    }

However i don't know how to manipulate the data thorugh an api controller (Trying to get it to work with swagger) with post and delete.
I have been able to add seed data thorugh this code in my DbContext but i don't know if it has any relavence:

//Seed for EmployeeTitles
            builder.Entity<Employee>().HasMany(e => e.Titles).WithMany(e => e.Employees)
            .UsingEntity(j => j.HasData(
                new {EmployeesId = 1, TitlesId = 1},
                new {EmployeesId = 1, TitlesId = 9},
                new {EmployeesId = 2, TitlesId = 3},
                new {EmployeesId = 2, TitlesId = 4},
                new {EmployeesId = 3, TitlesId = 10},
                new {EmployeesId = 3, TitlesId = 12},
                new {EmployeesId = 4, TitlesId = 11},
                new {EmployeesId = 5, TitlesId = 8}
                ));

I tried to use my DbContext defined as db in my controller to get a similair result as the above seed data code, but i've had no luck and haven't found any good answers online related to my specific question. Is there no other way then by creating the connection with fluent api and a entity class for EmployeeTitle?


问:
How to use a theme on all windows in Tkinter
I'm making a GUI in Tkinter and want the sun valley theme (https://github.com/rdbende/Sun-Valley-ttk-theme) to effect all my windows.

When I run my code only the first window in this case the Test class has the theme, when I click the button and run my next window Main the theme isn't applied.

I've tried it with and without Test.destroy(), not using sv_ttk.use_dark_theme() in Main() and I have also tried switching the theme back and forth with no change.

Here are two screen shots of both windows afterwards is my code:
Test() window
Main() window

```<code>import tkinter as tk
from tkinter import ttk
import sv_ttk

class Test(tk.Tk):

    def __init__(self):
        super().__init__()

        sv_ttk.use_dark_theme()

        self.geometry('250x150')
        self.title("Test")
        self.resizable(0,0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=3)

        testButton = ttk.Button(self, text="Press me!", command=lambda : self.newWindow()).grid(column=0, row=3, sticky=tk.E, padx=5, pady=5)

    def newWindow(self):
        self.newWindow = Main()
        Test.destroy()

class Main(tk.Tk):
    def __init__(self):
        super().__init__()
        sv_ttk.use_dark_theme()

        self.geometry('1200x800')
        self.title("Main")

        self.resizable(0,0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)

        self.test = ttk.Checkbutton(self, text="testing", style="Toggle.TButton")
        self.test.grid(column=0, row=0, sticky=tk.W, padx=5, pady=5)

if __name__ =="__main__":
    Test=Test()
    Test.mainloop()
</code>```

Body:
I'm making a GUI in Tkinter and want the sun valley theme (https://github.com/rdbende/Sun-Valley-ttk-theme) to effect all my windows.

When I run my code only the first window in this case the Test class has the theme, when I click the button and run my next window Main the theme isn't applied.

I've tried it with and without Test.destroy(), not using sv_ttk.use_dark_theme() in Main() and I have also tried switching the theme back and forth with no change.

Here are two screen shots of both windows afterwards is my code:
Test() window
Main() window

import tkinter as tk
from tkinter import ttk
import sv_ttk

class Test(tk.Tk):

    def __init__(self):
        super().__init__()

        sv_ttk.use_dark_theme()

        self.geometry('250x150')
        self.title("Test")
        self.resizable(0,0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=3)

        testButton = ttk.Button(self, text="Press me!", command=lambda : self.newWindow()).grid(column=0, row=3, sticky=tk.E, padx=5, pady=5)

    def newWindow(self):
        self.newWindow = Main()
        Test.destroy()

class Main(tk.Tk):
    def __init__(self):
        super().__init__()
        sv_ttk.use_dark_theme()

        self.geometry('1200x800')
        self.title("Main")

        self.resizable(0,0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)

        self.test = ttk.Checkbutton(self, text="testing", style="Toggle.TButton")
        self.test.grid(column=0, row=0, sticky=tk.W, padx=5, pady=5)

if __name__ =="__main__":
    Test=Test()
    Test.mainloop()


问:
How to pass filtered Excel data as arguments to VBA function
Say have a data table in Excel

```<code>| VarA | VarB | VarC
| A    |  1   | 3 |
| B    |  2   | 4 |
| A    |  3   | 9 |
</code>```

I want to use the FILTER function to filter variables VarB and VarC using some criteria on VarA and send the results as arguments to a VBA function. For example, input this formula in a cell to use a function called Test:

```<code>=Test(FILTER(VarB,VarA="A"),FILTER(VarC,VarA="A"))
</code>```

I tried this in VBA:

```<code>Function Test(vector1 As Object, vector2 As Object)
   a=vector1(1)
   b=vector2(1)
   Test=a*b
End function
</code>```

and also tried passing vector1 and vector2 as Variants
but I get a #VALUE! error instead of the result of the multiplication

Body:
Say have a data table in Excel

| VarA | VarB | VarC
| A    |  1   | 3 |
| B    |  2   | 4 |
| A    |  3   | 9 |

I want to use the FILTER function to filter variables VarB and VarC using some criteria on VarA and send the results as arguments to a VBA function. For example, input this formula in a cell to use a function called Test:

=Test(FILTER(VarB,VarA="A"),FILTER(VarC,VarA="A"))

I tried this in VBA:

Function Test(vector1 As Object, vector2 As Object)
   a=vector1(1)
   b=vector2(1)
   Test=a*b
End function

and also tried passing vector1 and vector2 as Variants
but I get a #VALUE! error instead of the result of the multiplication


问:
Would it be good idea to store mongoose documents in AsyncLocalStorage?
I have a web server which is made specifically for an app. Some of the services get very complex in terms of calling a lot of functions across multiple services and each of them querying multiple models. Would it be good idea to save the queried documents of each request in AsyncLocalStorage to reduce the time taken for querying?

So, I would check if document is present in ALS if yes then use it else fetch and save it there before using.

I tried to find references related to this but didn't find anything. Which led me to think maybe it is not such a good idea after all. But then querying the same document again and again over different services doesn't make sense either.


问:
Missing authorization header and hook return undefined while searching for data
Currently I'm working with a chat application which is based on json-server now the problem is while I'm requesting for conversations with like search (http://localhost:9000/conversations?participants_like=tushin@gmail.com&_sort=timestamp&_order=desc&_page=1&_limit=5) it showing 200 response but data won't shown up! while I check the json server it showing "missing authorization header"

Here is my conversation api

```<code>import { apiSlice } from "../api/apiSlice";

export const conversationsApi = apiSlice.injectEndpoints({
    endpoints: (builder) => ({
        //endpoints here
        getConversations: builder.query({
            query: (email) => `/conversations?participants_like=${email}&_sort=timestamp&_order=desc&_page=1&_limit=5`,
        })

    })
})

export const {useGetConversationsQuery } = conversationsApi;
</code>```

here is my converation slice

```<code>import { createSlice } from '@reduxjs/toolkit'
const initialState = {}

const conversationsSlice = createSlice({
    name: "conversations",
    initialState,
    reducers: {}
})

// export const { } = conversationsSlice.actions;
export default conversationsSlice.reducer;
</code>```

here is my apiSlice

```<code>import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const apiSlice = createApi({
    reducerPath: "api",
    baseQuery: fetchBaseQuery({
        baseUrl: process.env.REACT_APP_API_URL,
        prepareHeaders: async (headers, { getState, endpoint }) => {
            const token = getState()?.auth?.accessToken;
            if (token) {
                headers.set("Authorization", `Bearer ${token}`);
            }
            console.log(headers)
            return headers;
        }
    }),
    tagTypes: [],
    endpoints: (builder) => ({

    })
})
</code>```

Body:
Currently I'm working with a chat application which is based on json-server now the problem is while I'm requesting for conversations with like search (http://localhost:9000/conversations?participants_like=tushin@gmail.com&_sort=timestamp&_order=desc&_page=1&_limit=5) it showing 200 response but data won't shown up! while I check the json server it showing "missing authorization header"

Here is my conversation api

import { apiSlice } from "../api/apiSlice";

export const conversationsApi = apiSlice.injectEndpoints({
    endpoints: (builder) => ({
        //endpoints here
        getConversations: builder.query({
            query: (email) => `/conversations?participants_like=${email}&_sort=timestamp&_order=desc&_page=1&_limit=5`,
        })

    })
})

export const {useGetConversationsQuery } = conversationsApi;

here is my converation slice

import { createSlice } from '@reduxjs/toolkit'
const initialState = {}

const conversationsSlice = createSlice({
    name: "conversations",
    initialState,
    reducers: {}
})

// export const { } = conversationsSlice.actions;
export default conversationsSlice.reducer;

here is my apiSlice

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const apiSlice = createApi({
    reducerPath: "api",
    baseQuery: fetchBaseQuery({
        baseUrl: process.env.REACT_APP_API_URL,
        prepareHeaders: async (headers, { getState, endpoint }) => {
            const token = getState()?.auth?.accessToken;
            if (token) {
                headers.set("Authorization", `Bearer ${token}`);
            }
            console.log(headers)
            return headers;
        }
    }),
    tagTypes: [],
    endpoints: (builder) => ({

    })
})


问:
Installed truffle globally using npm but still cannot access it
I have installed nodejs and then tried running the following command to install truffle suit and ganache as follows:
npm install -g truffle
npm install -g ganache
It got installed as follows:
Installing truffle and ganache
I also checked whether its present in the directories or not by running the command:
npm list -g

Yet when I run the command:
truffle -v
ganache -v
I get the error:
Error after installation

The package although it was installed globally, I couldn't access the package. I do have VS CODE and python 3.11 installed. Any suggestions to how can I use it globally?
I did try the following:

running npm config edit
changing the prefix to 'C:\Users\username\AppData\Roaming\npm'
adding that path to the system path variable
reinstalling the package with -g.

explicitly set the path by
npm config set prefix c:/Users//AppData/Roaming/npm

Change the permission of node global package without tampering with default file permission by
rather changing the directory itself along creating a new profile.
mkdir ~/.npm-global
npm config set prefix ~/.npm-global
set PATH=~/.npm-global/bin:$PATH
source ~/.profile
npm install -g <npm_packages>

But none of them worked