问:
Amplify GraphQL API not responding
Amplify GraphQL on my React Native App just stopped working for no reasons at all. It is stuck on refreshing (trying to query the data). And I made no changed whatsoever to the API. What can I do?

I killed the server severally and restarted it, still stuck on loading. Had to wait 2 days to see if it's coming from Amplify, still no result. I'm considering starting a new project from scratch and then copying and pasting all the code but it will be at the expense of the already existing data.

Title: Amplify GraphQL API not responding


来源: stackexchange

问:
Log the inbound traffic to the VM
We are planning to migrate the workloads from a Windows Server based virtual machine. I wanted to capture all the inbound connections to this VM so that the dependencies are properly addressed after the migration to the new VM.

Reason for this is, the present VM is there since ages there are many other applications connects to this using IP / VM name / DNS alias.

I know netstat can be used, I wanted to run some kind of a process for about 2 days continuously and monitor and log the inbound so that the results can be reviewed.

or let me know any better way to accomplish this.

than you in advance.

Regards,
Pradeep

I tried netstat but looking something that can run continuously and log the appropriate results

ContentLicense: CC BY-SA 4.0

Title: Log the inbound traffic to the VM


问:
How to customize the API metadata of springdoc-openai?
I'm trying to customize the springdoc-openapi, make it can work with my framework, but I meet two problems.

1. How to treat methods that do not start with is/get as properties of Model?

If users use my ORM framework by Java language, the property getters in the entity interface can either start with is/get like a traditional Java Bean, or don't start with is/get like a Java record, for example

@Entity
public interface Book {

   @Id
   long id();

   String name();

   int edition();

   BigDecimal price();

   @ManyToOne
   BookStore store();

   @ManyToMany
   List<Author> authors();
}
```
<p>Here, the wording that does not start with <code>is/get</code> is used, which looks like a java record, not a traditional java bean.</p>
<p>However, doing this will cause swagger-ui to think that the model doesn't have any attributes. So I have to change the behavior of swagger.</p>
<p>After some research, I found that this behavior can be changed using <code>io.swagger.v3.core.converter.ModelConverter</code>, which is the most likely solution.</p>
<p>However, springdoc-openapi does not explain in detail how to use ModelConverter in the documentation. Ultimately, this goal was not achieved.</p>
<h1>2. How to control the shape of dynamic objects in HTTP response?</h1>
<p>My ORM is GraphQL-style, its entity objects are dynamic so that data structures of arbitrary shapes can be queried, just like GraphQL does. For example</p>
<pre class="lang-java prettyprint-override"><code>@RestController
public class BookController {

    @AutoWired
    private JSqlClient sqlClient;

    // Query simple book objects
    @GetMapping("/books")
    public List<Book> books() {
        return sqlClient.getEntities().findAll(Book.class);
    }

    // Query complex book objects
    @GetMapping("/books/details")
    public List<Book> bookDetails() {
        return sqlClient.getEntities().findAll(
            // Like the request body of GraphQL
            BookFetcher$
               .allScalarFields()
               .store(
                   BookStoreFetcher.$.allScalarFields()
               )
               .authors(
                   AuthorFetcher.$.allScalars()
               )
        );
    }
}
</code>```

The first query returns a list of simple book objects in the format {id, name, edition, price}

The second query returns a list of complex book objects in the format {id, name, edition, price, store: {id, name, website}, authors: {id, firstName, lastName, gender}}

Dynamic objects can vary in shape, and these are just two special cases.

I expect swgger to tell the client the shape of the object returned by each business scenario. So, I defined an annotation called @FetchBy. It should be used like this

@RestController
public class BookController {

    private static final Fetcher<Book> BOOK_DETAIL_FETCHER =
          BookFetcher$
               .allScalarFields()
               .store(
                   BookStoreFetcher.$.allScalarFields()
               )
               .authors(
                   AuthorFetcher.$.allScalars()
               );

    @AutoWired
    private JSqlClient sqlClient;

    @GetMapping("/books")
    public List<Book> books() {
        return sqlClient.getEntities().findAll(Book.class);
    }

    @GetMapping("/books/details")
    public List<@FetchBy("BOOK_DETAIL_FETCHER") Book> bookDetails() {
        return sqlClient.getEntities().findAll(BOOK_DETAIL_FETCHER);
    }
}
```

Declare the shape of the complex object as a static constant.

The @FetchBy annotation uses the constant name to tell swgger the shape of the returned dynamic object.

After some research, I found that this behavior can be changed using org.springdoc.core.customizers.OperationCustomizer, which is the most likely solution.

However, I found that the schema tree of swagger is not consistent with the generic type definition tree in the java language. For example, Spring's ResponseEntity<> wrapper will be ignored by swagger and will be not parsed as a node of schema tree. Theoretically speaking, this ability of swagger can be customized infinitely, so the two trees may not always be consistent and difficult to analyze.

Body:
I'm trying to customize the springdoc-openapi, make it can work with my framework, but I meet two problems.

1. How to treat methods that do not start with is/get as properties of Model?

If users use my ORM framework by Java language, the property getters in the entity interface can either start with is/get like a traditional Java Bean, or don't start with is/get like a Java record, for example

@Entity
public interface Book {

   @Id
   long id();

   String name();

   int edition();

   BigDecimal price();

   @ManyToOne
   BookStore store();

   @ManyToMany
   List<Author> authors();
}

Here, the wording that does not start with is/get is used, which looks like a java record, not a traditional java bean.

However, doing this will cause swagger-ui to think that the model doesn't have any attributes. So I have to change the behavior of swagger.

After some research, I found that this behavior can be changed using io.swagger.v3.core.converter.ModelConverter, which is the most likely solution.

However, springdoc-openapi does not explain in detail how to use ModelConverter in the documentation. Ultimately, this goal was not achieved.

2. How to control the shape of dynamic objects in HTTP response?

My ORM is GraphQL-style, its entity objects are dynamic so that data structures of arbitrary shapes can be queried, just like GraphQL does. For example

@RestController
public class BookController {

    @AutoWired
    private JSqlClient sqlClient;

    // Query simple book objects
    @GetMapping("/books")
    public List<Book> books() {
        return sqlClient.getEntities().findAll(Book.class);
    }

    // Query complex book objects
    @GetMapping("/books/details")
    public List<Book> bookDetails() {
        return sqlClient.getEntities().findAll(
            // Like the request body of GraphQL
            BookFetcher$
               .allScalarFields()
               .store(
                   BookStoreFetcher.$.allScalarFields()
               )
               .authors(
                   AuthorFetcher.$.allScalars()
               )
        );
    }
}

The first query returns a list of simple book objects in the format {id, name, edition, price}

The second query returns a list of complex book objects in the format {id, name, edition, price, store: {id, name, website}, authors: {id, firstName, lastName, gender}}

Dynamic objects can vary in shape, and these are just two special cases.

I expect swgger to tell the client the shape of the object returned by each business scenario. So, I defined an annotation called @FetchBy. It should be used like this

@RestController
public class BookController {

    private static final Fetcher<Book> BOOK_DETAIL_FETCHER =
          BookFetcher$
               .allScalarFields()
               .store(
                   BookStoreFetcher.$.allScalarFields()
               )
               .authors(
                   AuthorFetcher.$.allScalars()
               );

    @AutoWired
    private JSqlClient sqlClient;

    @GetMapping("/books")
    public List<Book> books() {
        return sqlClient.getEntities().findAll(Book.class);
    }

    @GetMapping("/books/details")
    public List<@FetchBy("BOOK_DETAIL_FETCHER") Book> bookDetails() {
        return sqlClient.getEntities().findAll(BOOK_DETAIL_FETCHER);
    }
}

Declare the shape of the complex object as a static constant.

The @FetchBy annotation uses the constant name to tell swgger the shape of the returned dynamic object.

After some research, I found that this behavior can be changed using org.springdoc.core.customizers.OperationCustomizer, which is the most likely solution.

However, I found that the schema tree of swagger is not consistent with the generic type definition tree in the java language. For example, Spring's ResponseEntity<> wrapper will be ignored by swagger and will be not parsed as a node of schema tree. Theoretically speaking, this ability of swagger can be customized infinitely, so the two trees may not always be consistent and difficult to analyze.


问:
What is 'Store as project file' in 'Run/Debug Configurations' - JetBrains IDE's
JetBrains IDEs like PhpStorm, WebStorm, PyCharm or IntelliJ have Run/Debug Configurations.

When creating or modifying a configuration, you can select a checkbox with a label "Store as project file".

From what I have seen, this will create a XML representation of the configuration and store the XML file inside a directory (defaults to .run).

What exactly is the benefit / intended use of this?


问:
How to resent OTP in FireBase Phone Authentication
I am trying to resent the OTP.
This is the code I have written.
But the firebase is not resending the OTP.
What changes should I do?</p>
```<code>tvRequestAgain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PhoneAuthProvider.getInstance().verifyPhoneNumber(
                    "+" + countryCode + mobileNumber,
                    60,
                    TimeUnit.SECONDS,
                    VerifyOTP.this,
                    new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                        @Override
                        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {

                        }

                        @Override
                        public void onVerificationFailed(@NonNull FirebaseException e) {
                            tvInvalidOTP.setText(e.getMessage());
                            tvInvalidOTP.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onCodeSent(@NonNull String newOTPFromFireBase, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                            Toast.makeText(VerifyOTP.this, "OTP resent successfully!", Toast.LENGTH_SHORT).show();
                            OTPFromBackEnd = newOTPFromFireBase;
                        }
                    }
            );
        }
    });
</code>```

Body:
I am trying to resent the OTP.
This is the code I have written.
But the firebase is not resending the OTP.
What changes should I do?

tvRequestAgain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PhoneAuthProvider.getInstance().verifyPhoneNumber(
                    "+" + countryCode + mobileNumber,
                    60,
                    TimeUnit.SECONDS,
                    VerifyOTP.this,
                    new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                        @Override
                        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {

                        }

                        @Override
                        public void onVerificationFailed(@NonNull FirebaseException e) {
                            tvInvalidOTP.setText(e.getMessage());
                            tvInvalidOTP.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onCodeSent(@NonNull String newOTPFromFireBase, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                            Toast.makeText(VerifyOTP.this, "OTP resent successfully!", Toast.LENGTH_SHORT).show();
                            OTPFromBackEnd = newOTPFromFireBase;
                        }
                    }
            );
        }
    });


Title: Tensorflow fit history is noisier than expected

Body:
I've fitted a model and this is the plot i get with te following code:

hist = model.fit(
    xs, ys, epochs=300, batch_size=100, validation_split=0.1,
    callbacks=[K.callbacks.EarlyStopping(patience=30)]
)
plt.figure(dpi=200)
plt.plot(hist.history["loss"])
plt.plot(hist.history["val_loss"])
plt.legend(["loss", "val_loss"])

However, the training logs are the following:

...
Epoch 200/300
9/9 [==============================] - 3s 384ms/step - loss: 514.2175 - val_loss: 584.2152
Epoch 201/300
9/9 [==============================] - 3s 385ms/step - loss: 510.9814 - val_loss: 581.8872
Epoch 202/300
9/9 [==============================] - 3s 391ms/step - loss: 518.9771 - val_loss: 582.4727
Epoch 203/300
9/9 [==============================] - 3s 383ms/step - loss: 521.8132 - val_loss: 582.9196
Epoch 204/300
9/9 [==============================] - 4s 393ms/step - loss: 516.8439 - val_loss: 584.0792
Epoch 205/300
9/9 [==============================] - 3s 391ms/step - loss: 513.7325 - val_loss: 582.6438
Epoch 206/300
9/9 [==============================] - 3s 390ms/step - loss: 514.4469 - val_loss: 583.5629
Epoch 207/300
9/9 [==============================] - 3s 391ms/step - loss: 522.0557 - val_loss: 581.7162
Epoch 208/300
9/9 [==============================] - 3s 389ms/step - loss: 518.6336 - val_loss: 582.8070
Epoch 209/300
9/9 [==============================] - 3s 391ms/step - loss: 518.0827 - val_loss: 582.4284
Epoch 210/300
9/9 [==============================] - 3s 389ms/step - loss: 514.1886 - val_loss: 582.4635
Epoch 211/300
9/9 [==============================] - 3s 390ms/step - loss: 514.4373 - val_loss: 582.1906
Epoch 212/300
9/9 [==============================] - 3s 391ms/step - loss: 514.9708 - val_loss: 582.1699
Epoch 213/300
9/9 [==============================] - 3s 388ms/step - loss: 521.1622 - val_loss: 582.3545
Epoch 214/300
9/9 [==============================] - 3s 388ms/step - loss: 513.5198 - val_loss: 582.7703
Epoch 215/300
9/9 [==============================] - 3s 392ms/step - loss: 514.6642 - val_loss: 582.3327
Epoch 216/300
9/9 [==============================] - 3s 392ms/step - loss: 514.0926 - val_loss: 583.9896
Epoch 217/300
9/9 [==============================] - 3s 385ms/step - loss: 520.9324 - val_loss: 583.9265
Epoch 218/300
9/9 [==============================] - 4s 397ms/step - loss: 510.2536 - val_loss: 584.6587
Epoch 219/300
9/9 [==============================] - 4s 394ms/step - loss: 515.7706 - val_loss: 583.2895
Epoch 220/300
9/9 [==============================] - 3s 391ms/step - loss: 520.9758 - val_loss: 582.2515
Epoch 221/300
9/9 [==============================] - 3s 386ms/step - loss: 517.8850 - val_loss: 582.1981
Epoch 222/300
9/9 [==============================] - 4s 395ms/step - loss: 514.2051 - val_loss: 583.0013
Epoch 223/300
9/9 [==============================] - 4s 402ms/step - loss: 509.3330 - val_loss: 583.7137
Epoch 224/300
9/9 [==============================] - 3s 388ms/step - loss: 516.6832 - val_loss: 582.0773
Epoch 225/300
9/9 [==============================] - 3s 387ms/step - loss: 515.5243 - val_loss: 582.2585
Epoch 226/300
9/9 [==============================] - 3s 389ms/step - loss: 517.6601 - val_loss: 582.3940
Epoch 227/300
9/9 [==============================] - 3s 388ms/step - loss: 515.7537 - val_loss: 582.3862
Epoch 228/300
9/9 [==============================] - 4s 394ms/step - loss: 516.1107 - val_loss: 582.7234
Epoch 229/300
9/9 [==============================] - 3s 389ms/step - loss: 517.5703 - val_loss: 583.3829
Epoch 230/300
9/9 [==============================] - 3s 388ms/step - loss: 516.7491 - val_loss: 583.4712
Epoch 231/300
9/9 [==============================] - 4s 392ms/step - loss: 520.6753 - val_loss: 583.2650
Epoch 232/300
9/9 [==============================] - 3s 388ms/step - loss: 516.1927 - val_loss: 581.9255
Epoch 233/300
9/9 [==============================] - 4s 393ms/step - loss: 512.5476 - val_loss: 583.1275
Epoch 234/300
9/9 [==============================] - 4s 392ms/step - loss: 513.5744 - val_loss: 583.0643
Epoch 235/300
9/9 [==============================] - 3s 385ms/step - loss: 520.2017 - val_loss: 582.6875
Epoch 236/300
9/9 [==============================] - 3s 386ms/step - loss: 518.7263 - val_loss: 583.0582
Epoch 237/300
9/9 [==============================] - 3s 382ms/step - loss: 521.4882 - val_loss: 582.8977

Infact, if with some regex I extract the training loss, and plot it, I get the following plot:

What am I missing about History?...


问:
Datatables under Wordpress loads correctly on a PC but not on a mobile device
I have a code snippet that loads datatables, gets data from the wordpress database and correctly displays it when viewed from a PC. However, visiting the site from a tablet (pc and tablet using Chrome), the page loads but only a blank white rectangle for the datatables grid. I am using the following in the code snippet:-

```<code><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs5/jq-3.6.0/jszip-2.5.0/dt-1.13.1/b-2.3.3/b-html5-2.3.3/date-1.2.0/r-2.4.0/sb-1.4.0/sl-1.5.0/datatables.min.css"/>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs5/jq-3.6.0/jszip-2.5.0/dt-1.13.1/b-2.3.3/b-html5-2.3.3/date-1.2.0/r-2.4.0/sb-1.4.0/sl-1.5.0/datatables.min.js"></script>
</code>```

Can anyone tell me why this should work properly on a pc but not on a mobile device. It is also correctly responsive on the PC.

I have discovered that if one taps the 3 vertical dots on the mobile screen (in Chrome)and selects View as desktop, the grids appear. I suspect this might differ on other browsers. This still does not seem to be the correct solution.

Body:
I have a code snippet that loads datatables, gets data from the wordpress database and correctly displays it when viewed from a PC. However, visiting the site from a tablet (pc and tablet using Chrome), the page loads but only a blank white rectangle for the datatables grid. I am using the following in the code snippet:-

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs5/jq-3.6.0/jszip-2.5.0/dt-1.13.1/b-2.3.3/b-html5-2.3.3/date-1.2.0/r-2.4.0/sb-1.4.0/sl-1.5.0/datatables.min.css"/>

Can anyone tell me why this should work properly on a pc but not on a mobile device. It is also correctly responsive on the PC.

I have discovered that if one taps the 3 vertical dots on the mobile screen (in Chrome)and selects View as desktop, the grids appear. I suspect this might differ on other browsers. This still does not seem to be the correct solution.


问:
How to change user in linux using python script?
I want to change user using python script, i tried os.system("su <username> -p <password>") but it did not work. And i will not run the python script on terminal, which is mean i should not do this: python


问:
Error while Upgrading gradle from version 4 to version 5 | Gradle sourceSets
After upgrading from gradle 4 to gradle 5 I am getting error and unable to understand what is expected compatible changes are required.

My project is multi modules and having same issue with other build files as well.


问:
Using Axios in Electron - Best Practice?
I am creating an app in Electron using React.  The first version will be a purely desktop based app using a local database for data storage etc.  However, eventually I would like to utilise as much of the same code base as possible and deploy the same app as a cloud-based alternative (by just leaving out the electron component).

I'd like some advice, thoughts, opinions from the community on if I should use axios for creating internal restAPI infrastructure rather than a API using javascript modules/functions etc. for performing requests such as getting data from a database.

My thinking is then that when I port the application to the cloud, I really just need to change the restAPI locations to point to a cloud version which would then get the data from a cloud database rather than a local database etc.

Would exposing such APIs locally within Electron using axios pose any security risks or other issues that I may need to consider?

Perhaps this answer/discussion may also provide useful for the community in the future.

Looking forward to thoughts, or even new suggestions on how this may be best approached.

Thanks.


问:
Migrating Already Installed Softwares to Homebrew
I am using MacOS. I have already bunch of softwares installed in my computer. Recently I have installed Homebrew. Now I want all my softwares (supported by homebrew) to get updated by Homebrew.

How can I migrate those to homebrew without uninstalling and reinstalling those?

I tried to find solution from web but didn't find anything.


问:
C#, How to get Client's certificate (acquire a client certificate during the TLS handshake process)
My project is a simple server which accepts connection requests on port 5123 also my server use a specific certificate.

If the department of computer science makes a connection request to my server and use any certificate allowed by my server, my server will accept that request and everything will be ok

But if the department of information technology makes a connection request to my server and used a different certificate! my server will force close that connection and throw this error A call to SSPI failed, see inner exception.

I made a function DisplayCertificateInformation which gives you certificate information of client. That function works if the client used any certificate allowed by my server. If the client used a different certificate that function will throw this error "A call to SSPI failed, see inner exception."

Also if client used a different cert my server will abort on this line by throwing this error "A call to SSPI failed, see inner exception." and will ignore the rest lines

```<code>ServerSslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls12, false);
</code>```

My question is how can I get client's cert when the client try to connect to my server, I just want to know which cert did the client use because I want to add an exception for some department's certificate, not all departments

Here is my code

```<code>private static void AcceptConnection_SSL(object client)
{
    TcpClient inClient = client as TcpClient;
    NetworkStream stream = inClient.GetStream();
    SslStream ServerSslStream = new SslStream(inClient.GetStream(), false, SslValidationCallback);

    // These two lines will throw error if client used different cert
    ServerSslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls12, false);
    DisplayCertificateInformation(ServerSslStream);
}

private static Boolean SslValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
{
    return true;
}

static void DisplayCertificateInformation(SslStream stream)
{
    Console.WriteLine("Certificate revocation list checked: {stream.CheckCertRevocationStatus}");

    X509Certificate localCertificate = stream.LocalCertificate;
    if (stream.LocalCertificate != null)
    {
        Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
            localCertificate.Subject,
            localCertificate.GetEffectiveDateString(),
            localCertificate.GetExpirationDateString());
    }
    else
    {
        Console.WriteLine("Local certificate is null.");
    }

    // Display the properties of the client's certificate.
    X509Certificate remoteCertificate = stream.RemoteCertificate;
    if (stream.RemoteCertificate != null)
    {
        if (remoteCertificate != null)
        {
            Console.WriteLine(
                "Remote cert was issued to {remoteCertificate.Subject} and is valid from {remoteCertificate.GetEffectiveDateString()} until {remoteCertificate.GetExpirationDateString()}.");
        }
    }
    else
    {
        Console.WriteLine("Remote certificate is null.");
    }
}
</code>```

C#, How to get Client's certificate (acquire a client certificate during the TLS handshake process)

Body:
My project is a simple server which accepts connection requests on port 5123 also my server use a specific certificate.

If the department of computer science makes a connection request to my server and use any certificate allowed by my server, my server will accept that request and everything will be ok

But if the department of information technology makes a connection request to my server and used a different certificate! my server will force close that connection and throw this error A call to SSPI failed, see inner exception.

I made a function DisplayCertificateInformation which gives you certificate information of client. That function works if the client used any certificate allowed by my server. If the client used a different certificate that function will throw this error "A call to SSPI failed, see inner exception."

Also if client used a different cert my server will abort on this line by throwing this error "A call to SSPI failed, see inner exception." and will ignore the rest lines

ServerSslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls12, false);

My question is how can I get client's cert when the client try to connect to my server, I just want to know which cert did the client use because I want to add an exception for some department's certificate, not all departments

Here is my code

private static void AcceptConnection_SSL(object client)
{
    TcpClient inClient = client as TcpClient;
    NetworkStream stream = inClient.GetStream();
    SslStream ServerSslStream = new SslStream(inClient.GetStream(), false, SslValidationCallback);

    // These two lines will throw error if client used different cert
    ServerSslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls12, false);
    DisplayCertificateInformation(ServerSslStream);
}

private static Boolean SslValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
{
    return true;
}

static void DisplayCertificateInformation(SslStream stream)
{
    Console.WriteLine("Certificate revocation list checked: {stream.CheckCertRevocationStatus}");

    X509Certificate localCertificate = stream.LocalCertificate;
    if (stream.LocalCertificate != null)
    {
        Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
            localCertificate.Subject,
            localCertificate.GetEffectiveDateString(),
            localCertificate.GetExpirationDateString());
    }
    else
    {
        Console.WriteLine("Local certificate is null.");
    }

    // Display the properties of the client's certificate.
    X509Certificate remoteCertificate = stream.RemoteCertificate;
    if (stream.RemoteCertificate != null)
    {
        if (remoteCertificate != null)
        {
            Console.WriteLine(
                "Remote cert was issued to {remoteCertificate.Subject} and is valid from {remoteCertificate.GetEffectiveDateString()} until {remoteCertificate.GetExpirationDateString()}.");
        }
    }
    else
    {
        Console.WriteLine("Remote certificate is null.");
    }
}

C#, How to get Client's certificate (acquire a client certificate during the TLS handshake process)


问:
Flask-Cache not caching objects attributes properly
I'm trying to cache and retrieve an object using the cache.set() and cache.get() methods, but I'm having some trouble getting it to work properly. I use the .set() method to cache an object (obj1) that has another object (obj2) as its attribute. After retrieving the cached object (obj1) using cache.get(), I am not able to access the attributes of obj2. I'm getting an AttributeError: 'CustomDataFrame' object has no attribute '_var1'.

Expected behavior:

```<code>Before caching, var1: Remember me
After caching, var1: Remember me
</code>```

Actual behavior:

```<code>Before caching, var1: Remember me
AttributeError: 'CustomDataFrame' object has no attribute 'var1'.
</code>```

Minimal reproducible example:

from flask import Flask
from flask_caching import Cache
import pandas as pd

app = Flask(__name__)

# Configure Flask-Cache
app.config["CACHE_TYPE"] = "filesystem"
app.config["CACHE_DIR"] = "/tmp"
app.config["CACHE_DEFAULT_TIMEOUT"] = 600

cache = Cache(app)

class CustomDataFrame(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.var1 = None

    def custom_method(self, arg1, arg2):
        # perform some custom operation
        pass

class DataFrameManager():
    def __init__(self, df: CustomDataFrame):
        self.df = df

    def custom_method(self, arg1, arg2):
        # perform some custom operation
        pass

# Set up a route that uses caching
@app.route("/")
def set_and_get_route():
    # Create custom object
    data = {'name': ['Alice', 'Bob'], 'age': [24, 32]}
    df = CustomDataFrame(data)
    df.var1 = "remember me"
    df_manager = DataFrameManager(df)

    # Use .set() to store a value in the cache
    print(f"Before caching, var1: {df_manager.df.var1}")
    cache.set("df_manager", df_manager)

    # Use .get() to retrieve a value from the cache
    retrieved_df_manager = cache.get("df_manager")
    print(f"After caching, var1: {retrieved_df_manager.df.var1}")

    return "dummy"

if __name__ == "__main__":
    app.run()
```

Body:
I'm trying to cache and retrieve an object using the cache.set() and cache.get() methods, but I'm having some trouble getting it to work properly. I use the .set() method to cache an object (obj1) that has another object (obj2) as its attribute. After retrieving the cached object (obj1) using cache.get(), I am not able to access the attributes of obj2. I'm getting an AttributeError: 'CustomDataFrame' object has no attribute '_var1'.

Expected behavior:

Before caching, var1: Remember me
After caching, var1: Remember me

Actual behavior:

Before caching, var1: Remember me
AttributeError: 'CustomDataFrame' object has no attribute 'var1'.

Minimal reproducible example:

from flask import Flask
from flask_caching import Cache
import pandas as pd

app = Flask(__name__)

# Configure Flask-Cache
app.config["CACHE_TYPE"] = "filesystem"
app.config["CACHE_DIR"] = "/tmp"
app.config["CACHE_DEFAULT_TIMEOUT"] = 600

cache = Cache(app)

class CustomDataFrame(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.var1 = None

    def custom_method(self, arg1, arg2):
        # perform some custom operation
        pass

class DataFrameManager():
    def __init__(self, df: CustomDataFrame):
        self.df = df

    def custom_method(self, arg1, arg2):
        # perform some custom operation
        pass

# Set up a route that uses caching
@app.route("/")
def set_and_get_route():
    # Create custom object
    data = {'name': ['Alice', 'Bob'], 'age': [24, 32]}
    df = CustomDataFrame(data)
    df.var1 = "remember me"
    df_manager = DataFrameManager(df)

    # Use .set() to store a value in the cache
    print(f"Before caching, var1: {df_manager.df.var1}")
    cache.set("df_manager", df_manager)

    # Use .get() to retrieve a value from the cache
    retrieved_df_manager = cache.get("df_manager")
    print(f"After caching, var1: {retrieved_df_manager.df.var1}")

    return "dummy"

if __name__ == "__main__":
    app.run()


问:
Set Cookie not working (nextJs + express)
I'm trying to set the cookie from my express backend to my nextjs front end using the response.setHeader, but it's not working, I get my json response but no cookies are set, I used postman to make some tests and in postman it did set the cookies as it should be.
NextJs version is 13.0.2, express version is 4.18.2 and cookie version is 0.5.0

My express server:

```<code>export const loginUser = async (req: Request, res: Response) => {
  const { email, password } = req.body;

  //limpa os cookies
  res.clearCookie("accessToken", { httpOnly: true });

  if (email !== "" && password !== "") {
    try {
      const foundUser: any = await prisma.users.findFirst({
        where: {
          email,
          password,
        },
      });

      try {
        const accessToken = jwt.sign(
          { id: foundUser.id, email },
          "dspaojdspoadsaodksa",
          {
            expiresIn: "10s",
          }
        );
        const refreshToken = jwt.sign(
          { id: foundUser.id, email },
          "dsaoindsadmnsaosda",
          {
            expiresIn: "50s",
          }
        );

        const savedRefresh = await prisma.refresh_token.upsert({
          where: {
            users_id: foundUser.id,
          },
          update: {
            access_token: accessToken,
            refresh_tk: refreshToken,
            users_id: foundUser.id,
          },
          create: {
            access_expires_in: "",
            refresh_expires_in: "",
            access_token: accessToken,
            refresh_tk: refreshToken,
            users_id: foundUser.id,
          },
        });

        res.setHeader(
          "Set-Cookie",
          cookie.serialize("accessToken", accessToken, {
            maxAge: 1000 * 60 * 15, //15 minutes
            httpOnly: true, // The cookie only accessible by the web server
          })
        );

        res.json({ accessToken, user: { email }, ok: true });
      } catch (error) {
        console.log("refresh cant be created");
        res.send({ message: "refresh cant be created" });
      }
    } catch (error) {
      res.send({ message: "user not found" });
    }
  } else {
    res.json({ message: "token creation failed" });
  }
};
</code>```

My nextJs front-end:

```<code>const handleLogin = async (event: React.SyntheticEvent) => {
    event.preventDefault();

    const email = (event?.target as any).email.value;
    const password = (event?.target as any).password.value;

    if (email === "" || password === "") {
      setError(true);
      return;
    }

    const data = {
      email,
      password,
    };

    const resp = await fetch("http://localhost:5000/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    const userData = await resp.json();
    console.log(userData);
  };
</code>```

Body:
I'm trying to set the cookie from my express backend to my nextjs front end using the response.setHeader, but it's not working, I get my json response but no cookies are set, I used postman to make some tests and in postman it did set the cookies as it should be.
NextJs version is 13.0.2, express version is 4.18.2 and cookie version is 0.5.0

My express server:

export const loginUser = async (req: Request, res: Response) => {
  const { email, password } = req.body;

  //limpa os cookies
  res.clearCookie("accessToken", { httpOnly: true });

  if (email !== "" && password !== "") {
    try {
      const foundUser: any = await prisma.users.findFirst({
        where: {
          email,
          password,
        },
      });

      try {
        const accessToken = jwt.sign(
          { id: foundUser.id, email },
          "dspaojdspoadsaodksa",
          {
            expiresIn: "10s",
          }
        );
        const refreshToken = jwt.sign(
          { id: foundUser.id, email },
          "dsaoindsadmnsaosda",
          {
            expiresIn: "50s",
          }
        );

        const savedRefresh = await prisma.refresh_token.upsert({
          where: {
            users_id: foundUser.id,
          },
          update: {
            access_token: accessToken,
            refresh_tk: refreshToken,
            users_id: foundUser.id,
          },
          create: {
            access_expires_in: "",
            refresh_expires_in: "",
            access_token: accessToken,
            refresh_tk: refreshToken,
            users_id: foundUser.id,
          },
        });

        res.setHeader(
          "Set-Cookie",
          cookie.serialize("accessToken", accessToken, {
            maxAge: 1000 * 60 * 15, //15 minutes
            httpOnly: true, // The cookie only accessible by the web server
          })
        );

        res.json({ accessToken, user: { email }, ok: true });
      } catch (error) {
        console.log("refresh cant be created");
        res.send({ message: "refresh cant be created" });
      }
    } catch (error) {
      res.send({ message: "user not found" });
    }
  } else {
    res.json({ message: "token creation failed" });
  }
};

My nextJs front-end:

const handleLogin = async (event: React.SyntheticEvent) => {
    event.preventDefault();

    const email = (event?.target as any).email.value;
    const password = (event?.target as any).password.value;

    if (email === "" || password === "") {
      setError(true);
      return;
    }

    const data = {
      email,
      password,
    };

    const resp = await fetch("http://localhost:5000/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    const userData = await resp.json();
    console.log(userData);
  };


问:
Pillow adding "Description" field to the originally copied EXIF
I have a problem with understanding why is the Pillow module adding a description field with nonsense values when I just copy EXIF from original photo. Does anyone know how to fix this issue?

```<code>import os
from PIL import Image

file_name = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'resources', 'exif.JPG')

with Image.open(file_name) as original:
    original.load()

exif = original.getexif()

original = original.resize((120, 120))
original.save('aa.jpg', exif=exif)
</code>```

I tried to find any useful information in the Pillow docs but I didn't find anything. When I do print the original.getexif() the dictionary doesn't contain description key-value pair.

Body:
I have a problem with understanding why is the Pillow module adding a description field with nonsense values when I just copy EXIF from original photo. Does anyone know how to fix this issue?

import os
from PIL import Image

file_name = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'resources', 'exif.JPG')

with Image.open(file_name) as original:
    original.load()

exif = original.getexif()

original = original.resize((120, 120))
original.save('aa.jpg', exif=exif)

I tried to find any useful information in the Pillow docs but I didn't find anything. When I do print the original.getexif() the dictionary doesn't contain description key-value pair.


问:
How to Make this html form responsive in small devices
I am unable to make this login form responsive. it looks awesome in desktop
I've made this using html and CSS.it looks like the problem is with width or height on opening this on small devices
I've tried using overflow:hidden;
@media width
but it did not worked
I want this to be reponsive as the view of desktop
here's the code
html

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Login Form</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="center">
      <h1>Login</h1>
      <form method="post">
        <div class="txt_field">
          <input type="text" required>
          <span></span>
          <label>Username</label>
        </div>
        <div class="txt_field">
          <input type="password" required>
          <span></span>
          <label>Password</label>
        </div>
        <div class="pass"><a href="#">Forgot Password ?</a> </div>
        <input type="submit" value="Login">
        <div class="signup_link"><span id="extext">
          </span><a href="signup.html">Not a member? Signup</a>
        </div>
      </form>
    </div>

  </body>
</html>
</code>```

CSS code

```<code>*{
  margin: 0;
  padding: 0;
  font-family: "Poppins", sans-serif;
  /* font-weight: bold; */
}
body{
  margin: 0;
  padding: 0;
  background: linear-gradient(120deg,#4e718a, #3e9778);
  height: 100vh;
  overflow: hidden;
}
.center{
  position: relative;
  top: 50%;
  left: 50%;
  right: 50%;
  transform: translate(-50%, -50%);
  height: 459px;
  width: 359px;
  background: linear-gradient(120deg,#9b3438ce, #8f21a7e8);;
  border-radius: 10px;
  box-shadow: 10px 10px 15px rgb(56 45 45 / 84%);
}
@media (max-width: 920px) {
  .center{
    display:block;
    position:relative;
    height: 76vh;
  width: 70vw;
  }
}
.center h1{
  text-align: center;
  padding: 20px 0;
  border-bottom: 3px solid #93c398;
}
.center form{
  padding: 0 40px;
  box-sizing: border-box;
}
form .txt_field{
  position: relative;
  border-bottom: 2px solid #adadad;
  margin: 30px 0;
}
.txt_field input{
  width: 100%;
  padding: 0 5px;
  height: 40px;
  font-size: 16px;
  border: none;
  background: none;
  outline: none;
}
.txt_field label{
  position: absolute;
  top: 50%;
  left: 5px;
  color: #a4a2a2;
  transform: translateY(-40%);
  font-size: 16px;
  transition: .7s;
}
.txt_field span::before{
  content: '';
  position: absolute;
  top: 40px;
  left: 0;
  width: 0%;
  height: 2px;
  background: #0a8eb6;
  transition: .7s;
}
.txt_field input:focus ~ label,
.txt_field input:valid ~ label{
  top: -5px;
  color: 0a8eb6;
}
.txt_field input:focus ~ span::before,
.txt_field input:valid ~ span::before{
  width: 100%;
}
.pass a{
  text-decoration: none!important;
  color: #d1dcdc;
}
.pass  a:hover{
  text-decoration: none!important;
  font-size: 17.8px;
  font-weight: 80px;
}
.pass{
  text-align:right;
  font-size:17px;
  margin: -5px 0 15px;
}
input[type="submit"]{
  width: 100%;
  height: 50px;
  border: 1px solid;
  background: #2691d9;
  border-radius: 25px;
  font-size: 18px;
  color: #e9f4fb;
  font-weight: 700;
  cursor: pointer;
  outline: none;
}
input[type="submit"]:hover{
  border-color: #2691d9;
  transition: .5s;
}
.signup_link{
  margin: 30px 0;
  text-align: center;
  font-size: 16px;
  color: #666666;
}
.signup_link a{
  color: #a6a4a4;
  text-decoration: none;
}
.signup_link a:hover{
  text-decoration: underline;
  color: #b2afaf;
  font-size:17.8px;
}
.txlog{
  font-size:17px;
}
.txlog:hover{
  color: rgb(118, 145, 136);
  font-size: 16.7px;
  font-weight: 80px;
}
</code>```

Body:
I am unable to make this login form responsive. it looks awesome in desktop
I've made this using html and CSS.it looks like the problem is with width or height on opening this on small devices
I've tried using overflow:hidden;
@media width
but it did not worked
I want this to be reponsive as the view of desktop
here's the code
html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Login Form</title>
    <link rel="stylesheet" href="style.css">

Login

      <form method="post">

          <input type="text" required>

          Username

          <input type="password" required>

          Password

Forgot Password ?

        <input type="submit" value="Login">

          Not a member? Signup

      </form>

CSS code

*{
  margin: 0;
  padding: 0;
  font-family: "Poppins", sans-serif;
  /* font-weight: bold; */
}
body{
  margin: 0;
  padding: 0;
  background: linear-gradient(120deg,#4e718a, #3e9778);
  height: 100vh;
  overflow: hidden;
}
.center{
  position: relative;
  top: 50%;
  left: 50%;
  right: 50%;
  transform: translate(-50%, -50%);
  height: 459px;
  width: 359px;
  background: linear-gradient(120deg,#9b3438ce, #8f21a7e8);;
  border-radius: 10px;
  box-shadow: 10px 10px 15px rgb(56 45 45 / 84%);
}
@media (max-width: 920px) {
  .center{
    display:block;
    position:relative;
    height: 76vh;
  width: 70vw;
  }
}
.center h1{
  text-align: center;
  padding: 20px 0;
  border-bottom: 3px solid #93c398;
}
.center form{
  padding: 0 40px;
  box-sizing: border-box;
}
form .txt_field{
  position: relative;
  border-bottom: 2px solid #adadad;
  margin: 30px 0;
}
.txt_field input{
  width: 100%;
  padding: 0 5px;
  height: 40px;
  font-size: 16px;
  border: none;
  background: none;
  outline: none;
}
.txt_field label{
  position: absolute;
  top: 50%;
  left: 5px;
  color: #a4a2a2;
  transform: translateY(-40%);
  font-size: 16px;
  transition: .7s;
}
.txt_field span::before{
  content: '';
  position: absolute;
  top: 40px;
  left: 0;
  width: 0%;
  height: 2px;
  background: #0a8eb6;
  transition: .7s;
}
.txt_field input:focus ~ label,
.txt_field input:valid ~ label{
  top: -5px;
  color: 0a8eb6;
}
.txt_field input:focus ~ span::before,
.txt_field input:valid ~ span::before{
  width: 100%;
}
.pass a{
  text-decoration: none!important;
  color: #d1dcdc;
}
.pass  a:hover{
  text-decoration: none!important;
  font-size: 17.8px;
  font-weight: 80px;
}
.pass{
  text-align:right;
  font-size:17px;
  margin: -5px 0 15px;
}
input[type="submit"]{
  width: 100%;
  height: 50px;
  border: 1px solid;
  background: #2691d9;
  border-radius: 25px;
  font-size: 18px;
  color: #e9f4fb;
  font-weight: 700;
  cursor: pointer;
  outline: none;
}
input[type="submit"]:hover{
  border-color: #2691d9;
  transition: .5s;
}
.signup_link{
  margin: 30px 0;
  text-align: center;
  font-size: 16px;
  color: #666666;
}
.signup_link a{
  color: #a6a4a4;
  text-decoration: none;
}
.signup_link a:hover{
  text-decoration: underline;
  color: #b2afaf;
  font-size:17.8px;
}
.txlog{
  font-size:17px;
}
.txlog:hover{
  color: rgb(118, 145, 136);
  font-size: 16.7px;
  font-weight: 80px;
}


问:
Finding ellipses and distinguishing ellipses that are connected
In the picture there are ellipses that I found but some of them are connected and fitEllipse found them as one and I need to split them into two

I have a problem when finding ellipses, it finds all ellipses, but I need to divide the connected ellipses into two, not one big one, I use fitEllipse, could anyone help me how to do that?

I need to divide one large ellipse as shown in the picture into two, they overlap but I don't know what algorithm to use to draw both like the others.

My code:

```<code>gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
blur = cv2.bilateralFilter(gray, 8, 70, 70)
ret = cv2.threshold(blur, 128, 255, cv2.THRESH_BINARY_INV)[1]
contour, hierarchy = cv2.findContours(ret, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
minEllipse = [None] * len(contour)

for i, c in enumerate(contour):
    if c.shape[0] > 5:
        minEllipse[i] = cv2.fitEllipse(c)
        cv2.ellipse(src, minEllipse[i], (0, 255, 0), 2)

cv2.imwrite('output.png', src)
cv2.imwrite('mask.png', ret)
cv2.imwrite('blur.png', blur)
</code>```

Body:
In the picture there are ellipses that I found but some of them are connected and fitEllipse found them as one and I need to split them into two

I have a problem when finding ellipses, it finds all ellipses, but I need to divide the connected ellipses into two, not one big one, I use fitEllipse, could anyone help me how to do that?

I need to divide one large ellipse as shown in the picture into two, they overlap but I don't know what algorithm to use to draw both like the others.

My code:

gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
blur = cv2.bilateralFilter(gray, 8, 70, 70)
ret = cv2.threshold(blur, 128, 255, cv2.THRESH_BINARY_INV)[1]
contour, hierarchy = cv2.findContours(ret, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
minEllipse = [None] * len(contour)

for i, c in enumerate(contour):
    if c.shape[0] > 5:
        minEllipse[i] = cv2.fitEllipse(c)
        cv2.ellipse(src, minEllipse[i], (0, 255, 0), 2)

cv2.imwrite('output.png', src)
cv2.imwrite('mask.png', ret)
cv2.imwrite('blur.png', blur)


问:
Error: ENOENT: no such file or directory when pasting a file into watched folder
I have an build an app with node.js that watches an folder.

the basic implementation is:

```<code>fs.watch("./folder", async (eventType, filename) => { ... })
</code>```

Now i have a test script that generates an file and place it into this ./folder to see if my app works correct. my problem i face is that i get this error

[Error: ENOENT: no such file or directory, open
'C:\Users\Administrator\Downloads\PontonXP-Messenger-4.0.1-Windows\data\hotfolder-1\inbox\DATEN_CRMSG.xml']
{   errno: -4058,   code: 'ENOENT',   syscall: 'open',   path:
'C:\Users\Administrator\Downloads\PontonXP-Messenger-4.0.1-Windows\data\hotfolder-1\inbox\DATEN_CRMSG.xml'
}

This happens when i try to write an file with fs.writeFile

```<code>export const writeFile = (path: string, file: string) => {
  return new Promise((res, rej) => {
    fs.writeFile(path, file, (err) => {
      if (err) return rej(err);
      res("Done");
    });
  });
};
</code>```

How can i fix this issue?

Body:
I have an build an app with node.js that watches an folder.

the basic implementation is:

fs.watch("./folder", async (eventType, filename) => { ... })

Now i have a test script that generates an file and place it into this ./folder to see if my app works correct. my problem i face is that i get this error

[Error: ENOENT: no such file or directory, open
'C:\Users\Administrator\Downloads\PontonXP-Messenger-4.0.1-Windows\data\hotfolder-1\inbox\DATEN_CRMSG.xml']
{   errno: -4058,   code: 'ENOENT',   syscall: 'open',   path:
'C:\Users\Administrator\Downloads\PontonXP-Messenger-4.0.1-Windows\data\hotfolder-1\inbox\DATEN_CRMSG.xml'
}

This happens when i try to write an file with fs.writeFile

export const writeFile = (path: string, file: string) => {
  return new Promise((res, rej) => {
    fs.writeFile(path, file, (err) => {
      if (err) return rej(err);
      res("Done");
    });
  });
};

How can i fix this issue?


问:
key value pair logging in mongoDB with winston logger (Node.js)
I am using winston logger for my project and I want to log the data in key value pair. Now usung the logger.log is saving the data in string both in local and mongoDB.

My current log style:

```<code>
{
  "_id": {
    "$oid": "638318fb3dc965073547d7d2"
  },
  "timestamp": {
    "$date": {
      "$numberLong": "1669535995715"
    }
  },
  "level": "info",
  "message": "{\"host\":\" api.art.com\",\"sec-ch-ua\":\" \\\"Google Chrome\\\";v=\\\"107\\\", \\\"Chromium\\\";v=\\\"107\\\", \\\"Not=A?Brand\\\";v=\\\"24\\\"\",\"accept\":\" application/json, text/plain, */*\",\"sec-ch-ua-mobile\":\" ?0\",\"user-agent\":\" Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/5.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36\",\"sec-ch-ua-platform\":\" \\\"macOS\\\"\",\"origin\":\" https\",\"sec-fetch-site\":\" cross-site\",\"sec-fetch-mode\":\" cors\",\"sec-fetch-dest\":\" empty\",\"referer\":\" https\",\"accept-encoding\":\" gzip,br\",\"accept-language\":\" en-GB,en-US;q=0.9,en;q=0.8\",\"if-none-match\":\" W/\\\"5f-B4TLD546Jcb2654ETkG654moW8/BMueSrsMk\\\"\",\"x-forwarded-proto\":\" https\",\"x-https\":\" on\",\"x-forwarded-for\":\" 1**.*1.**1.1*8,1*2.*13.***.39\",\"connection\":\" keep-alive\",\"x-forwarded-host\":\" api.art.com\",\"ip\":\"127.0.0.1\",\"url\":\"/api/checklogdata\",\"method\":\"GET\"}",
  "meta": null
}

</code>```

But I was wondeing if I could log like following: (JSON - Key value pair)

```<code>
{
  "_id": {
    "$oid": "638318fb3dc965073547d7d2"
  },
  "timestamp": {
    "$date": {
      "$numberLong": "1669535995715"
    }
  },
  "level": "info",
  "ip": "ip",
  "url": "url",
  "method": "method",
  "message": "",
  "meta": null
}

</code>```

Is there a way to do it with the winston logger package? I mean i can do this manually by grabbing req and destructing the datas from that and store it to mongodb but doing it with winston will be lot easier.

Body:
I am using winston logger for my project and I want to log the data in key value pair. Now usung the logger.log is saving the data in string both in local and mongoDB.

My current log style:

{
  "_id": {
    "$oid": "638318fb3dc965073547d7d2"
  },
  "timestamp": {
    "$date": {
      "$numberLong": "1669535995715"
    }
  },
  "level": "info",
  "message": "{\"host\":\" api.art.com\",\"sec-ch-ua\":\" \\\"Google Chrome\\\";v=\\\"107\\\", \\\"Chromium\\\";v=\\\"107\\\", \\\"Not=A?Brand\\\";v=\\\"24\\\"\",\"accept\":\" application/json, text/plain, */*\",\"sec-ch-ua-mobile\":\" ?0\",\"user-agent\":\" Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/5.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36\",\"sec-ch-ua-platform\":\" \\\"macOS\\\"\",\"origin\":\" https\",\"sec-fetch-site\":\" cross-site\",\"sec-fetch-mode\":\" cors\",\"sec-fetch-dest\":\" empty\",\"referer\":\" https\",\"accept-encoding\":\" gzip,br\",\"accept-language\":\" en-GB,en-US;q=0.9,en;q=0.8\",\"if-none-match\":\" W/\\\"5f-B4TLD546Jcb2654ETkG654moW8/BMueSrsMk\\\"\",\"x-forwarded-proto\":\" https\",\"x-https\":\" on\",\"x-forwarded-for\":\" 1**.*1.**1.1*8,1*2.*13.***.39\",\"connection\":\" keep-alive\",\"x-forwarded-host\":\" api.art.com\",\"ip\":\"127.0.0.1\",\"url\":\"/api/checklogdata\",\"method\":\"GET\"}",
  "meta": null
}

But I was wondeing if I could log like following: (JSON - Key value pair)

{
  "_id": {
    "$oid": "638318fb3dc965073547d7d2"
  },
  "timestamp": {
    "$date": {
      "$numberLong": "1669535995715"
    }
  },
  "level": "info",
  "ip": "ip",
  "url": "url",
  "method": "method",
  "message": "",
  "meta": null
}

Is there a way to do it with the winston logger package? I mean i can do this manually by grabbing req and destructing the datas from that and store it to mongodb but doing it with winston will be lot easier.


问:
Not Opening JAR Files On Windows 10
I am unable to open JAR files on my Windows 10 computer. Is it necessary to install a tool or software to open JAR files? I am utterly confused. Please help friends.

No, I am not expert on this field. So I am asking it here.

Title: Not Opening JAR Files On Windows 10


问:
schedule conflict flutter firebase in adding a date that has already been taken
I am trying to achieve schedule conflict in my uni app, itenerary, where  a user wouldnt be allowed to add a trip that has a date that is already taken.

I am struggling to get the right query but this is what i have tried

```<code>List dateinput= [];

DateTime? pickeddate = await showDatePicker(context: context,
                      initialDate:DateTime.now(),
                     firstDate: DateTime.now().subtract(Duration(days: 0)),
                     lastDate: DateTime(2025));
                     setState(() {
                       date.text= DateFormat('yyyy-MM-dd').format(pickeddate!);
                                });

//my query
final collection = FirebaseFirestore.instance.collection('UserTrip')
                                    .orderBy('tripDate')
                                    .get()
                                    .then((value) =>
                                        value.docs.forEach((element) {
                                          List data1 = element.data() as List;
                                          dateinput.add(data1);
                                          print(dateinput);
                                        }));

//and I'm trying to implement that return error on pressed on the add trip button
 if (dateinput.contains(date.text)) {
                                //return error
                              } else {
                                uploadFile();}
</code>```

Body:
I am trying to achieve schedule conflict in my uni app, itenerary, where  a user wouldnt be allowed to add a trip that has a date that is already taken.

I am struggling to get the right query but this is what i have tried

List dateinput= [];

DateTime? pickeddate = await showDatePicker(context: context,
                      initialDate:DateTime.now(),
                     firstDate: DateTime.now().subtract(Duration(days: 0)),
                     lastDate: DateTime(2025));
                     setState(() {
                       date.text= DateFormat('yyyy-MM-dd').format(pickeddate!);
                                });

//my query
final collection = FirebaseFirestore.instance.collection('UserTrip')
                                    .orderBy('tripDate')
                                    .get()
                                    .then((value) =>
                                        value.docs.forEach((element) {
                                          List data1 = element.data() as List;
                                          dateinput.add(data1);
                                          print(dateinput);
                                        }));

//and I'm trying to implement that return error on pressed on the add trip button
 if (dateinput.contains(date.text)) {
                                //return error
                              } else {
                                uploadFile();}


问:
How to authenticate to Gmail API in GCP environment without explicitly referring to a service account file or info
I am writing a script that will authenticate to the Gmail API, pull some emails and transform some email data. I can get this working locally since I have the service account file which I am creating a credentials object from and then referencing in the Gmail API, however since this will be running in Google Cloud Product (GCP) the credentials are stored in the environment.

I need to somehow either modify the code to not reference credentials or retrieve a credentials object in the environment.

The code below works locally, however where I am creating the credentials object, I either need to retrieve that from the environment or authenticate in a different way when creating the delegated_credentials and service objects.

```<code>from googleapiclient.discovery import build
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
SERVICE_ACCOUNT_FILE = 'secret.json'

credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)

delegated_credentials = credentials.with_subject('someone@gmail.com')
service = build('gmail', 'v1', credentials=delegated_credentials)
</code>```

As an example, when using the google cloud storage API, I create the client in GCP as follow:

```<code>storage_client = storage.Client()
</code>```

Body:
I am writing a script that will authenticate to the Gmail API, pull some emails and transform some email data. I can get this working locally since I have the service account file which I am creating a credentials object from and then referencing in the Gmail API, however since this will be running in Google Cloud Product (GCP) the credentials are stored in the environment.

I need to somehow either modify the code to not reference credentials or retrieve a credentials object in the environment.

The code below works locally, however where I am creating the credentials object, I either need to retrieve that from the environment or authenticate in a different way when creating the delegated_credentials and service objects.

from googleapiclient.discovery import build
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
SERVICE_ACCOUNT_FILE = 'secret.json'

credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)

delegated_credentials = credentials.with_subject('someone@gmail.com')
service = build('gmail', 'v1', credentials=delegated_credentials)

As an example, when using the google cloud storage API, I create the client in GCP as follow:

storage_client = storage.Client()


问:
Connect MongoDB to Python
I try to connect to MongoDB database from https://cloud.mongodb.com/

My code:

```<code>import pymongo
from pymongo.server_api import ServerApi

client = pymongo.MongoClient("mongodb+srv://<My-Username:<My-Password@test.umh3xqu.mongodb.net/?retryWrites=true&w=majority", server_api=ServerApi('1'))

print(client.list_database_names())`

</code>```

Errors:
pymongo.errors.ServerSelectionTimeoutError: ac-gyw4foz-shard-00-01.umh3xqu.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992),ac-gyw4foz-shard-00-00.umh3xqu.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992),ac-gyw4foz-shard-00-02.umh3xqu.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED]

How to fix???

List all databases

Title: Connect MongoDB to Python

Body:
I try to connect to MongoDB database from https://cloud.mongodb.com/

My code:

import pymongo
from pymongo.server_api import ServerApi

client = pymongo.MongoClient("mongodb+srv://<My-Username:<My-Password@test.umh3xqu.mongodb.net/?retryWrites=true&w=majority", server_api=ServerApi('1'))

print(client.list_database_names())`

Errors:
pymongo.errors.ServerSelectionTimeoutError: ac-gyw4foz-shard-00-01.umh3xqu.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992),ac-gyw4foz-shard-00-00.umh3xqu.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992),ac-gyw4foz-shard-00-02.umh3xqu.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED]

How to fix???

List all databases


问:
Visual Studio 2022 Multi Project Template - Failure to load type
We have a Visual Studio custom multi project template which was working fine in VS 2019.
However when we start using the same in VS 2022 it is giving error "Failure to load type" while creating new project using the template.
How can I resolve or find root cause for the issue.</p>


问:
How to get the column name with the its count distinct in flask-sqlalchemy?
I don't know how to select the column value with its count in flask-sqlalchemy.

I've used SELECT browser, COUNT(browser) FROM visitor_stats GROUP BY browser; to get the browser name column with its count using group by in SQL, but I cannot transform it into flask-sqlalchemy function.


问:
CSS making image size same in React Project
I work on the project about my travel in React. Data is provided from another file. Simple design: images should be on the left side and info covers right side. I have used display:flex on container div, width used on img-div and img, however images have different size. What should I do for fixing the size problem?

Thank you for the taking time.

```<code>* {
    margin: 0;
    box-sizing: border-box;
}

.trip-container {
    display: flex;
}

.img-div {
    width: 100%;
}

.img-div > img {
    width: 100%;
    object-fit: cover;
}

.info-div {
    display: flex;
    flex-direction: column;
}

.country-div {
    display: flex;
}
</code>```

and here is HTML:

```<code><>
            <div className="trip-container">
                <div className="img-div">
                    <img src={props.trip.img}
                    alt="city" />
                </div>
                <div className="info-div">
                    <div className="country-div">
                        <i className="fa-solid fa-location-dot"></i>
                        <h5>{props.trip.country}</h5>
                        <a href={props.trip.gps}>
                            <p>
                                View on Google Maps
                            </p>
                        </a>
                    </div>
                    <h1>{props.trip.destination}</h1>
                    <p><strong>{props.trip.date}</strong></p>
                    <p>{props.trip.info}</p>
                </div>
            </div>
        </>
</code>```

Body:
I work on the project about my travel in React. Data is provided from another file. Simple design: images should be on the left side and info covers right side. I have used display:flex on container div, width used on img-div and img, however images have different size. What should I do for fixing the size problem?

Thank you for the taking time.

* {
    margin: 0;
    box-sizing: border-box;
}

.trip-container {
    display: flex;
}

.img-div {
    width: 100%;
}

.img-div > img {
    width: 100%;
    object-fit: cover;
}

.info-div {
    display: flex;
    flex-direction: column;
}

.country-div {
    display: flex;
}

and here is HTML:

<>

{props.trip.country}

                                View on Google Maps

{props.trip.destination}

{props.trip.date}

{props.trip.info}

        </>


问:
How can we use Inorder traversal of a tree with multiple elements per leaf?
I have the following code to translate the InOrder of a Binary Tree:

```<code>ArrayList* BinaryTreeInOrder( BTNode* leaf, ArrayList* list ) {

/* if we reach the end of a branch */
if (leaf == NULL) return list;

/* first recur on left child */
BinaryTreeInOrder(leaf->left_child, list);

/* then add the data of node to the list */
ArrayList* nodelist = leaf->list;
for (int i = 0; i < nodelist->size; i++)
{
    Job* temp = getArray( nodelist, i );
    insertArray( list, temp );
}

/* now recur on right child */
 BinaryTreeInOrder(leaf->right_child, list);
}
</code>```

The ArrayList struct pointer has the functionality for insertion and has a size. In Addition each leaf carries an ArrayList for internal elements. I'd like to return the ArrayList containing the InOrder of the Binary Tree while there are multiple elements stored in each leaf. This function only return's from the first leaf/source.

Body:
I have the following code to translate the InOrder of a Binary Tree:

ArrayList* BinaryTreeInOrder( BTNode* leaf, ArrayList* list ) {

/* if we reach the end of a branch */
if (leaf == NULL) return list;

/* first recur on left child */
BinaryTreeInOrder(leaf->left_child, list);

/* then add the data of node to the list */
ArrayList* nodelist = leaf->list;
for (int i = 0; i < nodelist->size; i++)
{
    Job* temp = getArray( nodelist, i );
    insertArray( list, temp );
}

/* now recur on right child */
 BinaryTreeInOrder(leaf->right_child, list);
}

The ArrayList struct pointer has the functionality for insertion and has a size. In Addition each leaf carries an ArrayList for internal elements. I'd like to return the ArrayList containing the InOrder of the Binary Tree while there are multiple elements stored in each leaf. This function only return's from the first leaf/source.


问:
ERROR in src/App.tsx- TS2786: 'UserList' cannot be used as a JSX component. Its return type 'void' is not a valid JSX element
I am working in typescript using react platform (in VS code). I am facing the above error and I tried lot of solutions people have been discussed on forum but the issue still exist. Need help if someone has already resolved it.

I have a static Array named userList (in App.tsx file) and I declared type for it named UserType (in same file) and I'm trying to pass **userList **as a prop to next component (UserList.tsx).

In App.tsx file code where I got an error
`

```<code>import UserList from "./components/UserList";

function App() {
  console.log(userList);
 return (
    <div className="App">
      <UserList userProp={userList} />
    </div>
  )
}

export default App;
</code>```

`

UserList.tsx component/file where I'm trying to pass my prop (array)
`

```<code>import React from "react";
import {UserType} from "../App";

export default function UserList({userProp}: {userProp: UserType[]}) {
  console.log(userProp);
  //return <div>User</div>;
}
</code>```

`

package.json dependencies

`

```<code>{
  "name": "typescript-basic",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.7.13",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@types/react-router-dom": "^5.3.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.4.2",
    "web-vitals": "^2.1.0"
  }
</code>```

`

Please need help regarding this issue

Body:
I am working in typescript using react platform (in VS code). I am facing the above error and I tried lot of solutions people have been discussed on forum but the issue still exist. Need help if someone has already resolved it.

I have a static Array named userList (in App.tsx file) and I declared type for it named UserType (in same file) and I'm trying to pass **userList **as a prop to next component (UserList.tsx).

In App.tsx file code where I got an error
`

import UserList from "./components/UserList";

function App() {
  console.log(userList);
 return (

      <UserList userProp={userList} />

  )
}

export default App;

`

UserList.tsx component/file where I'm trying to pass my prop (array)
`

import React from "react";
import {UserType} from "../App";

export default function UserList({userProp}: {userProp: UserType[]}) {
  console.log(userProp);
  //return
User
;
}

`

package.json dependencies

`

{
  "name": "typescript-basic",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.7.13",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@types/react-router-dom": "^5.3.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.4.2",
    "web-vitals": "^2.1.0"
  }

`

Please need help regarding this issue


问:
How to get only 2 values after the decimal point in XSLT?
I have an value 938.2348

I want in decimal like 938.23 instead of full value.

How I can achieve this via XSLT 1.0?


问:
Next.js API's config object is not working on production level
Hy,
I'm working on project. I just want to disable the native bodyparcer of next.js and use formidable's parse for incoming requests. I am sending file and some other data from frontend and saveing file on my file system and other data in mongodb.
I did a following configuration for it in that end point.

```<code>export const config = {
  api: {
    bodyParser: false,
  },
}
</code>```

The full code is here.

```<code>const fs = require("fs");
const path = require("path")
const decompress = require("decompress");
import formidable from "formidable";

import connect from "../../../database/connect";
import Proposal from "../../../database/models/propSchema";

const directoryPath = e => path.join(process.cwd(), e),
videosDir = directoryPath("/public/videos")

export default function handler(req, res){
  res.setHeader("Content-Type", "application/json");
  if(req.method === 'POST')
  {
    console.log(req.method)
    const form = new formidable.IncomingForm();
    form.parse(req,(err, fields, files) => {
      if(err && !files.file){
        return res.status(404).json({status: false, error: "Error: Request is not parsed correctly"})
      }
      console.log("----------------------------",form._parser.globalOptions.maxFileSize)
      console.log(files, fields);

      const {client,published} = fields,
            id = Math.random().toString(36).substring(2) +
            (new Date()).getTime().toString(36);

      decompress(files.zipFile.filepath, videosDir + "/" + id)
      .then(files => {
        console.log(files)

        console.log(`Proposal API is called with following queries id:${id} and client:${JSON.stringify(client)}`)
        connect().catch(error => console.log(error))
        const proposal = new Proposal({id,client,published: published? JSON.parse(published) : true})
        proposal.save()
        .then(()=>{
            res.status(200).json(proposal)
        })
      })
      .catch((err) => {
        console.log(err);
        const path = `${videosDir}/${id}`;
        if(fs.existsSync(path)){
        fs.readdirSync(path).forEach((file) => fs.unlinkSync(path + "/" + file));
        fs.rmdirSync(path);
        }

        res.status(400).json({
          status: "fail",
          info: `${id} cannot be compress and Published`,
          err,
        });
      });

    });

  }
  else{
    res.setHeader('Allow', 'POST');
    res.status(403).json({status: false , discription: "This method is not allowed." })
  }

}

export const config = {
  api: {
    bodyParser: false,
  },
}
</code>```

I make another endpoint to make code simple to understand and remove all code that is unrelative to this error. The same error is occuring with both endpoints.

```<code>export const config = {
  api: {
    bodyParser: false,
  },
}

export default function handler(req, res){
  if(req.method !== 'POST')
  {
    res.setHeader('Allow', 'POST');
    return res.status(403).json({status: false , discription: "This method is not allowed." })
  }
  res.status(200).json({status: true});

};
</code>```

So, When I run it on my local environment and send data, it works fine but in production, it gives a "413 Request Entity Too Large" error. This is because I think the config object is not working correctly on a production level.
Because 1 MB is the maximum file limit of next.js body-parser and when I try to upload a file less than 1 MB it also works fine in production and local system. But when exceeding that limit it gives that error.
And I also try in my local system to send large files without the above configuration, in this case, it gives the same error.

Is this error in the config object? and who can I solve this error?Please help me also to understand it. Thanks

Body:
Hy,
I'm working on project. I just want to disable the native bodyparcer of next.js and use formidable's parse for incoming requests. I am sending file and some other data from frontend and saveing file on my file system and other data in mongodb.
I did a following configuration for it in that end point.

export const config = {
  api: {
    bodyParser: false,
  },
}

The full code is here.

const fs = require("fs");
const path = require("path")
const decompress = require("decompress");
import formidable from "formidable";

import connect from "../../../database/connect";
import Proposal from "../../../database/models/propSchema";

const directoryPath = e => path.join(process.cwd(), e),
videosDir = directoryPath("/public/videos")

export default function handler(req, res){
  res.setHeader("Content-Type", "application/json");
  if(req.method === 'POST')
  {
    console.log(req.method)
    const form = new formidable.IncomingForm();
    form.parse(req,(err, fields, files) => {
      if(err && !files.file){
        return res.status(404).json({status: false, error: "Error: Request is not parsed correctly"})
      }
      console.log("----------------------------",form._parser.globalOptions.maxFileSize)
      console.log(files, fields);

      const {client,published} = fields,
            id = Math.random().toString(36).substring(2) +
            (new Date()).getTime().toString(36);

      decompress(files.zipFile.filepath, videosDir + "/" + id)
      .then(files => {
        console.log(files)

        console.log(`Proposal API is called with following queries id:${id} and client:${JSON.stringify(client)}`)
        connect().catch(error => console.log(error))
        const proposal = new Proposal({id,client,published: published? JSON.parse(published) : true})
        proposal.save()
        .then(()=>{
            res.status(200).json(proposal)
        })
      })
      .catch((err) => {
        console.log(err);
        const path = `${videosDir}/${id}`;
        if(fs.existsSync(path)){
        fs.readdirSync(path).forEach((file) => fs.unlinkSync(path + "/" + file));
        fs.rmdirSync(path);
        }

        res.status(400).json({
          status: "fail",
          info: `${id} cannot be compress and Published`,
          err,
        });
      });

    });

  }
  else{
    res.setHeader('Allow', 'POST');
    res.status(403).json({status: false , discription: "This method is not allowed." })
  }

}

export const config = {
  api: {
    bodyParser: false,
  },
}

I make another endpoint to make code simple to understand and remove all code that is unrelative to this error. The same error is occuring with both endpoints.

export const config = {
  api: {
    bodyParser: false,
  },
}

export default function handler(req, res){
  if(req.method !== 'POST')
  {
    res.setHeader('Allow', 'POST');
    return res.status(403).json({status: false , discription: "This method is not allowed." })
  }
  res.status(200).json({status: true});

};

So, When I run it on my local environment and send data, it works fine but in production, it gives a "413 Request Entity Too Large" error. This is because I think the config object is not working correctly on a production level.
Because 1 MB is the maximum file limit of next.js body-parser and when I try to upload a file less than 1 MB it also works fine in production and local system. But when exceeding that limit it gives that error.
And I also try in my local system to send large files without the above configuration, in this case, it gives the same error.

Is this error in the config object? and who can I solve this error?Please help me also to understand it. Thanks


问:
How to develop an Android APP to transfer pictures with a USB device?
I want to develop an Android APP to transfer pictures with USB device. And I have finished the development of Android User Interface, the connection with USB device by Android USB API according official guide (https://developer.android.com/guide/topics/connectivity/usb/host).

But when I try to transfer data with the device, the guide just provides only one function : bulkTransfer(). So I don't know how to do next because I just only have Android developing experience.

Then I search in the github and find a lib-libaums is awesome. But I don't know the theory under this project.

Is there some tutorial to help me to develop the remain part of my APP? Or is there some theoretical guide to help me to develop a simple version of libaums? @Magnus


问:
How to split up an email body that contains replies (i.e. an email thread)?
I am reading an email body using the python imap and email libraries:

import imaplib
from email import message_from_bytes

imap = imaplib.IMAP4_SSL(host)
imap.login(email_address, pw)
_, output = imap.fetch("100", "(RFC822)")
raw_output = output[0]
msg = message_from_bytes(raw_output[1])
body = msg.get_payload(decode=True).decode()
```
<p>However, the body has the replies of many other emails in a chain:</p>
```second reply
________________________________
From: bob <bob@gmail.com>
Sent: 10 December 2022 11:35
To: susan <susan@outlook.com>
Subject: Re: creating a test thread

first reply

On 10 Dec 2022, at 11:34, blah dev <susan@outlook.com<mailto:susan@outlook.com>> wrote:

first message
```

Is there an easy way/library to strip/split the replies in the chain (especially given that the reply formatting seems to vary between email providers)?
i.e. something like a list ["second reply", "first reply", "first message" ]

Body:
I am reading an email body using the python imap and email libraries:

import imaplib
from email import message_from_bytes

imap = imaplib.IMAP4_SSL(host)
imap.login(email_address, pw)
_, output = imap.fetch("100", "(RFC822)")
raw_output = output[0]
msg = message_from_bytes(raw_output[1])
body = msg.get_payload(decode=True).decode()

However, the body has the replies of many other emails in a chain:

second reply
________________________________
From: bob <bob@gmail.com>
Sent: 10 December 2022 11:35
To: susan <susan@outlook.com>
Subject: Re: creating a test thread

first reply

On 10 Dec 2022, at 11:34, blah dev <susan@outlook.com<mailto:susan@outlook.com>> wrote:

first message

Is there an easy way/library to strip/split the replies in the chain (especially given that the reply formatting seems to vary between email providers)?
i.e. something like a list ["second reply", "first reply", "first message" ]


问:
Angular and Firebase issues
I develop an application in angular, where i use firebase as my backend. My problem is when i want to put image in storage it work good, but i can keep the download url in firestore.</p>
```<code>"dependencies": {
    "@angular/animations": "^14.0.0",
    "@angular/cdk": "^14.1.2",
    "@angular/common": "^14.0.0",
    "@angular/compiler": "^14.0.0",
    "@angular/core": "^14.0.0",
    "@angular/fire": "^7.4.1",
    "@angular/forms": "^14.0.0",
    "@angular/material": "^14.1.2",
    "@angular/platform-browser": "^14.0.0",
    "@angular/platform-browser-dynamic": "^14.0.0",
    "@angular/router": "^14.0.0",
    "@fortawesome/fontawesome-free": "^6.1.2",
    "@ngx-translate/core": "^14.0.0",
    "@ngx-translate/http-loader": "^7.0.0",
    "bootstrap": "^5.2.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.0.5",
    "@angular/cli": "~14.0.5",
    "@angular/compiler-cli": "^14.0.0",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.1.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.7.2"
  }
</code>```
```<code>public addImg(){
    const storageRef = ref(this.storage, `equipe_img/${this.file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, this.file);
    uploadTask.on('state_changed',
    (snapshot) =>{
      const progress = (snapshot.bytesTransferred / snapshot.totalBytes * 100);
      console.log('upload is ' + progress + '% done');
    },
    (error) => {
      console.log(error.message);
    },
    () => {
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) =>{
        this.image_url = downloadURL;
        console.log('File available at', this.image_url);
      });
    })
  }
</code>```
```<code> ngOnInit(): void {
    this.getEquipe();
    this.myForm = this.fb.group({
      Fname: ['', Validators.required],
      Lname: ['', Validators.required],
      Role : ['', Validators.required],
      PName: [this.image_url]
    });
  }
</code>```

Title: Angular and Firebase issues

Body:
I develop an application in angular, where i use firebase as my backend. My problem is when i want to put image in storage it work good, but i can keep the download url in firestore.

"dependencies": {
    "@angular/animations": "^14.0.0",
    "@angular/cdk": "^14.1.2",
    "@angular/common": "^14.0.0",
    "@angular/compiler": "^14.0.0",
    "@angular/core": "^14.0.0",
    "@angular/fire": "^7.4.1",
    "@angular/forms": "^14.0.0",
    "@angular/material": "^14.1.2",
    "@angular/platform-browser": "^14.0.0",
    "@angular/platform-browser-dynamic": "^14.0.0",
    "@angular/router": "^14.0.0",
    "@fortawesome/fontawesome-free": "^6.1.2",
    "@ngx-translate/core": "^14.0.0",
    "@ngx-translate/http-loader": "^7.0.0",
    "bootstrap": "^5.2.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.0.5",
    "@angular/cli": "~14.0.5",
    "@angular/compiler-cli": "^14.0.0",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.1.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.7.2"
  }

public addImg(){
    const storageRef = ref(this.storage, `equipe_img/${this.file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, this.file);
    uploadTask.on('state_changed',
    (snapshot) =>{
      const progress = (snapshot.bytesTransferred / snapshot.totalBytes * 100);
      console.log('upload is ' + progress + '% done');
    },
    (error) => {
      console.log(error.message);
    },
    () => {
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) =>{
        this.image_url = downloadURL;
        console.log('File available at', this.image_url);
      });
    })
  }

 ngOnInit(): void {
    this.getEquipe();
    this.myForm = this.fb.group({
      Fname: ['', Validators.required],
      Lname: ['', Validators.required],
      Role : ['', Validators.required],
      PName: [this.image_url]
    });
  }


问:
How do I dynamically change the body tag in React/NextJS when a state changes?
I'm trying to create a theme system using Tailwind, React, and NextJS, and I'm doing so by updating the class name of a given tag to the current theme name. This works fine for tags within the main app component, but how can I dynamically change the class of the body tag once my theme state changes?

For example, if I have theme A selected then the  should have a background color of black. If theme B is selected then  should have a background color of red.

Themes will change based on state, so I imagine it should look something like this:

const App = () => {
  const theme = themeGetter()

  return (

      ...

  )
}
```

But obviously, this won't actually change the classname of the body. Is there an easy way to accomplish this?

Body:
I'm trying to create a theme system using Tailwind, React, and NextJS, and I'm doing so by updating the class name of a given tag to the current theme name. This works fine for tags within the main app component, but how can I dynamically change the class of the body tag once my theme state changes?

For example, if I have theme A selected then the  should have a background color of black. If theme B is selected then  should have a background color of red.

Themes will change based on state, so I imagine it should look something like this:

const App = () => {
  const theme = themeGetter()

  return (

      ...

  )
}

But obviously, this won't actually change the classname of the body. Is there an easy way to accomplish this?


问:
BigDecimal serialization with unknown scale and precision
I am trying to serialize a data class using Avro4k.

```<code>@Serializable
class Aggregator(
    @ScalePrecision(10, 10)
    @Serializable(with = BigDecimalSerializer::class)
    val value: BigDecimal
)
</code>```

The problem is that I don't know the scale and precision of the BigDecimal beforehand, and I get rounding errors if they are not big enough.

Is there a way to not inform the scale and precision, and use whatever values the provided object have? I don't know if Avro / Avro4k would support that.

Body:
I am trying to serialize a data class using Avro4k.

@Serializable
class Aggregator(
    @ScalePrecision(10, 10)
    @Serializable(with = BigDecimalSerializer::class)
    val value: BigDecimal
)

The problem is that I don't know the scale and precision of the BigDecimal beforehand, and I get rounding errors if they are not big enough.

Is there a way to not inform the scale and precision, and use whatever values the provided object have? I don't know if Avro / Avro4k would support that.


问:
Android Studio finding apps in the wrong file directory
```<code>public void getallapps(View view) {
    List<ApplicationInfo> packList = getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
    for (ApplicationInfo packageInfo : packList) {
        if ((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
            String currAppName = getPackageManager().getApplicationLabel(packageInfo).toString();
            Log.d("System", currAppName);
        } else {
            String currAppName = getPackageManager().getApplicationLabel(packageInfo).toString();
            Log.d("Games", currAppName);
        }
    }
}
</code>```

The code prints system apps and non-system apps; however, it only finds some of the apps. How can I change the file directory?

I have found that apps are stored in the "android/data" portion of the device yet cannot change Android Studio

Body:
public void getallapps(View view) {
    List<ApplicationInfo> packList = getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
    for (ApplicationInfo packageInfo : packList) {
        if ((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
            String currAppName = getPackageManager().getApplicationLabel(packageInfo).toString();
            Log.d("System", currAppName);
        } else {
            String currAppName = getPackageManager().getApplicationLabel(packageInfo).toString();
            Log.d("Games", currAppName);
        }
    }
}

The code prints system apps and non-system apps; however, it only finds some of the apps. How can I change the file directory?

I have found that apps are stored in the "android/data" portion of the device yet cannot change Android Studio


问:
Why is vectorize so much slower with mpmath than just math
I'm trying to lower the error of my floating point calculation, to this end I wanted to use python mpmath to utilize the arbitrary precision of the library. But I notice that it is much slower than the math.

Consider the program

```<code>import math
import numpy as np
mathsin = np.vectorize(math.sin)
mathsin(np.arange(1,10**7)
</code>```

this take around a second or two, if I do this with mpmath

```<code>import mpmath as mp
import numpy as np
mpsin = np.vectorize(mp.sin)
mpsin(np.arange(1,10**7)
</code>```

this takes around forty second even if I lower the default settings of precision with mp.prec and mp.dps.
Is there a way to speed up such process for mpmath? And are there any general tips to making mpmath faster when using it also with numpy?

Body:
I'm trying to lower the error of my floating point calculation, to this end I wanted to use python mpmath to utilize the arbitrary precision of the library. But I notice that it is much slower than the math.

Consider the program

import math
import numpy as np
mathsin = np.vectorize(math.sin)
mathsin(np.arange(1,10**7)

this take around a second or two, if I do this with mpmath

import mpmath as mp
import numpy as np
mpsin = np.vectorize(mp.sin)
mpsin(np.arange(1,10**7)

this takes around forty second even if I lower the default settings of precision with mp.prec and mp.dps.
Is there a way to speed up such process for mpmath? And are there any general tips to making mpmath faster when using it also with numpy?


问:
my asp.net core web page on plesk shows a blank page
i have an asp.net core 5 project, i have copy my project in httpdocs folder and create my database,but my web page shows a blank page,what's the reason? i have used .net 5.0 in my project , but i don't know what's it exactly, there are sdk's 5.0.403 , 5.0.404 , 5.0.407 and .net core 5.0.12, 5.0.13 5.0.17 in my pc,but i don't know which version my project uses, just i know it's 5.0,i called to my server's support and they told that sdk 5 and asp.net core 5 is installed in the host, can anybody help me?</p>


问:
Pascal's triangle with modification
I wrote a function to print Pascal's triangle with modifications.
The sides of the triangle will appear in ascending order instead of the value 1.
Each values at the base of the triangle will continue to contain the sum of the 2 members above it.
Also need to print the max value of a given level.
Example :

Pascal Triangle With Modification Example

```<code>void printTriangle2(int rows,int level) {
    int i =0,j = 0,space,res = 0, isLevel = 0,max = 0;
    for (i = 0 ; i<rows ; i++){
        if (i == level)
            isLevel = 1;
        else isLevel = 0;
        for (space = 1 ; space <= rows - i ; space++) {
            printf(" ");
        }
        for (j = 0 ; j <= i ; j++) {
            if (i == 0 || j == 0)
                res++;
            else  {
                res = res * (i - j + 1) / j;
            }
            if (isLevel == 1) {
               if (res > max)
                max = res;
            }
            printf("%4d",res);
        }
        printf("\n");
    }
    printf(" the max value is : %d",max);
}
</code>```

my output for the input rows = 5 , level = 3:

Output Example

I have an issue with the calculation of res if the value is not in the side of the triangle

```<code>res = res * (i - j + 1) / j;
</code>```

What am I doing wrong?

Title: Pascal's triangle with modification

Body:
I wrote a function to print Pascal's triangle with modifications.
The sides of the triangle will appear in ascending order instead of the value 1.
Each values at the base of the triangle will continue to contain the sum of the 2 members above it.
Also need to print the max value of a given level.
Example :

Pascal Triangle With Modification Example

void printTriangle2(int rows,int level) {
    int i =0,j = 0,space,res = 0, isLevel = 0,max = 0;
    for (i = 0 ; i<rows ; i++){
        if (i == level)
            isLevel = 1;
        else isLevel = 0;
        for (space = 1 ; space <= rows - i ; space++) {
            printf(" ");
        }
        for (j = 0 ; j <= i ; j++) {
            if (i == 0 || j == 0)
                res++;
            else  {
                res = res * (i - j + 1) / j;
            }
            if (isLevel == 1) {
               if (res > max)
                max = res;
            }
            printf("%4d",res);
        }
        printf("\n");
    }
    printf(" the max value is : %d",max);
}

my output for the input rows = 5 , level = 3:

Output Example

I have an issue with the calculation of res if the value is not in the side of the triangle

res = res * (i - j + 1) / j;

What am I doing wrong?


问:
React - 504 Gateway Timeout when proxying
I'm using http-proxy-middleware to proxy some requests.
I can proxy correct some APIs but I'm getting 504 in one of them.

I believe this has something to do with the network (corp laptop).

I've run all of these commands to make sure it's all set corretly. My password has the character . (the dot). I don't think it has anything to do with it.. but we never now. I've also tried the base64 just in case but got the same result.

```<code>npm config set registry http://registry.npmjs.org/
npm config set http-proxy http://username:password@ip:port
npm config set https-proxy http://username:password@ip:port
npm config set proxy http://username:password@ip:port
npm set strict-ssl false
</code>```

I'm getting this in the console:

[HPM] Error occurred while proxying request localhost:3000/produXXXXXXXXXXXX to https://XXXXXXXX [ENOTFOUND] (https://nodejs.org/api/errors.html#errors_common_system_errors)

Just replaced with XXXX because it's a corp url.
It works perfectly from postman with the same proxy server auth.
Any advice?
Thanks!

Body:
I'm using http-proxy-middleware to proxy some requests.
I can proxy correct some APIs but I'm getting 504 in one of them.

I believe this has something to do with the network (corp laptop).

I've run all of these commands to make sure it's all set corretly. My password has the character . (the dot). I don't think it has anything to do with it.. but we never now. I've also tried the base64 just in case but got the same result.

npm config set registry http://registry.npmjs.org/
npm config set http-proxy http://username:password@ip:port
npm config set https-proxy http://username:password@ip:port
npm config set proxy http://username:password@ip:port
npm set strict-ssl false

I'm getting this in the console:

[HPM] Error occurred while proxying request localhost:3000/produXXXXXXXXXXXX to https://XXXXXXXX [ENOTFOUND] (https://nodejs.org/api/errors.html#errors_common_system_errors)

Just replaced with XXXX because it's a corp url.
It works perfectly from postman with the same proxy server auth.
Any advice?
Thanks!


问:
JVM/pod is not releasing memory even traffic cool down on k8s
Curranty our application is running on k8s with openjedk version8.
we already setup resource limit and request for application. when traffic goes high memory consumption increases but when traffic cool down pod/JVM is not releasing the occupied memory. it always runs on high limit.

Please help me into how release memory when traffic will cool down form application