问:
Freeing an already allocated memory by C.free(unsafe.Pointer) is crashing my program
I'm calling C APIs defined in another C library (main.dll) from my go code using cgo. The C API returns a ApiResponse pointer which populates error code and message. The memory for ApiResponsePtr is allocated by C API. After using this, when I call C.free to free the allocated memory, it crashes.

Crash log says : exit status 0xc0000374

Below is the working code, which can be used as it is.
Note I've used MSVC to create a main.dll from the main.c and main.h file. The same main.dll is linked in my go code.

main.go

```<code>package main

/*
#cgo CFLAGS: -g -Wall
#cgo CFLAGS: -I./
#cgo LDFLAGS: -L./ -lmain
#include <stdlib.h>
#include "main.h"
*/
import "C"
import (
    "fmt"
    "os"
    "unsafe"
)

func main() {

    var apiResponse *C.ApiResponse
    var instanceID *C.char

    property := C.CString(".\\properties")
    defer C.free(unsafe.Pointer(property))

    apiResponse = C.create_instance(property, &instanceID)

    id := C.GoString(instanceID)

    // I'm able to access data from apiResponse
    stat := int32(apiResponse.status)
    fmt.Println("status : ", stat)
    fmt.Println("response : ", C.GoString(apiResponse.response))
    fmt.Println("instanceID : ", id)

    fmt.Println("Before call to free apiResponse")
    // When I call free of the allocated memory, its crashing
    C.free(unsafe.Pointer(apiResponse))
    fmt.Println("After call to free apiResponse")

    os.Exit(0)
}

</code>```

main.c

```<code>
#include <stdio.h>
#include <stdlib.h>
#include "main.h"

void GetInstaceID(char ** instanceID)
{
    char * temp = NULL;

    if(instanceID) {

        temp = (char *) malloc(sizeof(char) * MAX_LEN_ID);
        if(temp){
            memset(temp, 0, MAX_LEN_ID);
            strncpy(temp, "ABC-XYX-1234", MAX_LEN_ID-1);
        }

        *instanceID = temp;
    }
}

ApiResponsePtr create_instance(char * property, char ** instanceID)
{

    ApiResponsePtr ptr = NULL;
    ptr = (ApiResponse *) calloc(1, sizeof(ApiResponse));

    // Internally it allocates memory for instanceID and fill ID
    GetInstaceID(instanceID);

    // Do other stuff

    // Fill ptr
    ptr->status = 0;

    ptr->response = (char *)malloc(MAX_STATUS_LEN * sizeof(char));
    if(ptr->response) {
        strncpy(ptr->response, "Success", MAX_STATUS_LEN-1); //hardcoding response as Success, actual would decide based on status
    }

    return ptr;
}

</code>```

main.h

```<code>#ifndef MAIN_H_
#define MAIN_H_

#define MAX_LEN_ID      30
#define MAX_STATUS_LEN  64
//#define INSTANCE_ID "ABC-XYX-1234" // hard coding here, actual code would generate it

typedef struct api_response_t
{
    int     status;         /*!< \details API status code */
    char    * response;     /*!< \details API response message  */
} ApiResponse, *ApiResponsePtr;

ApiResponsePtr create_instance(char * property, char ** instanceID);

#endif

</code>```

Body:
I'm calling C APIs defined in another C library (main.dll) from my go code using cgo. The C API returns a ApiResponse pointer which populates error code and message. The memory for ApiResponsePtr is allocated by C API. After using this, when I call C.free to free the allocated memory, it crashes.

Crash log says : exit status 0xc0000374

Below is the working code, which can be used as it is.
Note I've used MSVC to create a main.dll from the main.c and main.h file. The same main.dll is linked in my go code.

main.go

package main

/*
#cgo CFLAGS: -g -Wall
#cgo CFLAGS: -I./
#cgo LDFLAGS: -L./ -lmain
#include <stdlib.h>
#include "main.h"
*/
import "C"
import (
    "fmt"
    "os"
    "unsafe"
)

func main() {

    var apiResponse *C.ApiResponse
    var instanceID *C.char

    property := C.CString(".\\properties")
    defer C.free(unsafe.Pointer(property))

    apiResponse = C.create_instance(property, &instanceID)

    id := C.GoString(instanceID)

    // I'm able to access data from apiResponse
    stat := int32(apiResponse.status)
    fmt.Println("status : ", stat)
    fmt.Println("response : ", C.GoString(apiResponse.response))
    fmt.Println("instanceID : ", id)

    fmt.Println("Before call to free apiResponse")
    // When I call free of the allocated memory, its crashing
    C.free(unsafe.Pointer(apiResponse))
    fmt.Println("After call to free apiResponse")

    os.Exit(0)
}

main.c

#include <stdio.h>
#include <stdlib.h>
#include "main.h"

void GetInstaceID(char ** instanceID)
{
    char * temp = NULL;

    if(instanceID) {

        temp = (char *) malloc(sizeof(char) * MAX_LEN_ID);
        if(temp){
            memset(temp, 0, MAX_LEN_ID);
            strncpy(temp, "ABC-XYX-1234", MAX_LEN_ID-1);
        }

        *instanceID = temp;
    }
}

ApiResponsePtr create_instance(char * property, char ** instanceID)
{

    ApiResponsePtr ptr = NULL;
    ptr = (ApiResponse *) calloc(1, sizeof(ApiResponse));

    // Internally it allocates memory for instanceID and fill ID
    GetInstaceID(instanceID);

    // Do other stuff

    // Fill ptr
    ptr->status = 0;

    ptr->response = (char *)malloc(MAX_STATUS_LEN * sizeof(char));
    if(ptr->response) {
        strncpy(ptr->response, "Success", MAX_STATUS_LEN-1); //hardcoding response as Success, actual would decide based on status
    }

    return ptr;
}

main.h

#ifndef MAIN_H_
#define MAIN_H_

#define MAX_LEN_ID      30
#define MAX_STATUS_LEN  64
//#define INSTANCE_ID "ABC-XYX-1234" // hard coding here, actual code would generate it

typedef struct api_response_t
{
    int     status;         /*!< \details API status code */
    char    * response;     /*!< \details API response message  */
} ApiResponse, *ApiResponsePtr;

ApiResponsePtr create_instance(char * property, char ** instanceID);

#endif


来源: stackexchange

问:
Error using the connection to database when RDS scales out
We have a .net API hosted in ECS that queries data from a serverless v1 cluster using Entity Framework. Under normal load this service performs very well but when there's a large spike in traffic that require the RDS cluster to scale out to more ACUs we are seeing a lot of connection errors in our API.

An error occurred using the connection to database '\"ourdatabasename\"' on server '\"tcp://ourcluster.region.rds.amazonaws.com:5432\"'.

The high level overiew of the infrastructure looks like this:

CloudFront >> Load Balancer >> ECS Fargate >> RDS Aurora PostgeSQL Serverless v1

Stack information:

.Net 6 API compiled for Linux

Entity Framework Core 6.x

Npgsql.EntityFrameworkCore.PostgreSQL 6.x

PostgeSQL 10.18

We did open AWS support cases about this issue in the past year, but those basically always result in the answer that this is an implementation issue and not an infrastructure issue.

We can easily reproduce the issue by running a k6 stress test on our API (bypassing the CloudFront caching layer of course) to generate a spike high enough to trigger scaling of the RDS cluster.

For the past year we have worked around this issue by configuring RDS at a capacity at which it basically never needs to scale out. This is of course wasting money, and not the purpose of serverless as all, so we would like to find the underlying root cause and solve that.

Some things we have tried already:

We have experimented with serverless v2 which should scale in a completely different fashion as it's just the same vm consuming more resources from the hosting machine. But our preliminary conclusion is that this was even worse. We do not yet understand why that is, but it appears to trigger the same effect but than a lot faster/more as v2 scales a lot faster/more. With v1 we get in trouble around 400 requests per second, with v2 it was at 150rps.

EnableRetryOnFailure seemed to help a tiny bit, but not a lot. We have left it at the default configuration as implemented by Npgsql for now.

We have experimented with the Maximum Pool Size connection string parameter. At 300 it appears to be a bit better, but it does not solve the issue.

Changing the scaling behaviour of ECS/the ALB or even just prescaling that to handle peak load did not change anything.

We have not tried:

RDS Proxy, it's supposed to solve all your connection pooling issues. But we're not sure it's even a pooling issue. We're not keen on trusting on yet another black box service to solve the issues our first black box service (aurora serverless) has. And it's not really cheap. If all of SO will now convince us this is the holy grail, then surely we'll try it out.

Data API for RDS, you can't have connection management issues if you're not making them right? It's a huge investment to rewrite all EF code to Data API requests and I'm not sure what it says about the service if it's still not out for serverless v2. So, not for now I think.

The first purpose of this question here on SO it trying to find someone that could help us understand what is even going on. Helping us understand the error and where it comes from. We understand that you cannot expect that ECS+RDS can just magically handle all the load you throw at it. But if we do not fully understand how it breaks we are not able to come up with how to create potential failover mechanisms or how to make the system fail more gracefully.

If someone knows the magic setting but not the why that's also great of course :) We can then maybe figure out the why ourselves and share that back with the community ;)

Feel free to ask more questions where needed.

ContentLicense: CC BY-SA 4.0


问:
How to calculate the ROUGE measure for the text summarization of multiple docs?
I am trying to calculate the ROUGE-1, ROUGE-2 and ROUGE-l for text summarization of my custom dataset of 153 news articles. I have successfully calculated the ROUGE results for each news article. However, i am in dilemma that whether calculating the average of ROUGE measures such as precision, recall, and F-measure would be mathematically correct or not. In other words, would it be fruitful to take the average of these evaluation measures or not? Is there any other method to sum up the ROUGE results of multiple documents?
The python code is below for reference:

```<code>sum_p = 0.0
sum_r = 0.0
sum_f = 0.0
p = []
r = []
f = []
no_summ = len(scores_final)
for j in range(no_summ):
  d  = dict(scores_final[j][0])
  #print(j)
  #print(d)
  f_measure = d.get('rouge-l').get('f')
  f.append(f_measure)
  pre = d.get('rouge-l').get('p')
  p.append(pre)
  re = d.get('rouge-l').get('r')
  r.append(re)
  #print(f_measure)
  sum_p = sum_p  + pre
  sum_r = sum_r + re
  sum_f = sum_f + f_measure
  #print(pre)
avg_pre = sum_p/no_summ
avg_re = sum_r/no_summ
avg_f = sum_f/no_summ
print("average precision : " + str(avg_pre))
print("average recall : " + str(avg_re))
print("average f_measure : " + str(avg_f))
rouge_l = []
rouge_l.append([avg_pre, avg_re, avg_f])
</code>```

Average:

```<code>average precision : 0.5052324099414933
average recall : 0.9786333723121803
average f_measure : 0.6575725198241108
</code>```

An example of a few ROUGE-l results stored in a list scores_final:

```<code>[[{'rouge-1': {'r': 1.0, 'p': 0.4788732394366197, 'f': 0.6476190432399093},
   'rouge-2': {'r': 0.9871794871794872,
    'p': 0.3632075471698113,
    'f': 0.5310344788261593},
   'rouge-l': {'r': 1.0, 'p': 0.4788732394366197, 'f': 0.6476190432399093}}],
 [{'rouge-1': {'r': 1.0, 'p': 0.4672897196261682, 'f': 0.6369426708182888},
   'rouge-2': {'r': 0.9933333333333333,
    'p': 0.3860103626943005,
    'f': 0.5559701452230453},
   'rouge-l': {'r': 1.0, 'p': 0.4672897196261682, 'f': 0.6369426708182888}}]]
</code>```

Body:
I am trying to calculate the ROUGE-1, ROUGE-2 and ROUGE-l for text summarization of my custom dataset of 153 news articles. I have successfully calculated the ROUGE results for each news article. However, i am in dilemma that whether calculating the average of ROUGE measures such as precision, recall, and F-measure would be mathematically correct or not. In other words, would it be fruitful to take the average of these evaluation measures or not? Is there any other method to sum up the ROUGE results of multiple documents?
The python code is below for reference:

sum_p = 0.0
sum_r = 0.0
sum_f = 0.0
p = []
r = []
f = []
no_summ = len(scores_final)
for j in range(no_summ):
  d  = dict(scores_final[j][0])
  #print(j)
  #print(d)
  f_measure = d.get('rouge-l').get('f')
  f.append(f_measure)
  pre = d.get('rouge-l').get('p')
  p.append(pre)
  re = d.get('rouge-l').get('r')
  r.append(re)
  #print(f_measure)
  sum_p = sum_p  + pre
  sum_r = sum_r + re
  sum_f = sum_f + f_measure
  #print(pre)
avg_pre = sum_p/no_summ
avg_re = sum_r/no_summ
avg_f = sum_f/no_summ
print("average precision : " + str(avg_pre))
print("average recall : " + str(avg_re))
print("average f_measure : " + str(avg_f))
rouge_l = []
rouge_l.append([avg_pre, avg_re, avg_f])

Average:

average precision : 0.5052324099414933
average recall : 0.9786333723121803
average f_measure : 0.6575725198241108

An example of a few ROUGE-l results stored in a list scores_final:

[[{'rouge-1': {'r': 1.0, 'p': 0.4788732394366197, 'f': 0.6476190432399093},
   'rouge-2': {'r': 0.9871794871794872,
    'p': 0.3632075471698113,
    'f': 0.5310344788261593},
   'rouge-l': {'r': 1.0, 'p': 0.4788732394366197, 'f': 0.6476190432399093}}],
 [{'rouge-1': {'r': 1.0, 'p': 0.4672897196261682, 'f': 0.6369426708182888},
   'rouge-2': {'r': 0.9933333333333333,
    'p': 0.3860103626943005,
    'f': 0.5559701452230453},
   'rouge-l': {'r': 1.0, 'p': 0.4672897196261682, 'f': 0.6369426708182888}}]]


问:
Dealing with files in app running inside AppImage
I have an application written in Qt/C++ which is running under Linux.
Inside my application I have several functions which dealing with files located in:

QCoreApplication::applicationDirPath()

/tmp/

QStandardPaths::ConfigLocation

QStandardPaths::DataLocation

The application runs smoothly if executes as regular Linux executable. However there are problems if I pack it into AppImage. It doesn't see files in expected locations and can't create new files in there.
If I understand AppImage correctly - it is SquashFS which is readonly. So this behavior is understandable. But how can I deal with? Is that possible to solve this problem without changing source code of my app?

The output of QCoreApplication::applicationFilePath() when run the Linux executable is "/home/mike/projects/builds/build-testqtapp-Desktop_Qt_5_12_8_GCC_64bit-Debug/AppDir/testqtapp" The output of the same command from AppImage is "/tmp/.mount_testqtyEZUuH/testqtapp"


问:
Why is ftell() telling me that the parameter is invalid?
In the debugger, I get an unhandled exception from (ucrtbased.dll) in Executable.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.

I believe I am following the parameters of the functions as documented, so I am quite confused as to why this is happening.

The code is from me trying to encrypt a text file by using XOR, if this helps to provide any clarity. Thank you for reading this!

```<code>#include <stdio.h>
#include <string.h>
#include <windows.h>
int WINAPI WinMain()
{

    FILE* ptr;
    ptr = fopen("C:\\Users\\User\\Desktop\\text.txt", "rb+");
    fseek(ptr, 0, SEEK_END);
    long endpoint = ftell(ptr);     //<<<<<<<<<<<<<<<<<<<<<< Area where Unhandled exception occurs
    char* buffer = malloc(endpoint + 1);
    endpoint = fread(buffer, 1, endpoint, ptr);
    rewind(ptr);
    char* temp = buffer;
    for (int i = 0; i < endpoint; i++, temp++)
    {
        *temp = *temp ^ 21;
    }
    fwrite(temp, 1, endpoint, ptr);
    free(buffer);
    fclose(ptr);
    return 0;
}
</code>```

Body:
In the debugger, I get an unhandled exception from (ucrtbased.dll) in Executable.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.

I believe I am following the parameters of the functions as documented, so I am quite confused as to why this is happening.

The code is from me trying to encrypt a text file by using XOR, if this helps to provide any clarity. Thank you for reading this!

#include <stdio.h>
#include <string.h>
#include <windows.h>
int WINAPI WinMain()
{

    FILE* ptr;
    ptr = fopen("C:\\Users\\User\\Desktop\\text.txt", "rb+");
    fseek(ptr, 0, SEEK_END);
    long endpoint = ftell(ptr);     //<<<<<<<<<<<<<<<<<<<<<< Area where Unhandled exception occurs
    char* buffer = malloc(endpoint + 1);
    endpoint = fread(buffer, 1, endpoint, ptr);
    rewind(ptr);
    char* temp = buffer;
    for (int i = 0; i < endpoint; i++, temp++)
    {
        *temp = *temp ^ 21;
    }
    fwrite(temp, 1, endpoint, ptr);
    free(buffer);
    fclose(ptr);
    return 0;
}


问:
React-Bootstrap dynamic Image rendering
I am trying to display profile pic by calling the path and file name from database
Profile Image is not loading is it the path?
using json server local test.

Image is saved in folder ../src/image/

json data

image: "..image/pic.jpg"

```<code>import { Card, ListGroup } from "react-bootstrap";
import { useParams, useHistory } from "react-router-dom";
import useFetch from "./useFetch";

const MemberProfile = () => {
  const { id } = useParams();
  const {
    data: member,
    error,
    isLoading,
  } = useFetch("http://192.168.0.23:8000/members/" + id);
  const history = useHistory();

  const handleClick = () => {
    fetch("http://192.168.0.23:8000/members/" + member.id, {
      method: "DELETE",
    }).then(() => {
      history.push("/");
    });
  };

  return (
    <div className="memberProfile">
      {isLoading && <div>Loading...</div>}
      {error && <div>{error}</div>}
      {member && (
        <Card style={{}}>
          <Card.Img variant="top" src={member.image} />
          <Card.Body>
            <Card.Title>
              <h2>
                <strong>
                  Profile - {member.name} {id}
                </strong>
              </h2>
            </Card.Title>
            <Card.Text>
              <pre className="acordnBody">
                Gender : {member.gender} <hr />
                Phone : {member.tel} <hr />
                E-mail : {member.email} <hr />
                Address : {member.address}
              ```
            </Card.Text>
          </Card.Body>
        </Card>
      )}

  );
};

export default MemberProfile;

```

Title: React-Bootstrap dynamic Image rendering

Body:
I am trying to display profile pic by calling the path and file name from database
Profile Image is not loading is it the path?
using json server local test.

Image is saved in folder ../src/image/

json data

image: "..image/pic.jpg"

import { Card, ListGroup } from "react-bootstrap";
import { useParams, useHistory } from "react-router-dom";
import useFetch from "./useFetch";

const MemberProfile = () => {
  const { id } = useParams();
  const {
    data: member,
    error,
    isLoading,
  } = useFetch("http://192.168.0.23:8000/members/" + id);
  const history = useHistory();

  const handleClick = () => {
    fetch("http://192.168.0.23:8000/members/" + member.id, {
      method: "DELETE",
    }).then(() => {
      history.push("/");
    });
  };

  return (

      {isLoading &&
Loading...
}
      {error &&
{error}
}
      {member && (
        <Card style={{}}>
          <Card.Img variant="top" src={member.image} />
          <Card.Body>
            <Card.Title>

                  Profile - {member.name} {id}

            </Card.Title>
            <Card.Text>

                Gender : {member.gender}

                Phone : {member.tel}

                E-mail : {member.email}

                Address : {member.address}

            </Card.Text>
          </Card.Body>
        </Card>
      )}

  );
};

export default MemberProfile;


问:
Big Data Characteristics and Challenges to DBMSs: precise correspondences
If we consider the seven features of Big Data individually as challenges to (NoSQL) DBMSs, what would be the features of NoSQL DBMSs that meet each of the challenges?

Volume : (horizontal) Scalability

Velocity : Availability (over Consistency)

Variety : Schemaless - Schema-Flexibility

Veracity : ?

Variability : ?

Value : ?

Complexity :   ?


问:
Cannot handle classloader url -warning from liquibase
I'm getting this warning after updating liquibase-core to 4.17.2 version:

`

```<code>Dec 08, 2022 3:22:00 PM liquibase.resource
WARNING: Cannot handle classloader url file:/C:/Program%20Files/Java/jdk1.8.0_172/jre/lib/ext/jaccess.jar: null. Operations that need to list files from this location may not work as expected
java.lang.IllegalArgumentException
    at liquibase.resource.ZipResourceAccessor.<init>(ZipResourceAccessor.java:48)
    at liquibase.resource.ZipPathHandler.getResourceAccessor(ZipPathHandler.java:41)
    at liquibase.resource.PathHandlerFactory.getResourceAccessor(PathHandlerFactory.java:38)
    at liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors(ClassLoaderResourceAccessor.java:78)
    at liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors(ClassLoaderResourceAccessor.java:92)
    at liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors(ClassLoaderResourceAccessor.java:92)
    at liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors(ClassLoaderResourceAccessor.java:92)
    at liquibase.resource.ClassLoaderResourceAccessor.init(ClassLoaderResourceAccessor.java:61)
    at liquibase.resource.ClassLoaderResourceAccessor.search(ClassLoaderResourceAccessor.java:106)
    at liquibase.changelog.DatabaseChangeLog.includeAll(DatabaseChangeLog.java:618)
    at liquibase.changelog.DatabaseChangeLog.handleChildNode(DatabaseChangeLog.java:462)
    at liquibase.changelog.DatabaseChangeLog.load(DatabaseChangeLog.java:364)
    at liquibase.parser.core.xml.AbstractChangeLogParser.parse(AbstractChangeLogParser.java:23)
    at liquibase.Liquibase.getDatabaseChangeLog(Liquibase.java:408)
    at liquibase.Liquibase.getDatabaseChangeLog(Liquibase.java:393)
    at liquibase.Liquibase$16.run(Liquibase.java:2022)
    at liquibase.Scope.lambda$child$0(Scope.java:180)
    at liquibase.Scope.child(Scope.java:189)
    at liquibase.Scope.child(Scope.java:179)
    at liquibase.Scope.child(Scope.java:158)
    at liquibase.Liquibase.runInScope(Liquibase.java:2447)
    at liquibase.Liquibase.listUnrunChangeSets(Liquibase.java:2018)
    at liquibase.Liquibase.listUnrunChangeSets(Liquibase.java:2009)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.nio.file.FileSystemAlreadyExistsException
    at com.sun.nio.zipfs.ZipFileSystemProvider.newFileSystem(ZipFileSystemProvider.java:113)
    at java.nio.file.FileSystems.newFileSystem(FileSystems.java:326)
    at liquibase.resource.ZipResourceAccessor.<init>(ZipResourceAccessor.java:45)
    ... 29 more
</code>```

`

FYI: this is not causing any issue in the execution of liquibase

Why should it analyze the artifact of the project?

Body:
I'm getting this warning after updating liquibase-core to 4.17.2 version:

`

Dec 08, 2022 3:22:00 PM liquibase.resource
WARNING: Cannot handle classloader url file:/C:/Program%20Files/Java/jdk1.8.0_172/jre/lib/ext/jaccess.jar: null. Operations that need to list files from this location may not work as expected
java.lang.IllegalArgumentException
    at liquibase.resource.ZipResourceAccessor.<init>(ZipResourceAccessor.java:48)
    at liquibase.resource.ZipPathHandler.getResourceAccessor(ZipPathHandler.java:41)
    at liquibase.resource.PathHandlerFactory.getResourceAccessor(PathHandlerFactory.java:38)
    at liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors(ClassLoaderResourceAccessor.java:78)
    at liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors(ClassLoaderResourceAccessor.java:92)
    at liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors(ClassLoaderResourceAccessor.java:92)
    at liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors(ClassLoaderResourceAccessor.java:92)
    at liquibase.resource.ClassLoaderResourceAccessor.init(ClassLoaderResourceAccessor.java:61)
    at liquibase.resource.ClassLoaderResourceAccessor.search(ClassLoaderResourceAccessor.java:106)
    at liquibase.changelog.DatabaseChangeLog.includeAll(DatabaseChangeLog.java:618)
    at liquibase.changelog.DatabaseChangeLog.handleChildNode(DatabaseChangeLog.java:462)
    at liquibase.changelog.DatabaseChangeLog.load(DatabaseChangeLog.java:364)
    at liquibase.parser.core.xml.AbstractChangeLogParser.parse(AbstractChangeLogParser.java:23)
    at liquibase.Liquibase.getDatabaseChangeLog(Liquibase.java:408)
    at liquibase.Liquibase.getDatabaseChangeLog(Liquibase.java:393)
    at liquibase.Liquibase$16.run(Liquibase.java:2022)
    at liquibase.Scope.lambda$child$0(Scope.java:180)
    at liquibase.Scope.child(Scope.java:189)
    at liquibase.Scope.child(Scope.java:179)
    at liquibase.Scope.child(Scope.java:158)
    at liquibase.Liquibase.runInScope(Liquibase.java:2447)
    at liquibase.Liquibase.listUnrunChangeSets(Liquibase.java:2018)
    at liquibase.Liquibase.listUnrunChangeSets(Liquibase.java:2009)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.nio.file.FileSystemAlreadyExistsException
    at com.sun.nio.zipfs.ZipFileSystemProvider.newFileSystem(ZipFileSystemProvider.java:113)
    at java.nio.file.FileSystems.newFileSystem(FileSystems.java:326)
    at liquibase.resource.ZipResourceAccessor.<init>(ZipResourceAccessor.java:45)
    ... 29 more

`

FYI: this is not causing any issue in the execution of liquibase

Why should it analyze the artifact of the project?


问:
React & Typescript - custom hook to pull status updates resets back to initial status
Situation:

Im trying to write a custom hook that allows me to fetch data and launches a setInterval which polls status updates every two seconds. Once all data is processed, the interval is cleared to stop polling updates.

Problem:

My problem is that the function passed to setInterval only has the initial state (empty array) although it has already been updated. Either it is resetting back to the initial state or the function has an old reference.

Code:

Link to Codesandbox: https://codesandbox.io/s/pollingstate-9wziw7?file=/src/Hooks.tsx

Hook:

export type Invoice = {id: number, status: string};

export async function executeRequest<T>(callback: () => T, afterRequest: (response: {error: string | null, data: T}) => void) {
  const response = callback();
  afterRequest({error: null, data: response});
}

export function useInvoiceProcessing(formData: Invoice[]): [result: Invoice[], executeRequest: () => Promise<void>] {

  const timer: MutableRefObject<NodeJS.Timer | undefined> = useRef();

  const [result, setResult] = useState<Invoice[]>(formData);

  // Mock what the API would return
  const firstRequestResult: Invoice[] = [
    {id: 1, status: "Success"},
    {id: 2, status: "Pending"}, // This one needs to be polled again
    {id: 3, status: "Failed"}
  ];
  const firstPoll: Invoice = {id: 2, status: "Pending"};
  const secondPoll: Invoice = {id: 2, status: "Success"};

  // The function that triggers when the user clicks on "Execute Request"
  async function handleFirstRequest() {
    await executeRequest(() => firstRequestResult, response => {
      if (!response.error) {
        setResult(response.data)
        if (response.data.some(invoice => invoice.status === "Pending")) {
          // Initialize the timer to poll every 2 seconds
          timer.current = setInterval(() => updateStatus(), 2000);
        }
      } else {
        // setError
      }
    })
  }

  let isFirstPoll = true; // Helper variable to simulate a first poll
  async function updateStatus() {
    // Result has the initial formData values (NotUploaded) but should already have the values from the first request
    console.log(result);
    const newResult = [...result];
    let index = 0;
    for (const invoice of newResult) {
      if (invoice.status === "Pending") {
        await executeRequest(() => isFirstPoll ? firstPoll : secondPoll, response => {
          if (!response.error) {
            newResult[index] = response.data;
          } else {
            // Handle error
          }
        });
      }
      index++;
    }

    setResult(newResult);
    isFirstPoll = false;

    const areInvoicesPending = newResult.some(invoice => invoice.status === "Pending");
    if (!areInvoicesPending) {
      console.log("Manual clear")
      clearInterval(timer.current);
    }
  };

  useEffect(() => {
    return () => {
      console.log("Unmount clear")
      clearInterval(timer.current);
    }
  }, [])

  return [result, handleFirstRequest];
```
<p>Usage:</p>
<pre class="lang-js prettyprint-override"><code>const [result, executeRequest] = useInvoiceProcessing([
    { id: 1, status: "NotUploaded" },
    { id: 2, status: "NotUploaded" },
    { id: 3, status: "NotUploaded" }
  ]);

  async function handleRequest() {
    console.log("Start request");
    executeRequest();
  }

  return (
    <div className="App">
      <button onClick={handleRequest}>Execute Request</button>
      <p>
        {result.map((invoice) => (
          <Fragment key={invoice.id}>
            {invoice.status}
            <br />
          </Fragment>
        ))}
      </p>
    </div>
  );
</code>```

EDIT1

I have one possible solution. This post helped me in the right direction: React hooks functions have old version of a state var

The closure that updateStatus uses is outdated. To solve that, I saved updateStatus in a useRef (updateStatus also needs useCallback). Although not necessary, I had to store result in a useRef as well but I'm not sure yet why.

const updateStatusRef = useRef(updateStatus);
  useEffect(()=>{
    updateStatusRef.current = updateStatus;
  }, [updateStatus]);
```

Here's a working example: https://codesandbox.io/s/pollingstate-forked-njw4ct?file=/src/Hooks.tsx

Body:
Situation:

Im trying to write a custom hook that allows me to fetch data and launches a setInterval which polls status updates every two seconds. Once all data is processed, the interval is cleared to stop polling updates.

Problem:

My problem is that the function passed to setInterval only has the initial state (empty array) although it has already been updated. Either it is resetting back to the initial state or the function has an old reference.

Code:

Link to Codesandbox: https://codesandbox.io/s/pollingstate-9wziw7?file=/src/Hooks.tsx

Hook:

export type Invoice = {id: number, status: string};

export async function executeRequest<T>(callback: () => T, afterRequest: (response: {error: string | null, data: T}) => void) {
  const response = callback();
  afterRequest({error: null, data: response});
}

export function useInvoiceProcessing(formData: Invoice[]): [result: Invoice[], executeRequest: () => Promise<void>] {

  const timer: MutableRefObject<NodeJS.Timer | undefined> = useRef();

  const [result, setResult] = useState<Invoice[]>(formData);

  // Mock what the API would return
  const firstRequestResult: Invoice[] = [
    {id: 1, status: "Success"},
    {id: 2, status: "Pending"}, // This one needs to be polled again
    {id: 3, status: "Failed"}
  ];
  const firstPoll: Invoice = {id: 2, status: "Pending"};
  const secondPoll: Invoice = {id: 2, status: "Success"};

  // The function that triggers when the user clicks on "Execute Request"
  async function handleFirstRequest() {
    await executeRequest(() => firstRequestResult, response => {
      if (!response.error) {
        setResult(response.data)
        if (response.data.some(invoice => invoice.status === "Pending")) {
          // Initialize the timer to poll every 2 seconds
          timer.current = setInterval(() => updateStatus(), 2000);
        }
      } else {
        // setError
      }
    })
  }

  let isFirstPoll = true; // Helper variable to simulate a first poll
  async function updateStatus() {
    // Result has the initial formData values (NotUploaded) but should already have the values from the first request
    console.log(result);
    const newResult = [...result];
    let index = 0;
    for (const invoice of newResult) {
      if (invoice.status === "Pending") {
        await executeRequest(() => isFirstPoll ? firstPoll : secondPoll, response => {
          if (!response.error) {
            newResult[index] = response.data;
          } else {
            // Handle error
          }
        });
      }
      index++;
    }

    setResult(newResult);
    isFirstPoll = false;

    const areInvoicesPending = newResult.some(invoice => invoice.status === "Pending");
    if (!areInvoicesPending) {
      console.log("Manual clear")
      clearInterval(timer.current);
    }
  };

  useEffect(() => {
    return () => {
      console.log("Unmount clear")
      clearInterval(timer.current);
    }
  }, [])

  return [result, handleFirstRequest];

Usage:

const [result, executeRequest] = useInvoiceProcessing([
    { id: 1, status: "NotUploaded" },
    { id: 2, status: "NotUploaded" },
    { id: 3, status: "NotUploaded" }
  ]);

  async function handleRequest() {
    console.log("Start request");
    executeRequest();
  }

  return (

      <button onClick={handleRequest}>Execute Request</button>

        {result.map((invoice) => (
          <Fragment key={invoice.id}>
            {invoice.status}

          </Fragment>
        ))}

  );

EDIT1

I have one possible solution. This post helped me in the right direction: React hooks functions have old version of a state var

The closure that updateStatus uses is outdated. To solve that, I saved updateStatus in a useRef (updateStatus also needs useCallback). Although not necessary, I had to store result in a useRef as well but I'm not sure yet why.

const updateStatusRef = useRef(updateStatus);
  useEffect(()=>{
    updateStatusRef.current = updateStatus;
  }, [updateStatus]);

Here's a working example: https://codesandbox.io/s/pollingstate-forked-njw4ct?file=/src/Hooks.tsx


问:
Log all exceptions in MediatR
I'm trying to log any exception thrown by a MediatR handler using IRequestExceptionAction. I am not trying to handle these exceptions. They may have already been handled.

I'm using Microsoft dependency injection have the RequestExceptionActionProcessorStrategy set to ApplyForAllExceptions.

If I implement a IRequestExceptionAction, where I give T the concrete type of a specific request, logging is successful:

public class RequestExceptionLogger : IRequestExceptionAction<ClientIndexPageQuery>
{
    private readonly ILogger _logger;

    public RequestExceptionLogger(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger(GetType());
    }

    public Task Execute(ClientIndexPageQuery request, Exception exception, CancellationToken cancellationToken)
    {
        _logger.LogError(exception,
            $"Exception occurred while attempting to handle request '{request.GetType().Name}': {exception.Message}");
        return Task.CompletedTask;
    }
}
```
<p>However, if I try to create a single handler to log exceptions from all handlers, it does not. Here are the two implementations I've tried:</p>
<p>#1: Generic handler</p>
<pre class="lang-cs prettyprint-override"><code>public class RequestExceptionLogger<T> : IRequestExceptionAction<T> where T : notnull
{
    private readonly ILogger _logger;

    public RequestExceptionLogger(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger(GetType());
    }

    public Task Execute(T request, Exception exception, CancellationToken cancellationToken)
    {
        _logger.LogError(exception,
            $"Exception occurred while attempting to handle request '{request.GetType().Name}': {exception.Message}");
        return Task.CompletedTask;
    }
}
</code>```

#2: Use IRequest as TRequest

public class RequestExceptionLogger : IRequestExceptionAction<IRequest>
{
    private readonly ILogger _logger;

    public RequestExceptionLogger(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger(GetType());
    }

    public Task Execute(IRequest request, Exception exception, CancellationToken cancellationToken)
    {
        _logger.LogError(exception,
            $"Exception occurred while attempting to handle request '{request.GetType().Name}': {exception.Message}");
        return Task.CompletedTask;
    }
}
```

How do I add a single pipeline behavior that will fire for exceptions for all MediatR handlers?

Title: Log all exceptions in MediatR

Body:
I'm trying to log any exception thrown by a MediatR handler using IRequestExceptionAction. I am not trying to handle these exceptions. They may have already been handled.

I'm using Microsoft dependency injection have the RequestExceptionActionProcessorStrategy set to ApplyForAllExceptions.

If I implement a IRequestExceptionAction, where I give T the concrete type of a specific request, logging is successful:

public class RequestExceptionLogger : IRequestExceptionAction<ClientIndexPageQuery>
{
    private readonly ILogger _logger;

    public RequestExceptionLogger(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger(GetType());
    }

    public Task Execute(ClientIndexPageQuery request, Exception exception, CancellationToken cancellationToken)
    {
        _logger.LogError(exception,
            $"Exception occurred while attempting to handle request '{request.GetType().Name}': {exception.Message}");
        return Task.CompletedTask;
    }
}

However, if I try to create a single handler to log exceptions from all handlers, it does not. Here are the two implementations I've tried:

#1: Generic handler

public class RequestExceptionLogger<T> : IRequestExceptionAction<T> where T : notnull
{
    private readonly ILogger _logger;

    public RequestExceptionLogger(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger(GetType());
    }

    public Task Execute(T request, Exception exception, CancellationToken cancellationToken)
    {
        _logger.LogError(exception,
            $"Exception occurred while attempting to handle request '{request.GetType().Name}': {exception.Message}");
        return Task.CompletedTask;
    }
}

#2: Use IRequest as TRequest

public class RequestExceptionLogger : IRequestExceptionAction<IRequest>
{
    private readonly ILogger _logger;

    public RequestExceptionLogger(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger(GetType());
    }

    public Task Execute(IRequest request, Exception exception, CancellationToken cancellationToken)
    {
        _logger.LogError(exception,
            $"Exception occurred while attempting to handle request '{request.GetType().Name}': {exception.Message}");
        return Task.CompletedTask;
    }
}

How do I add a single pipeline behavior that will fire for exceptions for all MediatR handlers?


问:
NestJS not watching in docker
Since upgrading Docker Desktop for Windows recently, my nest start --watch stopped working. It is not reloading anymore for changes (not watching). It does work outside of docker.

The current version of Docker Desktop: 4.15.0. I tried reinstalling it without luck. The code is the same.

What could be the issue?

Title: NestJS not watching in docker


问:
Variable in a function still accessible after function call
This is an interview question/answer I found online (link).

Original Question: How could you cache execution of any function?

Example Answer:

function cacheFn(fn) {
    var cache = {};
    return function wrapper(arg){
        if (cache[arg]){
           console.log('used cache!!');
           return cache[arg];
        }
        else{
           cache[arg] = fn(arg);
            return cache[arg];
        }
    }
}
```
<p>My initial idea was that, <code>cache</code> will be removed after <code>cacheFn</code> is first called so no caching will be done. But when I tested it as below...</p>
<pre class="lang-js prettyprint-override"><code>function func(n) {
  return n+1;
}

const cachef1 = cacheFn(func);
console.log(cachef1(1));
console.log(cachef1(1)); // 'used cache!!'
</code>```

I'm not understanding how var cache = {}; survived after the first cachef1(1); call. It's as if when assigning cacheFn(func1) to cachef1, the whole block inside cacheFn were saved. I also found this does not do caching:

```<code>cacheFn(func)(1);
cacheFn(func)(1); // no caching when there was no assignment
</code>```

What concept am I missing or are confused about here?

Body:
This is an interview question/answer I found online (link).

Original Question: How could you cache execution of any function?

Example Answer:

function cacheFn(fn) {
    var cache = {};
    return function wrapper(arg){
        if (cache[arg]){
           console.log('used cache!!');
           return cache[arg];
        }
        else{
           cache[arg] = fn(arg);
            return cache[arg];
        }
    }
}

My initial idea was that, cache will be removed after cacheFn is first called so no caching will be done. But when I tested it as below...

function func(n) {
  return n+1;
}

const cachef1 = cacheFn(func);
console.log(cachef1(1));
console.log(cachef1(1)); // 'used cache!!'

I'm not understanding how var cache = {}; survived after the first cachef1(1); call. It's as if when assigning cacheFn(func1) to cachef1, the whole block inside cacheFn were saved. I also found this does not do caching:

cacheFn(func)(1);
cacheFn(func)(1); // no caching when there was no assignment

What concept am I missing or are confused about here?


问:
how to map and display a set of object from a data collection from mongodb in nextjs
I am currently trying to filter products of the same category and display on the page when the user clicks on a particular category. I've done this with the product detail page but I can't seem to figure out the right way to pull out all categories on the category page. Nothing expept the layout displays on the category page when redirected. Please help me using the following code

/pages/category/[slug].js

```<code>import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useContext } from 'react';
import { toast } from 'react-toastify';
import Layout from '../../components/Layout';
import ProductItem from '../../components/ProductItem';
import Product from '../../components/models/Product';
import db from '../../utils/db';
import { Store } from '../../utils/Store';
import { useRouter } from 'next/router';

export default function Home({ products }) {
  const router = useRouter();
  const { state, dispatch } = useContext(Store);
  const { cart } = state;

  const addToCartHandler = async (product) => {
    const existItem = cart.cartItems.find((x) => x.slug === product.slug);
    const quantity = existItem ? existItem.quantity + 1 : 1;
    const { data } = await axios.get(`/api/products/${product._id}`);

    if (data.countInStock < quantity) {
      return toast.error('Sorry. Product is out of stock');
    }
    dispatch({ type: 'CART_ADD_ITEM', payload: { ...product, quantity } });

    toast.success('Product added to the cart');
  };

  const buyNowHandler = async (product) => {
    const existItem = cart.cartItems.find((x) => x.slug === product.slug);
    const quantity = existItem ? existItem.quantity + 1 : 1;
    const { data } = await axios.get(`/api/products/${product._id}`);

    if (data.countInStock < quantity) {
      return toast.error('Sorry. Product is out of stock');
    }
    dispatch({ type: 'CART_ADD_ITEM', payload: { ...product, quantity } });
    toast.success('Product added to the cart');
    router.push('/cart');
  };

  return (
    <Layout title="Home Page">
      <div className="products-heading">
        <h2>Best Selling Products</h2>
        <p>Smoke accessories of many variations</p>
      </div>
      <div className="products-container">
        {products.map((item, index) => (
          <ProductItem
            product={item}
            key={index}
            addToCartHandler={addToCartHandler}
            buyNowHandler={buyNowHandler}
          ></ProductItem>
        ))}
      </div>
    </Layout>
  );
}

export async function getServerSideProps(params) {
  const { category } = params;
  await db.connect();
  const products = await Product.find().lean();
  return {
    props: {
      products: products.filter((productItem) =>
        productItem.category.includes(category)
      ),
    },
  };
}
</code>```

/components/Layout.jsx

```<code>import React, { useContext, useEffect, useState } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { Menu } from '@headlessui/react';
import Category from './Category';

export default function Layout() {
  return (
    <>
      <Head>
        <title>
          {title ? title + ' - Puffizzy' : 'Puffizzy Accessories'}
        </title>
        <meta name="description" content="Puffizzy Ecommerce Website" />
        <link rel="icon" href="/puffizzy_logo.png" />
      </Head>

      <ToastContainer position="bottom-center" limit={1} />

      <div className="flex min-h-screen flex-col justify-between">
        <header>
          <nav className="flex h-24 justify-between item-center px-4 py-4">
            <Link href="/">
              <img src="/puffizzy_logo_name.png" alt="" className="w-24" />
            </Link>
            <div className="navbar-right">
              <div className="categories">
                <Menu as="div" className="relative inline-block z-10 bg-white">
                  <Menu.Button className="">Categories</Menu.Button>
                  <Menu.Items className="absolute right-0 w-full origin-top-right shadow-lg">
                    <Menu.Item>
                      <Category />
                    </Menu.Item>
                  </Menu.Items>
                </Menu>
              </div>
            </div>
          </nav>
        </header>

        <main className="container m-auto mt-4 px-4">{children}</main>

        <footer className="flex h-10 justify-center items-center shadow-inner">
          <p>Footer</p>
        </footer>
      </div>
    </>
  );
}
</code>```

/componenets/Category.jsx

```<code>import Link from 'next/link';
import React from 'react';

export default function Category() {
  return (
    <div className="bg-gray-200">
      {['Lighter', 'Crusher', 'Pipe', 'Roller', 'Hookah', 'All'].map(
        (item, index) => (
          <div
            key={index}
            className="flex p-2 hover:bg-gray-100"
          >
            <Link href={`/category/${item}`}>{item}</Link>
          </div>
        )
      )}
    </div>
  );
}
</code>```

Body:
I am currently trying to filter products of the same category and display on the page when the user clicks on a particular category. I've done this with the product detail page but I can't seem to figure out the right way to pull out all categories on the category page. Nothing expept the layout displays on the category page when redirected. Please help me using the following code

/pages/category/[slug].js

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useContext } from 'react';
import { toast } from 'react-toastify';
import Layout from '../../components/Layout';
import ProductItem from '../../components/ProductItem';
import Product from '../../components/models/Product';
import db from '../../utils/db';
import { Store } from '../../utils/Store';
import { useRouter } from 'next/router';

export default function Home({ products }) {
  const router = useRouter();
  const { state, dispatch } = useContext(Store);
  const { cart } = state;

  const addToCartHandler = async (product) => {
    const existItem = cart.cartItems.find((x) => x.slug === product.slug);
    const quantity = existItem ? existItem.quantity + 1 : 1;
    const { data } = await axios.get(`/api/products/${product._id}`);

    if (data.countInStock < quantity) {
      return toast.error('Sorry. Product is out of stock');
    }
    dispatch({ type: 'CART_ADD_ITEM', payload: { ...product, quantity } });

    toast.success('Product added to the cart');
  };

  const buyNowHandler = async (product) => {
    const existItem = cart.cartItems.find((x) => x.slug === product.slug);
    const quantity = existItem ? existItem.quantity + 1 : 1;
    const { data } = await axios.get(`/api/products/${product._id}`);

    if (data.countInStock < quantity) {
      return toast.error('Sorry. Product is out of stock');
    }
    dispatch({ type: 'CART_ADD_ITEM', payload: { ...product, quantity } });
    toast.success('Product added to the cart');
    router.push('/cart');
  };

  return (
    <Layout title="Home Page">

Best Selling Products

Smoke accessories of many variations

        {products.map((item, index) => (
          <ProductItem
            product={item}
            key={index}
            addToCartHandler={addToCartHandler}
            buyNowHandler={buyNowHandler}
          ></ProductItem>
        ))}

    </Layout>
  );
}

export async function getServerSideProps(params) {
  const { category } = params;
  await db.connect();
  const products = await Product.find().lean();
  return {
    props: {
      products: products.filter((productItem) =>
        productItem.category.includes(category)
      ),
    },
  };
}

/components/Layout.jsx

import React, { useContext, useEffect, useState } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { Menu } from '@headlessui/react';
import Category from './Category';

export default function Layout() {
  return (
    <>

        <title>
          {title ? title + ' - Puffizzy' : 'Puffizzy Accessories'}
        </title>
        <meta name="description" content="Puffizzy Ecommerce Website" />
        <link rel="icon" href="/puffizzy_logo.png" />

      <ToastContainer position="bottom-center" limit={1} />

            <Link href="/">

            </Link>

                <Menu as="div" className="relative inline-block z-10 bg-white">
                  <Menu.Button className="">Categories</Menu.Button>
                  <Menu.Items className="absolute right-0 w-full origin-top-right shadow-lg">
                    <Menu.Item>
                      <Category />
                    </Menu.Item>
                  </Menu.Items>
                </Menu>

        {children}

Footer

    </>
  );
}

/componenets/Category.jsx

import Link from 'next/link';
import React from 'react';

export default function Category() {
  return (

      {['Lighter', 'Crusher', 'Pipe', 'Roller', 'Hookah', 'All'].map(
        (item, index) => (

            <Link href={`/category/${item}`}>{item}</Link>

        )
      )}

  );
}


问:
Vscode default Variables view access programatically
We want to select a TreeItem in Variables View of Run and Debug view Container through our extension .
Not able to find any vscode api to achieve that?</p>


问:
Unable to clone Private Git Repo in VS Code Remote Container
I have a VM running RedHat 8.6, which is running multiple LXC containers, each with Ubuntu 22.04 installed.

The RedHat VM is used as a SSH proxy to get to the LXC Containers. There are approx 10 developers in my team, each developer has their own LXC Container.

An example VS Code SSH Configuration is as follows

```<code>IdentityFile c:\users\simon.carr2\.ssh\id_ed25519
Host jump-box
  HostName 10.15.236.74
  IdentityFile c:\users\simon.carr2\.ssh\id_ed25519
  User bob

Host container
  HostName 10.36.165.29
  User bob
  IdentityFile c:\users\simon.carr2\.ssh\id_ed25519
  ProxyCommand ssh -q -W %h:%p jump-box
</code>```

I can connect to the Host called container (which is proxied through jump-box)

Once connected, in VSCode, I try to Clone Repository in Container Volume
When prompted I put the https link to my on-prem private repo (Running in GitLab)

But I am given the following error in the terminal

```<code>[85754 ms] Dev Containers 0.266.1 in VS Code 1.74.0 (5235c6bb189b60b01b1f49062f4ffa42384f8c91).
[85754 ms] Start: Run: ssh container /bin/sh
[85784 ms] Start: Run in host: id -un
[87248 ms] bob
[87249 ms]
[87251 ms] Start: Run in host: cat /etc/passwd
[87310 ms] Start: Run in host: echo ~
[87421 ms] /home/bob
[87422 ms]
[87424 ms] Start: Run in host: test -x '/home/bob/.vscode-remote-containers/bin/5235c6bb189b60b01b1f49062f4ffa42384f8c91/node'
[87546 ms]
[87547 ms]
[87547 ms] Exit code 1
[87548 ms] Start: Run in host: test -x '/home/bob/.vscode-server/bin/5235c6bb189b60b01b1f49062f4ffa42384f8c91/node'
[87654 ms]
[87655 ms]
[87656 ms] Start: Run in host: test -f '/home/bob/.vscode-server/bin/5235c6bb189b60b01b1f49062f4ffa42384f8c91/node_modules/node-pty/package.json'
[87761 ms]
[87761 ms]
[87761 ms] Start: Run in host: test -f '/home/bob/.vscode-remote-containers/dist/vscode-remote-containers-server-0.266.1.js'
[87865 ms]
[87866 ms]
[87898 ms] userEnvProbe: loginInteractiveShell (default)
[87899 ms] userEnvProbe shell: /bin/bash
[88078 ms] userEnvProbe PATHs:
Probe:     '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin'
Container: None
[88188 ms] Start: Run in Host: docker version --format {{.Server.APIVersion}}
[88422 ms] 1.41
[101518 ms] Start: Run in Host: git ls-remote https://gitlab.mydomain.net/gitlab-instance-eb474769/syclops-gui.git
[101724 ms]
[101725 ms] fatal: could not read Username for 'https://gitlab.mydomain.net': No such device or address

[101725 ms] Exit code 128
</code>```

How do I get VSCode to prompt me for Git Credentials?

Body:
I have a VM running RedHat 8.6, which is running multiple LXC containers, each with Ubuntu 22.04 installed.

The RedHat VM is used as a SSH proxy to get to the LXC Containers. There are approx 10 developers in my team, each developer has their own LXC Container.

An example VS Code SSH Configuration is as follows

IdentityFile c:\users\simon.carr2\.ssh\id_ed25519
Host jump-box
  HostName 10.15.236.74
  IdentityFile c:\users\simon.carr2\.ssh\id_ed25519
  User bob

Host container
  HostName 10.36.165.29
  User bob
  IdentityFile c:\users\simon.carr2\.ssh\id_ed25519
  ProxyCommand ssh -q -W %h:%p jump-box

I can connect to the Host called container (which is proxied through jump-box)

Once connected, in VSCode, I try to Clone Repository in Container Volume
When prompted I put the https link to my on-prem private repo (Running in GitLab)

But I am given the following error in the terminal

[85754 ms] Dev Containers 0.266.1 in VS Code 1.74.0 (5235c6bb189b60b01b1f49062f4ffa42384f8c91).
[85754 ms] Start: Run: ssh container /bin/sh
[85784 ms] Start: Run in host: id -un
[87248 ms] bob
[87249 ms]
[87251 ms] Start: Run in host: cat /etc/passwd
[87310 ms] Start: Run in host: echo ~
[87421 ms] /home/bob
[87422 ms]
[87424 ms] Start: Run in host: test -x '/home/bob/.vscode-remote-containers/bin/5235c6bb189b60b01b1f49062f4ffa42384f8c91/node'
[87546 ms]
[87547 ms]
[87547 ms] Exit code 1
[87548 ms] Start: Run in host: test -x '/home/bob/.vscode-server/bin/5235c6bb189b60b01b1f49062f4ffa42384f8c91/node'
[87654 ms]
[87655 ms]
[87656 ms] Start: Run in host: test -f '/home/bob/.vscode-server/bin/5235c6bb189b60b01b1f49062f4ffa42384f8c91/node_modules/node-pty/package.json'
[87761 ms]
[87761 ms]
[87761 ms] Start: Run in host: test -f '/home/bob/.vscode-remote-containers/dist/vscode-remote-containers-server-0.266.1.js'
[87865 ms]
[87866 ms]
[87898 ms] userEnvProbe: loginInteractiveShell (default)
[87899 ms] userEnvProbe shell: /bin/bash
[88078 ms] userEnvProbe PATHs:
Probe:     '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin'
Container: None
[88188 ms] Start: Run in Host: docker version --format {{.Server.APIVersion}}
[88422 ms] 1.41
[101518 ms] Start: Run in Host: git ls-remote https://gitlab.mydomain.net/gitlab-instance-eb474769/syclops-gui.git
[101724 ms]
[101725 ms] fatal: could not read Username for 'https://gitlab.mydomain.net': No such device or address

[101725 ms] Exit code 128

How do I get VSCode to prompt me for Git Credentials?


问:
GitHub Actions shared non-secret variables
I know about organization-wide secrets for GitHub Actions, but I'm looking for a way to define organization-wide non-secret variables, such as default environment variables or something similar.
Sometimes you simply don't want all your shared config to be secret. An example is for AWS credentials, where it may be beneficial to see the AWS_ACCESS_KEY_ID in plain text, but keep the AWS_SECRET_ACCESS_KEY as a secret.

It seems silly to have to put the same AWS_ACCESS_KEY_ID variable as an env variable in every single repo, while the secret half of that pair works perfectly to configure once for the entire organization... Is there such a way?
Perhaps a workaround could be to create a reused workflow action such as set-env that sets the shared environment variables and then include that in each and every job such as uses: my-org/github-actions/.github/workflows/set-env.yml@main, but it's not the cleanest solution I think.

Too bad there's simply not an option next to GitHub action secrets to allow them to be ... well, not so secret.


问:
SQLFluff `exclude_rules` configuration ignored
I have this in my .sqlfluff, as per SQLFluff's documentation:

```<code>[sqlfluff]
exclude_rules = L003
</code>```

When I run sqlfluff lint in the same directory where the configuration file is located, it still checks rule L003. What am I missing to exclude it?

Body:
I have this in my .sqlfluff, as per SQLFluff's documentation:

[sqlfluff]
exclude_rules = L003

When I run sqlfluff lint in the same directory where the configuration file is located, it still checks rule L003. What am I missing to exclude it?


问:
How could i show a global SnakBar using persistent_bottom_nav_bar?
I am using persistent_bottom_nav_bar: ^5.0.2, and until now keep the botton navigation bar for all the screen, but, How can i show a global snakbar? I want to generate a snakcbar in creen A, and when i swich to creen B (using botton navigation) keep it visible. Actually when i swich the snakbar dont show in the other one

```<code>class MainUI extends StatefulWidget {
  const MainUI({super.key});

  @override
  State<MainUI> createState() => _MainUIState();
}

class _MainUIState extends State<MainUI> {
  late PersistentTabController _controller;
  final screens = [
    SalesPage(), //<- I want that when i change to this one keep wathing it
    ConfigurationPage(), //<- I had inside this screen other screen and in this one is where i show my SnakcBar
  ];

  final _navBarsItems = [
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.food_bank),
      title: ("Sales"),
      activeColorPrimary: CupertinoColors.white,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: Icon(CupertinoIcons.settings),
      title: ("Configuration"),
      activeColorPrimary: CupertinoColors.white,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
  ];

  @override
  void initState() {
    super.initState();
    _controller = PersistentTabController(initialIndex: 0);
  }

  @override
  Widget build(BuildContext context) {
    return PersistentTabView(
      key: scaffoldKey,
      backgroundColor: Colors.blue.shade400,
      context,
      screens: screens,
      items: _navBarsItems,
    );
  }
}
</code>```

Body:
I am using persistent_bottom_nav_bar: ^5.0.2, and until now keep the botton navigation bar for all the screen, but, How can i show a global snakbar? I want to generate a snakcbar in creen A, and when i swich to creen B (using botton navigation) keep it visible. Actually when i swich the snakbar dont show in the other one

class MainUI extends StatefulWidget {
  const MainUI({super.key});

  @override
  State<MainUI> createState() => _MainUIState();
}

class _MainUIState extends State<MainUI> {
  late PersistentTabController _controller;
  final screens = [
    SalesPage(), //<- I want that when i change to this one keep wathing it
    ConfigurationPage(), //<- I had inside this screen other screen and in this one is where i show my SnakcBar
  ];

  final _navBarsItems = [
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.food_bank),
      title: ("Sales"),
      activeColorPrimary: CupertinoColors.white,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: Icon(CupertinoIcons.settings),
      title: ("Configuration"),
      activeColorPrimary: CupertinoColors.white,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
  ];

  @override
  void initState() {
    super.initState();
    _controller = PersistentTabController(initialIndex: 0);
  }

  @override
  Widget build(BuildContext context) {
    return PersistentTabView(
      key: scaffoldKey,
      backgroundColor: Colors.blue.shade400,
      context,
      screens: screens,
      items: _navBarsItems,
    );
  }
}


问:
Insert data after use 'delete' or 'truncate'
I have this two queries:

Query 1:

```<code>DELETE FROM table_2;
</code>```

Query 2:

```<code>INSERT IGNORE INTO table_2
SELECT * from table_1;
</code>```

Both queries work fine, running them separately does not give an error. But putting them together like this gives syntax error:

```<code>DELETE FROM table_2;
INSERT IGNORE INTO table_2
SELECT * from table_1;

SQL Error: ... syntax error near 'INSERT IGNORE INTO table_2...
</code>```

This error occurs because I can't use INSERT after a DELETE or TRUNCATE. I'm testing this in a scrypt before doing it in a stored procedure, how can I delete all the rows and then insert data? In case you suggest me to use UPDATE, what would your implementation look like?

EDIT SOLVED:

I was running the query in a scrypt, that's why it gave error. But if I put it in a stored procedure it doesn't give an error.

Body:
I have this two queries:

Query 1:

DELETE FROM table_2;

Query 2:

INSERT IGNORE INTO table_2
SELECT * from table_1;

Both queries work fine, running them separately does not give an error. But putting them together like this gives syntax error:

DELETE FROM table_2;
INSERT IGNORE INTO table_2
SELECT * from table_1;

SQL Error: ... syntax error near 'INSERT IGNORE INTO table_2...

This error occurs because I can't use INSERT after a DELETE or TRUNCATE. I'm testing this in a scrypt before doing it in a stored procedure, how can I delete all the rows and then insert data? In case you suggest me to use UPDATE, what would your implementation look like?

EDIT SOLVED:

I was running the query in a scrypt, that's why it gave error. But if I put it in a stored procedure it doesn't give an error.


问:
How to deploy angular universal on IIS
Can someone help me to deploy angular universal build on IIS server?
I have integrated angular universal in existing angular 13 project and its working fine. but my problem with deployment on IIS when deploying build as website it's working for example on root (https:www.domain.com) but I want this to deploy as application not website (https:www.domain.com/myapp).
Where myapp is application which is under sites.
Facing issues like MIME type or unexpected syntax error for CSS/JS files.

Can someone please help me on this

Tried with Deploy Angular Universal to IIS

But this is for website, want to deploy as application on iis

Title: How to deploy angular universal on IIS


问:
is the possible to pass the date from s3 to ecr container path?
We got the below error while ECS run the task. In that task, I need to pass the s3 bucket data to the container.
I try to download the data from s3 to the container. I got a file not found an error

I am downloading s3 data from s3 to the ECS container workspace.

```<code>s3.Bucket(BUCKET_NAME).download_file(s3 path, ecs container workspace path)
</code>```

What path needs to give in ecs container workspace path

Body:
We got the below error while ECS run the task. In that task, I need to pass the s3 bucket data to the container.
I try to download the data from s3 to the container. I got a file not found an error

I am downloading s3 data from s3 to the ECS container workspace.

s3.Bucket(BUCKET_NAME).download_file(s3 path, ecs container workspace path)

What path needs to give in ecs container workspace path


问:
How to get a particular Index from a shuffled array
I've been working on a quiz app using NextJs and after figuring out how to work around the hydration issue in Nextjs, Now I'm stuck trying to figure out how to keep track of a value in the array.

export default function quiz({ questions }) {
  const link = `https://the-trivia-api.com/api/questions`;

  const [number, setNumber] = useState(0);
  const [quizData, setQuizData] = useState(questions);
  const [numbering, setNumbering] = useState(1);
  const [initialRenderComplete, setInitialRenderComplete] = useState(false);

  console.log(quizData[number].correctAnswer);

  const oldArray = [...quizData[number].incorrectAnswers, quizData[number].correctAnswer];
  oldArray.push(quizData[number].correctAnswer); //Here I pushed the correct answer and incorrect answer into a single array.
  const newArray = [...new Set(oldArray)]; // 'newArray' is the new array containing all the four options.

  const increase = () => {
    setNumber(number + 1);
    setNumbering(numbering + 1);
  };
  const decrease = () => {
    setNumber(number - 1);
    setNumbering(numbering - 1);
  };

  useEffect(() => {
    setInitialRenderComplete(true);
  }, []);

  if (!initialRenderComplete) {
    return null;
  } else {
    newArray.sort(() => (Math.random() > 0.5 ? 1 : -1)); // Here i shuffled the newArray, So the correct and incorrect answer is shuffled.
    return (

{state}

            {numbering}. {questions[number].question}{" "}

A.

                <button>

{newArray[1]}

                </button>

B.

                <button>
                  {" "}

 {newArray[0]}

                </button>

C.

                <button>

{newArray[3]}

                </button>

D.

                <button>

{newArray[2]}

                </button>

            <button onClick={decrease} className={styles.prev}>
              Previous{" "}
            </button>
            <button onClick={increase} className={styles.next}>
              Next{" "}
            </button>

    );
  }
}

//Here is my Api Call
export const getStaticProps = async () => {
  const data = await Axios.get("https://the-trivia-api.com/api/questions");

  // const data = req;
  const initialData = data.data;
  return {
    props: {
      // question: data.data[indexing],
      questions: initialData,
    },
  };
};
```

Now I'm stuck on how to keep track of which is the correct or incorrect Option onClick of the button, I figured I could maybe keep track of the index of the correct answer in the array but I don't think it would work and I can't figure out how to do it, Thanks in Advance.

Body:
I've been working on a quiz app using NextJs and after figuring out how to work around the hydration issue in Nextjs, Now I'm stuck trying to figure out how to keep track of a value in the array.

export default function quiz({ questions }) {
  const link = `https://the-trivia-api.com/api/questions`;

  const [number, setNumber] = useState(0);
  const [quizData, setQuizData] = useState(questions);
  const [numbering, setNumbering] = useState(1);
  const [initialRenderComplete, setInitialRenderComplete] = useState(false);

  console.log(quizData[number].correctAnswer);

  const oldArray = [...quizData[number].incorrectAnswers, quizData[number].correctAnswer];
  oldArray.push(quizData[number].correctAnswer); //Here I pushed the correct answer and incorrect answer into a single array.
  const newArray = [...new Set(oldArray)]; // 'newArray' is the new array containing all the four options.

  const increase = () => {
    setNumber(number + 1);
    setNumbering(numbering + 1);
  };
  const decrease = () => {
    setNumber(number - 1);
    setNumbering(numbering - 1);
  };

  useEffect(() => {
    setInitialRenderComplete(true);
  }, []);

  if (!initialRenderComplete) {
    return null;
  } else {
    newArray.sort(() => (Math.random() > 0.5 ? 1 : -1)); // Here i shuffled the newArray, So the correct and incorrect answer is shuffled.
    return (

{state}

            {numbering}. {questions[number].question}{" "}

A.

                <button>

{newArray[1]}

                </button>

B.

                <button>
                  {" "}

 {newArray[0]}

                </button>

C.

                <button>

{newArray[3]}

                </button>

D.

                <button>

{newArray[2]}

                </button>

            <button onClick={decrease} className={styles.prev}>
              Previous{" "}
            </button>
            <button onClick={increase} className={styles.next}>
              Next{" "}
            </button>

    );
  }
}

//Here is my Api Call
export const getStaticProps = async () => {
  const data = await Axios.get("https://the-trivia-api.com/api/questions");

  // const data = req;
  const initialData = data.data;
  return {
    props: {
      // question: data.data[indexing],
      questions: initialData,
    },
  };
};

Now I'm stuck on how to keep track of which is the correct or incorrect Option onClick of the button, I figured I could maybe keep track of the index of the correct answer in the array but I don't think it would work and I can't figure out how to do it, Thanks in Advance.


问:
Ecto - How to populate List of IDs in Schema Elixir Postgres
I'm getting response from Ecto Schema query with joins multiple tables.

Here is my query:

```<code>    query =
      from(
        item in ItemSchema,
        join: item_cat in ItemCategorySchema,
        on: item.item_category_id == item_cat.item_category_id,
        preload: [:BusinessSchema],
        select: %{
          "item_id" => item.item_id,
          "item_name" => item.item_name,
          "description" => item.description,
          "item_category" => item_cat.category_name,
          "businesses" => item.business_ids,
        }
      )

    Repo.all(query)
</code>```

Here is Item Schema:

```<code>   schema "items" do
     field(:item_id, :string)
     field(:item_category_id, :string)
     field(:user_id, :string)
     field(:business_ids, {:array, :string})

     field(:item_name, :string)
     field(:description, :string)
   end
</code>```

Here is Item Category Schema:

```<code>   schema "item_categories" do
     field(:item_category_id, :string)
     field(:item_category_id, :string)
     field(:category_name, :string)
   end
</code>```

Here is Business Schema:

```<code>   schema "businesses" do
     field(:business_id, :string)
     field(:business_name, :string)
   end
</code>```

But business_ids not populated with an item. How to populate list of businesses which are in each item.

Desirable result:

```<code>     [
        %{
            "item_id" => "id_01",
            "item_name" => "A",
            "description" => "A description",
            "item_category" => "some category",
            "businesses" => [
                ${
                    "business_id" => "business_id_01",
                    "business_name" => "Business Name 1",
                },
                ${
                    "business_id" => "business_id_02",
                    "business_name" => "Business Name 2",
                },
            ]
        },
        %{
            "item_id" => "id_02",
            "item_name" => "B",
            "description" => "B description",
            "item_category" => "some category",
            "businesses" => [
                ${
                    "business_id" => "business_id_02",
                    "business_name" => "Business Name 2",
                },
                ${
                    "business_id" => "business_id_03",
                    "business_name" => "Business Name 3",
                }
            ]
        }
     ]
</code>```

Body:
I'm getting response from Ecto Schema query with joins multiple tables.

Here is my query:

    query =
      from(
        item in ItemSchema,
        join: item_cat in ItemCategorySchema,
        on: item.item_category_id == item_cat.item_category_id,
        preload: [:BusinessSchema],
        select: %{
          "item_id" => item.item_id,
          "item_name" => item.item_name,
          "description" => item.description,
          "item_category" => item_cat.category_name,
          "businesses" => item.business_ids,
        }
      )

    Repo.all(query)

Here is Item Schema:

   schema "items" do
     field(:item_id, :string)
     field(:item_category_id, :string)
     field(:user_id, :string)
     field(:business_ids, {:array, :string})

     field(:item_name, :string)
     field(:description, :string)
   end

Here is Item Category Schema:

   schema "item_categories" do
     field(:item_category_id, :string)
     field(:item_category_id, :string)
     field(:category_name, :string)
   end

Here is Business Schema:

   schema "businesses" do
     field(:business_id, :string)
     field(:business_name, :string)
   end

But business_ids not populated with an item. How to populate list of businesses which are in each item.

Desirable result:

     [
        %{
            "item_id" => "id_01",
            "item_name" => "A",
            "description" => "A description",
            "item_category" => "some category",
            "businesses" => [
                ${
                    "business_id" => "business_id_01",
                    "business_name" => "Business Name 1",
                },
                ${
                    "business_id" => "business_id_02",
                    "business_name" => "Business Name 2",
                },
            ]
        },
        %{
            "item_id" => "id_02",
            "item_name" => "B",
            "description" => "B description",
            "item_category" => "some category",
            "businesses" => [
                ${
                    "business_id" => "business_id_02",
                    "business_name" => "Business Name 2",
                },
                ${
                    "business_id" => "business_id_03",
                    "business_name" => "Business Name 3",
                }
            ]
        }
     ]


问:
After install OJS 3.X i cant acess the installation via Localhost
I have a problem, I installed OJS using Xampp, the installation went smoothly, but when accessing localhost/ojs I am receiving the error 500, in the index of my Xampp there is the following sentence:

Something is wrong with the XAMPP installation :-(

I don't know where to start, I've tried renaming index.php to index.txt with no results.

Thank you for your attention.

Tried to rename index.php
Tried reinstall ojs on another xampp database

localhost/phpmyadmin works fine.


问:
VS 2022 coding style options not being applied
I have configured VS 2022 to "prefer this." but the editor keeps removing "this." on code clean-up and suggesting that "name can be simplified" where I use them.

Anyone else encountered this issue?


问:
npm install cmd not working freezing longer time
In my project when I try to run npm install it is taking more time to execute and at the end it says

```<code>3948 Error An unknown git error occurred
  3949 error signal SIGTERM
  3950 error command
  git --no-replace-object clone http:/xyz/exam.git D:/npm-
  cache/_cacache/TMP/git-cloneiGr3M9 --recursive submodules--
  configcore.longpaths=true
  3951 error cloning D:/npm-cache/_cacache/TMP/git-cloneGr3M9....
</code>```

Os: windows 64,
Node version:18.9.0
NPM:8.19.1
Git: 2.37.3

in .npmrc file i have added

```<code>Fetch-retries=2,
Maxtimeout=1600000
Mintimeout=60000
no_proxy=
Strict-ssl=false
Registry=xyz.com
</code>```

and tried with npm install --no-audit
npm install --verbose
but the npm install cmd is showing above error only

Body:
In my project when I try to run npm install it is taking more time to execute and at the end it says

3948 Error An unknown git error occurred
  3949 error signal SIGTERM
  3950 error command
  git --no-replace-object clone http:/xyz/exam.git D:/npm-
  cache/_cacache/TMP/git-cloneiGr3M9 --recursive submodules--
  configcore.longpaths=true
  3951 error cloning D:/npm-cache/_cacache/TMP/git-cloneGr3M9....

Os: windows 64,
Node version:18.9.0
NPM:8.19.1
Git: 2.37.3

in .npmrc file i have added

Fetch-retries=2,
Maxtimeout=1600000
Mintimeout=60000
no_proxy=
Strict-ssl=false
Registry=xyz.com

and tried with npm install --no-audit
npm install --verbose
but the npm install cmd is showing above error only


问:
Create multiple columns when a condition is met in Pandas
I am trying to optimize some pandas code.
Right now we have code like this where df is a dataframe

```<code>df = df \
    .withColumn("models_with_cost", when(
            col("cost") != 0,
            col("models")
        ).otherwise(lit(None)))

df = df \
    .withColumn("product_line_with_cost", when(
            col("cost") != 0,
            col("product_line")
        ).otherwise(lit(None)))
</code>```

There are multiple such column creations where the cost column is being checked for the same condition.
Is there a possibility to optimize this code where cost is checked just once and the required columns are created and populated with correct values?

Body:
I am trying to optimize some pandas code.
Right now we have code like this where df is a dataframe

df = df \
    .withColumn("models_with_cost", when(
            col("cost") != 0,
            col("models")
        ).otherwise(lit(None)))

df = df \
    .withColumn("product_line_with_cost", when(
            col("cost") != 0,
            col("product_line")
        ).otherwise(lit(None)))

There are multiple such column creations where the cost column is being checked for the same condition.
Is there a possibility to optimize this code where cost is checked just once and the required columns are created and populated with correct values?


问:
Calcualting the empirical distribution function using statsmodels yields error
I would like to plot an empirical distribution function using statmodels. I tried what is advised here How to plot empirical cdf (ecdf):

```<code>import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt

price_values = [[4.2],
    [4.1],
    [4],
    [3.8],
    [3.9],
    [4.2],
    [4.5],
    [4.8],
    [5.2],
    [5.2],
    [5.2],
    [5.6],
    [5.2],
    [5.1],
    [5.3],
    [6],
    [6.2],
    [6.3],
    [6.2],
    [6],
    [5.5] ,
    [5.2],
    [4.8],
    [4.6]]

sample = price_values
ecdf = sm.distributions.ECDF(sample)

x = np.linspace(min(sample), max(sample))
y = ecdf(x)
plt.step(x, y)
plt.show()
</code>```

Unforunately, the line ecdf = sm.distributions.ECDF(sample) yields the error "ValueError: x and y do not have the same shape" that I don't understand. Any idea why this error occurs and how to tackle it?

Update: Here is the whole traceback of the error:

```<code>Traceback (most recent call last):
  File "C:\Users\wi9632\PycharmProjects\building-optimization\src\Plot_EDF.py", line 31, in <module>
    ecdf = sm.distributions.ECDF(sample)
  File "C:\Users\wi9632\Anaconda3\lib\site-packages\statsmodels\distributions\empirical_distribution.py", line 139, in __init__
    super(ECDF, self).__init__(x, y, side=side, sorted=True)
  File "C:\Users\wi9632\Anaconda3\lib\site-packages\statsmodels\distributions\empirical_distribution.py", line 89, in __init__
    raise ValueError(msg)
ValueError: x and y do not have the same shape

Process finished with exit code 1
</code>```

Body:
I would like to plot an empirical distribution function using statmodels. I tried what is advised here How to plot empirical cdf (ecdf):

import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt

price_values = [[4.2],
    [4.1],
    [4],
    [3.8],
    [3.9],
    [4.2],
    [4.5],
    [4.8],
    [5.2],
    [5.2],
    [5.2],
    [5.6],
    [5.2],
    [5.1],
    [5.3],
    [6],
    [6.2],
    [6.3],
    [6.2],
    [6],
    [5.5] ,
    [5.2],
    [4.8],
    [4.6]]

sample = price_values
ecdf = sm.distributions.ECDF(sample)

x = np.linspace(min(sample), max(sample))
y = ecdf(x)
plt.step(x, y)
plt.show()

Unforunately, the line ecdf = sm.distributions.ECDF(sample) yields the error "ValueError: x and y do not have the same shape" that I don't understand. Any idea why this error occurs and how to tackle it?

Update: Here is the whole traceback of the error:

Traceback (most recent call last):
  File "C:\Users\wi9632\PycharmProjects\building-optimization\src\Plot_EDF.py", line 31, in <module>
    ecdf = sm.distributions.ECDF(sample)
  File "C:\Users\wi9632\Anaconda3\lib\site-packages\statsmodels\distributions\empirical_distribution.py", line 139, in __init__
    super(ECDF, self).__init__(x, y, side=side, sorted=True)
  File "C:\Users\wi9632\Anaconda3\lib\site-packages\statsmodels\distributions\empirical_distribution.py", line 89, in __init__
    raise ValueError(msg)
ValueError: x and y do not have the same shape

Process finished with exit code 1


问:
Show parent title if sub item selected
If I have list item and list item has sub items, but they are separated. Not like regularly it is inside list item.

I need to show item text inside breadcrumbs. If user clicks item it shows that list item text inside breadcrumb. Issue comes with childs because they are not grouped with parents.

At the moment if use clicks "Item 2.2" it shows in breadcrumb "Home > Item 2.2" but it should show "Home > Item 2 > Item 2.2"

As soon I've got working only if user clicks item it takes its text and shows in breadcrumb but I cant figure out if user clicks on child it would take also parent category title.

I have list like this:

```<code><div class="list">
    <div class="item">Item 1</div>
    <div class="item parent">Item 2</div>
    <div class="item child">
        <div class="item">Item 2.1</div>
        <div class="item">Item 2.2</div>
    </div>
    <div class="item">Item 3</div>
</div>
</code>```

My codepen test: codepen

Title: Show parent title if sub item selected

Body:
If I have list item and list item has sub items, but they are separated. Not like regularly it is inside list item.

I need to show item text inside breadcrumbs. If user clicks item it shows that list item text inside breadcrumb. Issue comes with childs because they are not grouped with parents.

At the moment if use clicks "Item 2.2" it shows in breadcrumb "Home > Item 2.2" but it should show "Home > Item 2 > Item 2.2"

As soon I've got working only if user clicks item it takes its text and shows in breadcrumb but I cant figure out if user clicks on child it would take also parent category title.

I have list like this:

Item 1

Item 2

Item 2.1

Item 2.2

Item 3

My codepen test: codepen


问:
MySQL COUNT results for first two entries on an ID in one table only if value is set in the first row but not in the second
my problem revolves around expanding a working MySQL query by limiting the rows it takes into consideration to the first two.

The table evaluations looks like this:

```<code>id |  item_id   |  in  |  out  |
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1  |    232     | NULL |   1   |
2  |    834     | NULL |   1   |
3  |    232     |   1  |  NULL |
4  |     56     | NULL |   1   |

</code>```

Currently, there can be N entries for each item_id. The goal is to compare if there is any mismatch between in & out for one item_id.

I currently achieve this with the following SQL-statement:

```<code>SELECT COUNT(DISTINCT item_id), item_id
FROM evaluations x1
WHERE in IS NOT NULL and EXISTS(
Select 1
FROM evaluations x2
WHERE x1.item_id = x2.item_id AND out IS NOT NULL AND
x1.id <> x2.id);
</code>```

This returns the cases where in & out are mismatched once over all ids reliably.

I now want to limit the above query to only consider the first two rows for each item_id for the mismatch check. Just LIMITing the subquery logically does not lead to any success as it would only limit once out is found.

Using LIMIT using the current query does not lead to anything; unfortunately, the MariaDB I'm running does not support LIMIT in subqueries.

```<code>This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery
</code>```

I've tried using HAVING and JOINing the table to itself to no avail:

```<code>SELECT e1.in, e1.form_id, COUNT(e2.form_id), e2.out, e2.in AS res
FROM evaluations AS e1
INNER JOIN evaluations AS e2 USING(form_id)
GROUP BY e1.form_id
HAVING e1.in > 0 and e2.out > 0
LIMIT 2;
</code>```

I'm really at a loss here.

Any guidance is very much appreciated. Thank you in advance.

Kind regards

Phil

Body:
my problem revolves around expanding a working MySQL query by limiting the rows it takes into consideration to the first two.

The table evaluations looks like this:

id |  item_id   |  in  |  out  |
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1  |    232     | NULL |   1   |
2  |    834     | NULL |   1   |
3  |    232     |   1  |  NULL |
4  |     56     | NULL |   1   |

Currently, there can be N entries for each item_id. The goal is to compare if there is any mismatch between in & out for one item_id.

I currently achieve this with the following SQL-statement:

SELECT COUNT(DISTINCT item_id), item_id
FROM evaluations x1
WHERE in IS NOT NULL and EXISTS(
Select 1
FROM evaluations x2
WHERE x1.item_id = x2.item_id AND out IS NOT NULL AND
x1.id <> x2.id);

This returns the cases where in & out are mismatched once over all ids reliably.

I now want to limit the above query to only consider the first two rows for each item_id for the mismatch check. Just LIMITing the subquery logically does not lead to any success as it would only limit once out is found.

Using LIMIT using the current query does not lead to anything; unfortunately, the MariaDB I'm running does not support LIMIT in subqueries.

This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery

I've tried using HAVING and JOINing the table to itself to no avail:

SELECT e1.in, e1.form_id, COUNT(e2.form_id), e2.out, e2.in AS res
FROM evaluations AS e1
INNER JOIN evaluations AS e2 USING(form_id)
GROUP BY e1.form_id
HAVING e1.in > 0 and e2.out > 0
LIMIT 2;

I'm really at a loss here.

Any guidance is very much appreciated. Thank you in advance.

Kind regards

Phil


问:
Change principal_name value in oauth2authorizedclient spring security
I am working in social media portal backend with spring boot framework using oauth2 to get access the user account so my app works as client role in oauth2 framework so spring security after success authorization it create Oauth2AuthorizedClient and persist it in memory so i change the implementation to persist it into database by register a bean type OAuth2AuthorizedClientService

```<code>
    @Bean
    public OAuth2AuthorizedClientService oAuth2AuthorizedClientService
        (JdbcOperations jdbc, ClientRegistrationRepository repo) {
        return new JdbcOAuth2AuthorizedClientService(jdbcOperations, clientRegistrationRepository);
    }

    @Bean
    @Order(value = Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain securityFilterChain(HttpSecurity http,
            ClientRegistrationRepository clientRegistrationRepository
            ) throws Exception {
        return http.csrf().disable()
            .authorizeRequests(
                auth -> auth.antMatchers("/api/v1/auth/**").permitAll()
                    .anyRequest().authenticated())
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
            .oauth2Client()
            .authorizedClientService(oAuth2AuthorizedClientService())
            .and()
            .build();
    }

</code>```

After the created OAuth2AuthorizedClient saved to database , it saved with principal name of email address of signed in user , i want to use id of user's account in facebook as a principal name the scopes also null

How can i solve this issue

enter image description here

Body:
I am working in social media portal backend with spring boot framework using oauth2 to get access the user account so my app works as client role in oauth2 framework so spring security after success authorization it create Oauth2AuthorizedClient and persist it in memory so i change the implementation to persist it into database by register a bean type OAuth2AuthorizedClientService

    @Bean
    public OAuth2AuthorizedClientService oAuth2AuthorizedClientService
        (JdbcOperations jdbc, ClientRegistrationRepository repo) {
        return new JdbcOAuth2AuthorizedClientService(jdbcOperations, clientRegistrationRepository);
    }

    @Bean
    @Order(value = Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain securityFilterChain(HttpSecurity http,
            ClientRegistrationRepository clientRegistrationRepository
            ) throws Exception {
        return http.csrf().disable()
            .authorizeRequests(
                auth -> auth.antMatchers("/api/v1/auth/**").permitAll()
                    .anyRequest().authenticated())
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
            .oauth2Client()
            .authorizedClientService(oAuth2AuthorizedClientService())
            .and()
            .build();
    }

After the created OAuth2AuthorizedClient saved to database , it saved with principal name of email address of signed in user , i want to use id of user's account in facebook as a principal name the scopes also null

How can i solve this issue

enter image description here


问:
Exception in thread "main" java.lang.NoClassDefFoundError: com/talend/csv/CSVWriter when create Schema in Talend
Good day,

I am new to Talend, I am trying to create a Schema for tFileInputDelimited component. The Schema is trying to read a text file from a folder.

However, during step 3 on creating this Schema, I am hitting some class not found exception:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/talend/csv/CSVWriter
    at orion_dl_track.shadowfileinputtodelimitedoutput_0_1.ShadowFileInputToDelimitedOutput.tFileInputDelimitedProcess(ShadowFileInputToDelimitedOutput.java:1709)
    at orion_dl_track.shadowfileinputtodelimitedoutput_0_1.ShadowFileInputToDelimitedOutput.runJobInTOS(ShadowFileInputToDelimitedOutput.java:2436)
    at orion_dl_track.shadowfileinputtodelimitedoutput_0_1.ShadowFileInputToDelimitedOutput.main(ShadowFileInputToDelimitedOutput.java:2295)
Caused by: java.lang.ClassNotFoundException: com.talend.csv.CSVWriter
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 3 more

Preview error. Some settings must be changed.
Note: Preview errors are generally due to a wrong encoding setting.
org.talend.designer.runprocess.shadow.ShadowFilePreview.preview(ShadowFilePreview.java:90)
org.talend.metadata.managment.ui.utils.ShadowProcessHelper.getCsvArray(ShadowProcessHelper.java:383)
org.talend.repository.ui.wizards.metadata.connection.files.delimited.DelimitedFileStep2Form$PreviewProcessor.nonUIProcessInThread(DelimitedFileStep2Form.java:1309)
org.talend.commons.ui.swt.thread.SWTUIThreadProcessor$1.run(SWTUIThreadProcessor.java:74)
</code>```

For java program, then I will know I need to import this library into my project, like adding the gradle implementation script from Maven website.

But how about this talend? Is it I need to go some where to download the jar and import into Talend Studio?

Body:
Good day,

I am new to Talend, I am trying to create a Schema for tFileInputDelimited component. The Schema is trying to read a text file from a folder.

However, during step 3 on creating this Schema, I am hitting some class not found exception:

Exception in thread "main" java.lang.NoClassDefFoundError: com/talend/csv/CSVWriter
    at orion_dl_track.shadowfileinputtodelimitedoutput_0_1.ShadowFileInputToDelimitedOutput.tFileInputDelimitedProcess(ShadowFileInputToDelimitedOutput.java:1709)
    at orion_dl_track.shadowfileinputtodelimitedoutput_0_1.ShadowFileInputToDelimitedOutput.runJobInTOS(ShadowFileInputToDelimitedOutput.java:2436)
    at orion_dl_track.shadowfileinputtodelimitedoutput_0_1.ShadowFileInputToDelimitedOutput.main(ShadowFileInputToDelimitedOutput.java:2295)
Caused by: java.lang.ClassNotFoundException: com.talend.csv.CSVWriter
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 3 more

Preview error. Some settings must be changed.
Note: Preview errors are generally due to a wrong encoding setting.
org.talend.designer.runprocess.shadow.ShadowFilePreview.preview(ShadowFilePreview.java:90)
org.talend.metadata.managment.ui.utils.ShadowProcessHelper.getCsvArray(ShadowProcessHelper.java:383)
org.talend.repository.ui.wizards.metadata.connection.files.delimited.DelimitedFileStep2Form$PreviewProcessor.nonUIProcessInThread(DelimitedFileStep2Form.java:1309)
org.talend.commons.ui.swt.thread.SWTUIThreadProcessor$1.run(SWTUIThreadProcessor.java:74)

For java program, then I will know I need to import this library into my project, like adding the gradle implementation script from Maven website.

But how about this talend? Is it I need to go some where to download the jar and import into Talend Studio?


问:
Save a pivot table structure based on external source without saving/cacheing the data
I have an external data source that implements row-level security.

I have an XLSX file which I want to distribute which will have a pivot table based on the external source. All of my users have an identically configured ODBC connection, except it uses each of their personal credentials and thus they have access to different data.

I've explored all of the connection & pivot table settings that supposedly give you such controls but they are not working for me. When I save my workbook, it seems that it is not possible to prevent the contents of the pivot table (as they currently look) from being saved. When a new user opens it, they will be able to see the current pivot table contents (which they perhaps shouldn't have access to) until they click "enable content", accept the various popups and/or wait for refresh.

Previously, I created a table based on external source and configured the connection to not save data - this worked. I then created a pivot table on top of the table range and configured it to not save source data. This sort of works except the table refreshes first and so the pivot table loses its settings and you have to start again with a blank pivot.

If you create a pivot table directly on the external source (rather than indirectly via a table), which I expect is the best practice, the tickbox in pivot table options for "Save source data with file" is greyed - presumably because excel knows the source data is actually external and so the question isn't relevant - except is is relevant because the pivot table output still contains data when saved

The only thing I can think of is is save the workbook as a user with 0 permission so the pivot table is structured correctly but with 0 contents and then send that round. Users will then see no/harmless data before it auto-refreshes at which point, they'll see what they should see.

Kind of feels like a glaring omission from excel. Am I missing something?


问:
Use mobilenet ssd instead of efficientdet lite
```<code>#Create whichever object detector's spec you want
spec = object_detector.EfficientDetLite4Spec(
   model_name='efficientdet-lite4',
   uri='https://tfhub.dev/tensorflow/efficientdet/lite4/feature-vector/2',
   hparams='', #enable grad_checkpoint=True if you want
   model_dir=checkpoint_dir,
   epochs=epochs,
   batch_size=batch_size,
   steps_per_execution=1,
   moving_average_decay=0,
   var_freeze_expr='(efficientnet|fpn_cells|resample_p6)',
   tflite_max_detections=25,
   strategy=None,
   tpu=None,
   gcp_project=None,
   tpu_zone=None,
   use_xla=False,
   profile=False,
   debug=False,
   tf_random_seed=111111,
   verbose=1
)
</code>```

How to use mobilenet ssd V1 instead of efficientdet lite4 and what could be imported to do so

Body:
#Create whichever object detector's spec you want
spec = object_detector.EfficientDetLite4Spec(
   model_name='efficientdet-lite4',
   uri='https://tfhub.dev/tensorflow/efficientdet/lite4/feature-vector/2',
   hparams='', #enable grad_checkpoint=True if you want
   model_dir=checkpoint_dir,
   epochs=epochs,
   batch_size=batch_size,
   steps_per_execution=1,
   moving_average_decay=0,
   var_freeze_expr='(efficientnet|fpn_cells|resample_p6)',
   tflite_max_detections=25,
   strategy=None,
   tpu=None,
   gcp_project=None,
   tpu_zone=None,
   use_xla=False,
   profile=False,
   debug=False,
   tf_random_seed=111111,
   verbose=1
)

How to use mobilenet ssd V1 instead of efficientdet lite4 and what could be imported to do so