问:
nptyping + beartype, arrays with common dimensions and multiple possible types
I am trying to use nptyping together with beartype to type-check a number of arrays passed to a function, which have dimensions or arbitrary length in common, and which should accept multiple possible types.

I am only able to force the number of dimensions and a single dtype, but I am not able to accept multiple dtypes or to enforce that the dimensions match. Perhaps this is not possible at the moment, but if it is I would very much appreciate some hints on how to do this.

To be more specific what I need at the moment (but I have other use-cases as well) is to make a function accept four two-dimensional arrays of real numbers, something like:

```<code>A: NDArray[Shape['N, N'], Real]
B: NDArray[Shape['N, M'], Real]
C: NDArray[Shape['L, N'], Real]
D: NDArray[Shape['L, M'], Real]
</code>```

This is what I have got so far:

```<code>from nptyping import NDArray, Shape, Int, Float
import numpy as np

from beartype import beartype
from beartype.roar import BeartypeCallHintException

# noinspection PyPep8Naming
@beartype
def foo(A: NDArray[Shape['N, N'], Float],
        B: NDArray[Shape['N, M'], Float],
        C: NDArray[Shape['L, N'], Float],
        D: NDArray[Shape['L, M'], Float]):

    pass

N = np.random.randint(0, 10)
M = np.random.randint(0, 4)
L = np.random.randint(0, 4)

A = np.random.uniform(-1, 1, (N, N))
B = np.random.uniform(-1, 1, (N, M))
C = np.random.uniform(-1, 1, (L, N))
D = np.random.uniform(-1, 1, (L, M))

foo(A, B, C, D)
</code>```

But this has two issues:

It does not enforce that the dimensions match between the different arrays

I have tried many different things (Union etc.) but I am not able to accept more than one dtype.

I have tried to read through the documentation of nptyping but other than the examples I have not been able to find any detailed documentation (or any documentation at all in fact) for any of the classes or functions, perhaps I have not been looking in the right place.

Body:
I am trying to use nptyping together with beartype to type-check a number of arrays passed to a function, which have dimensions or arbitrary length in common, and which should accept multiple possible types.

I am only able to force the number of dimensions and a single dtype, but I am not able to accept multiple dtypes or to enforce that the dimensions match. Perhaps this is not possible at the moment, but if it is I would very much appreciate some hints on how to do this.

To be more specific what I need at the moment (but I have other use-cases as well) is to make a function accept four two-dimensional arrays of real numbers, something like:

A: NDArray[Shape['N, N'], Real]
B: NDArray[Shape['N, M'], Real]
C: NDArray[Shape['L, N'], Real]
D: NDArray[Shape['L, M'], Real]

This is what I have got so far:

from nptyping import NDArray, Shape, Int, Float
import numpy as np

from beartype import beartype
from beartype.roar import BeartypeCallHintException

# noinspection PyPep8Naming
@beartype
def foo(A: NDArray[Shape['N, N'], Float],
        B: NDArray[Shape['N, M'], Float],
        C: NDArray[Shape['L, N'], Float],
        D: NDArray[Shape['L, M'], Float]):

    pass

N = np.random.randint(0, 10)
M = np.random.randint(0, 4)
L = np.random.randint(0, 4)

A = np.random.uniform(-1, 1, (N, N))
B = np.random.uniform(-1, 1, (N, M))
C = np.random.uniform(-1, 1, (L, N))
D = np.random.uniform(-1, 1, (L, M))

foo(A, B, C, D)

But this has two issues:

It does not enforce that the dimensions match between the different arrays

I have tried many different things (Union etc.) but I am not able to accept more than one dtype.

I have tried to read through the documentation of nptyping but other than the examples I have not been able to find any detailed documentation (or any documentation at all in fact) for any of the classes or functions, perhaps I have not been looking in the right place.


来源: stackexchange

问:
The program has exited with code 2147516551 (0x80008087)
I have a solution that was compiling and running fine in Visual Studio 2022.  I added another project to the same solution, did some work on the new project and then checked it all into Devops.  Now, everything compiles fine.  I can "publish" to a folder and get the EXE and it runs.  But I CAN'T run it in Visual Studio or by trying to run the EXE in the bin folder structure.  When I click the run button in VS, I get:

The target process exited without raising a CoreCLR started event. Ensure that the target process is configured to use .NET Core. This may be expected if the target process did not run on .NET Core.

The program '[21684] Enable Instant Book.exe' has exited with code 2147516551 (0x80008087).

Now, this is a Winforms application targeting .Net 6.0 on Windows.  So I'm not sure why it's suddenly throwing this error nor why it says "CoreCLR" in the error when I'm not targeting Core.  I'm so frustrated with it that I'm thinking of dumping it all and redoing it in VS 2019 with .Net 4.x. But I thought I would see if any of you knew some magic to get it to return to a working state first.

Some of the things I've tried:

Clean and rebuild

Remove all projects except the very first one that I know was working and rebuild

Close and reopen VS / Reboot PC

Delete everything in "bin" folder and rebuild

Changing the compile from "Any CPU" to x64

Any ideas?

ContentLicense: CC BY-SA 4.0


问:
How can I manually produce a legend/key for a line plot produced from 3 separate dataframes?
Using ggplot2, I have produced a plot with 3 lines, colour coded for 3 experimental conditions. I have had to detail these outside of ggplot(aes()) but in stead within geom_line(aes()) such that I could collate the data from their respective, separate dataframes. As such, ggplot has not produced a legend. Code for the plot is here:

```<code>ggplot()+
  geom_line(data = linedatac1df, aes(x=time, y=c1y), size=1.2, colour=rgb(0.6,0.9,0.9))+
  geom_line(data = linedatac2df, aes(x=time, y=c2y), size=1.2, colour=rgb(0,0.5,0.5))+
  geom_line(data = linedatacidf, aes(x=time, y=Iy), size=1.2, colour=rgb(0.9,0.3,0.4))+
  theme_light()+
  scale_y_continuous(breaks = c(-2e-23, -1e-23, 0, 1e-23, 2e-23, 3e-23))+
  scale_x_continuous(breaks = c(-250, 0, 250, 500, 750, 1000, 1250, 1500))+
  ggtitle("Changes in Mean Theta Power Across Conditions")+
  theme(plot.title = element_text(hjust = 0.5))+
  xlab("Time (ms)")+
  ylab("Mean theta power ( mV^2)")+
  theme(panel.background = element_rect(colour = "black", size=2))+
  geom_vline(xintercept = -100, linetype="dashed",
             colour="black", size=1)+
  geom_vline(xintercept = 0, linetype="dashed",
             colour="black", size=1)+
  geom_vline(xintercept = -350, linetype="dotted",
             colour="black", size=1)+
  geom_vline(xintercept = -150, linetype="dotted",
             colour="black",size=1)+
  geom_vline(xintercept = 400, linetype="dotted",
             colour="black",size=1)+
  geom_vline(xintercept = 600, linetype="dotted",
             colour = "black",size=1)
</code>```

I attempted to manually add a legend using the following code, but it did not work:

```<code>+
  scale_colour_manual(name="Key",,
                      breaks = c("Single control", "Double control", "Inhibition"),
                      values = c("Single control"=rgb(0.6,0.9,0.9), "Double control"=rgb(0,0.5,0.5), "Inhibition"=rgb(0.9,0.3,0.4)))
</code>```

Any help on this would be much appreciated!

Body:
Using ggplot2, I have produced a plot with 3 lines, colour coded for 3 experimental conditions. I have had to detail these outside of ggplot(aes()) but in stead within geom_line(aes()) such that I could collate the data from their respective, separate dataframes. As such, ggplot has not produced a legend. Code for the plot is here:

ggplot()+
  geom_line(data = linedatac1df, aes(x=time, y=c1y), size=1.2, colour=rgb(0.6,0.9,0.9))+
  geom_line(data = linedatac2df, aes(x=time, y=c2y), size=1.2, colour=rgb(0,0.5,0.5))+
  geom_line(data = linedatacidf, aes(x=time, y=Iy), size=1.2, colour=rgb(0.9,0.3,0.4))+
  theme_light()+
  scale_y_continuous(breaks = c(-2e-23, -1e-23, 0, 1e-23, 2e-23, 3e-23))+
  scale_x_continuous(breaks = c(-250, 0, 250, 500, 750, 1000, 1250, 1500))+
  ggtitle("Changes in Mean Theta Power Across Conditions")+
  theme(plot.title = element_text(hjust = 0.5))+
  xlab("Time (ms)")+
  ylab("Mean theta power ( mV^2)")+
  theme(panel.background = element_rect(colour = "black", size=2))+
  geom_vline(xintercept = -100, linetype="dashed",
             colour="black", size=1)+
  geom_vline(xintercept = 0, linetype="dashed",
             colour="black", size=1)+
  geom_vline(xintercept = -350, linetype="dotted",
             colour="black", size=1)+
  geom_vline(xintercept = -150, linetype="dotted",
             colour="black",size=1)+
  geom_vline(xintercept = 400, linetype="dotted",
             colour="black",size=1)+
  geom_vline(xintercept = 600, linetype="dotted",
             colour = "black",size=1)

I attempted to manually add a legend using the following code, but it did not work:

+
  scale_colour_manual(name="Key",,
                      breaks = c("Single control", "Double control", "Inhibition"),
                      values = c("Single control"=rgb(0.6,0.9,0.9), "Double control"=rgb(0,0.5,0.5), "Inhibition"=rgb(0.9,0.3,0.4)))

Any help on this would be much appreciated!


问:
Why is my Text Editor not updating to my selected background color?
Very annoying issue. I have a text editor that I am using within a ZStack stack so that it will grow as the user types. I am trying to set the background color of it, but it is just showing as a transparent box within the list. Any tips on how to set the color?
(code has been reduced for clarity). Adding the background color in the init method DOES NOT WORK HERE

my view:

struct AddItem: View {
var body: some View {
   NavigationView {
      VStack {
      ...
        List {
          ZStack {
            Text(viewModel.description).opacity(0).listRowSeparator(.hidden)
            TextEditor(text: $viewModel.description)
            .onAppear() {
              UITextView.appearance().backgroundColor = .clear
            }
            .listRowSeparator(.hidden)
            .background(RoundedRectangle(cornerRadius: 25.0).fill(Color(.systemGray6))) // this doesn't work. nor does .overlay
          }
         .listRowBackground(RoundedRectangle(cornerRadius: 25.0).fill(Color(.systemGray6)))
         .frame(height: 190)
         .padding([.leading, .trailing])
         .listStyle(PlainListStyle())
        }
      }
    }
  }
}
```

I've also tried putting this code UITextView.appearance().backgroundColor = .clear in the init() method and still no results. I have also tried putting an overlay over the text editor with .overlay(), and it gives the desired result, but then I can't interact with the text editor. I would go to iOS 16 and use their new text field, but this needs to work with iOS 15 so please keep that in mind.

Body:
Very annoying issue. I have a text editor that I am using within a ZStack stack so that it will grow as the user types. I am trying to set the background color of it, but it is just showing as a transparent box within the list. Any tips on how to set the color?
(code has been reduced for clarity). Adding the background color in the init method DOES NOT WORK HERE

my view:

struct AddItem: View {
var body: some View {
   NavigationView {
      VStack {
      ...
        List {
          ZStack {
            Text(viewModel.description).opacity(0).listRowSeparator(.hidden)
            TextEditor(text: $viewModel.description)
            .onAppear() {
              UITextView.appearance().backgroundColor = .clear
            }
            .listRowSeparator(.hidden)
            .background(RoundedRectangle(cornerRadius: 25.0).fill(Color(.systemGray6))) // this doesn't work. nor does .overlay
          }
         .listRowBackground(RoundedRectangle(cornerRadius: 25.0).fill(Color(.systemGray6)))
         .frame(height: 190)
         .padding([.leading, .trailing])
         .listStyle(PlainListStyle())
        }
      }
    }
  }
}

I've also tried putting this code UITextView.appearance().backgroundColor = .clear in the init() method and still no results. I have also tried putting an overlay over the text editor with .overlay(), and it gives the desired result, but then I can't interact with the text editor. I would go to iOS 16 and use their new text field, but this needs to work with iOS 15 so please keep that in mind.


问:
Programmatically create a Mockito SpyBean of a given Class
My abstract test needs to create a SpyBean of a defined class within the concrete implementation and I do not want the implementation or the "user" to have to add the @SpyBean annotation.

How can I programmatically create a SpyBean of a given Class without using the @SpyBean annotation?


问:
How to rename and save files in a directory using identor as parameter and correcting the "1, 2, 3.. 9" to "01, 02, 03, 04... 09"
I'm renaming files and saving in a new directory using this code:

```<code>import os
# Function to rename multiple files
def main():
    i = 0
    path="./path/"
    for filename in os.listdir(path):
        my_dest ="Layer" + str(i) + ".dcm"
        my_source =path + filename
        my_dest = "./Layers/" + my_dest
    # rename() function will
    # rename all the files
        os.rename(my_source, my_dest)
        i += 1
# Driver Code
if __name__ == '__main__':
    # Calling main() function
    main()
</code>```

But it's turning the files into "0, 1, 2...9, 10", and when the directory order by name, th files go by "0, 1, 10, 101, 102...11, 110...2" messing up all the order.

I tried to search for a way to rename like "001, 002, 003, 004... 010... 099, 100" so it will stay in order, but the answers are in c++, r and all and I don't know this languages, so if there's a answer in python I could use some help.

Body:
I'm renaming files and saving in a new directory using this code:

import os
# Function to rename multiple files
def main():
    i = 0
    path="./path/"
    for filename in os.listdir(path):
        my_dest ="Layer" + str(i) + ".dcm"
        my_source =path + filename
        my_dest = "./Layers/" + my_dest
    # rename() function will
    # rename all the files
        os.rename(my_source, my_dest)
        i += 1
# Driver Code
if __name__ == '__main__':
    # Calling main() function
    main()

But it's turning the files into "0, 1, 2...9, 10", and when the directory order by name, th files go by "0, 1, 10, 101, 102...11, 110...2" messing up all the order.

I tried to search for a way to rename like "001, 002, 003, 004... 010... 099, 100" so it will stay in order, but the answers are in c++, r and all and I don't know this languages, so if there's a answer in python I could use some help.


问:
Monitoring Spring Security application with a bearer_tocken
I want to set up monitoring Spring Security application, which has updated bearer token.
I connect monitoring using a combination of Grafana and Prometheus, but after a token refresh time, it disconnects.
The Spring Security application implements a token refresh mechanism after authorization.

pom.xml dependensies:

```<code><dependency>
     <groupId>io.micrometer.prometheus</groupId>
     <artifactId>prometheus-rsocket-spring</artifactId>
     <version>1.5.0</version>
 </dependency>
 <dependency>
     <groupId>io.micrometer</groupId>
     <artifactId>micrometer-registry-prometheus</artifactId>
 </dependency>
</code>```

Example of the prometheus config file I use:

```<code>scrape_configs:
  - job_name: 'project_manager'
    scrape_interval: 5s
    bearer_token: 'my.bearer.tocken.example'
    metrics_path: '/api/actuator/prometheus'
    static_configs:
      - targets: ['host.docker.internal:8200']
</code>```

I tried use this settings in application:

```<code>management.security.enabled=false
management.metrics.sensitive=false
</code>```

Monitoring works successfully for an hour, after which the token is updated and the connection between Prometheus and the application is lost.
Perhaps I can set up a refresh token in the prometneus configuration?

Body:
I want to set up monitoring Spring Security application, which has updated bearer token.
I connect monitoring using a combination of Grafana and Prometheus, but after a token refresh time, it disconnects.
The Spring Security application implements a token refresh mechanism after authorization.

pom.xml dependensies:

<dependency>
     <groupId>io.micrometer.prometheus</groupId>
     <artifactId>prometheus-rsocket-spring</artifactId>
     <version>1.5.0</version>
 </dependency>
 <dependency>
     <groupId>io.micrometer</groupId>
     <artifactId>micrometer-registry-prometheus</artifactId>
 </dependency>

Example of the prometheus config file I use:

scrape_configs:
  - job_name: 'project_manager'
    scrape_interval: 5s
    bearer_token: 'my.bearer.tocken.example'
    metrics_path: '/api/actuator/prometheus'
    static_configs:
      - targets: ['host.docker.internal:8200']

I tried use this settings in application:

management.security.enabled=false
management.metrics.sensitive=false

Monitoring works successfully for an hour, after which the token is updated and the connection between Prometheus and the application is lost.
Perhaps I can set up a refresh token in the prometneus configuration?


问:
How to upload image file in post request in python?
```<code>
class UpdateProfilePictureSerializer(serializers.ModelSerializer):
    user_uuid = serializers.UUIDField(label=("uuid"), required=True, error_messages={
                                  "invalid": "uuid_require", "required": "uuid_require", "blank": "blank_uuid"})

    profile_picture = serializers.ImageField(
        label=("Profile Picture"), required=True, error_messages={
            "invalid": "invalid_profile", "required": "profile_required", "blank": "blank_profile"})

    class Meta:
        model = User
        fields = ['user_uuid', 'profile_picture']

    def validate(self, validated_data):
        user_uuid = validated_data.get('user_uuid')
        try:
            user = User.objects.get(user_uuid=user_uuid)
            profile_picture = validated_data.get('profile_picture')
            if (profile_picture is not None):
                check_validate_image_extension(profile_picture.name)
                if profile_picture.size > MAX_FILE_SIZE:
                    raise serializers.ValidationError("invalid_image_size")
                user.profile_picture = profile_picture
            else:
                raise serializers.ValidationError("profile_error")
            user.save()
        except User.DoesNotExist:
            raise serializers.ValidationError("user_not_exist")
        return validated_data
</code>```

This is my serializer which will handle data from request body from a view

My question is that I'm writing test cases
For this endpoint
I want to test it in a test file
So what I have to do is make
Post request using below code.

```<code>response = self.client.post(url='api/endpoint', data = {'profile_picture':'', 'user_uuid':'some valid uuid'}
</code>```

My question is what should I pass in profile_picture key. So it will be a valid file. I mean i want to upload image from a path that is  app/tests/test.jpg

According to serializer what should i pass in. Both key's value's

If pass file with open('test.jpg','rb') throwing me error

Body:
class UpdateProfilePictureSerializer(serializers.ModelSerializer):
    user_uuid = serializers.UUIDField(label=("uuid"), required=True, error_messages={
                                  "invalid": "uuid_require", "required": "uuid_require", "blank": "blank_uuid"})

    profile_picture = serializers.ImageField(
        label=("Profile Picture"), required=True, error_messages={
            "invalid": "invalid_profile", "required": "profile_required", "blank": "blank_profile"})

    class Meta:
        model = User
        fields = ['user_uuid', 'profile_picture']

    def validate(self, validated_data):
        user_uuid = validated_data.get('user_uuid')
        try:
            user = User.objects.get(user_uuid=user_uuid)
            profile_picture = validated_data.get('profile_picture')
            if (profile_picture is not None):
                check_validate_image_extension(profile_picture.name)
                if profile_picture.size > MAX_FILE_SIZE:
                    raise serializers.ValidationError("invalid_image_size")
                user.profile_picture = profile_picture
            else:
                raise serializers.ValidationError("profile_error")
            user.save()
        except User.DoesNotExist:
            raise serializers.ValidationError("user_not_exist")
        return validated_data

This is my serializer which will handle data from request body from a view

My question is that I'm writing test cases
For this endpoint
I want to test it in a test file
So what I have to do is make
Post request using below code.

response = self.client.post(url='api/endpoint', data = {'profile_picture':'', 'user_uuid':'some valid uuid'}

My question is what should I pass in profile_picture key. So it will be a valid file. I mean i want to upload image from a path that is  app/tests/test.jpg

According to serializer what should i pass in. Both key's value's

If pass file with open('test.jpg','rb') throwing me error


问:
AWS Elastic Beanstalk https not working with hostinger domain
I have deployed my .NET Core Web API application to AWS Elastic Beanstalk , then I purchased a domain from hostinger to get a free SSL certification from Amazon ACM .
After I validated the ownership of the domain by DNS , the SSL certification was issued by ACM , after that I headed to my environment , and edited in configuration section Load Balancers .
I added a Listener with Port 443 and HTTPS protocol , then chose the certificate and the SSL policy TLS-1-2-2017...
then saved the changes .
The configuration was successfully carried , but when I access my Elastic Beanstalk url with https it gives certificate not valid like that in the picture below :
enter image description here

can someone please guide , I have been stuck for 2 days and didn't find a solution .


问:
Files have executable permission by default
I am using Linux and out of nowhere files have 755 permission by default. I create a file with touch and it's permission is 755. However I would expect 644 by default.

```<code>root@example:/app/src# touch foobar
root@example:/app/src# ls -ld foobar
-rwxr-xr-x 1 root root 0 Jan 10 14:41 foobar
</code>```

How can I figure out, why the files have execute permissions? Are there any settings to touch?

Umask is 0022, however that should not affect the execution bit.

Body:
I am using Linux and out of nowhere files have 755 permission by default. I create a file with touch and it's permission is 755. However I would expect 644 by default.

root@example:/app/src# touch foobar
root@example:/app/src# ls -ld foobar
-rwxr-xr-x 1 root root 0 Jan 10 14:41 foobar

How can I figure out, why the files have execute permissions? Are there any settings to touch?

Umask is 0022, however that should not affect the execution bit.


问:
Flyway Community edition filtering out resource Java file - why?
I'm using the Community version of Flyway.  What Flyway is doing:

```<code>...
DEBUG: Found resource: myfolder/V1.2__description1.java
...
DEBUG: Filtering out resource: myfolder/V1.2__description1.java (filename: V1.2__description1.java)
...
</code>```

My "locations" folder is correct:

```<code>flyway.locations=classpath:myfolder
</code>```

I've even tried setting jarDirs setting (it did nothing to help):

```<code>flyway.jarDirs=myfolder
</code>```

Why can't Flyway print out "why" a file/resource is being filtered out?

Do I also have to compile the Java file into a class file? The Flyway documentation didn't say to do that.

Body:
I'm using the Community version of Flyway.  What Flyway is doing:

...
DEBUG: Found resource: myfolder/V1.2__description1.java
...
DEBUG: Filtering out resource: myfolder/V1.2__description1.java (filename: V1.2__description1.java)
...

My "locations" folder is correct:

flyway.locations=classpath:myfolder

I've even tried setting jarDirs setting (it did nothing to help):

flyway.jarDirs=myfolder

Why can't Flyway print out "why" a file/resource is being filtered out?

Do I also have to compile the Java file into a class file? The Flyway documentation didn't say to do that.


问:
How do I disable the default in-app banner in safari
The site uses smartbanner.js to display a banner to go to the app if the site is open on the phone. But ios has a standard banner, which by default is triggered if universal link via apple-app-site-association are used, even without connecting <meta name="apple-itunes-app"... and it turns out that on ios both banners are shown. How can this be avoided?

There was a similar question here How can I disable the "open in app" banner on ios safari for pages that support universal links?, but smartbanner.js was not used there and there was no problem displaying two banners at once and the solution does not fit


问:
SSIS ETL Population began hanging and now takes twice as long to complete
Can Someone explain what these codes are and how they might explain why my ETL Duration times have doubled in the last
few weeks?

```<code>select collationname(0x0904D00034)
sys.sp_describe_first_result_set;1
</code>```

Same for these messages, but they are from the logs

```<code>The Service Broker endpoint is in disabled or stopped state

SQL Server has encountered 1 occurrence(s) of I/O requests taking longer than 15 seconds to complete on file [<Data File Name.ndf> in database id 18.  The OS file handle is 0x0000000000002380.  The offset of the latest long I/O is: 0x0000083de64000.  The duration of the long I/O is: 29818 ms.

</code>```

I have researched each, but I cant find any sensible connection between these and longer data population times

Body:
Can Someone explain what these codes are and how they might explain why my ETL Duration times have doubled in the last
few weeks?

select collationname(0x0904D00034)
sys.sp_describe_first_result_set;1

Same for these messages, but they are from the logs

The Service Broker endpoint is in disabled or stopped state

SQL Server has encountered 1 occurrence(s) of I/O requests taking longer than 15 seconds to complete on file [<Data File Name.ndf> in database id 18.  The OS file handle is 0x0000000000002380.  The offset of the latest long I/O is: 0x0000083de64000.  The duration of the long I/O is: 29818 ms.

I have researched each, but I cant find any sensible connection between these and longer data population times


问:
How do I find out the samplingRate, cutoff, and width for scipy.signal.lfilter?
For context, I am trying to implement the discounted cumulative sum of rewards using MathNet.Filtering.IIR.IIRCoefficients.LowPass which takes in the samplingRate, cutoff, and width. See: https://filtering.mathdotnet.com/api/MathNet.Filtering.IIR/IirCoefficients.htm

double samplingRate
Samples per unit.

double cutoff
Cutoff frequency in samples per unit.

double width
bandwidth in samples per unit.

How can I figure out the samplingRate, cutoff, and width from the below code that implements the discounted cumulative sum of rewards using Python scipy.signal.lfilter?

def discount_lfilter(rewards, discount):
  return lfilter(b=[1], a=[1, -discount], x=rewards[::-1])[::-1]```

Thanks in advance!

Body:
For context, I am trying to implement the discounted cumulative sum of rewards using MathNet.Filtering.IIR.IIRCoefficients.LowPass which takes in the samplingRate, cutoff, and width. See: https://filtering.mathdotnet.com/api/MathNet.Filtering.IIR/IirCoefficients.htm

double samplingRate
Samples per unit.

double cutoff
Cutoff frequency in samples per unit.

double width
bandwidth in samples per unit.

How can I figure out the samplingRate, cutoff, and width from the below code that implements the discounted cumulative sum of rewards using Python scipy.signal.lfilter?

def discount_lfilter(rewards, discount):
  return lfilter(b=[1], a=[1, -discount], x=rewards[::-1])[::-1]

Thanks in advance!


问:
symfony apiplatform different result between itemOperation and collectionOperations
I am looking to get an array when retrieving a onetomany junction for itemOperation. It works for collectionOperation but not ItemOperation.

GET /api/helper

```<code>        "helperDUpdate": null,
        "helperSuivi": [
            {
                "@type": "HelperSuivi",
                "@id": "_:18359",
                "savCSuiviMessage": "My info 4",
                "savDSuiviCreate": "2023-01-09",
                "savCSuiviCreePar": "user2"
            },
            {
                "@type": "HelperSuivi",
                "@id": "_:17724",
                "savCSuiviMessage": "My info",
                "savDSuiviCreate": "2023-01-09",
                "savCSuiviCreePar": "user1"
            }
        ],
</code>```

helperSuivi it's an array, ok for me.

and result for itemoperation :
get /api/helper/24

```<code>"helperDUpdate": null,
"helperSuivi": {
    "@context": "\/api\/contexts\/Sav",
    "@id": "\/api\/sav",
    "@type": "hydra:Collection",
    "hydra:member": [
        {
            "@type": "HelperSuivi",
            "@id": "_:11887",
            "savCSuiviMessage": "My info 4",
            "savDSuiviCreate": "2023-01-09",
            "savCSuiviCreePar": "user2"
        },
        {
            "@type": "HelperSuivi",
            "@id": "_:12028",
            "savCSuiviMessage": "My info",
            "savDSuiviCreate": "2023-01-09",
            "savCSuiviCreePar": "user2"
        }
    ],
    "hydra:totalItems": 2,
    "hydra:search": {
        "@type": "hydra:IriTemplate",
</code>```

It's a collection object not array...

why is it different?

Thank !
Guillaume

Body:
I am looking to get an array when retrieving a onetomany junction for itemOperation. It works for collectionOperation but not ItemOperation.

GET /api/helper

        "helperDUpdate": null,
        "helperSuivi": [
            {
                "@type": "HelperSuivi",
                "@id": "_:18359",
                "savCSuiviMessage": "My info 4",
                "savDSuiviCreate": "2023-01-09",
                "savCSuiviCreePar": "user2"
            },
            {
                "@type": "HelperSuivi",
                "@id": "_:17724",
                "savCSuiviMessage": "My info",
                "savDSuiviCreate": "2023-01-09",
                "savCSuiviCreePar": "user1"
            }
        ],

helperSuivi it's an array, ok for me.

and result for itemoperation :
get /api/helper/24

"helperDUpdate": null,
"helperSuivi": {
    "@context": "\/api\/contexts\/Sav",
    "@id": "\/api\/sav",
    "@type": "hydra:Collection",
    "hydra:member": [
        {
            "@type": "HelperSuivi",
            "@id": "_:11887",
            "savCSuiviMessage": "My info 4",
            "savDSuiviCreate": "2023-01-09",
            "savCSuiviCreePar": "user2"
        },
        {
            "@type": "HelperSuivi",
            "@id": "_:12028",
            "savCSuiviMessage": "My info",
            "savDSuiviCreate": "2023-01-09",
            "savCSuiviCreePar": "user2"
        }
    ],
    "hydra:totalItems": 2,
    "hydra:search": {
        "@type": "hydra:IriTemplate",

It's a collection object not array...

why is it different?

Thank !
Guillaume


问:
any improvement in following linqtosql query where i shouldn't need select if possible
following is my query

```<code> return await (from ofr in _context.table1
                          join aca in _context.table2
                          on new { a = ofr.f1, b = ofr.f2}
                         equals new { a = (int?)aca.f1, b = aca.f2}
                          where lstStatusesTocheck.Contains(ofr.status)
                          select new { ofr.id }
                          ).CountAsync();
</code>```

can i avoid select new { ofr.id } and directly get the count somehow

Body:
following is my query

 return await (from ofr in _context.table1
                          join aca in _context.table2
                          on new { a = ofr.f1, b = ofr.f2}
                         equals new { a = (int?)aca.f1, b = aca.f2}
                          where lstStatusesTocheck.Contains(ofr.status)
                          select new { ofr.id }
                          ).CountAsync();

can i avoid select new { ofr.id } and directly get the count somehow


问:
Cannot access autospawn lock Debian
I followed a tutorial that helped me setup a Proxmox/Truenas/Docker server. It has you create a share drive on the Truenas VM and then automount it to the Docker VM. I then tried to install a Docker App for Obsidian and had this error:

E: [autospawn] core-util.c: Failed to symlink /config/.config/pulse/fdcd261a83bb46b7ae984385e3448e98-runtime to /tmp/pulse-FwqVeKeiSoJO: Operation not supported
W: [autospawn] lock-autospawn.c: Cannot access autospawn lock.
E: [pulseaudio] main.c: Failed to acquire autospawn lock

On doing further research, I've found that it's probably caused by the automount system I'm using. I'm using /etc/fstab. I don't have access to the line of code that I used at this moment, but when I do I will update this or put it in a comment.

Does anyone have any ideas what I need to do in order to get it to work?

I've tried a couple solutions, but most of them were before I found out about the issue with the mounting. I have not been able to find any solutions or similar problems so I haven't been able to try much.

Title: Cannot access autospawn lock Debian


问:
how images rendering in react slider
i am try to show image slider in react js but the images not rendering in my screen.
images store in publice folder
i am not seen any error console

code:
Backgroundslider page
may be the problem is inthis code area,but i try a lot to discover

```<code>import { useState } from "react";
import "./Backgroundslider.css";
import ImagesData from "./Imagesliderdata";

const Backgroundslider = () => {
  const [currentState, setCurrentState] = useState(0);
  const bgImageStyle = {
    backgroundImage: ` url (${ImagesData[currentState].url})`,
    backgroundPosition: "center",
    backgroundSize: "cover",
    height: "100%",
  };
  return (
    <div className="container">
      <div style={bgImageStyle}></div>
    </div>
  );
};
export default Backgroundslider;

</code>```

home page:

```<code>1. import Backgroundslider from "./components/Backgroundslider";
const Home = () => {
  return (
    <div className="home">
      <div className="image">
        <Backgroundslider />
      </div>
    </div>
  );
};
export default Home;

</code>```

data part:

```<code>  {
    url: "city1.jpg",
    title: "city image",
    body: "visit new ",
  },
  {
    url: "city2.jpg",
    title: "city image",
    body: "visit new ",
  },
  {
    url: "city2.jpg",
    title: "city image",
    body: "visit new ",

];
export default Imagesliderdata;

i want the first image rander in screen(image1.jpg)
</code>```

Title: how images rendering in react slider

Body:
i am try to show image slider in react js but the images not rendering in my screen.
images store in publice folder
i am not seen any error console

code:
Backgroundslider page
may be the problem is inthis code area,but i try a lot to discover

import { useState } from "react";
import "./Backgroundslider.css";
import ImagesData from "./Imagesliderdata";

const Backgroundslider = () => {
  const [currentState, setCurrentState] = useState(0);
  const bgImageStyle = {
    backgroundImage: ` url (${ImagesData[currentState].url})`,
    backgroundPosition: "center",
    backgroundSize: "cover",
    height: "100%",
  };
  return (

  );
};
export default Backgroundslider;

home page:

1. import Backgroundslider from "./components/Backgroundslider";
const Home = () => {
  return (

        <Backgroundslider />

  );
};
export default Home;

data part:

  {
    url: "city1.jpg",
    title: "city image",
    body: "visit new ",
  },
  {
    url: "city2.jpg",
    title: "city image",
    body: "visit new ",
  },
  {
    url: "city2.jpg",
    title: "city image",
    body: "visit new ",

];
export default Imagesliderdata;

i want the first image rander in screen(image1.jpg)


问:
Use global package.json in pnpm workspace for Linter/Prettier
I configured my project into pnpm workspace with :

```<code>|-node_modules
|-package.json (A)
|-eslintrc
|-app1
|   |-node_modules
|   |-package.json (B)
|   |-app.ts
|-app2
|   |-node_modules
|   |-package.json (C)
|   |-app.ts
|-packages
|   |-lib1
|   |   |-node_modules
|   |   |-package.json (D)
|   |   |-index.ts
</code>```

In the global package.json (A), i have all the eslint, prettier and plugins dependencies.

When i use husky+lint-stage, i've got an error because eslint is run in subfolder and package.json (B)(C)(D) don't have eslint, prettier and plugins dependencies installed.

I saw that i can create a local package with global conf and install it on each project.
But if i do that, my problem is IntelliJ. IntelliJ prettier config want only one prettier node_modules binary.
But i am in a monorepo with 3 projects.

How can i use a global eslint conf and force eslint to use the global package.json as reference ?
OR
How can i configure the prettier conf in IntelliJ to use a global prettier ?

Best regards,

Body:
I configured my project into pnpm workspace with :

|-node_modules
|-package.json (A)
|-eslintrc
|-app1
|   |-node_modules
|   |-package.json (B)
|   |-app.ts
|-app2
|   |-node_modules
|   |-package.json (C)
|   |-app.ts
|-packages
|   |-lib1
|   |   |-node_modules
|   |   |-package.json (D)
|   |   |-index.ts

In the global package.json (A), i have all the eslint, prettier and plugins dependencies.

When i use husky+lint-stage, i've got an error because eslint is run in subfolder and package.json (B)(C)(D) don't have eslint, prettier and plugins dependencies installed.

I saw that i can create a local package with global conf and install it on each project.
But if i do that, my problem is IntelliJ. IntelliJ prettier config want only one prettier node_modules binary.
But i am in a monorepo with 3 projects.

How can i use a global eslint conf and force eslint to use the global package.json as reference ?
OR
How can i configure the prettier conf in IntelliJ to use a global prettier ?

Best regards,


问:
Rendring every word as a span in quill
I'm using quill for a project and I saw that everyone line in quill is a p tag and all the content of that line is inside the p tag. I want every word to be wrapped in a span tag with a data-time attribute and classes/styles like this

    like
    this

```

how can I do that? if there is no built-in way then how can I change the source code to do that myself?

thanks

Title: Rendring every word as a span in quill

Body:
I'm using quill for a project and I saw that everyone line in quill is a p tag and all the content of that line is inside the p tag. I want every word to be wrapped in a span tag with a data-time attribute and classes/styles like this

    like
    this

how can I do that? if there is no built-in way then how can I change the source code to do that myself?

thanks


问:
Conduct a mediation model, mediator Sexual Disgust,x-Gender, Y- Political views,incorporating Age. Use the 'mediation' package
I am trying to out age with sexual disgust and it is not working.

```<code>#Mediate package
library(mediation)
install.packages("gvlma")
library(gvlma)
fitM <- lm((Sexual_Disgust)+(Age) ~ Gender,     data=Tyburdata) #IV on M; Hours since dawn predicting coffee consumption
fitY <- lm(PolOri_Social ~ Gender + Age + Sexual_Disgust, data=Tyburdata) #IV and M on DV; Hours since dawn and coffee predicting wakefulness
gvlma(fitM) #data is positively skewed; could log transform (see Chap. 10 on assumptions)

fitMed <- mediate(fitM, fitY, treat="Gender", mediator="Sexual_Disgust",mediator="Age")
summary(fitMed)

#Bootstrap
fitMedBoot <- mediate(fitM, fitY, boot=TRUE, sims=999, treat="X", mediator="M")
summary(fitMedBoot)
</code>```

I keep on getting this error when about the line fitmedd<-mediate

```<code>Error in mediate(fitM, fitY, treat = "Gender", mediator = "Sexual_Disgust",  :
  formal argument "mediator" matched by multiple actual arguments
</code>```

Body:
I am trying to out age with sexual disgust and it is not working.

#Mediate package
library(mediation)
install.packages("gvlma")
library(gvlma)
fitM <- lm((Sexual_Disgust)+(Age) ~ Gender,     data=Tyburdata) #IV on M; Hours since dawn predicting coffee consumption
fitY <- lm(PolOri_Social ~ Gender + Age + Sexual_Disgust, data=Tyburdata) #IV and M on DV; Hours since dawn and coffee predicting wakefulness
gvlma(fitM) #data is positively skewed; could log transform (see Chap. 10 on assumptions)

fitMed <- mediate(fitM, fitY, treat="Gender", mediator="Sexual_Disgust",mediator="Age")
summary(fitMed)

#Bootstrap
fitMedBoot <- mediate(fitM, fitY, boot=TRUE, sims=999, treat="X", mediator="M")
summary(fitMedBoot)

I keep on getting this error when about the line fitmedd<-mediate

Error in mediate(fitM, fitY, treat = "Gender", mediator = "Sexual_Disgust",  :
  formal argument "mediator" matched by multiple actual arguments


问:
How to resize the axes of my scatterplot?
I would that dimensions of my axis=1 (vertical) is between (0 a 100 000).
I don't want to see outliers in my scartterplot.

```<code>pl = sns.scatterplot(data = data,x=data["spent"], y=data["Income"],hue=data["Clusters"], palette= pal)
pl.set_title("Cluster's Profile Based On Income And Spending")
plt.legend()
plt.rcParams["figure.figsize"] = (10, 10)
plt.show()
</code>```

result is
enter image description here

Body:
I would that dimensions of my axis=1 (vertical) is between (0 a 100 000).
I don't want to see outliers in my scartterplot.

pl = sns.scatterplot(data = data,x=data["spent"], y=data["Income"],hue=data["Clusters"], palette= pal)
pl.set_title("Cluster's Profile Based On Income And Spending")
plt.legend()
plt.rcParams["figure.figsize"] = (10, 10)
plt.show()

result is
enter image description here


问:
conditional queries do not work on a single select form filterbar
Sorry for my approximately english,

I have created a filter bar to list my courses by selected category. Here is the form

```<code><form id="formFilter" method="get">
    <select name="thematique" id="thematique">
       <? if (isset($_GET['thematique'])) : ?>
            <option value="all">Toutes les formations</option>
            <? foreach ($thematiques as $term) : ?>
               <? if ($_GET['thematique'] === $term->slug) : ?>
                  <option value="<? echo $term->slug ?>" selected><? echo $term->name ?></option>
               <? else : ?>
                   <option name="<? echo $term->slug ?>" value="<? echo $term->slug ?>"><? echo $term->name ?></option>
               <? endif ?>
            <? endforeach; ?>
        <? else : ?>
            <option value="all" selected>Toutes les formations</option>
            <? foreach ($thematiques as $term) : ?>
              <option name="<? echo $term->slug ?>" value="<? echo $term->slug ?>"><? echo $term->name ?></option>
            <? endforeach; ?>
        <? endif; ?>
   </select>
   <input type="submit" value="Filtrer">
</form>
</code>```

When I click on a category, everything works and I only have the courses of the selected category.  But when I click on All courses I don't see my page from the beginning where there are all the courses
Here is the link if you want test http://cedille-formation.ftalps.fr/formations/

I tried this for now but it doesn't work

```<code>if (isset($_GET['thematique'])) {
    for ($i = 0; $i < sizeof($thematiques); $i++) :
        if ($_GET['thematique'] !== $thematiques[$i]->slug) :
            $my_posts = new WP_Query(array('post_type' => 'formations'));
        else :
            $my_posts = new WP_Query(array(
                'post_type' => 'formations',
                'thematique' => $_GET['thematique']
            ));
        endif;
    endfor;
} else {
    $my_posts = new WP_Query(array('post_type' => 'formations'));
}
</code>```

I check if my variable $_GET['thematique'] isset, if it exists I browse my category array and I check if $_GET is strictly equal to the slug of my category. If it is not part of my category array then my query is a general query that retrieves all my formations otherwise I launch a query with the name of the chosen category.

I enter in my condition if it is not part of my table but I have an error as nothing was found while it is the same request when we arrive on the page all the formations.

I also tried to check if $_GET['thematique'] isset && $_GET['thematique'] !== "all" but I have the same result.

So I want to do is that when the filter bar has already been used on a category (displays only the courses of this category) when I sort on All courses I want to display all courses again.

Thanks for your help

Body:
Sorry for my approximately english,

I have created a filter bar to list my courses by selected category. Here is the form

<form id="formFilter" method="get">
    <select name="thematique" id="thematique">
       <? if (isset($_GET['thematique'])) : ?>
            <option value="all">Toutes les formations</option>
            <? foreach ($thematiques as $term) : ?>
               <? if ($_GET['thematique'] === $term->slug) : ?>
                  <option value="<? echo $term->slug ?>" selected><? echo $term->name ?></option>
               <? else : ?>
                   <option name="<? echo $term->slug ?>" value="<? echo $term->slug ?>"><? echo $term->name ?></option>
               <? endif ?>
            <? endforeach; ?>
        <? else : ?>
            <option value="all" selected>Toutes les formations</option>
            <? foreach ($thematiques as $term) : ?>
              <option name="<? echo $term->slug ?>" value="<? echo $term->slug ?>"><? echo $term->name ?></option>
            <? endforeach; ?>
        <? endif; ?>
   </select>
   <input type="submit" value="Filtrer">
</form>

When I click on a category, everything works and I only have the courses of the selected category.  But when I click on All courses I don't see my page from the beginning where there are all the courses
Here is the link if you want test http://cedille-formation.ftalps.fr/formations/

I tried this for now but it doesn't work

if (isset($_GET['thematique'])) {
    for ($i = 0; $i < sizeof($thematiques); $i++) :
        if ($_GET['thematique'] !== $thematiques[$i]->slug) :
            $my_posts = new WP_Query(array('post_type' => 'formations'));
        else :
            $my_posts = new WP_Query(array(
                'post_type' => 'formations',
                'thematique' => $_GET['thematique']
            ));
        endif;
    endfor;
} else {
    $my_posts = new WP_Query(array('post_type' => 'formations'));
}

I check if my variable $_GET['thematique'] isset, if it exists I browse my category array and I check if $_GET is strictly equal to the slug of my category. If it is not part of my category array then my query is a general query that retrieves all my formations otherwise I launch a query with the name of the chosen category.

I enter in my condition if it is not part of my table but I have an error as nothing was found while it is the same request when we arrive on the page all the formations.

I also tried to check if $_GET['thematique'] isset && $_GET['thematique'] !== "all" but I have the same result.

So I want to do is that when the filter bar has already been used on a category (displays only the courses of this category) when I sort on All courses I want to display all courses again.

Thanks for your help


问:
Apache Velocity template turkish characters problem
I'm trying to create an vm template to convert to pdf. But characters like "İ" , "ş" , "ı" etc. is missing from the pdf. Like here :
This text must've been İmza Sahibi:
$sincomModelData.
imza_sahibi
bu belgeyle aşağıda belirtilen
aracın
But the letters are missing in the pdf.

I encode the vm template like this : Template t = ve.getTemplate("templates/helloworld.vm", "UTF-8");
but it only works for some of the characters like "ö" , "ü". How could I encode all turkish letters properly to work with velocity template?
Thanks for the help.

Trying to encode turkish characters in velocity template.
Here is the code of the conversion of html -> xhtml -> pdf

```<code>VelocityEngine ve = new VelocityEngine();
    System.out.println(sincomModel);
    /* next, get the Template */
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class",
            ClasspathResourceLoader.class.getName());
    ve.init();
    System.out.println(vehicleDto);
    Template t = ve.getTemplate("templates/helloworld.vm", "UTF-8");
    VelocityContext context = new VelocityContext();
    context.put("sincomModelData", sincomModel);
    context.put("tanitim_numFirst", tanitim_numFirst);
    context.put("tanitim_numSec", tanitim_numSec);
    context.put("vehicleDate",vehicleDto.getDate());
    context.put("vehicleRenk",vehicleDto.getRenk());
    context.put("yakitIc",yakitIc);
    context.put("yakitDis",yakitDis);
    StringWriter writer = new StringWriter();
    t.merge(context, writer);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    baos = xhtmlToPdf(writer.toString());

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(baos.toByteArray().length);

    return new HttpEntity<byte[]>(baos.toByteArray(), header);

}
private static String htmlToXhtml(String html) {
    Document document = Jsoup.parse(html);
    document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
    return document.html();
}
private ByteArrayOutputStream xhtmlToPdf(String xhtml) throws IOException {
    String xhtml_son = htmlToXhtml(xhtml);
    ITextRenderer iTextRenderer = new ITextRenderer();
    iTextRenderer.setDocumentFromString(xhtml_son);
    iTextRenderer.layout();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    iTextRenderer.createPDF(baos);
    return baos;
}
</code>```

Body:
I'm trying to create an vm template to convert to pdf. But characters like "İ" , "ş" , "ı" etc. is missing from the pdf. Like here :
This text must've been İmza Sahibi:
$sincomModelData.
imza_sahibi
bu belgeyle aşağıda belirtilen
aracın
But the letters are missing in the pdf.

I encode the vm template like this : Template t = ve.getTemplate("templates/helloworld.vm", "UTF-8");
but it only works for some of the characters like "ö" , "ü". How could I encode all turkish letters properly to work with velocity template?
Thanks for the help.

Trying to encode turkish characters in velocity template.
Here is the code of the conversion of html -> xhtml -> pdf

VelocityEngine ve = new VelocityEngine();
    System.out.println(sincomModel);
    /* next, get the Template */
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class",
            ClasspathResourceLoader.class.getName());
    ve.init();
    System.out.println(vehicleDto);
    Template t = ve.getTemplate("templates/helloworld.vm", "UTF-8");
    VelocityContext context = new VelocityContext();
    context.put("sincomModelData", sincomModel);
    context.put("tanitim_numFirst", tanitim_numFirst);
    context.put("tanitim_numSec", tanitim_numSec);
    context.put("vehicleDate",vehicleDto.getDate());
    context.put("vehicleRenk",vehicleDto.getRenk());
    context.put("yakitIc",yakitIc);
    context.put("yakitDis",yakitDis);
    StringWriter writer = new StringWriter();
    t.merge(context, writer);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    baos = xhtmlToPdf(writer.toString());

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(baos.toByteArray().length);

    return new HttpEntity<byte[]>(baos.toByteArray(), header);

}
private static String htmlToXhtml(String html) {
    Document document = Jsoup.parse(html);
    document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
    return document.html();
}
private ByteArrayOutputStream xhtmlToPdf(String xhtml) throws IOException {
    String xhtml_son = htmlToXhtml(xhtml);
    ITextRenderer iTextRenderer = new ITextRenderer();
    iTextRenderer.setDocumentFromString(xhtml_son);
    iTextRenderer.layout();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    iTextRenderer.createPDF(baos);
    return baos;
}


问:
Iterate through array of ids in Observable and add data from each id query to the same object
I have a "Group" document which contains an array of "Member" IDs. The data for each "Member" is stored in another "users" collection. For every ID in the array I want to fetch the user data and add it to the original group object. The desired output should look like:

```<code>{
 name: "Group 1",
 members: ["id1", "id2", "id3"],
 membersData: [
  { id: "id1", name: "Max", img: "..." },
  { id: "id2", name: "Peter", img: "..." },
  { id: "id3", name: "John", img: "..." },
 ]
}
</code>```

this is what my function looks like right now:

```<code>this.groupService
      .getById(this.user.currentGroup)
      .pipe(
        mergeMap((group: IGroup) => {
          return forkJoin(
            group.members.map((member: any) =>
              this.userService.getById(member).pipe(
                take(1),
                map((userData: PublicUser) => ({ ...group, userData })),
              ),
            ),
          );
        }),
      )
      .subscribe((data) => console.log(data));
</code>```

and the current output looks like this:

```<code>[{
 name: "Group 1",
 members: ["id1", "id2", "id3"],
 membersData: { id: "id1", name: "Max", img: "..." },
},
{
 name: "Group 1",
 members: ["id1", "id2", "id3"],
 membersData: { id: "id2", name: "Peter", img: "..." },
},
{
 name: "Group 1",
 members: ["id1", "id2", "id3"],
 membersData: { id: "id3", name: "John", img: "..." },
}]
</code>```

the problem is that when I use the spread syntax to combine the group and user data, I get a new object for every user that gets fetched instead of one group object where every user data is story in the membersData array. I know that I can't use the spread syntax here but I just can't figure out how to adjust the function to get the desired behavior. Every advice is greatly appreciated.

Body:
I have a "Group" document which contains an array of "Member" IDs. The data for each "Member" is stored in another "users" collection. For every ID in the array I want to fetch the user data and add it to the original group object. The desired output should look like:

{
 name: "Group 1",
 members: ["id1", "id2", "id3"],
 membersData: [
  { id: "id1", name: "Max", img: "..." },
  { id: "id2", name: "Peter", img: "..." },
  { id: "id3", name: "John", img: "..." },
 ]
}

this is what my function looks like right now:

this.groupService
      .getById(this.user.currentGroup)
      .pipe(
        mergeMap((group: IGroup) => {
          return forkJoin(
            group.members.map((member: any) =>
              this.userService.getById(member).pipe(
                take(1),
                map((userData: PublicUser) => ({ ...group, userData })),
              ),
            ),
          );
        }),
      )
      .subscribe((data) => console.log(data));

and the current output looks like this:

[{
 name: "Group 1",
 members: ["id1", "id2", "id3"],
 membersData: { id: "id1", name: "Max", img: "..." },
},
{
 name: "Group 1",
 members: ["id1", "id2", "id3"],
 membersData: { id: "id2", name: "Peter", img: "..." },
},
{
 name: "Group 1",
 members: ["id1", "id2", "id3"],
 membersData: { id: "id3", name: "John", img: "..." },
}]

the problem is that when I use the spread syntax to combine the group and user data, I get a new object for every user that gets fetched instead of one group object where every user data is story in the membersData array. I know that I can't use the spread syntax here but I just can't figure out how to adjust the function to get the desired behavior. Every advice is greatly appreciated.


问:
Class is using Angular features but is not decorated. Please add an explicit Angular decorator in Angular 15
When I am writing this export class MyTelInput implements ControlValueAccessor, MatFormFieldControl<MyTel>, OnDestroy {  } in Angular 15 version then it gives error that is:

Class is using Angular features but is not decorated. Please add an explicit Angular decorator

I tried to resolve it but any type of solution is not working in 15th version. What can I do?

I tried Stack Overflow solutions and so many other solutions but this doesn't work in new Angular feature. I tried to add so many libraries and importing so many files but I fail to resolve this error only, I copy this code from Angular material and doing everything in proper manner.


问:
Prisma throws error while creating nested input
I am using prisma with NestJS and Typscript. I'm having a problem that I can't understand why. Could anyone help me out?

I have a model Cliente that references a Pessoa model:

```<code>model Pessoa {
  id             String     @id @default(uuid())
  cpfCnpj        String     @unique
  nome           String
  email          String     @unique
  instagram      String?    @unique
  sexo           Sexo?
  dataNascimento DateTime?
  dataCadastro   DateTime   @default(now())
  dataAlteracao  DateTime   @updatedAt
  Contato        Contato[]
  Endereco       Endereco[]
  Usuario        Usuario?
  Empresa        Empresa?
  Cliente        Cliente[]
}
model Cliente {
  id        String   @id @default(uuid())
  marketing Boolean  @default(true)
  Pessoa    Pessoa   @relation(fields: [pessoaId], references: [id], onDelete: Cascade)
  pessoaId  String
  Pedido    Pedido[]
}
</code>```

I am trying to create a Cliente, but prisma is throwing this error:

```<code>  77 await this.prisma.$transaction([
  78   ...clients.map((row) => {
  79     if (!row.clienteUuid)
→ 80       return this.prisma.cliente.create({
             data: {
               marketing: true,
               Pessoa: {
               ~~~~~~
                 create: {
                   nome: 'Teste',
                   cpfCnpj: '12345678900',
                   email: 'teste@teste.com',
                   sexo: 'FEMININO',
                   dataNascimento: '1993-11-03',
                   dataCadastro: '2023-01-06T13:19:14',
                   dataAlteracao: '2023-01-10T05:49:01',
                 }
               },
           +   pessoaId: String,
           ?   id?: String,
           ?   Pedido?: {
           ?     create?: PedidoCreateWithoutClienteInput | PedidoCreateWithoutClienteInput | PedidoUncheckedCreateWithoutClienteInput | PedidoUncheckedCreateWithoutClienteInput,
           ?     connectOrCreate?: PedidoCreateOrConnectWithoutClienteInput | PedidoCreateOrConnectWithoutClienteInput,
           ?     createMany?: PedidoCreateManyClienteInputEnvelope,
           ?     connect?: PedidoWhereUniqueInput | PedidoWhereUniqueInput
           ?   }
             }
           })
Unknown arg `Pessoa` in data.Pessoa for type ClienteUncheckedCreateInput. Did you mean `pessoaId`?
Argument pessoaId for data.pessoaId is missing.
</code>```

This is the function that calls it:

  async saveClients(data: OpencartSale[]): Promise<void> {
    const clients = await this.getClients(data);

    try {
      await this.prisma.$transaction([
        ...clients.map((row) => {
          if (!row.clienteUuid)
            return this.prisma.cliente.create({
              data: { ...CreateClientImportMapper.map(row) },
            });

          return this.prisma.cliente.update({
            where: { id: row.clienteUuid },
            data: { ...UpdateClientImportMapper.map(row) },
          });
        }),
      ]);
    } catch (error) {
      console.error(error);
    }
  }
```
<p>And here is the mapper function:</p>
<pre class="lang-js prettyprint-override"><code>import { Prisma, Sexo } from '@prisma/client';
import { OpencartSale } from '../entities/opencart.entity';

export class CreateClientImportMapper {
  static map(data: OpencartSale): Prisma.ClienteCreateInput {
    return {
      marketing: true,
      Pessoa: {
        create: {
          nome: data.cliente,
          cpfCnpj:
            data.cpf.replace(/[^0-9]/g, '') || data.cnpj.replace(/[^0-9]/g, ''),
          email: data.cliente_email,
          sexo: data.sexo === '2' ? Sexo.FEMININO : Sexo.MASCULINO,
          dataNascimento: data.data_de_nascimento
            .replace(/\//g, '-')
            .split('-')
            .reverse()
            .join('-'),
          dataCadastro: data.date_added.split(' ').join('T'),
          dataAlteracao: data.date_modified.split(' ').join('T'),
        },
      },
    };
  }
}
</code>```

The type to create a Cliente generated by prisma is here:

  export type ClienteCreateArgs = {
    /**
     * Select specific fields to fetch from the Cliente
     *
    **/
    select?: ClienteSelect | null
    /**
     * Choose, which related nodes to fetch as well.
     *
    **/
    include?: ClienteInclude | null
    /**
     * The data needed to create a Cliente.
     *
    **/
    data: XOR<ClienteCreateInput, ClienteUncheckedCreateInput>
  }

  export type ClienteCreateInput = {
    id?: string
    marketing?: boolean
    Pessoa: PessoaCreateNestedOneWithoutClienteInput
    Pedido?: PedidoCreateNestedManyWithoutClienteInput
  }
```

It seams prisma is acknowledging the create input type as ClienteUncheckedCreateInput but not ClienteCreateInput.

I have lost so many hours trying to figure this out. I have done this same thing in other segments of the app and just now it is throwing error.

My prisma version is: 4.6.1

Body:
I am using prisma with NestJS and Typscript. I'm having a problem that I can't understand why. Could anyone help me out?

I have a model Cliente that references a Pessoa model:

model Pessoa {
  id             String     @id @default(uuid())
  cpfCnpj        String     @unique
  nome           String
  email          String     @unique
  instagram      String?    @unique
  sexo           Sexo?
  dataNascimento DateTime?
  dataCadastro   DateTime   @default(now())
  dataAlteracao  DateTime   @updatedAt
  Contato        Contato[]
  Endereco       Endereco[]
  Usuario        Usuario?
  Empresa        Empresa?
  Cliente        Cliente[]
}
model Cliente {
  id        String   @id @default(uuid())
  marketing Boolean  @default(true)
  Pessoa    Pessoa   @relation(fields: [pessoaId], references: [id], onDelete: Cascade)
  pessoaId  String
  Pedido    Pedido[]
}

I am trying to create a Cliente, but prisma is throwing this error:

  77 await this.prisma.$transaction([
  78   ...clients.map((row) => {
  79     if (!row.clienteUuid)
→ 80       return this.prisma.cliente.create({
             data: {
               marketing: true,
               Pessoa: {
               ~~~~~~
                 create: {
                   nome: 'Teste',
                   cpfCnpj: '12345678900',
                   email: 'teste@teste.com',
                   sexo: 'FEMININO',
                   dataNascimento: '1993-11-03',
                   dataCadastro: '2023-01-06T13:19:14',
                   dataAlteracao: '2023-01-10T05:49:01',
                 }
               },
           +   pessoaId: String,
           ?   id?: String,
           ?   Pedido?: {
           ?     create?: PedidoCreateWithoutClienteInput | PedidoCreateWithoutClienteInput | PedidoUncheckedCreateWithoutClienteInput | PedidoUncheckedCreateWithoutClienteInput,
           ?     connectOrCreate?: PedidoCreateOrConnectWithoutClienteInput | PedidoCreateOrConnectWithoutClienteInput,
           ?     createMany?: PedidoCreateManyClienteInputEnvelope,
           ?     connect?: PedidoWhereUniqueInput | PedidoWhereUniqueInput
           ?   }
             }
           })
Unknown arg `Pessoa` in data.Pessoa for type ClienteUncheckedCreateInput. Did you mean `pessoaId`?
Argument pessoaId for data.pessoaId is missing.

This is the function that calls it:

  async saveClients(data: OpencartSale[]): Promise<void> {
    const clients = await this.getClients(data);

    try {
      await this.prisma.$transaction([
        ...clients.map((row) => {
          if (!row.clienteUuid)
            return this.prisma.cliente.create({
              data: { ...CreateClientImportMapper.map(row) },
            });

          return this.prisma.cliente.update({
            where: { id: row.clienteUuid },
            data: { ...UpdateClientImportMapper.map(row) },
          });
        }),
      ]);
    } catch (error) {
      console.error(error);
    }
  }

And here is the mapper function:

import { Prisma, Sexo } from '@prisma/client';
import { OpencartSale } from '../entities/opencart.entity';

export class CreateClientImportMapper {
  static map(data: OpencartSale): Prisma.ClienteCreateInput {
    return {
      marketing: true,
      Pessoa: {
        create: {
          nome: data.cliente,
          cpfCnpj:
            data.cpf.replace(/[^0-9]/g, '') || data.cnpj.replace(/[^0-9]/g, ''),
          email: data.cliente_email,
          sexo: data.sexo === '2' ? Sexo.FEMININO : Sexo.MASCULINO,
          dataNascimento: data.data_de_nascimento
            .replace(/\//g, '-')
            .split('-')
            .reverse()
            .join('-'),
          dataCadastro: data.date_added.split(' ').join('T'),
          dataAlteracao: data.date_modified.split(' ').join('T'),
        },
      },
    };
  }
}

The type to create a Cliente generated by prisma is here:

  export type ClienteCreateArgs = {
    /**
     * Select specific fields to fetch from the Cliente
     *
    **/
    select?: ClienteSelect | null
    /**
     * Choose, which related nodes to fetch as well.
     *
    **/
    include?: ClienteInclude | null
    /**
     * The data needed to create a Cliente.
     *
    **/
    data: XOR<ClienteCreateInput, ClienteUncheckedCreateInput>
  }

  export type ClienteCreateInput = {
    id?: string
    marketing?: boolean
    Pessoa: PessoaCreateNestedOneWithoutClienteInput
    Pedido?: PedidoCreateNestedManyWithoutClienteInput
  }

It seams prisma is acknowledging the create input type as ClienteUncheckedCreateInput but not ClienteCreateInput.

I have lost so many hours trying to figure this out. I have done this same thing in other segments of the app and just now it is throwing error.

My prisma version is: 4.6.1


问:
Stumped on how mainform - subform1 - subform2 handles what record shows when subform1 becomes the active form
I have a mainform (Cruises) with a subform (DiveSites) which itself has several other subforms (Notes, Samples, Photos)

My user can interact with the Notes subform to add dive notes (New button) and start and end transects (Start and End buttons), among other things.  Transects are just paths followed along the seafloor that have a start lat/lon/depth and an end lat/lon/depth.  The application should maintain a running list of transect numbers for the entire cruise.

I keep the last used transect number in the Cruises table so that whenever the user starts a new transect in that cruise, it will look up the last used transect number and then add 1 to set the new transect number.

The Start button is the only case where I lose my place in the DiveSites form when that form gets the focus again.  It resets back to the first DiveSites record for that form.

I think it must be because in that code, I have to open the Cruises recordset and look up that transect number. Other than that, the code for the other buttons is very similar and doesn't cause the reset to the first record.

I have not used Bookmarks before and am having trouble finding an example of how those work for these nested forms and applying that to my situation.

```<code>
Private Sub StartTransect_Click()
' when a new transect is started, set the XS# to the next available transect number for this operation (saved in the Cruise Information table) and read the putty_log for the latest location and depth
Dim db As Database
Dim puttylog As Recordset
Dim CruiseInfo As Recordset
Dim currcruise As String
Dim templat, templon, tempdepth As String
Dim msg As String
Dim response As Variant

' first set up the environment and open the putty_log recordset to read the submersible current lat/lon/depth
' also open the Cruise Information table as a recordset to read in the lasttransect number
Set db = CurrentDb()
Set puttylog = db.OpenRecordset("putty_log")
Set CruiseInfo = db.OpenRecordset("dbo_tbl_CruiseInformation", dbOpenDynaset)
msg = "You must end the previous transect before starting a new one"

If transectstarted Then
    response = MsgBox(msg, vbOKOnly)
    GoTo ESub

Else
    transectstarted = True
    currcruise = Forms!Frm_tbl_Cruise_Form!CruiseID
    CruiseInfo.FindFirst "CruiseID = '" & currcruise & "'"
    lasttransect = CruiseInfo!lastTransectNum
    TransectNumber = lasttransect + 1

    DoCmd.GoToRecord , , acNewRec
    Me!Transect_Number = TransectNumber
    Me!ExtraNote_ID = Me!DiveNote_ID
    Me!Date_Time_Notes = Now()
    Me!TransectStartStop = "Photo XS- Start: " & Now()
    templat = Str(puttylog![lat_GPRMC])
    templon = Str(puttylog![lon_GPRMC])
    tempdepth = Str(puttylog!Depth)
    Me!Latitude = Format(templat, "0000.0000")
    Me!Longitude = Format(templon, "00000.0000")
    Me!Depth = Format(tempdepth, "0000.0")

    CruiseInfo.Edit
    CruiseInfo!lastTransectNum = TransectNumber
    CruiseInfo.Update
End If

ESub:
' reset the recordset and database to nothing to release it

Set CruiseInfo = Nothing
Set puttylog = Nothing
Set db = Nothing

End Sub

</code>```

Body:
I have a mainform (Cruises) with a subform (DiveSites) which itself has several other subforms (Notes, Samples, Photos)

My user can interact with the Notes subform to add dive notes (New button) and start and end transects (Start and End buttons), among other things.  Transects are just paths followed along the seafloor that have a start lat/lon/depth and an end lat/lon/depth.  The application should maintain a running list of transect numbers for the entire cruise.

I keep the last used transect number in the Cruises table so that whenever the user starts a new transect in that cruise, it will look up the last used transect number and then add 1 to set the new transect number.

The Start button is the only case where I lose my place in the DiveSites form when that form gets the focus again.  It resets back to the first DiveSites record for that form.

I think it must be because in that code, I have to open the Cruises recordset and look up that transect number. Other than that, the code for the other buttons is very similar and doesn't cause the reset to the first record.

I have not used Bookmarks before and am having trouble finding an example of how those work for these nested forms and applying that to my situation.

Private Sub StartTransect_Click()
' when a new transect is started, set the XS# to the next available transect number for this operation (saved in the Cruise Information table) and read the putty_log for the latest location and depth
Dim db As Database
Dim puttylog As Recordset
Dim CruiseInfo As Recordset
Dim currcruise As String
Dim templat, templon, tempdepth As String
Dim msg As String
Dim response As Variant

' first set up the environment and open the putty_log recordset to read the submersible current lat/lon/depth
' also open the Cruise Information table as a recordset to read in the lasttransect number
Set db = CurrentDb()
Set puttylog = db.OpenRecordset("putty_log")
Set CruiseInfo = db.OpenRecordset("dbo_tbl_CruiseInformation", dbOpenDynaset)
msg = "You must end the previous transect before starting a new one"

If transectstarted Then
    response = MsgBox(msg, vbOKOnly)
    GoTo ESub

Else
    transectstarted = True
    currcruise = Forms!Frm_tbl_Cruise_Form!CruiseID
    CruiseInfo.FindFirst "CruiseID = '" & currcruise & "'"
    lasttransect = CruiseInfo!lastTransectNum
    TransectNumber = lasttransect + 1

    DoCmd.GoToRecord , , acNewRec
    Me!Transect_Number = TransectNumber
    Me!ExtraNote_ID = Me!DiveNote_ID
    Me!Date_Time_Notes = Now()
    Me!TransectStartStop = "Photo XS- Start: " & Now()
    templat = Str(puttylog![lat_GPRMC])
    templon = Str(puttylog![lon_GPRMC])
    tempdepth = Str(puttylog!Depth)
    Me!Latitude = Format(templat, "0000.0000")
    Me!Longitude = Format(templon, "00000.0000")
    Me!Depth = Format(tempdepth, "0000.0")

    CruiseInfo.Edit
    CruiseInfo!lastTransectNum = TransectNumber
    CruiseInfo.Update
End If

ESub:
' reset the recordset and database to nothing to release it

Set CruiseInfo = Nothing
Set puttylog = Nothing
Set db = Nothing

End Sub


问:
replacing file after sending form and editing it again
please is there available setting, that after sending form a editing it again is possible to replace attached file by other one? I didnt manage to find it.

Could it possibly be done with assistance of form administrator?

I was testing it and it didnt work. File attached for first time is not possible to replace.
I would need to help someone, who is editing a form I created, to replace it.

Thank you.

Milan


问:
how could I use promise or await in this case?
I am doing LBS application which requires to include this outside map source to get location's address:

and there is my code:

```
<p>how do  I get the return address to the variable showLocation? I know  is async ,I have read some answers about javascript async solution but  how could I use something like await, then ,promise in this case? since I could not modify the outside source.
please let me know what can I do, thanks!</p>
<p>well here is my answer after stack overflow close my question:
var geolocation = new qq.maps.Geolocation("xxxxxxxxxx", "myapp");</p>
```    let getLoc = new Promise((resolve, reject) => {
        geolocation.getLocation(good, bad, options)

        function good(p) {
            console.log(p);
            return resolve(p)

        }
        function bad(p) {
            return reject(p)
        }
        var options = 4000;

    })

    getLoc.then(
        res => {
            console.log(res);
            //correctly print out the address!
        }
    ).catch(
        res => {
            console.log(res);
        }
    )
```

Body:
I am doing LBS application which requires to include this outside map source to get location's address:

and there is my code:

how do  I get the return address to the variable showLocation? I know  is async ,I have read some answers about javascript async solution but  how could I use something like await, then ,promise in this case? since I could not modify the outside source.
please let me know what can I do, thanks!

well here is my answer after stack overflow close my question:
var geolocation = new qq.maps.Geolocation("xxxxxxxxxx", "myapp");

    let getLoc = new Promise((resolve, reject) => {
        geolocation.getLocation(good, bad, options)

        function good(p) {
            console.log(p);
            return resolve(p)

        }
        function bad(p) {
            return reject(p)
        }
        var options = 4000;

    })

    getLoc.then(
        res => {
            console.log(res);
            //correctly print out the address!
        }
    ).catch(
        res => {
            console.log(res);
        }
    )


问:
How to setup Spring Security's Authorization Config for Method Security?
It is Spring Security's recommendation to deny all requests with missing authorization rules by default:

```<code>http
    .authorizeRequests((authorize) -> authorize
        .filterSecurityInterceptorOncePerRequest(true)
        .mvcMatchers("/app/**").hasRole("APP")
        // ...
        .anyRequest().denyAll()
    )
    // ...
</code>```

Now let's apply this to a simple real-world example.

The goal is to define 3 endpoints with different access permissions:

"/": homepage, everyone can access

"/login": only anonymous users can access

"/private": only logged in users with the authority "ROLE_USER" can access

All other pages should automatically be considered as not allowed as long as no explicit permission has been set via annotation at the endpoint method.

The controller therefore looks as follows:

```<code>@Controller
@RequestMapping
public class MainController {

    @GetMapping
    public String index() { return "index"; }

    @GetMapping("/login")
    @PreAuthorize("isAnonymous()")
    public String login() { return "login"; }

    @GetMapping("/private")
    @PreAuthorize("hasAuthority('ROLE_USER')")
    public String secrets() { return "private"; }
}
</code>```

According to Spring Security's suggestion, the WebSecurityConfig looks like this:

```<code>@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain mainFilterChain(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequestsauthorize -> authorize
                .anyRequest().denyAll())
            // ...
}
</code>```

This configuration should declare all endpoints as restricted by default and since method declarations have a higher precedence, permissions on the methods should override accordingly.

But that is not what happens. With this approach, all endpoints are forbidden and the method annotations are not considered.

The following customization of the authorization config object respects the method annotations but ignores denyall():

```<code>@Bean
public SecurityFilterChain mainFilterChain(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequestsauthorize -> authorize
            .mvcMatchers("/**").permitAll()
            .anyRequest().denyAll())
        // ...
}
</code>```

What sense does it make if you have to give permissions both in the filterchain and on the method itself, without the possibility to declare new endpoints as forbidden by default? With this approach, any new endpoint that is not explicitly restricted on method level is completely open to any user.

So my question is:

How do I configure the SecurityFilterChain in a way that all endpoints, and thus also all new endpoints, are automatically considered as forbidden, and access is exclusively set via method annotations?

Many thanks to all of you who can help to clarify the situation

Body:
It is Spring Security's recommendation to deny all requests with missing authorization rules by default:

http
    .authorizeRequests((authorize) -> authorize
        .filterSecurityInterceptorOncePerRequest(true)
        .mvcMatchers("/app/**").hasRole("APP")
        // ...
        .anyRequest().denyAll()
    )
    // ...

Now let's apply this to a simple real-world example.

The goal is to define 3 endpoints with different access permissions:

"/": homepage, everyone can access

"/login": only anonymous users can access

"/private": only logged in users with the authority "ROLE_USER" can access

All other pages should automatically be considered as not allowed as long as no explicit permission has been set via annotation at the endpoint method.

The controller therefore looks as follows:

@Controller
@RequestMapping
public class MainController {

    @GetMapping
    public String index() { return "index"; }

    @GetMapping("/login")
    @PreAuthorize("isAnonymous()")
    public String login() { return "login"; }

    @GetMapping("/private")
    @PreAuthorize("hasAuthority('ROLE_USER')")
    public String secrets() { return "private"; }
}

According to Spring Security's suggestion, the WebSecurityConfig looks like this:

@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain mainFilterChain(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequestsauthorize -> authorize
                .anyRequest().denyAll())
            // ...
}

This configuration should declare all endpoints as restricted by default and since method declarations have a higher precedence, permissions on the methods should override accordingly.

But that is not what happens. With this approach, all endpoints are forbidden and the method annotations are not considered.

The following customization of the authorization config object respects the method annotations but ignores denyall():

@Bean
public SecurityFilterChain mainFilterChain(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequestsauthorize -> authorize
            .mvcMatchers("/**").permitAll()
            .anyRequest().denyAll())
        // ...
}

What sense does it make if you have to give permissions both in the filterchain and on the method itself, without the possibility to declare new endpoints as forbidden by default? With this approach, any new endpoint that is not explicitly restricted on method level is completely open to any user.

So my question is:

How do I configure the SecurityFilterChain in a way that all endpoints, and thus also all new endpoints, are automatically considered as forbidden, and access is exclusively set via method annotations?

Many thanks to all of you who can help to clarify the situation


问:
How to get non-default Windows Firewall rules in PowerShell?
I've tried using Get-NetFirewallRule | fl * to see if I can tell the difference between Windows Firewall rules that were created by 3rd party programs vs rules that are native and present by default in Windows Firewall, but I couldn't.

Is there any command, script or .NET method that can do that? want to list all non-native ones.

The only difference I can see between Windows built-in Firewall rules and Firewall rules created by 3rd party programs is that Windows built-in rules always have Group names and are placed in groups, but 3rd party Firewall rules don't have groups, of course they can have groups too but so far, at least on my computer, they don't. looking for a more concrete identifier though.

Update: another Identifier I can see is that in the "Program" section of all Windows built-in Firewall things like this exist:

%SystemRoot%\*

System

SYSTEM

Although I haven't figured out how I can use that. I'm not sure if 3rd party Firewall rules can use system or SYSTEM too or what program system even is exactly.


问:
Could not load file or assembly 'System.text.json' , version 4.0.1.0
I have created an SSIS package in VS 2019 to consume an API, doing deserialization using System.Text.Json. It works perfectly when I execute it locally but when I deployed it to SQL Server (SQL Server 2019) and run it as an SQL Job it fails with the error:
"System.IO.FileNotFoundException: Could not load file or assembly 'System.Text.Json, Version 4.0.1.0, Culture=neutral, PublicKeyToken = cc7b13ffcd2ddd51' or one of its dependencies'."

Where do i have to look for if this file/assembly on the server? or what I need to do to get it to work?

Any help appreciated.
Thanks


问:
Use Koin fileProperties with an absolute path
I am trying to deploy a koin application. So far I am using fileProperties pointing to a location in src/main/resources called local.properties.

Now I am deploying a jar and would like to tell Koin to look in a particular folder for the server properties, eg /usr/share/my-app/config/

Unfortunately every attempt to run results in this exception

```<code>org.koin.core.error.NoPropertyFileFoundException: No properties found for file
</code>```

I have tried including the file specifically on the class path of the jar command but without any luck.

Is this by design? That the file properties should be within the jar? Or am I doing something totally wrong...

snippets below

```<code>install(Koin) {
    fileProperties(propertiesFileName)
    modules(properties, monitoring, etc)
}
</code>```

with various run configs

```<code>val propertiesFileName = "/usr/share/my-app/config/app.properties"

val propertiesFileName = "file:///usr/share/my-app/config/app.properties"

val propertiesFileName = "/app.properties" //with -cp including the file specifically
</code>```

Body:
I am trying to deploy a koin application. So far I am using fileProperties pointing to a location in src/main/resources called local.properties.

Now I am deploying a jar and would like to tell Koin to look in a particular folder for the server properties, eg /usr/share/my-app/config/

Unfortunately every attempt to run results in this exception

org.koin.core.error.NoPropertyFileFoundException: No properties found for file

I have tried including the file specifically on the class path of the jar command but without any luck.

Is this by design? That the file properties should be within the jar? Or am I doing something totally wrong...

snippets below

install(Koin) {
    fileProperties(propertiesFileName)
    modules(properties, monitoring, etc)
}

with various run configs

val propertiesFileName = "/usr/share/my-app/config/app.properties"

val propertiesFileName = "file:///usr/share/my-app/config/app.properties"

val propertiesFileName = "/app.properties" //with -cp including the file specifically


问:
viewModelScope.launch runs on first call, but is not invoked on subsequent calls after using viewModelScope.launch in another ViewModel
I have a function that makes an asynchronous call to a REST API. The function works well in the init block, but when I use pullRefresh to call the function executes up to this line, Log.d("Refresh token", "$accessTokenResponse $userIdResponse"), but then it is stuck. This happens when I add to the collection that the function is supposed to fetch from another function collectWaste (included below), which is located in a different viewModel

Here is the function in the viewModel that I to call fetchCollection from the composable

```<code>fun retry() {
    collectionListState = CollectionHistoryResource.Loading
    fetchCollection()
}
</code>```

Here is how I am calling the retry function in the composable

```<code>val refreshing = collectionViewModel.collectionListState is CollectionHistoryResource.Loading

val refreshState =
    rememberPullRefreshState(refreshing, onRefresh = { collectionViewModel.retry() })
</code>```

Below is a copy of the fetchCollection function

```<code>private fun fetchCollection() {
        Log.d("Refresh function", "Fetching collection history")
        val accessTokenResponse = state.get<String>("accessToken")
        val userIdResponse = state.get<Int>("user_id")
        Log.d("Refresh function", "Fetching collection stage 2")
        if (accessTokenResponse != null && userIdResponse != null) {
            Log.d("Refresh token", "$accessTokenResponse $userIdResponse")
            val accessToken = "Bearer $accessTokenResponse"
            viewModelScope.launch {
                try {
                    val responseData =
                        collectionHistoryRepository.getCollection(accessToken, userIdResponse)
                    val list = responseData.data?.map {
                        getCollectionItem(it)
                    }
                    if (list != null) {
                        _collectionList.update {
                            list
                        }
                    }
                    collectionListState = CollectionHistoryResource.Success
                } catch (e: IOException) {
                    Log.d("collection fetch error", "Network failure ${e.message}")
                    collectionListState =
                        CollectionHistoryResource.Error(error = "Could not fetch collection history! Check your connection and try again")
                } catch (e: HttpException) {
                    Log.d("collection fetch error", "Http Error ${e.message}")
                    collectionListState =
                        CollectionHistoryResource.Error(error = "Access to collection history denied! Sign in and try again")
                }
            }
        }
    }
</code>```

Below is a copy of the collectWaste function that after calling to add to the collection, the viewModelScope.launch execution in fetchCollection is no longer invoked

```<code>  fun collectWaste(leaderId: Int?, token: String?) {
    Log.d("Refresh function", "We are collecting")
    _collectUiState.update { currentState ->
        currentState.copy(
            collectNetworkError = false,
            HTTPAuthError = "",
            IOAuthError = ""
        )
    }
    val userId = collectFormState.value.userId
    val quantity = collectFormState.value.quantity
    var token = "Bearer $token"

    if (leaderId == null || leaderId == 0) {
        Log.d("Id Error", "We have an Id error")
        updateCollectErrors(idError = "User does not have permission to collect waste")
        return
    }

    Log.d("Refresh function", "We got to stage 2")

    userIdValidation(userId)
    quantityValidation(quantity)

    if (collectUiState.value.collectUiError) return

    Log.d("Refresh function", "We got to stage 3")

    viewModelScope.launch {
        collectState = CollectResource.Loading
        Log.d("Refresh function", "We got to stage 4")
        try {
            val userBody = collectWasteRepository.collectWaste(
                selectedBlock.id,
                selectedLocation.id,
                quantity.toFloat().toInt(),
                leaderId,
                userId,
                selectedWaste.id,
                selectedWasteType.id,
                selectedZone.id,
                token
            )
            Log.d("Collect successful", "${userBody.success}")
            Log.d("Refresh function", "We got to stage 5")
            collectFormState.value = collectFormState.value.copy(userId = "")
            collectFormState.value = collectFormState.value.copy(quantity = "")
            collectState = CollectResource.Collected
        } catch (e: IOException) {
            Log.d("Collect error", "Network failure ${e.message}")
            _collectUiState.update { currentState ->
                currentState.copy(
                    IOAuthError = "Check your internet connection and try again",
                    collectNetworkError = true
                )
            }
            collectState = CollectResource.NotCollected
        } catch (e: HttpException) {
            Log.d("Collect error", "${e.code()}")

            val errorMessage = if (e.code() == 422) {
                "Please enter valid details including member id"
            } else {
                "Could not collect! Try again later"
            }
            _collectUiState.update { currentState ->
                currentState.copy(HTTPAuthError = errorMessage, collectNetworkError = true)
            }
            collectState = CollectResource.NotCollected
        }
    }
}
</code>```

Body:
I have a function that makes an asynchronous call to a REST API. The function works well in the init block, but when I use pullRefresh to call the function executes up to this line, Log.d("Refresh token", "$accessTokenResponse $userIdResponse"), but then it is stuck. This happens when I add to the collection that the function is supposed to fetch from another function collectWaste (included below), which is located in a different viewModel

Here is the function in the viewModel that I to call fetchCollection from the composable

fun retry() {
    collectionListState = CollectionHistoryResource.Loading
    fetchCollection()
}

Here is how I am calling the retry function in the composable

val refreshing = collectionViewModel.collectionListState is CollectionHistoryResource.Loading

val refreshState =
    rememberPullRefreshState(refreshing, onRefresh = { collectionViewModel.retry() })

Below is a copy of the fetchCollection function

private fun fetchCollection() {
        Log.d("Refresh function", "Fetching collection history")
        val accessTokenResponse = state.get<String>("accessToken")
        val userIdResponse = state.get<Int>("user_id")
        Log.d("Refresh function", "Fetching collection stage 2")
        if (accessTokenResponse != null && userIdResponse != null) {
            Log.d("Refresh token", "$accessTokenResponse $userIdResponse")
            val accessToken = "Bearer $accessTokenResponse"
            viewModelScope.launch {
                try {
                    val responseData =
                        collectionHistoryRepository.getCollection(accessToken, userIdResponse)
                    val list = responseData.data?.map {
                        getCollectionItem(it)
                    }
                    if (list != null) {
                        _collectionList.update {
                            list
                        }
                    }
                    collectionListState = CollectionHistoryResource.Success
                } catch (e: IOException) {
                    Log.d("collection fetch error", "Network failure ${e.message}")
                    collectionListState =
                        CollectionHistoryResource.Error(error = "Could not fetch collection history! Check your connection and try again")
                } catch (e: HttpException) {
                    Log.d("collection fetch error", "Http Error ${e.message}")
                    collectionListState =
                        CollectionHistoryResource.Error(error = "Access to collection history denied! Sign in and try again")
                }
            }
        }
    }

Below is a copy of the collectWaste function that after calling to add to the collection, the viewModelScope.launch execution in fetchCollection is no longer invoked

  fun collectWaste(leaderId: Int?, token: String?) {
    Log.d("Refresh function", "We are collecting")
    _collectUiState.update { currentState ->
        currentState.copy(
            collectNetworkError = false,
            HTTPAuthError = "",
            IOAuthError = ""
        )
    }
    val userId = collectFormState.value.userId
    val quantity = collectFormState.value.quantity
    var token = "Bearer $token"

    if (leaderId == null || leaderId == 0) {
        Log.d("Id Error", "We have an Id error")
        updateCollectErrors(idError = "User does not have permission to collect waste")
        return
    }

    Log.d("Refresh function", "We got to stage 2")

    userIdValidation(userId)
    quantityValidation(quantity)

    if (collectUiState.value.collectUiError) return

    Log.d("Refresh function", "We got to stage 3")

    viewModelScope.launch {
        collectState = CollectResource.Loading
        Log.d("Refresh function", "We got to stage 4")
        try {
            val userBody = collectWasteRepository.collectWaste(
                selectedBlock.id,
                selectedLocation.id,
                quantity.toFloat().toInt(),
                leaderId,
                userId,
                selectedWaste.id,
                selectedWasteType.id,
                selectedZone.id,
                token
            )
            Log.d("Collect successful", "${userBody.success}")
            Log.d("Refresh function", "We got to stage 5")
            collectFormState.value = collectFormState.value.copy(userId = "")
            collectFormState.value = collectFormState.value.copy(quantity = "")
            collectState = CollectResource.Collected
        } catch (e: IOException) {
            Log.d("Collect error", "Network failure ${e.message}")
            _collectUiState.update { currentState ->
                currentState.copy(
                    IOAuthError = "Check your internet connection and try again",
                    collectNetworkError = true
                )
            }
            collectState = CollectResource.NotCollected
        } catch (e: HttpException) {
            Log.d("Collect error", "${e.code()}")

            val errorMessage = if (e.code() == 422) {
                "Please enter valid details including member id"
            } else {
                "Could not collect! Try again later"
            }
            _collectUiState.update { currentState ->
                currentState.copy(HTTPAuthError = errorMessage, collectNetworkError = true)
            }
            collectState = CollectResource.NotCollected
        }
    }
}


问:
How to perform range queries efficiently in GridDB for both ascending and descending order without creating separate containers?
Using GridDB, I have a use case where I need to perform range queries on the data stored in a container. Sometimes I need to retrieve data in ascending order of a certain column, while other times I need to retrieve data in descending order of that same column. Using the current approach of creating separate containers for each order is functional but not very efficient. Is there a more efficient way to perform these range queries in GridDB, such as by inverting the order of a container or by adjusting the search criteria?</p>