问:
Assign Pacific Standard Time Zone in R (with no daylight saving)
I am working on an hourly time series dataset—the location of the data in California, while the column showing the date and time with POSIXct is in UTC. I want my time label to show local time at regular intervals, so I want to avoid daylight saving time.

If the dataset is in New York, my plan to handle the dataset is as follows:

```<code># Load packages
library(dplyr)
library(lubridate)

# Create example data frame
# The time zone is in UTC
dat <- data.frame(
  Time = as.POSIXct(c("2022-03-13 06:00:00",
                      "2022-03-13 07:00:00",
                      "2022-03-13 08:00:00",
                      "2022-03-13 09:00:00",
                      "2022-03-13 10:00:00",
                      "2022-03-13 11:00:00"), tz = "UTC")
)

# Convert to Eastern Standard Time Zone
# This is my preferred output
dat2 <- dat %>%
  mutate(Time = with_tz(Time, tz = "America/Jamaica"))

print(dat2$Time)
# [1] "2022-03-13 01:00:00 EST" "2022-03-13 02:00:00 EST" "2022-03-13 03:00:00 EST" "2022-03-13 04:00:00 EST" "2022-03-13 05:00:00 EST"
# [6] "2022-03-13 06:00:00 EST"

# Convert to Eastern daylight saving time
# This is not my preferred output, but an example
dat3 <- dat %>%
  mutate(Time = with_tz(Time, tz = "America/New_York"))

dat3$Time
# [1] "2022-03-13 01:00:00 EST" "2022-03-13 03:00:00 EDT" "2022-03-13 04:00:00 EDT" "2022-03-13 05:00:00 EDT" "2022-03-13 06:00:00 EDT"
# [6] "2022-03-13 07:00:00 EDT"
</code>```

Notice that dat2 is my preferred output. It is not the correct time in New York as daylight saving time begins at 2022-03-13. However, I want the interval between each time point is the same.

Now my question is: how to do the same for a California dataset? I could only find cities in Pacific time zone with daylight saving time. In other words, I don't know how to specify a time zone name using with_tz to make the Time column showing "PST" with regular intervals during daylight saving transition. Using "America/Los_Angeles" will not work.

Body:
I am working on an hourly time series dataset—the location of the data in California, while the column showing the date and time with POSIXct is in UTC. I want my time label to show local time at regular intervals, so I want to avoid daylight saving time.

If the dataset is in New York, my plan to handle the dataset is as follows:

# Load packages
library(dplyr)
library(lubridate)

# Create example data frame
# The time zone is in UTC
dat <- data.frame(
  Time = as.POSIXct(c("2022-03-13 06:00:00",
                      "2022-03-13 07:00:00",
                      "2022-03-13 08:00:00",
                      "2022-03-13 09:00:00",
                      "2022-03-13 10:00:00",
                      "2022-03-13 11:00:00"), tz = "UTC")
)

# Convert to Eastern Standard Time Zone
# This is my preferred output
dat2 <- dat %>%
  mutate(Time = with_tz(Time, tz = "America/Jamaica"))

print(dat2$Time)
# [1] "2022-03-13 01:00:00 EST" "2022-03-13 02:00:00 EST" "2022-03-13 03:00:00 EST" "2022-03-13 04:00:00 EST" "2022-03-13 05:00:00 EST"
# [6] "2022-03-13 06:00:00 EST"

# Convert to Eastern daylight saving time
# This is not my preferred output, but an example
dat3 <- dat %>%
  mutate(Time = with_tz(Time, tz = "America/New_York"))

dat3$Time
# [1] "2022-03-13 01:00:00 EST" "2022-03-13 03:00:00 EDT" "2022-03-13 04:00:00 EDT" "2022-03-13 05:00:00 EDT" "2022-03-13 06:00:00 EDT"
# [6] "2022-03-13 07:00:00 EDT"

Notice that dat2 is my preferred output. It is not the correct time in New York as daylight saving time begins at 2022-03-13. However, I want the interval between each time point is the same.

Now my question is: how to do the same for a California dataset? I could only find cities in Pacific time zone with daylight saving time. In other words, I don't know how to specify a time zone name using with_tz to make the Time column showing "PST" with regular intervals during daylight saving transition. Using "America/Los_Angeles" will not work.


来源: stackexchange

问:
Jetpack Compose onPress of detectTapGestures don't work as expected
I have some data in two arrays. Some buttons are being generated from the data of array1 and array2. But onPress of detectTapGestures don't pass releted data from array2. It always returning data from array1.

```<code>@Composable
fun MyButton1(data: String, onPress: () -> Unit) {
    Box(
        Modifier
            .size(50.dp)
            .background(Color.Red)
            .pointerInput(Unit) {
                detectTapGestures(
                    onPress = {
                        MyConst.mText = data // <- always gettting data from array1
                        onPress()
                    },
                    onLongPress = {},
                    onTap = {}
                )
            }
    ) {
        Text(text = data)
    }
}

@Composable
fun MyButton2(data: String, onPress: () -> Unit) {

    Button(onClick = {
        MyConst.mText = data //this works but I need to implement **detectTapGestures**
        onPress()
    }) { Text(text = data) }
}
</code>```

Here is the two array. MyButton1() always return (123) but MyButton2() works return data from both array according to UI. But I need to implement detectTapGestures for other works

```<code>object MyConst {
    var mText = "Not data"
    val part1 = arrayOf("1", "2", "3")
    val part2 = arrayOf("A", "B", "C")
}

@Composable
fun TestMe() {

    var isShowNumber by remember { mutableStateOf(true) }

    Column(Modifier.background(Color.White)) {

        Text(text = MyConst.mText, color = Color.Green)

        Row {
            val abc = if(isShowNumber) MyConst.part1 else MyConst.part2
            abc.forEach {
               MyButton1(
                    data = it,
                    onPress = {
                        isShowNumber = !isShowNumber
                    }
               )
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some data in two arrays. Some buttons are being generated from the data of array1 and array2. But onPress of detectTapGestures don't pass releted data from array2. It always returning data from array1.

@Composable
fun MyButton1(data: String, onPress: () -> Unit) {
    Box(
        Modifier
            .size(50.dp)
            .background(Color.Red)
            .pointerInput(Unit) {
                detectTapGestures(
                    onPress = {
                        MyConst.mText = data // <- always gettting data from array1
                        onPress()
                    },
                    onLongPress = {},
                    onTap = {}
                )
            }
    ) {
        Text(text = data)
    }
}

@Composable
fun MyButton2(data: String, onPress: () -> Unit) {

    Button(onClick = {
        MyConst.mText = data //this works but I need to implement **detectTapGestures**
        onPress()
    }) { Text(text = data) }
}

Here is the two array. MyButton1() always return (123) but MyButton2() works return data from both array according to UI. But I need to implement detectTapGestures for other works

object MyConst {
    var mText = "Not data"
    val part1 = arrayOf("1", "2", "3")
    val part2 = arrayOf("A", "B", "C")
}

@Composable
fun TestMe() {

    var isShowNumber by remember { mutableStateOf(true) }

    Column(Modifier.background(Color.White)) {

        Text(text = MyConst.mText, color = Color.Green)

        Row {
            val abc = if(isShowNumber) MyConst.part1 else MyConst.part2
            abc.forEach {
               MyButton1(
                    data = it,
                    onPress = {
                        isShowNumber = !isShowNumber
                    }
               )
            }
        }
    }
}


问:
flutter web: make side scroll down to a specific position
TL,DR: I'm building a webside with flutter.
I want the side to scroll to a specific position after the user pressed a button.
How can I accomplish that?

Longer explaination: To illustrate my point, I will make the following example: when you visit the wikipedia-page for some topic and you go to the contents in the beginning,

when you click on one section, the side scrolls down to that section:

I want the same behaviour in my flutter webside.

How can I accomplish that?


问:
Is there any way to input a range of languages for the :lang() pseudo-class?
I'm targeting a bunch of different languages in my LESS/CSS with the :lang() pseudo-class. It looks like this (but even more languages):

```<code>:lang(af),
:lang(sq),
:lang(eu),
:lang(bs),
:lang(ca),
:lang(kw),
:lang(hr),
:lang(cs),
:lang(da),
:lang(nl) {
  font-size: 100px;
}
</code>```

Is there a way to clean this up? I'd love to enter in a list of languages somehow.

Thanks

Body:
I'm targeting a bunch of different languages in my LESS/CSS with the :lang() pseudo-class. It looks like this (but even more languages):

:lang(af),
:lang(sq),
:lang(eu),
:lang(bs),
:lang(ca),
:lang(kw),
:lang(hr),
:lang(cs),
:lang(da),
:lang(nl) {
  font-size: 100px;
}

Is there a way to clean this up? I'd love to enter in a list of languages somehow.

Thanks


问:
IndexedDB error Unhandled rejection: AbortError: Transaction aborted
I am a trying to save a JSON object in IndexedDB with Dexie:

```<code>      var db = new Dexie ("List",);

      db.version(2).stores({
        list2: "++id,name",
        Itemslist: JSON.stringify(this.AllItems)
        });

      db.open().then(result => {
      }).catch(e => {
      console.log("error: " + e);
      });
</code>```

Getting this error in Chrome console:

```<code>Unhandled rejection: AbortError: Transaction aborted
</code>```

The array 'this.AllItems' has 80MB of data.

How can I Fix the error?

Body:
I am a trying to save a JSON object in IndexedDB with Dexie:

      var db = new Dexie ("List",);

      db.version(2).stores({
        list2: "++id,name",
        Itemslist: JSON.stringify(this.AllItems)
        });

      db.open().then(result => {
      }).catch(e => {
      console.log("error: " + e);
      });

Getting this error in Chrome console:

Unhandled rejection: AbortError: Transaction aborted

The array 'this.AllItems' has 80MB of data.

How can I Fix the error?


问:
Copy and pasting Excel / Sheets into form / table
I have a form with 8 inputs in my HTML, with a button that adds new rows.

Is there any approach I can take so that users can copy rows from their excel files and paste them into the form, populating it, like Google Sheets does? ¿Can I treat my form as a table?

I don't know where to start with this, and I want to avoid uploading / parsing of XLS files (Mailchimp style)

¿Any guidance on how to achieve this?

¡Thanks a lot!


问:
Deploy API that saves images on file system
I‘m working on a personal project with friends that is like a site/app to register your pets, when the user register a pet there’s a picture of the pet that is saved on the file system of the project. If I deploy this API on heroku (for example) will the image saving part work? I have never deployed anything and I don’t know how it works, specially with file system

Nothing, I’m learning


问:
Should I use from_logits on AUC keras metric with sigmoid activation function?
I'm currently implementing a convolutional neural network model that outputs binary classification (true or false), and the labels are all either 0 or 1. When using the "sigmoid" activation function for the final dense layer, I was wondering whether to set from_logits to true or false in the "binary_crossentropy" loss and the AUC keras metric. I.E. does the sigmoid activation function output logits?

The accuracy with either seems somewhat similar, although it is different, I'm wondering which is most accurate to the parameters of the model. I'm using ResNet50 at the moment.


问:
npm run build in docker container never exits
I tried to move angular building in docker container. It successfully generates dist folder and files in it, but npm script stays running infinitely. Interesting thing is that on the host it stops using node 1.18 but has same behavior using node 1.19. I changed my docker node version to 1.18 and nothing changed.

Dockerfile contains this:

```<code>FROM node:18.12 as build
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build
</code>```

Body:
I tried to move angular building in docker container. It successfully generates dist folder and files in it, but npm script stays running infinitely. Interesting thing is that on the host it stops using node 1.18 but has same behavior using node 1.19. I changed my docker node version to 1.18 and nothing changed.

Dockerfile contains this:

FROM node:18.12 as build
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build


问:
Camera with Pytmx and pygame?
So far with my map I have gotten to blitting the tiles and getting collisions with them. But the thing is my map doesn't work with my previous camera setup, so I have to turn it off to see my player on the tiles. Basically whats happening is that the map that I'm loading is visible, and I can collide with it, the problem is that the images aren't moving with the rects. I have tried to offset my tiles in the code, but no effect takes place. I am also using a very unusual method of blitting the tiles:

```<code>class Level_1():

    def __init__(self, surface, tile_rects):
        # properties
        self.display = surface
        self.tile_rects = tile_rects
        self.tmx_data = load_pygame('data/levels/level_1.tmx')
        true_scroll = [0,0]

        # layers
        self.terrain = self.tmx_data.get_layer_by_name('terrain')
        self.coins = self.tmx_data.get_layer_by_name('coins')
        self.grass = self.tmx_data.get_layer_by_name('grass')
        self.rocks = self.tmx_data.get_layer_by_name('rocks')
        self.start = self.tmx_data.get_layer_by_name('start')

    # loads terrain layer ----------------------------------
    def load_terrain(self):
        for x, y, surf in self.terrain.tiles():
            self.tile = Tile(surf, (x * TILESIZE, y * TILESIZE))
            self.tile_rects.append(self.tile.rect)
            self.display.blit(self.tile.image, self.tile.position)

    # loads coins layer ------------------------------------
    def load_coins(self):
        for x, y, surf in self.coins.tiles():
            self.tile = Tile(surf, (x * TILESIZE, y * TILESIZE))
            self.display.blit(self.tile.image, self.tile.position)

    # loads grass layer ------------------------------------
    def load_grass(self):
        for x, y, surf in self.grass.tiles():
            self.tile = Tile(surf, (x * TILESIZE, y * TILESIZE))
            self.display.blit(self.tile.image, self.tile.position)

    # loads rocks layer ------------------------------------
    def load_rocks(self):
        for x, y, surf in self.rocks.tiles():
            self.tile = Tile(surf, (x * TILESIZE, y * TILESIZE))
            self.display.blit(self.tile.image, self.tile.position)

    def run(self):
        # runs level 1 -------------------------------------
        self.load_terrain()
        self.load_rocks()
        self.load_grass()
        self.load_coins()
</code>```

I then import this class into my main file and just do:

```<code>level = Level_1(display, tile_rects)
level.run
</code>```

I do the latter in the main loop. I am using DaFluffyPotato's tutorial.

Title: Camera with Pytmx and pygame?

Body:
So far with my map I have gotten to blitting the tiles and getting collisions with them. But the thing is my map doesn't work with my previous camera setup, so I have to turn it off to see my player on the tiles. Basically whats happening is that the map that I'm loading is visible, and I can collide with it, the problem is that the images aren't moving with the rects. I have tried to offset my tiles in the code, but no effect takes place. I am also using a very unusual method of blitting the tiles:

class Level_1():

    def __init__(self, surface, tile_rects):
        # properties
        self.display = surface
        self.tile_rects = tile_rects
        self.tmx_data = load_pygame('data/levels/level_1.tmx')
        true_scroll = [0,0]

        # layers
        self.terrain = self.tmx_data.get_layer_by_name('terrain')
        self.coins = self.tmx_data.get_layer_by_name('coins')
        self.grass = self.tmx_data.get_layer_by_name('grass')
        self.rocks = self.tmx_data.get_layer_by_name('rocks')
        self.start = self.tmx_data.get_layer_by_name('start')

    # loads terrain layer ----------------------------------
    def load_terrain(self):
        for x, y, surf in self.terrain.tiles():
            self.tile = Tile(surf, (x * TILESIZE, y * TILESIZE))
            self.tile_rects.append(self.tile.rect)
            self.display.blit(self.tile.image, self.tile.position)

    # loads coins layer ------------------------------------
    def load_coins(self):
        for x, y, surf in self.coins.tiles():
            self.tile = Tile(surf, (x * TILESIZE, y * TILESIZE))
            self.display.blit(self.tile.image, self.tile.position)

    # loads grass layer ------------------------------------
    def load_grass(self):
        for x, y, surf in self.grass.tiles():
            self.tile = Tile(surf, (x * TILESIZE, y * TILESIZE))
            self.display.blit(self.tile.image, self.tile.position)

    # loads rocks layer ------------------------------------
    def load_rocks(self):
        for x, y, surf in self.rocks.tiles():
            self.tile = Tile(surf, (x * TILESIZE, y * TILESIZE))
            self.display.blit(self.tile.image, self.tile.position)

    def run(self):
        # runs level 1 -------------------------------------
        self.load_terrain()
        self.load_rocks()
        self.load_grass()
        self.load_coins()

I then import this class into my main file and just do:

level = Level_1(display, tile_rects)
level.run

I do the latter in the main loop. I am using DaFluffyPotato's tutorial.


问:
LFTP mirror script giving unexpected results
I've inherited a script that is meant to mirror files from one server to another. It is supposed to move only files that are less than 4 hours old and those are supposed to be the only files in the destination directory after the script is complete.

```<code>open -p 22 -u {$username},{$password} sftp://{$thehost}; mirror -L -R --newer-than='4 hours ago'  -X .* --older-than=now-65seconds --log={$tmpDir}mirror.log --parallel=5 {$remoteDir} {$localDir}
</code>```

It has been running fine on existing servers, but now I'm running it on a new server and getting unexpected results. It does move the newer files over, but it also leaves the older files, so the destination server ends up with all the new files plus files that are one or two days old.  I've checked the logs and see no errors.

On the original server, where this has been running for years, there are no old files in the destination directory. Just the ones that are less than 4 hours.

I want to make sure I understand what this command is supposed to do. When it's complete should the destination be left with only files that are less than 4 hours old. Is the mirror process supposed to remove the older ones?

Body:
I've inherited a script that is meant to mirror files from one server to another. It is supposed to move only files that are less than 4 hours old and those are supposed to be the only files in the destination directory after the script is complete.

open -p 22 -u {$username},{$password} sftp://{$thehost}; mirror -L -R --newer-than='4 hours ago'  -X .* --older-than=now-65seconds --log={$tmpDir}mirror.log --parallel=5 {$remoteDir} {$localDir}

It has been running fine on existing servers, but now I'm running it on a new server and getting unexpected results. It does move the newer files over, but it also leaves the older files, so the destination server ends up with all the new files plus files that are one or two days old.  I've checked the logs and see no errors.

On the original server, where this has been running for years, there are no old files in the destination directory. Just the ones that are less than 4 hours.

I want to make sure I understand what this command is supposed to do. When it's complete should the destination be left with only files that are less than 4 hours old. Is the mirror process supposed to remove the older ones?


问:
Next.js rewrites + custom dynamical header for axios on the server-side
How i can do dynamical header for axios on the serve-side? I want to make functionality of cities, without edit nextjs folder structure. Rewrities from nextjs solves my problem, but I can't set the header for axios request functions on the server side. useRouter() hook returns non-proxied path.

// next.config.js

...
async Rewrites() {
  return [
    {
      source: '/new-york/:path*',
      destination: '/:path*',
    },
  ]
}
...
```
<p>Im tried use axios intreception function:</p>
<pre class="lang-js prettyprint-override"><code>// destination _app.js

export default function AxiosInterceptors() {
...
    const router = useRouter();
    const asPath = router.asPath; // asPath return not non-proxied path, if i use url /new-york/blogs, here i see /blogs;

    apiQr.interceptors.request.use(function (config) {
        config.headers['city'] = asPath.includes('/new-york') ? '2' : '1'; // city id
        return config;
    }, function (error) {
        return Promise.reject(error);
    });
...

}
</code>```

Im also tried set headers from NextJS _middleware.js but there is no access to axios requests and the axios interceptor function is not called there.
Where and how can I get a stable variable depending on the entered url on the server side so that I can adjust the axios headers?

I expect to get the proxied url in the axios interceptors instance as I showed above, but I get the proxied path.

Body:
How i can do dynamical header for axios on the serve-side? I want to make functionality of cities, without edit nextjs folder structure. Rewrities from nextjs solves my problem, but I can't set the header for axios request functions on the server side. useRouter() hook returns non-proxied path.

// next.config.js

...
async Rewrites() {
  return [
    {
      source: '/new-york/:path*',
      destination: '/:path*',
    },
  ]
}
...

Im tried use axios intreception function:

// destination _app.js

export default function AxiosInterceptors() {
...
    const router = useRouter();
    const asPath = router.asPath; // asPath return not non-proxied path, if i use url /new-york/blogs, here i see /blogs;

    apiQr.interceptors.request.use(function (config) {
        config.headers['city'] = asPath.includes('/new-york') ? '2' : '1'; // city id
        return config;
    }, function (error) {
        return Promise.reject(error);
    });
...

}

Im also tried set headers from NextJS _middleware.js but there is no access to axios requests and the axios interceptor function is not called there.
Where and how can I get a stable variable depending on the entered url on the server side so that I can adjust the axios headers?

I expect to get the proxied url in the axios interceptors instance as I showed above, but I get the proxied path.


问:
merging gcs files and pasting to another gcs bucket using python
i am able to read the files from gcs bucket, but i am not able to merge the sample files and write it to another gcs location.

i have to merge all the files in one folder of gcs bucket and move that merged file to other gcs bucket location using python.
ex: gs://hello/test
test contains 5 files and the contnet of all 5 files to be merged and moved to another folder say test1.

i tried to move one file from one gcs to other, but the use case is merge all the files in one folder and move the merged file to other gcs bucket.


问:
Chi square function: how to?
I don't understand if what I'm doing is correct.
I wish to perform a chi-squared test on a dataset, but I'm not sure about the result.

This is my dataset:

```<code>> dput(chi)
structure(list(`Age.(days)` = c("< 7 days", "7-10 days", "10-12 days",
"12-15 days", "15-20 days", "20-25 days"), Broods = c(6, 9, 10,
6, 14, 5), N.Carnus = c(92, 74, 48, 17, 37, 10)), row.names = c(NA,
6L), class = "data.frame")
</code>```

And this is the test:

```<code>chi$"Age.(days)" <- as.character(chi$"Age.(days)")
chisq.test(table(chi$"Age.(days)", chi$"N.Carnus"))
</code>```

What I wish to find is if there is a significant connection between age of the host and number of parasites (coming from a certain number of broods).

Thank you :)

Title: Chi square function: how to?

Body:
I don't understand if what I'm doing is correct.
I wish to perform a chi-squared test on a dataset, but I'm not sure about the result.

This is my dataset:

> dput(chi)
structure(list(`Age.(days)` = c("< 7 days", "7-10 days", "10-12 days",
"12-15 days", "15-20 days", "20-25 days"), Broods = c(6, 9, 10,
6, 14, 5), N.Carnus = c(92, 74, 48, 17, 37, 10)), row.names = c(NA,
6L), class = "data.frame")

And this is the test:

chi$"Age.(days)" <- as.character(chi$"Age.(days)")
chisq.test(table(chi$"Age.(days)", chi$"N.Carnus"))

What I wish to find is if there is a significant connection between age of the host and number of parasites (coming from a certain number of broods).

Thank you :)


问:
Reverse dial gRPC service with rust and tonic
I'm developing a set of gRPC microservices using rust and tonic library. One of those microservices is behind a firewall that does not allow any inbound connections. I'd like to know if it's still possible for this service to act as a server for unary grpc calls. I was thinking of rearranging parts of hyper/tower stack to force the server to connect to client and then proceed with regular gRPC communication but I'm not sure where to start (if at all possible). In my research I also came across yamux library, is this something I could use for this purpose?</p>


问:
Hot Chocolate how to query nested tree
I've set up a project using HotChocolate and Entity Framework. The query looks like this.
post -> comment -> comment...

```<code>fragment comment on CommentType {
    id
    creatorId
    text
    timeStamp
}

query {
    posts {
        edges {
            node {
                id
                communityName
                title
                text
                timestamp
                creatorId
                comments {
                    postId
                    ...comment
                    replies {
                        ...comment
                        replies {
                            ...comment
                            replies {
                                ...comment
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

The Commenttype looks like this. I use dataLoaders for the nested relationships.

```<code>public class CommentType : ISearchResult {
        [GraphQLNonNullType]
        public Guid Id { get; set; }
        public string Text { get; set; }
        public DateTime TimeStamp { get; set; }

        [IsProjected(true)]
        public string CreatorId { get; set; }

        public async Task<UserType> User([DataLoader] UserDataLoader dataLoader) {
            return await dataLoader.LoadAsync(CreatorId, CancellationToken.None);
        }

        [IsProjected(true)]
        public Guid PostId { get; set; }
        public async Task<PostType> Post([DataLoader] PostDataLoader dataLoader) {
            return await dataLoader.LoadAsync(PostId, CancellationToken.None);
        }

        [IsProjected(true)]
        public Guid? ReplyToId { get; set; }
        public async Task<CommentType?> ReplyTo([DataLoader] CommentDataLoader dataLoader) {
            if (ReplyToId == null)
                return null;
            else
                return (CommentType?)await dataLoader.LoadAsync(ReplyToId, CancellationToken.None);
        }

        [IsProjected(true)]
        public IEnumerable<Guid> ReplyIds { get; set; }

        [UseProjection]
        public async Task<IEnumerable<CommentType>> Replies([DataLoader] CommentDataLoader dataLoader) {
            return await dataLoader.LoadAsync(ReplyIds.ToArray(), CancellationToken.None);
        }
    }
</code>```

`

```<code>[ExtendObjectType(typeof(Query))]
    public class PostQuery {
        private readonly IMapper _mapper;

        public PostQuery(IMapper mapper) {
            _mapper = mapper;
        }

        [UseDbContext(typeof(ApplicationDbContext))]
        [UsePaging(IncludeTotalCount = true, DefaultPageSize = 20)]
        [UseProjection]
        [UseFiltering]
        [UseSorting]
        public IQueryable<PostType> GetPosts([ScopedService] ApplicationDbContext context) {
            return context.Posts.ProjectTo<PostType>(_mapper.ConfigurationProvider);
        }
    }
</code>```

This works but it never goes deeper than the first nested object in any of my queries. I've tried adding projection to the nested list, but that doesn't seem to help either.

```<code>{
    "data": {
        "posts": {
            "edges": [
                {
                    "node": {
                        "id": "e9f2cedc-6c1d-4977-81b7-65b819e8131d",
                        "communityName": "Test Community",
                        "title": "Test Post",
                        "text": "testing post",
                        "timestamp": "2022-12-23T16:40:14.649Z",
                        "creatorId": "ilIlLJ1g7CTRhcCfZAWG5V9j4rx1",
                        "comments": [
                            {
                                "postId": "e9f2cedc-6c1d-4977-81b7-65b819e8131d",
                                "id": "7804eada-64ea-4a03-b9aa-7127affb9f32",
                                "creatorId": "ilIlLJ1g7CTRhcCfZAWG5V9j4rx1",
                                "text": "comment on post",
                                "timeStamp": "2022-12-23T17:51:33.808Z",
                                "replies": []
                            }
                        ]
                    }
                }
            ]
        }
    }
}
</code>```

Is there a specific way to do this with HotChocolate?

Edit: Ok so I forgot to add the Include(c => c.Replies) when fetching the ids from the repository, which makes sense since the dataloader doesn't make use of IQueryable. I suppose won't overfetch since it only reaches this point if it's included in the query anyway. This seems to have solved it.

Title: Hot Chocolate how to query nested tree

Body:
I've set up a project using HotChocolate and Entity Framework. The query looks like this.
post -> comment -> comment...

fragment comment on CommentType {
    id
    creatorId
    text
    timeStamp
}

query {
    posts {
        edges {
            node {
                id
                communityName
                title
                text
                timestamp
                creatorId
                comments {
                    postId
                    ...comment
                    replies {
                        ...comment
                        replies {
                            ...comment
                            replies {
                                ...comment
                            }
                        }
                    }
                }
            }
        }
    }
}

The Commenttype looks like this. I use dataLoaders for the nested relationships.

public class CommentType : ISearchResult {
        [GraphQLNonNullType]
        public Guid Id { get; set; }
        public string Text { get; set; }
        public DateTime TimeStamp { get; set; }

        [IsProjected(true)]
        public string CreatorId { get; set; }

        public async Task<UserType> User([DataLoader] UserDataLoader dataLoader) {
            return await dataLoader.LoadAsync(CreatorId, CancellationToken.None);
        }

        [IsProjected(true)]
        public Guid PostId { get; set; }
        public async Task<PostType> Post([DataLoader] PostDataLoader dataLoader) {
            return await dataLoader.LoadAsync(PostId, CancellationToken.None);
        }

        [IsProjected(true)]
        public Guid? ReplyToId { get; set; }
        public async Task<CommentType?> ReplyTo([DataLoader] CommentDataLoader dataLoader) {
            if (ReplyToId == null)
                return null;
            else
                return (CommentType?)await dataLoader.LoadAsync(ReplyToId, CancellationToken.None);
        }

        [IsProjected(true)]
        public IEnumerable<Guid> ReplyIds { get; set; }

        [UseProjection]
        public async Task<IEnumerable<CommentType>> Replies([DataLoader] CommentDataLoader dataLoader) {
            return await dataLoader.LoadAsync(ReplyIds.ToArray(), CancellationToken.None);
        }
    }

`

[ExtendObjectType(typeof(Query))]
    public class PostQuery {
        private readonly IMapper _mapper;

        public PostQuery(IMapper mapper) {
            _mapper = mapper;
        }

        [UseDbContext(typeof(ApplicationDbContext))]
        [UsePaging(IncludeTotalCount = true, DefaultPageSize = 20)]
        [UseProjection]
        [UseFiltering]
        [UseSorting]
        public IQueryable<PostType> GetPosts([ScopedService] ApplicationDbContext context) {
            return context.Posts.ProjectTo<PostType>(_mapper.ConfigurationProvider);
        }
    }

This works but it never goes deeper than the first nested object in any of my queries. I've tried adding projection to the nested list, but that doesn't seem to help either.

{
    "data": {
        "posts": {
            "edges": [
                {
                    "node": {
                        "id": "e9f2cedc-6c1d-4977-81b7-65b819e8131d",
                        "communityName": "Test Community",
                        "title": "Test Post",
                        "text": "testing post",
                        "timestamp": "2022-12-23T16:40:14.649Z",
                        "creatorId": "ilIlLJ1g7CTRhcCfZAWG5V9j4rx1",
                        "comments": [
                            {
                                "postId": "e9f2cedc-6c1d-4977-81b7-65b819e8131d",
                                "id": "7804eada-64ea-4a03-b9aa-7127affb9f32",
                                "creatorId": "ilIlLJ1g7CTRhcCfZAWG5V9j4rx1",
                                "text": "comment on post",
                                "timeStamp": "2022-12-23T17:51:33.808Z",
                                "replies": []
                            }
                        ]
                    }
                }
            ]
        }
    }
}

Is there a specific way to do this with HotChocolate?

Edit: Ok so I forgot to add the Include(c => c.Replies) when fetching the ids from the repository, which makes sense since the dataloader doesn't make use of IQueryable. I suppose won't overfetch since it only reaches this point if it's included in the query anyway. This seems to have solved it.


问:
How to add phone number validation in AJV
I have a form field called phone number with country code. So when the user inputs the phone, it is required to validate the phone number with its country code. I did it before with Yup and yup-phone libraries which use google's libphonenumber. However, I found no way to do it with AJV. Here is my schema.

export const ProfileRequestSchema = {
  type: "object",
  properties: {
    firstName: {
      type: "string",
      minLength: 1,
    },
    lastName: {
      type: "string",
      minLength: 1,
    },
    countryCode: {
      minLength: 1,
      type: "string",
    },
    phoneNumber: {
      minLength: 1,
      type: "string",
    },
  },
  //additionalProperties: false,
  required: [
    "firstName",
    "lastName",
    "countryCode",
    "phoneNumber",
  ],
  errorMessage: {
    type: "should be an object",
    properties: {
      firstName: t`First name is required and must be a string`,
      lastName: t`Last name is required and must be a string`,
      countryCode: t`Country Code is required and must be a string`,
      phoneNumber: t`Phone number is required and must be a string`,
    },
  },
};

export const ProfileRequestValidator = ajv.compile(ProfileRequestSchema);

```

So, is there any way to integrate phone number validator library like libphonenumber-js with AJV?
TIA

Body:
I have a form field called phone number with country code. So when the user inputs the phone, it is required to validate the phone number with its country code. I did it before with Yup and yup-phone libraries which use google's libphonenumber. However, I found no way to do it with AJV. Here is my schema.

export const ProfileRequestSchema = {
  type: "object",
  properties: {
    firstName: {
      type: "string",
      minLength: 1,
    },
    lastName: {
      type: "string",
      minLength: 1,
    },
    countryCode: {
      minLength: 1,
      type: "string",
    },
    phoneNumber: {
      minLength: 1,
      type: "string",
    },
  },
  //additionalProperties: false,
  required: [
    "firstName",
    "lastName",
    "countryCode",
    "phoneNumber",
  ],
  errorMessage: {
    type: "should be an object",
    properties: {
      firstName: t`First name is required and must be a string`,
      lastName: t`Last name is required and must be a string`,
      countryCode: t`Country Code is required and must be a string`,
      phoneNumber: t`Phone number is required and must be a string`,
    },
  },
};

export const ProfileRequestValidator = ajv.compile(ProfileRequestSchema);

So, is there any way to integrate phone number validator library like libphonenumber-js with AJV?
TIA


问:
Storing numbers as int or as formatted text in DB for code speed?
I'm a hardware engineer with lots of firmware coding experience in C and assembly ("low level languages"), with some coding exposure to C++ and prelim knowledge with JS, Pascal, etc. ("high level languages").

I have hired a couple of developers to write a Web App that will later handle high volume in traffic.  The app is written in .NET Core, PostgreSQL, Vue.js, C#, ... where my syntactical knowledge is zero so I cannot write test routines to prove/disprove anything so am requesting your help as follows --

The developers are contending that it makes virtually no difference in execution of speed whether they store 10-digit and 12-digit numbers in DB fields marked as "text" or as "int" (or long int).  These numbers will be searched very frequently with potentially millions of entries, so speed differences will become apparent under heavy load.

The 10-digit numbers are mobile numbers that need to be displayed in the format 00000-00000 and 12-digit numbers are Indian Aadhaar card numbers to be shown as 0000 0000 0000, so instead of formatting these numbers in the front-end JavaScript code, they are storing them formatted as text along with the hyphen and spaces.

My understanding makes me believe that the search of a text like "12345-67890" in a text column containing will be very slow as compared to a search of a number 1234567890 (int) in a column containing ints.

Two reasons for my belief:
a) A number is stored in fewer bytes than a string, consequently faster processing and lower storage

b) A text search uses ASCII stored in bytes whereas number searches directly in the bytes, besides the fact that SQL query gets converted to C which gets converted to Assembly, where the optimized machine code will be probably an order of magnitude faster in numerical searches.

Can any of you experts confirm please?

Thank you


问:
creating a matlab code for Box evolutionary search method
Solve the following nonlinear system of equations in the interval 0 ≤ ,  ≤ 5 by using the
Box Evolutionary optimization algorithm.
Take, the initial point =(x,y)T=(1,1)T and size of reduction parameter delta=(2,2)T
x^2+y=11
x+y^2=7
after running my code it is getting into infinite loop,can anyone help me out?

```<code>clc
clear
syms x y
e=1;
a=2;
f(x,y)=(x^2+y-11)^2;
g(x,y)=(x+y^2-7)^2;
k=1;
while(k~=0)
    d1=2;
    d2=2;
    D=(d1^2+d2^2)^(0.5);
    x0=1;
    y0=1;
    xb1=x0;
    xb2=y0;
    x1=xb1+d1/2;
    y1=xb2+d2/2;
    x2=xb1+d1/2;
    y2=xb2-d2/2;
    x3=xb1-d1/2;
    y3=xb2+d2/2;
    x4=xb1-d1/2;
    y4=xb2-d2/2;
    f1=f(x1,y1)+g(x1,y1);
    f2=f(x2,y2)+g(x2,y2);
    f3=f(x3,y3)+g(x3,y3);
    f4=f(x4,y4)+g(x4,y4);
    if f1<f2 && f1<f3 && f1<f4
        xb1=x1;
        xb2=y1;
    elseif f2<f1 && f2<f3 && f2<f4
        xb1=x2;
        xb2=y2;
    elseif f3<f1 && f3<f2 && f3<f4
        xb1=x3;
        xb2=y3;
    elseif f4<f1 && f4<f2 && f4<f3
        xb1=x4;
        xb2=y4;
    end
    if xb1==x0 && xb2==y0
        d1=d1/a;
        d2=d2/a;
        if D<e
            disp("x value is")
            disp(xb1)
            k=0;
            break
        end
    else
        x0=xb1;
        y0=xb2;
    end
end

</code>```

i am using k as condition for while loop

Body:
Solve the following nonlinear system of equations in the interval 0 ≤ ,  ≤ 5 by using the
Box Evolutionary optimization algorithm.
Take, the initial point =(x,y)T=(1,1)T and size of reduction parameter delta=(2,2)T
x^2+y=11
x+y^2=7
after running my code it is getting into infinite loop,can anyone help me out?

clc
clear
syms x y
e=1;
a=2;
f(x,y)=(x^2+y-11)^2;
g(x,y)=(x+y^2-7)^2;
k=1;
while(k~=0)
    d1=2;
    d2=2;
    D=(d1^2+d2^2)^(0.5);
    x0=1;
    y0=1;
    xb1=x0;
    xb2=y0;
    x1=xb1+d1/2;
    y1=xb2+d2/2;
    x2=xb1+d1/2;
    y2=xb2-d2/2;
    x3=xb1-d1/2;
    y3=xb2+d2/2;
    x4=xb1-d1/2;
    y4=xb2-d2/2;
    f1=f(x1,y1)+g(x1,y1);
    f2=f(x2,y2)+g(x2,y2);
    f3=f(x3,y3)+g(x3,y3);
    f4=f(x4,y4)+g(x4,y4);
    if f1<f2 && f1<f3 && f1<f4
        xb1=x1;
        xb2=y1;
    elseif f2<f1 && f2<f3 && f2<f4
        xb1=x2;
        xb2=y2;
    elseif f3<f1 && f3<f2 && f3<f4
        xb1=x3;
        xb2=y3;
    elseif f4<f1 && f4<f2 && f4<f3
        xb1=x4;
        xb2=y4;
    end
    if xb1==x0 && xb2==y0
        d1=d1/a;
        d2=d2/a;
        if D<e
            disp("x value is")
            disp(xb1)
            k=0;
            break
        end
    else
        x0=xb1;
        y0=xb2;
    end
end

i am using k as condition for while loop


问:
Pass spring property to a jmx file
I need to pass a spring property(that's defined via property source) to a jmx file.

```<code>The spring property is defined as @PropertySource(value="file:/etc/secrets/secret.properties")
</code>```

Within this file, we have a property called as pass.key that I am trying to extract out.
I can do this in spring via

```<code>@Value("${pass.key}")
private string passKey
</code>```

I have defined a jmx file that firsts calls an authentication API, gets the token as response, then we use the token to authorize the user and call subsequent API's.
For the authentication API, I need to pass in username,password(password would be the pass.key)
But when I pass this to jmx file for one of the API calls as an argument, its not able to parse that property.
Here's how I am passing it:

```<code><stringProp name="Argument.value"> {
"password": ${pass.key}&#xd
}</stringProp>
</code>```

Instead, I get the output as "password": ${pass.key} instead of the value associated with the secret.

I believe I am unable to pass spring properties to a JMX file. I need a way to pass them either via global variable or some other way.

Please assist.

Title: Pass spring property to a jmx file

Body:
I need to pass a spring property(that's defined via property source) to a jmx file.

The spring property is defined as @PropertySource(value="file:/etc/secrets/secret.properties")

Within this file, we have a property called as pass.key that I am trying to extract out.
I can do this in spring via

@Value("${pass.key}")
private string passKey

I have defined a jmx file that firsts calls an authentication API, gets the token as response, then we use the token to authorize the user and call subsequent API's.
For the authentication API, I need to pass in username,password(password would be the pass.key)
But when I pass this to jmx file for one of the API calls as an argument, its not able to parse that property.
Here's how I am passing it:

<stringProp name="Argument.value"> {
"password": ${pass.key}&#xd
}</stringProp>

Instead, I get the output as "password": ${pass.key} instead of the value associated with the secret.

I believe I am unable to pass spring properties to a JMX file. I need a way to pass them either via global variable or some other way.

Please assist.


问:
JUnit/Mockito to test a class containing "code table" like static data loaded from a DB
I have a Java class that contains all my code table like data; e.g. code table is called "Status" and has three values like so:

1 => Good

2 => Bad

3 => Ugly

Simplified it looks like this

```<code>public class Codes
{
    private static Map<String, Map<String, String>> CODES;

    public static void init(List<String> ctList) throws Exception
    {
        try (Connection con = ...)
        {
            // the SQL executed has an IN(?) where the ctList defines a list of the tables to load
            ResultSet results = prepStmt.execute();

            while(results.next())
            {
                String id = results.getString("TYP");
                String code = results.getString("CODE");
                String desc = results.getString("DESC");

                if(!CODES.containsKey(id))
                    CODES.put(id, new HashMap<>());

                Map<String, String> ct = CODES.get(id);

                ct.put(code, code);
                ct.put(desc.toUpperCase().trim(), code); // allows searching for code by description
            }
        }
    }

    public static String getCodeStr(String table, String key)
    {
        return CODES.get(table).get(key);
    }
}
</code>```

Now inside my application I frequently refer to this class.  Simple example

```<code>String test = Codes.getCodeStr("test_table_id", "test_code_value");
</code>```

When mocking I won't be able to connect to a database.  So what must I do to be able to test with this class?

One thing I have considered is collect all the code table data into a file and then initialize from the file based on some switch.  I just have to make sure the file is kept up to date...

Any ideas or suggestions are welcome but I do prefer to avoid/limit injection when I can.

Body:
I have a Java class that contains all my code table like data; e.g. code table is called "Status" and has three values like so:

1 => Good

2 => Bad

3 => Ugly

Simplified it looks like this

public class Codes
{
    private static Map<String, Map<String, String>> CODES;

    public static void init(List<String> ctList) throws Exception
    {
        try (Connection con = ...)
        {
            // the SQL executed has an IN(?) where the ctList defines a list of the tables to load
            ResultSet results = prepStmt.execute();

            while(results.next())
            {
                String id = results.getString("TYP");
                String code = results.getString("CODE");
                String desc = results.getString("DESC");

                if(!CODES.containsKey(id))
                    CODES.put(id, new HashMap<>());

                Map<String, String> ct = CODES.get(id);

                ct.put(code, code);
                ct.put(desc.toUpperCase().trim(), code); // allows searching for code by description
            }
        }
    }

    public static String getCodeStr(String table, String key)
    {
        return CODES.get(table).get(key);
    }
}

Now inside my application I frequently refer to this class.  Simple example

String test = Codes.getCodeStr("test_table_id", "test_code_value");

When mocking I won't be able to connect to a database.  So what must I do to be able to test with this class?

One thing I have considered is collect all the code table data into a file and then initialize from the file based on some switch.  I just have to make sure the file is kept up to date...

Any ideas or suggestions are welcome but I do prefer to avoid/limit injection when I can.


问:
spring boot application has Whitelabel Error Page
I made this apllication that connect to mongodb database and want to test it on swagger ui but i have this error:

How can i solve this problem? Some files are shown below, thank you so much.

Here is the construction of my project:

Here is pom file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.linhday</groupId>
    <artifactId>springboot-mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mongodb</name>
    <description>springboot-mongodb</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

</code>```

Here is controller file:

```<code>package com.linhday.springbootmongodb.controller;

import com.linhday.springbootmongodb.collections.Article;
import com.linhday.springbootmongodb.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    public String save(@RequestBody Article article) {
        return articleService.save(article);
    }

}
</code>```

Try to run the spring boot application but it didn't work.

Body:
I made this apllication that connect to mongodb database and want to test it on swagger ui but i have this error:

How can i solve this problem? Some files are shown below, thank you so much.

Here is the construction of my project:

Here is pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/>
    </parent>
    <groupId>com.linhday</groupId>
    <artifactId>springboot-mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mongodb</name>
    <description>springboot-mongodb</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Here is controller file:

package com.linhday.springbootmongodb.controller;

import com.linhday.springbootmongodb.collections.Article;
import com.linhday.springbootmongodb.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    public String save(@RequestBody Article article) {
        return articleService.save(article);
    }

}

Try to run the spring boot application but it didn't work.


问:
Can't Get Data from MediSource Stream when get data in middle of streaming
I'm working on a live video streaming service. I get data from the camera and turn the binary array to base64 and send base64 strings to other clients. in the receiver part, I'm using Mediasource API to provide src for the HTML video elements. everything works fine when the receiver gets video data from the beginning of the stream. but the problem is that the receiver cant
turn received data into video if start receiving them from the middle of streaming.I used this doc for my work

this is appending method

```<code>const mediaSource = new MediaSource();

mediaSource.addEventListener('sourceopen', async () => {
    const sourceBuffer = mediaSource.addSourceBuffer(webm9MimeCodec);
    sourceBuffer.mode = 'sequence';
    sourceBuffer.addEventListener('updateend', async () => {
        if (videoTarget.paused)
            videoTarget.play();

        const ab = await channel.pull()
        sourceBuffer.appendBuffer(ab)
    });

    const ab = await channel.pull()
    sourceBuffer.appendBuffer(ab)
});

videoTarget.src = URL.createObjectURL(mediaSource);
</code>```

this is the method I use create  array buffer

```<code>const channelFactory = function () {
    const _arrayBufferBuffer = []
    const pullResolveQueue = []

    return {
        push: (ab) => {
            if (pullResolveQueue.length > 0) {
                const pull = pullResolveQueue.pop()
                pull(ab)
            } else {
                _arrayBufferBuffer.push(ab)
            }
        },
        pull: () => new Promise((res, rej) => {
            if (_arrayBufferBuffer.length > 0) {
                res(_arrayBufferBuffer.pop())
            }
            pullResolveQueue.push(res)
        })
    }
}
</code>```

and this is how I get data from the server

```<code>var lastIndex = -1
    var partBuffer = []
    var playing = false;

    connection.on('video-data', async (r) => {

        console.log(r.part.length);
        if (r.part.length === 0) {
            return
        }

        if (!playing && r.index !== 0) {
            return
        }
        playing = true

        if (lastIndex >= r.index) {
            const ba = base64js.toByteArray(partBuffer.reduce((a, b) => a + b))
            channel.push(ba.buffer)
            partBuffer = []
        }

        partBuffer.push(r.part)

        lastIndex = r.index
    })
</code>```

thanks for reading

Body:
I'm working on a live video streaming service. I get data from the camera and turn the binary array to base64 and send base64 strings to other clients. in the receiver part, I'm using Mediasource API to provide src for the HTML video elements. everything works fine when the receiver gets video data from the beginning of the stream. but the problem is that the receiver cant
turn received data into video if start receiving them from the middle of streaming.I used this doc for my work

this is appending method

const mediaSource = new MediaSource();

mediaSource.addEventListener('sourceopen', async () => {
    const sourceBuffer = mediaSource.addSourceBuffer(webm9MimeCodec);
    sourceBuffer.mode = 'sequence';
    sourceBuffer.addEventListener('updateend', async () => {
        if (videoTarget.paused)
            videoTarget.play();

        const ab = await channel.pull()
        sourceBuffer.appendBuffer(ab)
    });

    const ab = await channel.pull()
    sourceBuffer.appendBuffer(ab)
});

videoTarget.src = URL.createObjectURL(mediaSource);

this is the method I use create  array buffer

const channelFactory = function () {
    const _arrayBufferBuffer = []
    const pullResolveQueue = []

    return {
        push: (ab) => {
            if (pullResolveQueue.length > 0) {
                const pull = pullResolveQueue.pop()
                pull(ab)
            } else {
                _arrayBufferBuffer.push(ab)
            }
        },
        pull: () => new Promise((res, rej) => {
            if (_arrayBufferBuffer.length > 0) {
                res(_arrayBufferBuffer.pop())
            }
            pullResolveQueue.push(res)
        })
    }
}

and this is how I get data from the server

var lastIndex = -1
    var partBuffer = []
    var playing = false;

    connection.on('video-data', async (r) => {

        console.log(r.part.length);
        if (r.part.length === 0) {
            return
        }

        if (!playing && r.index !== 0) {
            return
        }
        playing = true

        if (lastIndex >= r.index) {
            const ba = base64js.toByteArray(partBuffer.reduce((a, b) => a + b))
            channel.push(ba.buffer)
            partBuffer = []
        }

        partBuffer.push(r.part)

        lastIndex = r.index
    })

thanks for reading


问:
save_post for custom meta box returns 302
I have a php class inside my plugin that generates custom metaboxes for my post types.

Theses metaboxes contain inputs that I want to save with the "save_post" hook, as I have done a million times :

```<code>class CcmComponentMetaboxElement{
    public function __construct($config){
        /* Some logic */
        $this->config = $config;
        $this->ccm_metabox_display();
        $this->ccm_metabox_save();
    }

    public function ccm_metabox_display(){
        $metabox_id = $this->config->id;
        $context = property_exists($this->config, 'context') ? $this->config->context : 'advanced';
        $priority = property_exists($this->config, 'priority') ? $this->config->priority : 'default';

        add_meta_box(
            $metabox_id,
            $this->config->title,
            array($this, 'ccm_metabox_display_callback'),
            $this->config->screens,
            $context,
            $priority
        );
    }

    public function ccm_metabox_display_callback(){
        /* Some logic that displays metabox with custom post_metadata inside */
    }

    public function ccm_metabox_save(){
        foreach($this->config->screens as $screen){
            $action_name = 'save_post_' . $screen;

            add_action($action_name, function($post_id){
                if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
                    return;
                }
                if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
                    return;
                }

                if(empty($_POST)){
                    error_log( 'EMPTY POST' );
                    return;
                }

                if ( ! array_key_exists( $this->nonce_name, $_POST ) ||
                    !wp_verify_nonce( $_POST[$this->nonce_name], $this->nonce_value )) {
                    error_log( 'NONCE NOT VERIFIED' );
                    return;
                }

                foreach($this->config->fields as $field){
                    if(array_key_exists( $field->id, $_POST )){
                        update_post_meta( $post_id, $field->id, $_POST[$field->id]);
                    }
                }
            }, 10, 1);
        }
    }
}
</code>```

The issue i'm facing this time, is that when I'm saving a post with a custom metabox, my hook from my plugin is well executed, but the script stops when checking if $_POST is empty (it records the 'EMPTY POST' inside my debug.log file).

After clicking on "update", fetch executes the save action but returns 302 from the server

The system always returns a 302 status code and $_POST is always empty, no matter what I write in my function, except when I var_dump the $_SERVER variable (for some reason, when I do this it works fine, but the Worpress fetch api doesn't like it).

Does anyone have any suggestions to help me ?

Thanks !

I tried many solutions that didn't work in my case, including refreshing permalinks, forcing https in wp-config, ....

I only activated my plugin and an empty theme of mine with the bare minimum.

I have the same problem with the hook 'restafterinsert_post'

Body:
I have a php class inside my plugin that generates custom metaboxes for my post types.

Theses metaboxes contain inputs that I want to save with the "save_post" hook, as I have done a million times :

class CcmComponentMetaboxElement{
    public function __construct($config){
        /* Some logic */
        $this->config = $config;
        $this->ccm_metabox_display();
        $this->ccm_metabox_save();
    }

    public function ccm_metabox_display(){
        $metabox_id = $this->config->id;
        $context = property_exists($this->config, 'context') ? $this->config->context : 'advanced';
        $priority = property_exists($this->config, 'priority') ? $this->config->priority : 'default';

        add_meta_box(
            $metabox_id,
            $this->config->title,
            array($this, 'ccm_metabox_display_callback'),
            $this->config->screens,
            $context,
            $priority
        );
    }

    public function ccm_metabox_display_callback(){
        /* Some logic that displays metabox with custom post_metadata inside */
    }

    public function ccm_metabox_save(){
        foreach($this->config->screens as $screen){
            $action_name = 'save_post_' . $screen;

            add_action($action_name, function($post_id){
                if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
                    return;
                }
                if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
                    return;
                }

                if(empty($_POST)){
                    error_log( 'EMPTY POST' );
                    return;
                }

                if ( ! array_key_exists( $this->nonce_name, $_POST ) ||
                    !wp_verify_nonce( $_POST[$this->nonce_name], $this->nonce_value )) {
                    error_log( 'NONCE NOT VERIFIED' );
                    return;
                }

                foreach($this->config->fields as $field){
                    if(array_key_exists( $field->id, $_POST )){
                        update_post_meta( $post_id, $field->id, $_POST[$field->id]);
                    }
                }
            }, 10, 1);
        }
    }
}

The issue i'm facing this time, is that when I'm saving a post with a custom metabox, my hook from my plugin is well executed, but the script stops when checking if $_POST is empty (it records the 'EMPTY POST' inside my debug.log file).

After clicking on "update", fetch executes the save action but returns 302 from the server

The system always returns a 302 status code and $_POST is always empty, no matter what I write in my function, except when I var_dump the $_SERVER variable (for some reason, when I do this it works fine, but the Worpress fetch api doesn't like it).

Does anyone have any suggestions to help me ?

Thanks !

I tried many solutions that didn't work in my case, including refreshing permalinks, forcing https in wp-config, ....

I only activated my plugin and an empty theme of mine with the bare minimum.

I have the same problem with the hook 'restafterinsert_post'


问:
Plotting a static hexagonal topology using MiniSom with a color scheme
I'm using the MiniSom package to make a Self Organizing Map of my data, in one of their examples on GitHub they plot a nice static hexagonal topology visualising the distance between the neighbouring neurons using a color based on an array with distance values (floats between 0 and 1) and an overlay of symbols showing the corresponding classes.

(see example here: https://github.com/JustGlowing/minisom/blob/master/examples/HexagonalTopology.ipynb)

I successfully copied this code and applied it to my dataset but now I'd like to alter the code such that I can use a different array to base the colors on, specifically an array with larger values which are not between 0 and 1. I tried doing this by simply exchanging the umatrix by my self-made matrix with different values. See below in a snippet of the example

```<code># iteratively add hexagons
for i in range(weights.shape[0]):
    for j in range(weights.shape[1]):
        wy = yy[(i, j)] * np.sqrt(3) / 2
        hex = RegularPolygon((xx[(i, j)], wy),
                             numVertices=6,
                             radius=.95 / np.sqrt(3),
                             facecolor=cm.Blues(umatrix[i, j]),  "___________I replace umatrix here by my own array"
                             alpha=.4,
                             edgecolor='gray')
        ax.add_patch(hex)
</code>```

Simply applying the same code to this array with larger values gives the following output: (note, I am not plotting the symbols in this example outcome, only this color)

All non-null hexagons get the same color as the values are all way above 1 in this different array and the colorbar does not adapt automatically. How can I alter this colorbar to fit this different array of larger numbers? Or is there a way to set a min and max of this colorbar? Any help would be appreciated!

Body:
I'm using the MiniSom package to make a Self Organizing Map of my data, in one of their examples on GitHub they plot a nice static hexagonal topology visualising the distance between the neighbouring neurons using a color based on an array with distance values (floats between 0 and 1) and an overlay of symbols showing the corresponding classes.

(see example here: https://github.com/JustGlowing/minisom/blob/master/examples/HexagonalTopology.ipynb)

I successfully copied this code and applied it to my dataset but now I'd like to alter the code such that I can use a different array to base the colors on, specifically an array with larger values which are not between 0 and 1. I tried doing this by simply exchanging the umatrix by my self-made matrix with different values. See below in a snippet of the example

# iteratively add hexagons
for i in range(weights.shape[0]):
    for j in range(weights.shape[1]):
        wy = yy[(i, j)] * np.sqrt(3) / 2
        hex = RegularPolygon((xx[(i, j)], wy),
                             numVertices=6,
                             radius=.95 / np.sqrt(3),
                             facecolor=cm.Blues(umatrix[i, j]),  "___________I replace umatrix here by my own array"
                             alpha=.4,
                             edgecolor='gray')
        ax.add_patch(hex)

Simply applying the same code to this array with larger values gives the following output: (note, I am not plotting the symbols in this example outcome, only this color)

All non-null hexagons get the same color as the values are all way above 1 in this different array and the colorbar does not adapt automatically. How can I alter this colorbar to fit this different array of larger numbers? Or is there a way to set a min and max of this colorbar? Any help would be appreciated!


问:
Docker Java class error when I try to run docker image of a spring boot application
I'm trying to run a docker image but I keep having the error below

```<code>docker run -p 8080:8080 nacer/my-image-name-1
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/springframework/boot/loader/JarLauncher has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:473)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)
</code>```

This is my Dockerfile

```<code>FROM openjdk:8

EXPOSE 8080

ADD target/docker-demo-1.jar docker-demo-1.jar

ENTRYPOINT ["java","-jar","docker-demo-1.jar"]
</code>```

Is that because because the java version?
this my java version (java version "1.8.0_351")

I try to run spring boot application from my image in docker hub. I was expecting to run the spring application. after I type :
docker run -p 8080:8080 nacer/my-image-name-1

Body:
I'm trying to run a docker image but I keep having the error below

docker run -p 8080:8080 nacer/my-image-name-1
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/springframework/boot/loader/JarLauncher has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:473)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)

This is my Dockerfile

FROM openjdk:8

EXPOSE 8080

ADD target/docker-demo-1.jar docker-demo-1.jar

ENTRYPOINT ["java","-jar","docker-demo-1.jar"]

Is that because because the java version?
this my java version (java version "1.8.0_351")

I try to run spring boot application from my image in docker hub. I was expecting to run the spring application. after I type :
docker run -p 8080:8080 nacer/my-image-name-1


问:
HTTP Request Avoiding SSL
I'm trying to make a POST request with axios to a 3rd party API and I get an error of expired certificate.
Any recommendation to avoid this error?</p>

Title: HTTP Request Avoiding SSL


问:
Is there a way to implement case insensitive and case sensitive searches on the same field in Elasticsearch without using a multi-field?
The project I am working on requires that a user can search the content of a document with both case sensitivity and case insensitivity at the same time. The case I provide below, the query is asking for a document that contains both the phrases "it was no use trying" (case insensitive) and "BIG BROTHER IS WATCHING YOU" (case sensitive) at the same time. All the research that I have done for case sensitivity with Elasticsearch seems to say that I need to have a multi-field with a "standard" tokenizer to implement this. The problem comes when the highlights come back from Elasticsearch, they are separated into the two separate fields and I get incorrect highlighting when the case sensitive and case insensitive sections of the highlight overlap.

I am going to explain the steps that I took to implement case sensitive searching and then go over the problem.

First, I added an analyzer to my solution using the “standard” tokenizer and called it document_cs_analyzer. See code below:

```<code>.Analyzers(an => an
    .Custom("document_analyzer", ca => ca
        .Tokenizer("lowercase")
        .CharFilters("sentence_and_paragraph")
    )
    .Custom("document_cs_analyzer", ca => ca
        .Tokenizer("standard")
        .CharFilters("sentence_and_paragraph")
    )
)
</code>```

Next I applied this analyzer to a multi-field under my “attachment.content” field named “case_sensitive”. See code below:

```<code>.Map<TElasticSearchDocument>(mp => mp
    .Properties(ps => ps
        .Object<CustomNestAttachment>(n => n
            .Name(nn => nn.Attachment)
            .Properties(pps => pps
                .Text(tt => tt
                .Analyzer("document_analyzer")
                    .Name(nn => nn.Content)
                    .Fields(f => f
                        .Text(pd => pd
                            .Name("case_sensitive")
                            .Analyzer("document_cs_analyzer")
                        )
                    )
                )
            )
        )
    )
)
</code>```

This means that when I run a query, I can get case insensitive results using the base “attachment.content” field and case sensitive results using the multi-field “attachment.content.case_sensitive”

Here is an example query that gets both case sensitive and case insensitive that a user might write:

```<code>"bool": {
    "must": [
        {
            "match_phrase": {
                "attachment.content.case_sensitive": {
                    "query": "\"BIG BROTHER IS WATCHING YOU\""
                }
            }
        },
        {
            "match_phrase": {
                "attachment.content": {
                    "query": "\"it was no use trying\""
                }
            }
        }
    ]
}
</code>```

Notice the use of both fields at the same time. This search works just fine, the issue comes with the response object. See image below:

enter image description here

Looking at the “Highlight” field we an array of highlighted snippets for both “attachment.content” and “attachment.content.case_sensitive”. We want to show the user the first snippet that comes back from the document, but the first snippet only includes case insensitive bolding, and the second snippet only includes case sensitive bolding. In the common case of these snippets overlapping in the document, no matter which snippet we take we will get incorrect highlighting. This is the primary issue.

Restating the question: Is there a method for searching case sensitive and case insensitive on the same field without getting separate highlights back?

Here is the code I use to search the indices and produce highlighting if it helps:
enter image description here

Let me know if more information is needed.
Thanks!

Body:
The project I am working on requires that a user can search the content of a document with both case sensitivity and case insensitivity at the same time. The case I provide below, the query is asking for a document that contains both the phrases "it was no use trying" (case insensitive) and "BIG BROTHER IS WATCHING YOU" (case sensitive) at the same time. All the research that I have done for case sensitivity with Elasticsearch seems to say that I need to have a multi-field with a "standard" tokenizer to implement this. The problem comes when the highlights come back from Elasticsearch, they are separated into the two separate fields and I get incorrect highlighting when the case sensitive and case insensitive sections of the highlight overlap.

I am going to explain the steps that I took to implement case sensitive searching and then go over the problem.

First, I added an analyzer to my solution using the “standard” tokenizer and called it document_cs_analyzer. See code below:

.Analyzers(an => an
    .Custom("document_analyzer", ca => ca
        .Tokenizer("lowercase")
        .CharFilters("sentence_and_paragraph")
    )
    .Custom("document_cs_analyzer", ca => ca
        .Tokenizer("standard")
        .CharFilters("sentence_and_paragraph")
    )
)

Next I applied this analyzer to a multi-field under my “attachment.content” field named “case_sensitive”. See code below:

.Map<TElasticSearchDocument>(mp => mp
    .Properties(ps => ps
        .Object<CustomNestAttachment>(n => n
            .Name(nn => nn.Attachment)
            .Properties(pps => pps
                .Text(tt => tt
                .Analyzer("document_analyzer")
                    .Name(nn => nn.Content)
                    .Fields(f => f
                        .Text(pd => pd
                            .Name("case_sensitive")
                            .Analyzer("document_cs_analyzer")
                        )
                    )
                )
            )
        )
    )
)

This means that when I run a query, I can get case insensitive results using the base “attachment.content” field and case sensitive results using the multi-field “attachment.content.case_sensitive”

Here is an example query that gets both case sensitive and case insensitive that a user might write:

"bool": {
    "must": [
        {
            "match_phrase": {
                "attachment.content.case_sensitive": {
                    "query": "\"BIG BROTHER IS WATCHING YOU\""
                }
            }
        },
        {
            "match_phrase": {
                "attachment.content": {
                    "query": "\"it was no use trying\""
                }
            }
        }
    ]
}

Notice the use of both fields at the same time. This search works just fine, the issue comes with the response object. See image below:

enter image description here

Looking at the “Highlight” field we an array of highlighted snippets for both “attachment.content” and “attachment.content.case_sensitive”. We want to show the user the first snippet that comes back from the document, but the first snippet only includes case insensitive bolding, and the second snippet only includes case sensitive bolding. In the common case of these snippets overlapping in the document, no matter which snippet we take we will get incorrect highlighting. This is the primary issue.

Restating the question: Is there a method for searching case sensitive and case insensitive on the same field without getting separate highlights back?

Here is the code I use to search the indices and produce highlighting if it helps:
enter image description here

Let me know if more information is needed.
Thanks!


问:
Why django codes not updating automatically using supervisorctl and Gunicorn?
Using Supervisor, I deployed Django. Django codes are not updated, instead I must restart Nginx or Supervisor. If you could help me with this issue, that would be great.

Supervisor configuration

```<code>[program:program_name]
directory=/home/user/django/dir/django_dir/
command=/home/user/django/dir/venv/bin/gunicorn --workers 3 --bind unix:/home/user/django/dir/name.sock ingen>
#command=/home/user/django/dir/venv/bin/ssh_filename.sh
numprocs=3
process_name=name%(process_num)d
autostart=true
autorestart=true
stopasgroup=true
user=user
Group=www-data
stderr_logfile=/home/user/django/dir/logs/supervisor_err.log
stdout_logfile=/home/user/django/dir/logs/supervisor.log
redirect_stderr=true
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8
</code>```

I am trying to restart the supervisor process with the below command in order to update the Django backend codes, but it doesn't always work.

```<code>sudo supervisorctl restart program_name:*
//'program_name' refers to the name of the program in the supervisor configuration file
</code>```

METHOD 2

A second trail with a ssh_filename.sh file and the second command in the above supervisor configuration is used to run the ssh_filename.sh script.

```<code>#!/bin/bash
NAME="django_dir"  #Django application name
DIR_PARENT=/home/user/django/dir
DIR=${DIR_PARENT}/django_dir #Directory where project is located
USER=user   #User to run this script as
GROUP=www-data  #Group to run this script as
WORKERS=3     #Number of workers that Gunicorn should spawn
SOCKFILE=unix:${DIR_PARENT}/dir.sock   #This socket file will communicate with Nginx
DJANGO_SETTINGS_MODULE=django_dir.settings   #Which Django setting file should use
DJANGO_WSGI_MODULE=django_dir.wsgi           #Which WSGI file should use
LOG_LEVEL=debug
cd $DIR
source ${DIR_PARENT}/venv/bin/activate  #Activate the virtual environment
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DIR_PARENT:$PYTHONPATH

#Command to run the progam under supervisor
exec ${DIR_PARENT}/venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $WORKERS \
--user=$USER \
--group=$GROUP \
--bind=$SOCKFILE \
--log-level=$LOG_LEVEL \
--log-file=-
</code>```

Nginx web server throws a "BAD GATEWAY"" error when using the second method. If the above ssh_filename.sh script is run manually, the website works. Following are the codes I use to manually run the above ssh_filename.sh script

cd /home/user/django/dir

source venv/bin/activate

sudo venv/bin/sh_filename.sh //It works only if run with sudo

Questions

I activated the virtual environment in the above ssh_filename.sh script. Is it a smart idea?

What is the best way to update Django codes automatically without restarting Supervisor?

How to prevent the "BAD GATEWAY" error using the second method?

Body:
Using Supervisor, I deployed Django. Django codes are not updated, instead I must restart Nginx or Supervisor. If you could help me with this issue, that would be great.

Supervisor configuration

[program:program_name]
directory=/home/user/django/dir/django_dir/
command=/home/user/django/dir/venv/bin/gunicorn --workers 3 --bind unix:/home/user/django/dir/name.sock ingen>
#command=/home/user/django/dir/venv/bin/ssh_filename.sh
numprocs=3
process_name=name%(process_num)d
autostart=true
autorestart=true
stopasgroup=true
user=user
Group=www-data
stderr_logfile=/home/user/django/dir/logs/supervisor_err.log
stdout_logfile=/home/user/django/dir/logs/supervisor.log
redirect_stderr=true
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8

I am trying to restart the supervisor process with the below command in order to update the Django backend codes, but it doesn't always work.

sudo supervisorctl restart program_name:*
//'program_name' refers to the name of the program in the supervisor configuration file

METHOD 2

A second trail with a ssh_filename.sh file and the second command in the above supervisor configuration is used to run the ssh_filename.sh script.

#!/bin/bash
NAME="django_dir"  #Django application name
DIR_PARENT=/home/user/django/dir
DIR=${DIR_PARENT}/django_dir #Directory where project is located
USER=user   #User to run this script as
GROUP=www-data  #Group to run this script as
WORKERS=3     #Number of workers that Gunicorn should spawn
SOCKFILE=unix:${DIR_PARENT}/dir.sock   #This socket file will communicate with Nginx
DJANGO_SETTINGS_MODULE=django_dir.settings   #Which Django setting file should use
DJANGO_WSGI_MODULE=django_dir.wsgi           #Which WSGI file should use
LOG_LEVEL=debug
cd $DIR
source ${DIR_PARENT}/venv/bin/activate  #Activate the virtual environment
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DIR_PARENT:$PYTHONPATH

#Command to run the progam under supervisor
exec ${DIR_PARENT}/venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $WORKERS \
--user=$USER \
--group=$GROUP \
--bind=$SOCKFILE \
--log-level=$LOG_LEVEL \
--log-file=-

Nginx web server throws a "BAD GATEWAY"" error when using the second method. If the above ssh_filename.sh script is run manually, the website works. Following are the codes I use to manually run the above ssh_filename.sh script

cd /home/user/django/dir

source venv/bin/activate

sudo venv/bin/sh_filename.sh //It works only if run with sudo

Questions

I activated the virtual environment in the above ssh_filename.sh script. Is it a smart idea?

What is the best way to update Django codes automatically without restarting Supervisor?

How to prevent the "BAD GATEWAY" error using the second method?


问:
Missing "nonce" claim with Quickbooks + Authlib
When I try to implement an OAuth flow into Quickbooks Online with the openid scope, I receive an error authlib.jose.errors.MissingClaimError: missing_claim: Missing "nonce" claim.

Here is the code:

from authlib.integrations.flask_client import OAuth

oauth = OAuth(app)
oauth.register(
    name="qbo",
    client_id='x',
    client_secret='x',
    server_metadata_url='https://developer.api.intuit.com/.well-known/openid_sandbox_configuration',
    client_kwargs={"scope": "openid email profile com.intuit.quickbooks.accounting"},
)

@app.route("/login")
def login():
    redirect_uri = url_for("callback", _external=True)
    client = getattr(oauth, 'qbo')
    return client.authorize_redirect(redirect_uri, state='hello')

@app.route("/callback")
def callback():
    client = getattr(oauth, 'qbo')
    token = client.authorize_access_token()
    return 'authorized'
```

The line client.authorize_access_token() is failing. This also fails when I pass a nonce param to the authorize_redirect() method.

When I remove the openid email profile scopes, then this works without an issue. I have similar code for openid and Google, and that works without any issues.

Any ideas on what is happening in this case?

Body:
When I try to implement an OAuth flow into Quickbooks Online with the openid scope, I receive an error authlib.jose.errors.MissingClaimError: missing_claim: Missing "nonce" claim.

Here is the code:

from authlib.integrations.flask_client import OAuth

oauth = OAuth(app)
oauth.register(
    name="qbo",
    client_id='x',
    client_secret='x',
    server_metadata_url='https://developer.api.intuit.com/.well-known/openid_sandbox_configuration',
    client_kwargs={"scope": "openid email profile com.intuit.quickbooks.accounting"},
)

@app.route("/login")
def login():
    redirect_uri = url_for("callback", _external=True)
    client = getattr(oauth, 'qbo')
    return client.authorize_redirect(redirect_uri, state='hello')

@app.route("/callback")
def callback():
    client = getattr(oauth, 'qbo')
    token = client.authorize_access_token()
    return 'authorized'

The line client.authorize_access_token() is failing. This also fails when I pass a nonce param to the authorize_redirect() method.

When I remove the openid email profile scopes, then this works without an issue. I have similar code for openid and Google, and that works without any issues.

Any ideas on what is happening in this case?


问:
LazyVGrid code behaves differently in different Xcode versions?
I was just watching Standord's CS193p (2021 editions)

The instructor shows this as an example of LazyVGrid:

As you see the spacing is equal in every direction.

Now here is how I see it with the exact same code in Xcode 14.2 (it's the same with 9 cards too):

I double checked and the code is exactly the same for both of us!

```<code>import SwiftUI

struct ContentView: View {
    var emojis = ["✈", "", "", "", "", "", "", "", ""]
    @State var emojiCount = 8

    var body: some View {
        VStack {
            LazyVGrid(columns: [GridItem(),GridItem(),GridItem(),GridItem()]) {
                ForEach(emojis[0..<emojiCount], id: \.self) { emoji in
                    CardView(content: emoji).aspectRatio(2/3, contentMode: .fit)
                }
            }
            .foregroundColor(.red)
            Spacer()
            HStack {
                remove
                Spacer()
                add
            }
            .font(.largeTitle)
            .padding(.horizontal)
        }
        .padding(.horizontal)
    }

    var remove: some View {
        Button {
            if emojiCount > 1 {
                emojiCount -= 1
            }
        } label: {
            Image(systemName: "minus.circle")
        }
    }

    var add: some View {
        Button {
            if emojiCount < emojis.count {
                emojiCount += 1
            }
        } label: {
            Image(systemName: "plus.circle")
        }
    }
}

struct CardView: View {
    var content: String
    @State var isFaceUp: Bool = true

    var body: some View {
        ZStack {
            let shape = RoundedRectangle(cornerRadius: 25)
            if isFaceUp {
                shape.fill(.white)
                shape.stroke(lineWidth: 3)
                Text(content).font(.largeTitle)
            } else {
                shape.fill(.red)
            }
        }
        .onTapGesture {
            isFaceUp = !isFaceUp
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        ContentView()
            .preferredColorScheme(.dark)
    }
}
</code>```

How is that possible? if Apple just changes the behavior like that, what happens to old apps when running in newer devices?

Also, how can I set the vertical spacing to be exactly the same as horizonal spacing? (I am aware I can set the vertical spacing like this: LazyVGrid(columns:..., spacing: 10), but that is a fixed amount and not always equal to horizontal spacing depending on the cols)

Timed link to the video on Youtube

Edit:

Funny enough, removing the Text() inside card or adding .padding() to it fixes the issue, but I still don't understand why, it is more confusing when you watch the video:

Link to Video

Body:
I was just watching Standord's CS193p (2021 editions)

The instructor shows this as an example of LazyVGrid:

As you see the spacing is equal in every direction.

Now here is how I see it with the exact same code in Xcode 14.2 (it's the same with 9 cards too):

I double checked and the code is exactly the same for both of us!

import SwiftUI

struct ContentView: View {
    var emojis = ["✈", "", "", "", "", "", "", "", ""]
    @State var emojiCount = 8

    var body: some View {
        VStack {
            LazyVGrid(columns: [GridItem(),GridItem(),GridItem(),GridItem()]) {
                ForEach(emojis[0..<emojiCount], id: \.self) { emoji in
                    CardView(content: emoji).aspectRatio(2/3, contentMode: .fit)
                }
            }
            .foregroundColor(.red)
            Spacer()
            HStack {
                remove
                Spacer()
                add
            }
            .font(.largeTitle)
            .padding(.horizontal)
        }
        .padding(.horizontal)
    }

    var remove: some View {
        Button {
            if emojiCount > 1 {
                emojiCount -= 1
            }
        } label: {
            Image(systemName: "minus.circle")
        }
    }

    var add: some View {
        Button {
            if emojiCount < emojis.count {
                emojiCount += 1
            }
        } label: {
            Image(systemName: "plus.circle")
        }
    }
}

struct CardView: View {
    var content: String
    @State var isFaceUp: Bool = true

    var body: some View {
        ZStack {
            let shape = RoundedRectangle(cornerRadius: 25)
            if isFaceUp {
                shape.fill(.white)
                shape.stroke(lineWidth: 3)
                Text(content).font(.largeTitle)
            } else {
                shape.fill(.red)
            }
        }
        .onTapGesture {
            isFaceUp = !isFaceUp
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        ContentView()
            .preferredColorScheme(.dark)
    }
}

How is that possible? if Apple just changes the behavior like that, what happens to old apps when running in newer devices?

Also, how can I set the vertical spacing to be exactly the same as horizonal spacing? (I am aware I can set the vertical spacing like this: LazyVGrid(columns:..., spacing: 10), but that is a fixed amount and not always equal to horizontal spacing depending on the cols)

Timed link to the video on Youtube

Edit:

Funny enough, removing the Text() inside card or adding .padding() to it fixes the issue, but I still don't understand why, it is more confusing when you watch the video:

Link to Video


问:
ngx-cropper: Make cropper size and position fix and move the image
I have searched and cannot find the solution I am looking for with ngx-image-cropper. I would like is to fix the position of the cropper to be center of the image and immovable once the image is loaded. Instead of moving the cropper, I would like to move the image within the cropper window.
Here is the stackblitz example:

https://stackblitz.com/edit/angular-ivy-c99rna?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts

I'm able to set the fix width and height of the cropper, set the image to be movable with setting the ngx-image-cropper inputs. However my ngx crop function doesn't captured the moved image. Also setting the position to be center for the cropper tool doesnt work.


问:
How do I design an Actor model?
I am trying to implement an Actor model in Java.

I have started with the following [class diagram].

As you can see, the ActorRunner created in the ActorContext is responsible for controlling the life cycle of the actors: it has the message queue and it calls the process() method of the actor for each received message in its loop (run()). Actors simply implement the Actor interface with the single process() method.

Now, I want to add a decorator (Decorator pattern) and be able to decorate the send() and process() methods. However, since the Actor interface does not have the send() I cannot decorate it and spawn a decorated actor with ActorContext.spawnActor().

How can I modify the design to suit my needs?

Title: How do I design an Actor model?