问:
Converting jupyter notebook to PDF removes table structure
I am trying to make a pdf file from my jupyter notebook, when i choose the PDF via LaTeX option, after the generation of pdf file, the structure of the table disappears. What can be done to prevent this issue?

Here is the markdown code of my table :

```<code>| Col1      | Col2 |
| ----------- | ----------- |
| line1<br> line2      | line_1<br> line_2       |
| another line   | some text        |
</code>```

Here is the output in jupyter notebook :

And here is the generated table in the pdf file :

As you can see line1 and line2 are written in a single line in the pdf file.

Body:
I am trying to make a pdf file from my jupyter notebook, when i choose the PDF via LaTeX option, after the generation of pdf file, the structure of the table disappears. What can be done to prevent this issue?

Here is the markdown code of my table :

| Col1      | Col2 |
| ----------- | ----------- |
| line1
 line2      | line_1
 line_2       |
| another line   | some text        |

Here is the output in jupyter notebook :

And here is the generated table in the pdf file :

As you can see line1 and line2 are written in a single line in the pdf file.


来源: stackexchange

问:
what is the theme from serokell example?
What is the theme on the picture? I can not find, thanks

Expection to get an answer

ContentLicense: CC BY-SA 4.0


问:
How can I run Lua through the terminal WITH file path?
I have added lua's interpreter to path and it works with file names but I can't run lua through the terminal with file path. I am looking for a way to run lua through the terminal with the file path. I've encountered this while making a macro to automatically run lua files. My macro to run lua in Visual Studio Code uses this argument in keybindings:

```<code>"args": { "text": "lua '${file}'\u000D" }
</code>```

I have tried the command of lua D:/Downloads/Useful stuff/code/lua/a.lua but I'm getting the error: lua: cannot open D:/Downloads/Useful: No such file or directory. I have tried that command both without and with '', both of them don't work.

Body:
I have added lua's interpreter to path and it works with file names but I can't run lua through the terminal with file path. I am looking for a way to run lua through the terminal with the file path. I've encountered this while making a macro to automatically run lua files. My macro to run lua in Visual Studio Code uses this argument in keybindings:

"args": { "text": "lua '${file}'\u000D" }

I have tried the command of lua D:/Downloads/Useful stuff/code/lua/a.lua but I'm getting the error: lua: cannot open D:/Downloads/Useful: No such file or directory. I have tried that command both without and with '', both of them don't work.


问:
Drag and drop two elements and execute POST call with InteractJS and Htmx
Disclaimer: This is more an architectual question.

I am trying to build a quite simple UI. I have two lists of elements, all elements in boths lists are of the same type. If I drag one element from the left to the right onto an element of this list, I want to execute a POST call to the backend sending both data-obj-id attribute values along.

I settled on InteractJS and HTMX but its f**** hard to build something like this.

My approach: I need to fire some kind of event to trigger the HTMX POST call. But the event needs to know which elements are being dropped on each other. So I need a custom event (not possible to get the drop event anyway), which contains the ID of the other element.

I tried:

const newEvent = new Event('interactjs:drop-'+draggableElement.getAttribute('data-obj-id'));
document.body.dispatchEvent(newEvent);
```
<pre class="lang-html prettyprint-override"><code><div data-obj-id="{{ my_obj.id }}"
     hx-post="/my-post-call"
     hx-trigger="interactjs:drop-{{ my_obj.id }} from:body">...</div>
</code>```

But the moment the event contains a number, it's not recognised anymore. I guess I just chose a poor choice of architecture to solve my problem?

Thx!

Body:
Disclaimer: This is more an architectual question.

I am trying to build a quite simple UI. I have two lists of elements, all elements in boths lists are of the same type. If I drag one element from the left to the right onto an element of this list, I want to execute a POST call to the backend sending both data-obj-id attribute values along.

I settled on InteractJS and HTMX but its f**** hard to build something like this.

My approach: I need to fire some kind of event to trigger the HTMX POST call. But the event needs to know which elements are being dropped on each other. So I need a custom event (not possible to get the drop event anyway), which contains the ID of the other element.

I tried:

const newEvent = new Event('interactjs:drop-'+draggableElement.getAttribute('data-obj-id'));
document.body.dispatchEvent(newEvent);

...

But the moment the event contains a number, it's not recognised anymore. I guess I just chose a poor choice of architecture to solve my problem?

Thx!


问:
Static type hint for decorator that adds attribute to a class
Is it possible to create a type hint for a class decorator that adds an attribute to the given class? Since PEP612 it's possible to use ParamSpec and Concatenate for decorators that modify signatures, but I haven't found any equivalents for decorators that modify classes.

def add_x(cls_):
  cls_.x: int = 5
  return cls_

@add_x
class Example: pass
```

How would I have to type add_x to have x: int hinted on my Example class?

Body:
Is it possible to create a type hint for a class decorator that adds an attribute to the given class? Since PEP612 it's possible to use ParamSpec and Concatenate for decorators that modify signatures, but I haven't found any equivalents for decorators that modify classes.

def add_x(cls_):
  cls_.x: int = 5
  return cls_

@add_x
class Example: pass

How would I have to type add_x to have x: int hinted on my Example class?


问:
Unable to run the script in nest js getting missing script error
I have added the script in my packege.json file,but when trying to run in terminal by using command " npm run seed:ambassadors " it gives error missing script ,

Error:

```<code>    npm ERR! missing script: seed:ambassadors

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-12-29T11_33_08_599Z-debug.log
</code>```

docker-compose.yaml

packege.json

```<code>"scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "seed:ambassadors": "ts-node src/command/ambassador.seeder.ts"
  },
</code>```

NOTE: I am running that "npm run seed:ambassadors" commad in docker container and to run docker container I am using "docker-compose exec backend sh".

any suggestion plzzzz?????

Body:
I have added the script in my packege.json file,but when trying to run in terminal by using command " npm run seed:ambassadors " it gives error missing script ,

Error:

    npm ERR! missing script: seed:ambassadors

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-12-29T11_33_08_599Z-debug.log

docker-compose.yaml

packege.json

"scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "seed:ambassadors": "ts-node src/command/ambassador.seeder.ts"
  },

NOTE: I am running that "npm run seed:ambassadors" commad in docker container and to run docker container I am using "docker-compose exec backend sh".

any suggestion plzzzz?????


问:
PowerMockito is calling the real method instead of the moked one and gives NullPointException
I have a private method and calls another private method in its body. I want to mock the behaviour of the second one but when I use PowerMock, it calls the actuall method instead of the mocked one and gives NPE.

First private method

```<code>private UserTypes getUserType(String msisdn, String uuid) throws BaseException {
        logger.info("{}| getUserType method started",msisdn);
        UserTypes userType;
        Relationship relationship = relationshipService.getRelationshipByChildMsisdn(msisdn);

        if (relationship !=null){
            if (relationship.getMasterMsisdn() != null){
                userType = UserTypes.CHILD;
            }else {
                userType = UserTypes.CHILD_WITHOUT_MASTER;
            }
        } else if ( relationshipService.isMasterExists(msisdn)) {
            userType = UserTypes.MASTER;
        } else {
            QuerySubscribedGroupStatus subscribedGroupStatus = querySubscribedGroupAPICallService.querySubscribedGroupToGetStatus(uuid,msisdn);
            if (subscribedGroupStatus.equals(QuerySubscribedGroupStatus.NEW_USER)){
                if (checkForCallBlock(msisdn)) userType = UserTypes.NON_ELIGIBLE_USER;
                else userType = UserTypes.FRESH_USER;
            } else if (subscribedGroupStatus.equals(QuerySubscribedGroupStatus.BELONGS_TO_ANOTHER_CUG)) {
                userType = UserTypes.NON_ELIGIBLE_USER;
            } else if (subscribedGroupStatus.equals(QuerySubscribedGroupStatus.SUBSCRIBER_NOT_FOUND)) {
                BaseResponseData data = new BaseResponseData(ReasonCodes.SUB_NOT_IN_OCS.getReasonCode(), ReasonCodes.SUB_NOT_IN_OCS.getReasonDescription());
                throw new BaseException(ResultCode.REQUEST_FAILED.getCode(), ResultCode.REQUEST_FAILED.getDescription(), HttpStatus.OK,data);
            } else {
                BaseResponseData data = new BaseResponseData(ReasonCodes.ERROR_IN_QUERY_SUB_GROUP.getReasonCode(), ReasonCodes.ERROR_IN_QUERY_SUB_GROUP.getReasonDescription());
                throw new BaseException(ResultCode.EXTERNAL_API_CALL_FAILURE.getCode(), ResultCode.EXTERNAL_API_CALL_FAILURE.getDescription(), HttpStatus.INTERNAL_SERVER_ERROR,data);
            }
        }

        logger.info("{}| getUserType method ended | Returned userType: {}",msisdn,userType);
        return userType;
    }

</code>```

Second private method.

```<code> private boolean checkForCallBlock(String msisdn) throws BaseException {
        logger.info("{}| checkForCallBlock method started",msisdn);
        boolean callBlockActivated = false;
        try{
            vasMgtAPICallService.isRemoteVASPackageActivated(msisdn,msisdn,callBlockPackage);
        }catch (BaseException ex){
            if (ex.getData().getReasonCode() == 30010){
                logger.info("{}|Call block activated subscriber detected",msisdn);
                return true;
            }else {
                throw new BaseException (ex.getResultCode(),ex.getResultDescription(),ex.getStatus(),ex.getData());
            }
        }
        return callBlockActivated;
    }

</code>```

This is what I have tried.

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest(StatusMainService.class)
class StatusMainServiceTest {
    @Spy
    @InjectMocks
    StatusMainService statusMainService;

    @Mock
    QuerySubscribedGroupAPICallService querySubscribedGroupAPICallService;

    @Mock
    RelationshipService relationshipService;

    @Mock
    VASMgtAPICallService vasMgtAPICallService;

    @Mock
    PcrfPackageAPICallService pcrfPackageAPICallService;

    @Mock
    RestrictionPacksService restrictionPacksService;

    @Mock
    CcbsNumberBasicInfoApiCallService ccbsNumberBasicInfoApiCallService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.initMocks(this);

        ReflectionTestUtils.setField(statusMainService,"callBlockPackage", "I_CB");
    }

    @Test
    void getStatusData() {
    }

    @Test
    void processDataRestriction() {
    }

    @Test
    void getUserType() throws Exception {

        Relationship relationship1 = new Relationship();
        relationship1.setMasterMsisdn("779021671");
        doReturn(relationship1).when(relationshipService).getRelationshipByChildMsisdn("761408091");

        doReturn(new Relationship()).when(relationshipService).getRelationshipByChildMsisdn("761408092");

        doReturn(null).when(relationshipService).getRelationshipByChildMsisdn("761408093");
        doReturn(true).when(relationshipService).isMasterExists("761408093");

        doReturn(null).when(relationshipService).getRelationshipByChildMsisdn("761408094");
        doReturn(false).when(relationshipService).isMasterExists("761408094");
        doReturn(QuerySubscribedGroupStatus.NEW_USER).when(querySubscribedGroupAPICallService).querySubscribedGroupToGetStatus("1234567890", "761408094");

        StatusMainService statusMainServiceMock = PowerMockito.spy(new StatusMainService());
        PowerMockito.doReturn(true).when(statusMainServiceMock,"checkForCallBlock", "761408094");

        UserTypes userType1 = Whitebox.invokeMethod(statusMainService, "getUserType", "761408091", "1234567890");
        UserTypes userType2 = Whitebox.invokeMethod(statusMainService, "getUserType", "761408092", "1234567890");
        UserTypes userType3 = Whitebox.invokeMethod(statusMainService, "getUserType", "761408093", "1234567890");
        UserTypes userType4 = Whitebox.invokeMethod(statusMainService, "getUserType", "761408094", "1234567890");

        assertEquals(UserTypes.CHILD, userType1);
        assertEquals(UserTypes.CHILD_WITHOUT_MASTER, userType2);
        assertEquals(UserTypes.MASTER, userType3);
        assertEquals(UserTypes.NON_ELIGIBLE_USER, userType4);
    }

</code>```

This is where I mocked the second private method.
PowerMockito.doReturn(true).when(statusMainServiceMock,"checkForCallBlock", "761408094")

How I can solve this issue?

Body:
I have a private method and calls another private method in its body. I want to mock the behaviour of the second one but when I use PowerMock, it calls the actuall method instead of the mocked one and gives NPE.

First private method

private UserTypes getUserType(String msisdn, String uuid) throws BaseException {
        logger.info("{}| getUserType method started",msisdn);
        UserTypes userType;
        Relationship relationship = relationshipService.getRelationshipByChildMsisdn(msisdn);

        if (relationship !=null){
            if (relationship.getMasterMsisdn() != null){
                userType = UserTypes.CHILD;
            }else {
                userType = UserTypes.CHILD_WITHOUT_MASTER;
            }
        } else if ( relationshipService.isMasterExists(msisdn)) {
            userType = UserTypes.MASTER;
        } else {
            QuerySubscribedGroupStatus subscribedGroupStatus = querySubscribedGroupAPICallService.querySubscribedGroupToGetStatus(uuid,msisdn);
            if (subscribedGroupStatus.equals(QuerySubscribedGroupStatus.NEW_USER)){
                if (checkForCallBlock(msisdn)) userType = UserTypes.NON_ELIGIBLE_USER;
                else userType = UserTypes.FRESH_USER;
            } else if (subscribedGroupStatus.equals(QuerySubscribedGroupStatus.BELONGS_TO_ANOTHER_CUG)) {
                userType = UserTypes.NON_ELIGIBLE_USER;
            } else if (subscribedGroupStatus.equals(QuerySubscribedGroupStatus.SUBSCRIBER_NOT_FOUND)) {
                BaseResponseData data = new BaseResponseData(ReasonCodes.SUB_NOT_IN_OCS.getReasonCode(), ReasonCodes.SUB_NOT_IN_OCS.getReasonDescription());
                throw new BaseException(ResultCode.REQUEST_FAILED.getCode(), ResultCode.REQUEST_FAILED.getDescription(), HttpStatus.OK,data);
            } else {
                BaseResponseData data = new BaseResponseData(ReasonCodes.ERROR_IN_QUERY_SUB_GROUP.getReasonCode(), ReasonCodes.ERROR_IN_QUERY_SUB_GROUP.getReasonDescription());
                throw new BaseException(ResultCode.EXTERNAL_API_CALL_FAILURE.getCode(), ResultCode.EXTERNAL_API_CALL_FAILURE.getDescription(), HttpStatus.INTERNAL_SERVER_ERROR,data);
            }
        }

        logger.info("{}| getUserType method ended | Returned userType: {}",msisdn,userType);
        return userType;
    }

Second private method.

 private boolean checkForCallBlock(String msisdn) throws BaseException {
        logger.info("{}| checkForCallBlock method started",msisdn);
        boolean callBlockActivated = false;
        try{
            vasMgtAPICallService.isRemoteVASPackageActivated(msisdn,msisdn,callBlockPackage);
        }catch (BaseException ex){
            if (ex.getData().getReasonCode() == 30010){
                logger.info("{}|Call block activated subscriber detected",msisdn);
                return true;
            }else {
                throw new BaseException (ex.getResultCode(),ex.getResultDescription(),ex.getStatus(),ex.getData());
            }
        }
        return callBlockActivated;
    }

This is what I have tried.

@RunWith(PowerMockRunner.class)
@PrepareForTest(StatusMainService.class)
class StatusMainServiceTest {
    @Spy
    @InjectMocks
    StatusMainService statusMainService;

    @Mock
    QuerySubscribedGroupAPICallService querySubscribedGroupAPICallService;

    @Mock
    RelationshipService relationshipService;

    @Mock
    VASMgtAPICallService vasMgtAPICallService;

    @Mock
    PcrfPackageAPICallService pcrfPackageAPICallService;

    @Mock
    RestrictionPacksService restrictionPacksService;

    @Mock
    CcbsNumberBasicInfoApiCallService ccbsNumberBasicInfoApiCallService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.initMocks(this);

        ReflectionTestUtils.setField(statusMainService,"callBlockPackage", "I_CB");
    }

    @Test
    void getStatusData() {
    }

    @Test
    void processDataRestriction() {
    }

    @Test
    void getUserType() throws Exception {

        Relationship relationship1 = new Relationship();
        relationship1.setMasterMsisdn("779021671");
        doReturn(relationship1).when(relationshipService).getRelationshipByChildMsisdn("761408091");

        doReturn(new Relationship()).when(relationshipService).getRelationshipByChildMsisdn("761408092");

        doReturn(null).when(relationshipService).getRelationshipByChildMsisdn("761408093");
        doReturn(true).when(relationshipService).isMasterExists("761408093");

        doReturn(null).when(relationshipService).getRelationshipByChildMsisdn("761408094");
        doReturn(false).when(relationshipService).isMasterExists("761408094");
        doReturn(QuerySubscribedGroupStatus.NEW_USER).when(querySubscribedGroupAPICallService).querySubscribedGroupToGetStatus("1234567890", "761408094");

        StatusMainService statusMainServiceMock = PowerMockito.spy(new StatusMainService());
        PowerMockito.doReturn(true).when(statusMainServiceMock,"checkForCallBlock", "761408094");

        UserTypes userType1 = Whitebox.invokeMethod(statusMainService, "getUserType", "761408091", "1234567890");
        UserTypes userType2 = Whitebox.invokeMethod(statusMainService, "getUserType", "761408092", "1234567890");
        UserTypes userType3 = Whitebox.invokeMethod(statusMainService, "getUserType", "761408093", "1234567890");
        UserTypes userType4 = Whitebox.invokeMethod(statusMainService, "getUserType", "761408094", "1234567890");

        assertEquals(UserTypes.CHILD, userType1);
        assertEquals(UserTypes.CHILD_WITHOUT_MASTER, userType2);
        assertEquals(UserTypes.MASTER, userType3);
        assertEquals(UserTypes.NON_ELIGIBLE_USER, userType4);
    }

This is where I mocked the second private method.
PowerMockito.doReturn(true).when(statusMainServiceMock,"checkForCallBlock", "761408094")

How I can solve this issue?


问:
Losing the .txt extension of .txt.gz file after saving a python requests response as .gz
I have a list of HTTP URLs which return file content and I have saved those in a file. I don't know which URL will return what file content type. One of the URLs, when manually loaded on browser, downloads a .txt.gz file. However when I check for the content type of the request response it is application/x-gzip, and the file signature is 1f8b08 indicating a .gz file. When I save this file as .gz, the .txt extension of internal file is lost. And a file without any extension is present in the saved .gz file.

Is there any way to know what the file type of the file compressed inside the .gz or .zip file is from the requests content? Or to know that the file is a .txt.gz file?

In the image above we can see that the file inside 12345.gz does not have a .txt extension when I write the response content to a .gz file. But when I load the URL manually, the internal file has a .txt extension.

After reading the response content:

I am able to identify that the file signature is for .gz file but is there any way to know that file inside .gz archive is .txt or other type of file.

Here is an example of .gz file i get by manually downloading and saving the response.


问:
Micropython/Circuitpython --> Writing directly to an FTP server?
Is it possible to write to a file directly on an FTP server without first writing the file locally? In other words: writing to a remote file from local memory.

```<code>Board: ESP32-CAM
IDE: Thonny
Language: MicroPython (Lemariva's firmware)
</code>```
```<code>    from ftplib import FTP
    import camera

    ftp = FTP('192.168.1.65', '2121')
    ftp.login('user', '12345')
    ftp.cwd("/Cam/")

    filename = "test.jpeg"

    camera.init(0, format=camera.JPEG, fb_location=camera.PSRAM)
    camera.quality(10)
    camera.framesize(camera.FRAME_240X240)

    pic = camera.capture()
    fh = open(filename, 'rwb')
    ftp.storbinary('STOR '+filename, fh)
    fh.close()
</code>```

I'm assuming that I have to convert the camera.capture() object into a Byte array? But how do I do so without first capturing the image and thus writing to disk?

Body:
Is it possible to write to a file directly on an FTP server without first writing the file locally? In other words: writing to a remote file from local memory.

Board: ESP32-CAM
IDE: Thonny
Language: MicroPython (Lemariva's firmware)

    from ftplib import FTP
    import camera

    ftp = FTP('192.168.1.65', '2121')
    ftp.login('user', '12345')
    ftp.cwd("/Cam/")

    filename = "test.jpeg"

    camera.init(0, format=camera.JPEG, fb_location=camera.PSRAM)
    camera.quality(10)
    camera.framesize(camera.FRAME_240X240)

    pic = camera.capture()
    fh = open(filename, 'rwb')
    ftp.storbinary('STOR '+filename, fh)
    fh.close()

I'm assuming that I have to convert the camera.capture() object into a Byte array? But how do I do so without first capturing the image and thus writing to disk?


问:
Getting error message as INVALID_ARGUMENT: Invalid recognition 'config': Invalid class id speech-to-text API
we are using Google's speech-to-text API. We are trying to implement an adaptation model with the API. However, while doing so, we are getting an error message as 'INVALID_ARGUMENT: Invalid recognition 'config': Invalid class id {id}'. When I see whether CustomClass is available from cloud API, it shows it is available. However, still get the same error while using it in speech adaptation configuration. I am following this document https://github.com/googleapis/java-speech/blob/d1307be7e5510f4e5d9cf075a8efc3bd924d7bcf/samples/snippets/src/main/java/com/example/speech/SpeechModelAdaptationBeta.java. Any help would be greatly appreciated.

I tried using https://github.com/googleapis/java-speech/blob/d1307be7e5510f4e5d9cf075a8efc3bd924d7bcf/samples/snippets/src/main/java/com/example/speech/SpeechModelAdaptationBeta.java. But got exception only.

Below is the code which I am trying with:

`SpeechSettings speechSettings = SpeechSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();
AdaptationSettings adaptationSettings = AdaptationSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();
// Instantiates a client
SpeechClient speechClient = SpeechClient.create(speechSettings);

AdaptationClient adaptationClient = AdaptationClient.create(adaptationSettings);
String customClassUUID = UUID.randomUUID().toString().replace("-", "");

List<PhraseSet.Phrase> phraseArray = new ArrayList();

phraseArray.addAll(Phrase.newBuilder()
.setValue(
String.format("Visit restaurants like %s%n", customClassUUID)));
phraseArray.add(Phrase.newBuilder().setValue("Burger").build());

List classItemArray = new ArrayList();

classItemArray.add(ClassItem.newBuilder().setValue("Lettuce").build());
classItemArray.add(ClassItem.newBuilder().setValue("Burger").build());

CustomClass customClass = adaptationClient.createCustomClass(CreateCustomClassRequest.newBuilder().setParent(parent).setCustomClassId(customClassUUID).setCustomClass(CustomClass.newBuilder().addAllItems(classItemArray).build()).build());

String customClassName = parent+"/customClasses/"+customClassUUID;
String phraseSetUUID = UUID.randomUUID().toString().replace("-", "");
PhraseSet phraseSet = adaptationClient.createPhraseSet(CreatePhraseSetRequest.newBuilder().setParent(parent).setPhraseSetId(phraseSetUUID).setPhraseSet(PhraseSet.newBuilder().setBoost(10f).addPhrases(
Phrase.newBuilder()
.setValue(
String.format("Visit restaurants like %s%n", customClassUUID))).build()).build());

RecognitionConfig config =
RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.LINEAR16)
.setSampleRateHertz(8000)
.setLanguageCode("en-US")
.setUseEnhanced(true)
.setModel("phone_call")
.setAdaptation(SpeechAdaptation.newBuilder()
.addPhraseSets(adaptationClient.createPhraseSet(CreatePhraseSetRequest.newBuilder().setParent(parent).setPhraseSetId(phraseSetUUID).setPhraseSet(PhraseSet.newBuilder().setBoost(10f).addAllPhrases(phraseArray).build()).build()))
.addCustomClasses(adaptationClient.createCustomClass(CreateCustomClassRequest.newBuilder().setParent(parent).setCustomClassId(customClassUUID).setCustomClass(CustomClass.newBuilder().addAllItems(classItemArray).build()).build())).build())
.build();`


问:
Extract event data from process execution from Bonitastudio
I am working on a project and constructed my Bonita solution and executed it over a hundred of time. I would like to carry the project to the process mining phase and for me to carry out process mining I must have 3 fundamentals information: ID of the activities found in my process, the name of the activities and the timestamp of when the activities have been done.

I now need to extract the information from Bonitastudio but don't know how to extract these information. I had a look from the app website but could not find something that fulfilled my need.

I will be glad if you could give a help that could guide me please.

Thanks!


问:
Understanding batched `F.cosine_similarity` in `torch`
In the SimCLR torch implementation, cosine similarity is computed between feature maps of shape (512,128) in the following way:

```<code>cos_sim = F.cosine_similarity(feats[:,None,:], feats[None,:,:], dim=-1)
</code>```

Why do we need to expand the dimensions this way, instead of just computing F.cosine_similarity(feats, feats) according to the documentation? I would really like to see more examples for that.

Body:
In the SimCLR torch implementation, cosine similarity is computed between feature maps of shape (512,128) in the following way:

cos_sim = F.cosine_similarity(feats[:,None,:], feats[None,:,:], dim=-1)

Why do we need to expand the dimensions this way, instead of just computing F.cosine_similarity(feats, feats) according to the documentation? I would really like to see more examples for that.


问:
Load screen data after animation ended
Is there any way how to load screen data (for example from API or Room) after animated transition between two screens is done?
I am using LaunchedEffect for loading data from ViewModel, but I always get data while animation is still running and this looks very laggy.
I know there is a way how to do it with delay in use-case to get data later, but of course there must be a better solution for this...

Title: Load screen data after animation ended


问:
tag:[composer] install dependency error error [php7.0]
Nothing to install, update or remove
Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
Package yii2tech/ar-softdelete is abandoned, you should avoid using it. No replacement was suggested.
Package zendframework/zend-escaper is abandoned, you should avoid using it. Use laminas/laminas-escaper instead.
Package zendframework/zend-stdlib is abandoned, you should avoid using it. Use laminas/laminas-stdlib instead.

the above error should not appear while running composer install


问:
Connection of WEB API into MVC project for JWT authentication and authorization
I have onr ASP DotNet(6) Core MVC App and now I want to add a web api into to the JWT authentication and authorization.So How will I send the data to the web api for JWT authentication.And after generating the token how will I be able to reuse the token again?

I have studied a lot of articles on JWT addition with WEB API.They are just generating the token by hardcoding.I want to send the login details from the mvc app to the web api and after generating the token I want to reuse it.


问:
Jasper Reports dynamic expression inside $R
How to use dynamic expressions inside $R block?

I've tried

```<code>$R{"myEnum."+$F{enumValue}}
</code>```

but I'm getting syntax errors:

Syntax error, insert ")" to complete MethodInvocation Syntax error,
insert ";" to complete BlockStatements

etc.

Body:
How to use dynamic expressions inside $R block?

I've tried

$R{"myEnum."+$F{enumValue}}

but I'm getting syntax errors:

Syntax error, insert ")" to complete MethodInvocation Syntax error,
insert ";" to complete BlockStatements

etc.


问:
Why can't add capacitor to app in Nx monorepro?
We have two Angular applications with libraries in our Nx monorepro. I want add a capacitor to the apps.
Use to command:
 nx run my-app:add:android
and get error:

Any steps, I execute from docs: https://nxtend.dev/docs/ionic-angular/getting-started

Environment:

```<code> >  NX   Report complete - copy this into the issue template

   Node : 14.20.0
   OS   : win32 x64
   npm  : 6.14.17

   nx : 15.4.2
   @nrwl/angular : 15.4.2
   @nrwl/cypress : 15.4.2
   @nrwl/detox : Not Found
   @nrwl/devkit : 15.4.2
   @nrwl/esbuild : Not Found
   @nrwl/eslint-plugin-nx : 15.4.2
   @nrwl/expo : Not Found
   @nrwl/express : Not Found
   @nrwl/jest : 15.4.2
   @nrwl/js : 15.4.2
   @nrwl/linter : 15.4.2
   @nrwl/nest : Not Found
   @nrwl/next : Not Found
   @nrwl/node : 13.10.6
   @nrwl/nx-cloud : 15.0.2
   @nrwl/nx-plugin : Not Found
   @nrwl/react : Not Found
   @nrwl/react-native : Not Found
   @nrwl/rollup : Not Found
   @nrwl/schematics : Not Found
   @nrwl/storybook : Not Found
   @nrwl/web : Not Found
   @nrwl/webpack : 15.4.2
   @nrwl/workspace : 15.4.2
   @nrwl/vite : Not Found
   typescript : 4.8.4
   ---------------------------------------
   Local workspace plugins:
   ---------------------------------------
   Community plugins:
         @ionic/angular: 6.1.9
         @nxtend/capacitor: 13.0.0
         @nxtend/ionic-angular: 13.1.0
         @nxtend/capacitor: 13.0.0

</code>```

Body:
We have two Angular applications with libraries in our Nx monorepro. I want add a capacitor to the apps.
Use to command:
 nx run my-app:add:android
and get error:

Any steps, I execute from docs: https://nxtend.dev/docs/ionic-angular/getting-started

Environment:

 >  NX   Report complete - copy this into the issue template

   Node : 14.20.0
   OS   : win32 x64
   npm  : 6.14.17

   nx : 15.4.2
   @nrwl/angular : 15.4.2
   @nrwl/cypress : 15.4.2
   @nrwl/detox : Not Found
   @nrwl/devkit : 15.4.2
   @nrwl/esbuild : Not Found
   @nrwl/eslint-plugin-nx : 15.4.2
   @nrwl/expo : Not Found
   @nrwl/express : Not Found
   @nrwl/jest : 15.4.2
   @nrwl/js : 15.4.2
   @nrwl/linter : 15.4.2
   @nrwl/nest : Not Found
   @nrwl/next : Not Found
   @nrwl/node : 13.10.6
   @nrwl/nx-cloud : 15.0.2
   @nrwl/nx-plugin : Not Found
   @nrwl/react : Not Found
   @nrwl/react-native : Not Found
   @nrwl/rollup : Not Found
   @nrwl/schematics : Not Found
   @nrwl/storybook : Not Found
   @nrwl/web : Not Found
   @nrwl/webpack : 15.4.2
   @nrwl/workspace : 15.4.2
   @nrwl/vite : Not Found
   typescript : 4.8.4
   ---------------------------------------
   Local workspace plugins:
   ---------------------------------------
   Community plugins:
         @ionic/angular: 6.1.9
         @nxtend/capacitor: 13.0.0
         @nxtend/ionic-angular: 13.1.0
         @nxtend/capacitor: 13.0.0


问:
I am not able to parse mysql data to the face recognition camera window
In the face Recognition window tab, it recognizes my face but it is unable to get information of Name, ID, Roll No, and Department from MySQL Database.

Code for drawing coordinates on Face and putting text :

```<code>    def face_recog(self):
    def draw_boudary(img, classifier, scaleFactor, minNeigbors, color, text, clf):
        if img is not None and img.shape[0] > 0 and img.shape[1] > 0:
            gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            features = classifier.detectMultiScale(gray_image, scaleFactor, minNeigbors)

            coord = []

            for (x, y, w, h) in features:
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)
                id, predict = clf.predict(gray_image[y:y + h, x:x + w])
                confidence = int((100 * (1 - predict / 300)))

                conn = mysql.connector.connect(host="localhost", user="root", password="08052002H@ck",
                                               database="face_recognizer")
                my_cursor = conn.cursor()

                my_cursor.execute("select name from student where ID=" + str(id))
                n = "+".join(my_cursor)

                my_cursor.execute("select Dep from student where ID=" + str(id))
                d = "+".join(my_cursor)

                my_cursor.execute("select Roll_No from student where ID=" + str(id))
                r = "+".join(my_cursor)

                my_cursor.execute("select ID from student where ID=" + str(id))
                i = "+".join(my_cursor)

                if confidence > 77:
                    cv2.putText(img, f"ID:{i}", (x, y - 80), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)
                    cv2.putText(img, f"Roll No:{r}", (x, y - 55), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)
                    cv2.putText(img, f"Department:{d}", (x, y - 30), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255),3)
                    cv2.putText(img, f"Name:{n}", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)

                else:
                    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)
                    cv2.putText(img, "Unknown Face", (x, y - 30), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)

                coord = [x, y, w, h]

            return coord
</code>```

Body:
In the face Recognition window tab, it recognizes my face but it is unable to get information of Name, ID, Roll No, and Department from MySQL Database.

Code for drawing coordinates on Face and putting text :

    def face_recog(self):
    def draw_boudary(img, classifier, scaleFactor, minNeigbors, color, text, clf):
        if img is not None and img.shape[0] > 0 and img.shape[1] > 0:
            gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            features = classifier.detectMultiScale(gray_image, scaleFactor, minNeigbors)

            coord = []

            for (x, y, w, h) in features:
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)
                id, predict = clf.predict(gray_image[y:y + h, x:x + w])
                confidence = int((100 * (1 - predict / 300)))

                conn = mysql.connector.connect(host="localhost", user="root", password="08052002H@ck",
                                               database="face_recognizer")
                my_cursor = conn.cursor()

                my_cursor.execute("select name from student where ID=" + str(id))
                n = "+".join(my_cursor)

                my_cursor.execute("select Dep from student where ID=" + str(id))
                d = "+".join(my_cursor)

                my_cursor.execute("select Roll_No from student where ID=" + str(id))
                r = "+".join(my_cursor)

                my_cursor.execute("select ID from student where ID=" + str(id))
                i = "+".join(my_cursor)

                if confidence > 77:
                    cv2.putText(img, f"ID:{i}", (x, y - 80), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)
                    cv2.putText(img, f"Roll No:{r}", (x, y - 55), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)
                    cv2.putText(img, f"Department:{d}", (x, y - 30), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255),3)
                    cv2.putText(img, f"Name:{n}", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)

                else:
                    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)
                    cv2.putText(img, "Unknown Face", (x, y - 30), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)

                coord = [x, y, w, h]

            return coord


问:
Google pay library to scan debit/credit card details like card number, expiry date and CVV, facing an issue on Production its working on QA
I have implemented the google pay library to scan debit/credit card details, its working fine in the QA environment but when I try to test it on production I am facing a crash.

https://developers.google.com/pay/payment-card-recognition/debit-credit-card-recognition

```<code>private fun createPaymentsClient(activity: Activity): PaymentsClient {
        val walletOptions = Wallet.WalletOptions.Builder()
                           .setEnvironment(WalletConstants.ENVIRONMENT_PRODUCTION)
                           .build()
        return Wallet.getPaymentsClient(activity, walletOptions)
    }
</code>```

when I change environment to "WalletConstants.ENVIRONMENT_PRODUCTION" from "setEnvironment(Constants.PAYMENTS_ENVIRONMENT)" facing the crash below is crash log

```<code>FATAL EXCEPTION: main
                                                                                Process: com.dhl.pay.google, PID: 5219
                                                                                kotlin.UninitializedPropertyAccessException: lateinit property cardRecognitionPendingIntent has not been initialized
at com.dhl.pay.google.MainActivity.startPaymentCardOcr(MainActivity.kt:80)                                                                                at com.dhl.pay.google.MainActivity.onCreate$lambda$0(MainActivity.kt:38)                            at com.dhl.pay.google.MainActivity.$r8$lambda$9ZIx61lkQCSM4mTsrQGymHGsZ_g(Unknown Source:0)                             at com.dhl.pay.google.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)          at android.view.View.performClick(View.java:7488)
at android.view.View.performClickInternal(View.java:7464)                                                                                at android.view.View.access$3700(View.java:841)
at android.view.View$PerformClick.run(View.java:28911)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:233)
at android.os.Looper.loop(Looper.java:344)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)

</code>```

Body:
I have implemented the google pay library to scan debit/credit card details, its working fine in the QA environment but when I try to test it on production I am facing a crash.

https://developers.google.com/pay/payment-card-recognition/debit-credit-card-recognition

private fun createPaymentsClient(activity: Activity): PaymentsClient {
        val walletOptions = Wallet.WalletOptions.Builder()
                           .setEnvironment(WalletConstants.ENVIRONMENT_PRODUCTION)
                           .build()
        return Wallet.getPaymentsClient(activity, walletOptions)
    }

when I change environment to "WalletConstants.ENVIRONMENT_PRODUCTION" from "setEnvironment(Constants.PAYMENTS_ENVIRONMENT)" facing the crash below is crash log

FATAL EXCEPTION: main
                                                                                Process: com.dhl.pay.google, PID: 5219
                                                                                kotlin.UninitializedPropertyAccessException: lateinit property cardRecognitionPendingIntent has not been initialized
at com.dhl.pay.google.MainActivity.startPaymentCardOcr(MainActivity.kt:80)                                                                                at com.dhl.pay.google.MainActivity.onCreate$lambda$0(MainActivity.kt:38)                            at com.dhl.pay.google.MainActivity.$r8$lambda$9ZIx61lkQCSM4mTsrQGymHGsZ_g(Unknown Source:0)                             at com.dhl.pay.google.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)          at android.view.View.performClick(View.java:7488)
at android.view.View.performClickInternal(View.java:7464)                                                                                at android.view.View.access$3700(View.java:841)
at android.view.View$PerformClick.run(View.java:28911)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:233)
at android.os.Looper.loop(Looper.java:344)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)


问:
how to implement i18n in existing angular project(multiple languages)
I need to implement i18n in existing angular application.

There are number of pages in a application, how to name particular page in json file for key & value.


问:
Executing my function before loading of kernel (Laravel)
Would like to build in a simple validation for the value of the APP_ENV parameter in my Laravel application. I want the parameter to be either dev, tst, acc or prd. If it's not one of these, my Laravel application should throw an exception and quit. Something like:

```<code>use Illuminate\Support\Facades\App;
use Exception;

$envs = ['dev','tst','acc','prd'];
if(!in_array(App::environment(), $envs)) {
  throw new Exception('Invalid APP_ENV value.');
}
</code>```

I would like this to be done early in the bootstrapping sequence. I suspect I should put it in a service container and register that in /config/app.php. But this particular thing is still a bit untransparent for me, with my limited experience.

Where should I put my code snippet above, so that it gets executed early in the bootstrapping process?

Body:
Would like to build in a simple validation for the value of the APP_ENV parameter in my Laravel application. I want the parameter to be either dev, tst, acc or prd. If it's not one of these, my Laravel application should throw an exception and quit. Something like:

use Illuminate\Support\Facades\App;
use Exception;

$envs = ['dev','tst','acc','prd'];
if(!in_array(App::environment(), $envs)) {
  throw new Exception('Invalid APP_ENV value.');
}

I would like this to be done early in the bootstrapping sequence. I suspect I should put it in a service container and register that in /config/app.php. But this particular thing is still a bit untransparent for me, with my limited experience.

Where should I put my code snippet above, so that it gets executed early in the bootstrapping process?


问:
SelectPdf Error : System.InvalidCastException: 'Conversion from string "" to type 'Integer' is not valid.'
I tried to merge two pdf using SelectPdf library. I used Vb.Net as language.It gave me an error like this

```<code>System.InvalidCastException: 'Conversion from string ""D:\PDF\1.pdf" to type 'Integer' is not valid.'
</code>```

I did all the things after reading their references. Please help me to solve this problem.

```<code> Public Sub MergePDF()

        Dim file1 As String = "D:\PDF\1.pdf"
        Dim file2 As String = "D:\PDF\2.pdf"

        ' load the 2 pdf documents
        Dim doc1 As New PdfDocument(file1)  //error generate here
        Dim doc2 As New PdfDocument(file2)

        ' create a new pdf document
        Dim doc As New PdfDocument()

        ' add the pages of those 2 documents to the new document
        doc.Append(doc1)
        doc.Append(doc2)

        ' save pdf document
        doc.Save(Response, False, "Sample.pdf")

        ' close pdf document
        doc.Close()

        ' close the original pdf documents
        doc1.Close()
        doc2.Close()

    End Sub
</code>```

Body:
I tried to merge two pdf using SelectPdf library. I used Vb.Net as language.It gave me an error like this

System.InvalidCastException: 'Conversion from string ""D:\PDF\1.pdf" to type 'Integer' is not valid.'

I did all the things after reading their references. Please help me to solve this problem.

 Public Sub MergePDF()

        Dim file1 As String = "D:\PDF\1.pdf"
        Dim file2 As String = "D:\PDF\2.pdf"

        ' load the 2 pdf documents
        Dim doc1 As New PdfDocument(file1)  //error generate here
        Dim doc2 As New PdfDocument(file2)

        ' create a new pdf document
        Dim doc As New PdfDocument()

        ' add the pages of those 2 documents to the new document
        doc.Append(doc1)
        doc.Append(doc2)

        ' save pdf document
        doc.Save(Response, False, "Sample.pdf")

        ' close pdf document
        doc.Close()

        ' close the original pdf documents
        doc1.Close()
        doc2.Close()

    End Sub


问:
How to add custom textbox field on shopify product page that also shown in cart under product description
I need to add custom textbox field on shopify product pages.

My requirement is to add textbox field on product page and when customer add product in cart than that textbox field value also display on cart page and also on checkout page.

```<code><p class="line-item-property__field">   <label for="custom-field">Your custom field</label>   <input id="custom-field" type="text" name="properties[Your custom field]"> </p>
</code>```

Body:
I need to add custom textbox field on shopify product pages.

My requirement is to add textbox field on product page and when customer add product in cart than that textbox field value also display on cart page and also on checkout page.

   Your custom field   <input id="custom-field" type="text" name="properties[Your custom field]">


问:
How to set a complete wheel filename?
I'm looking for to create a wheel filname with complete wheel filename as I can see on Pypi wheel files of many projects and avoid to use setup.cfg or other tools as it is describe at https://packaging.python.org/en/latest/tutorials/packaging-projects/

Actually I'm using the build package and the build-backend Hatch to generate my wheel file (pyprojectfile.toml).

I wish to obtain a shape wheel filename as {dist}-{version}(-{build})?-{python.version}-{os_platform}.whl, i.e for my project, cleanmysurface-0.0.3-cp310-cp310-macosx_10_9_x86_64.whl

```<code>with my build command :

python -m build

I obtain a wheel filename ***cleanmysurface-0.0.3-py3-none-any.whl***

As I understand the effecting mapping is :

name --> cleanmysurface
version --> 0.0.3
build --> py3
python.version --> none
os_platform} --> any

**but** I want to obtain :

name --> cleanmysurface
version --> 0.0.3
build --> py310
python.version --> py310
os_platform --> macosx_10_9_x86_64

Are my metadata correct ? Do I need an another tool to create this wheel (Poetry, Flit, ...) ?

pyproject.toml :

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "cleanmysurface"
version = "0.0.3"
authors = [
{ name="blabla", email="blabla@icloud.com" },
]
description = "A melange package to calculate your mixture to clean surfaces"
readme = "README.md"
requires-python = ">=3.10"
platform = "macosx_10_9_x86_64"

classifiers = [
"Programming Language :: Python :: 3.10",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]

[project.urls]
"Homepage" = "https://github.com/blabla/melange"
"Bug Tracker" = "https://github.com/blabla/melange/issues"

</code>```

Title: How to set a complete wheel filename?

Body:
I'm looking for to create a wheel filname with complete wheel filename as I can see on Pypi wheel files of many projects and avoid to use setup.cfg or other tools as it is describe at https://packaging.python.org/en/latest/tutorials/packaging-projects/

Actually I'm using the build package and the build-backend Hatch to generate my wheel file (pyprojectfile.toml).

I wish to obtain a shape wheel filename as {dist}-{version}(-{build})?-{python.version}-{os_platform}.whl, i.e for my project, cleanmysurface-0.0.3-cp310-cp310-macosx_10_9_x86_64.whl

with my build command :

python -m build

I obtain a wheel filename ***cleanmysurface-0.0.3-py3-none-any.whl***

As I understand the effecting mapping is :

name --> cleanmysurface
version --> 0.0.3
build --> py3
python.version --> none
os_platform} --> any

**but** I want to obtain :

name --> cleanmysurface
version --> 0.0.3
build --> py310
python.version --> py310
os_platform --> macosx_10_9_x86_64

Are my metadata correct ? Do I need an another tool to create this wheel (Poetry, Flit, ...) ?

pyproject.toml :

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "cleanmysurface"
version = "0.0.3"
authors = [
{ name="blabla", email="blabla@icloud.com" },
]
description = "A melange package to calculate your mixture to clean surfaces"
readme = "README.md"
requires-python = ">=3.10"
platform = "macosx_10_9_x86_64"

classifiers = [
"Programming Language :: Python :: 3.10",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]

[project.urls]
"Homepage" = "https://github.com/blabla/melange"
"Bug Tracker" = "https://github.com/blabla/melange/issues"


问:
Displaying a Custom Avatar in Wordpress using wp_nav_menu_objects filter hook
Am creating a WordPress site whereby am enabling users to upload their own custom avatars using a Plugin called  One user Avatar.

The upload functionality is working fine

I want the image to be shown as an avatar when a user logs in. This should appear in the top-right corner. Since my menus are created dynamically using Wp Custom Navwalker. Am using a filter called wp_nav_menu_objects to filter the menu of a logged in user and add the avatar beside the username eg Welcome [avatar image] John Doe ,

The problem is that instead of the avatar showing, what shows is the code . Below is the filter hook am using:

```<code>//Filter inside functions.php
function my_dynamic_menu_items( $menu_items ) {

    foreach ( $menu_items as $menu_item ) {
        if ( strpos($menu_item->title, 'Welcome') !== false) {
        $menu_item->title =  'Welcome' . ' ' . get_wp_user_avatar( get_the_author_meta( 'ID' ), 'medium' );
        }
    }
    return $menu_items;
}
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items', 10 );
</code>```

This is the output on the frontend

Body:
Am creating a WordPress site whereby am enabling users to upload their own custom avatars using a Plugin called  One user Avatar.

The upload functionality is working fine

I want the image to be shown as an avatar when a user logs in. This should appear in the top-right corner. Since my menus are created dynamically using Wp Custom Navwalker. Am using a filter called wp_nav_menu_objects to filter the menu of a logged in user and add the avatar beside the username eg Welcome [avatar image] John Doe ,

The problem is that instead of the avatar showing, what shows is the code . Below is the filter hook am using:

//Filter inside functions.php
function my_dynamic_menu_items( $menu_items ) {

    foreach ( $menu_items as $menu_item ) {
        if ( strpos($menu_item->title, 'Welcome') !== false) {
        $menu_item->title =  'Welcome' . ' ' . get_wp_user_avatar( get_the_author_meta( 'ID' ), 'medium' );
        }
    }
    return $menu_items;
}
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items', 10 );

This is the output on the frontend


问:
Jaspersoft - Use subdatasource for a chart in subreport
Scenario:
Main report with json datasource.
Subreport with two chart inside.

I'm able to subdatasource the subreport using a JRDataSourceExpression:
((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("response.graficiPercentuali.sostenibilita")

My question is:
Is possible to do the same thing for fill the charts in the subreport?

First chart should use for example:
((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("response.graficiPercentuali.sostenibilita.chart1")

The second one:
((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("response.graficiPercentuali.sostenibilita.chart2")

I have tried to right click on the Dataset of the chart in the Outline but the JRDataSourceExpression
is disabled. Probaly because in the Dataset Run I have main dataset..

How or where I can do that?
Thanks
Andrea


问:
React App not redirecting properly on GCloud
I am trying to deploy the react app on gcloud. The app builds and starts normally when I do it locally.
If I npm start from gcloud console it's also available.

The problem is that when I build the app and deploy it to App Engine, the redirects does not work.
I have a google sign in added to the page but when I click Sign In, instead of redirecting, page says that the URL was not found and the url string after {app-url}/ consists of the contents of index.html.

I have tried different variations of the app.yaml file. The one I'm using right now looks like this.

```<code>runtime: nodejs16

handlers:

  # Serve all static files with url ending with a file extension

  - url: /(.*\..+)$

    static_files: build/\1

    upload: build/(.*\..+)$

  # Catch all handler to index.html

  - url: /.*

    static_files: build/index.html

    upload: build/index.html
</code>```

I'm a noob to gcloud so would appreciate any help.
Thanks

Body:
I am trying to deploy the react app on gcloud. The app builds and starts normally when I do it locally.
If I npm start from gcloud console it's also available.

The problem is that when I build the app and deploy it to App Engine, the redirects does not work.
I have a google sign in added to the page but when I click Sign In, instead of redirecting, page says that the URL was not found and the url string after {app-url}/ consists of the contents of index.html.

I have tried different variations of the app.yaml file. The one I'm using right now looks like this.

runtime: nodejs16

handlers:

  # Serve all static files with url ending with a file extension

  - url: /(.*\..+)$

    static_files: build/\1

    upload: build/(.*\..+)$

  # Catch all handler to index.html

  - url: /.*

    static_files: build/index.html

    upload: build/index.html

I'm a noob to gcloud so would appreciate any help.
Thanks


问:
Javascript: Uncaught TypeError: this.x is not a function but it is defined
I have a Typescript class called Game. This is the compiled JavaScript code:

import { Player } from './player.js';
export class Game {
    _currentPlayer = Player.X;
    start() {
        document.addEventListener('DOMContentLoaded', () => {
            document.body.addEventListener('click', this.markField);
        });
    }
    nextTurn() {
        this._currentPlayer = this.currentPlayer === Player.X ? Player.O : Player.X;
    }
    // Some code omitted
    isCompleted() {
        return false; // TODO
    }
    markField(event) {
        const button = event.target;
        if (!this.isCompleted() && button instanceof HTMLButtonElement) {
            button.setAttribute('aria-label', this.currentPlayer);
            button.setAttribute('disabled', 'disabled');
            this.nextTurn();
        }
    }
}
```

My main.js file initialises the game and calls game.start()

But when I click my buttons, the browser complains about this.isCompleted() not being a function;
Uncaught TypeError: this.isCompleted is not a function

I edited the JavaScript output by removing the brackets for the isCompleted() function, but then my browser told me that this.nextTurn() is not a function as well.

Body:
I have a Typescript class called Game. This is the compiled JavaScript code:

import { Player } from './player.js';
export class Game {
    _currentPlayer = Player.X;
    start() {
        document.addEventListener('DOMContentLoaded', () => {
            document.body.addEventListener('click', this.markField);
        });
    }
    nextTurn() {
        this._currentPlayer = this.currentPlayer === Player.X ? Player.O : Player.X;
    }
    // Some code omitted
    isCompleted() {
        return false; // TODO
    }
    markField(event) {
        const button = event.target;
        if (!this.isCompleted() && button instanceof HTMLButtonElement) {
            button.setAttribute('aria-label', this.currentPlayer);
            button.setAttribute('disabled', 'disabled');
            this.nextTurn();
        }
    }
}

My main.js file initialises the game and calls game.start()

But when I click my buttons, the browser complains about this.isCompleted() not being a function;
Uncaught TypeError: this.isCompleted is not a function

I edited the JavaScript output by removing the brackets for the isCompleted() function, but then my browser told me that this.nextTurn() is not a function as well.


问:
django PostgreSQL Partitioning reference error
We have two models. I'm implementing partitioning on the PaymentModel. It gives an error when I want to add to the BuyerModel table linked to this table;

insert or update on table "betik_app_payment_buyermodel" violates
foreign key constraint
"betik_app_payment_bu_payment_id_d7022880_fk_betik_app" DETAIL:  Key
(payment_id)=(2) is not present in table
"betik_app_payment_paymentmodel".

models.py

```<code>@architect.install('partition', type='range', subtype='date', constraint='month', column='dt')
class PaymentModel(models.Model):
    class Meta:
        app_label = 'betik_app_payment'
        indexes = [
            models.Index(fields=['user_email'])
        ]

    payment_status = models.PositiveIntegerField(default=1)
    price = MoneyField(max_digits=20, decimal_places=2)
    dt = models.DateTimeField()
    user_email = models.EmailField(null=True, blank=True)
    token = models.CharField(max_length=255, null=True, blank=True)

class BuyerModel(models.Model):
    class Meta:
        app_label = 'betik_app_payment'
        indexes = [
            models.Index(fields=['name', 'surname'])
        ]

    payment = models.OneToOneField(to='betik_app_payment.PaymentModel', on_delete=models.CASCADE,related_name='buyer')
    name = models.CharField(max_length=100)
    surname = models.CharField(max_length=100)
    email = models.EmailField(null=True, blank=True)
    ip = models.GenericIPAddressField(null=True, blank=True)
</code>```

main.py

```<code>from datetime import datetime
from djmoney.money import Money

buyer_name="Name"
buyer_surname="Surname"
buyer_email="developer@betik.com.tr"
buyer_ip="10.0.0.1"
price= Money("100.00","TRY")

payment_instance = PaymentModel.objects.create(
        price=price,
        dt=datetime.now(),
        user_email=buyer_email
    )

# raise error at here
buyer_instance = BuyerModel.objects.create(
        payment=payment_instance,
        name=buyer_name,
        surname=buyer_surname,
        email=buyer_email,
        ip=buyer_ip
    )
</code>```

using library:

money
partition

I'm looking at the tables in the database with the pgadmin tool and the partition has been applied successfully.

data added in both tables. But BuyerModel table is empty

PaymentModel table has two triggers. These triggers are created automatically by the architect library. Maybe there is an error here?;

after_insert_betik_app_payment_paymentmodel_trigger.

```<code>-- FUNCTION: public.betik_app_payment_paymentmodel_delete_master()

-- DROP FUNCTION IF EXISTS public.betik_app_payment_paymentmodel_delete_master();

CREATE OR REPLACE FUNCTION public.betik_app_payment_paymentmodel_delete_master()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
                BEGIN
                    DELETE FROM ONLY "betik_app_payment_paymentmodel" WHERE id = NEW.id;
                    RETURN NEW;
                END;

$BODY$;

ALTER FUNCTION public.betik_app_payment_paymentmodel_delete_master()
    OWNER TO postgres_user;
</code>```

before_insert_betik_app_payment_paymentmodel_trigger.

```<code>-- FUNCTION: public.betik_app_payment_paymentmodel_insert_child()

-- DROP FUNCTION IF EXISTS public.betik_app_payment_paymentmodel_insert_child();

CREATE OR REPLACE FUNCTION public.betik_app_payment_paymentmodel_insert_child()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF SECURITY DEFINER
AS $BODY$
                DECLARE
                    match "betik_app_payment_paymentmodel"."dt"%TYPE;
                    tablename VARCHAR;
                    checks TEXT;

                BEGIN
                    IF NEW."dt" IS NULL THEN
                        tablename := 'betik_app_payment_paymentmodel_null';
                        checks := '"dt" IS NULL';
                    ELSE
                        match := DATE_TRUNC('month', NEW."dt");
                        tablename := 'betik_app_payment_paymentmodel_' || TO_CHAR(NEW."dt", '"y"YYYY"m"MM');
                        checks := '"dt" >= ''' || match || ''' AND "dt" < ''' || (match + INTERVAL '1 month') || '''';
                    END IF;

                    BEGIN
                        EXECUTE 'CREATE TABLE IF NOT EXISTS ' || tablename || ' (
                            CHECK (' || checks || '),
                            LIKE "betik_app_payment_paymentmodel" INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES
                        ) INHERITS ("betik_app_payment_paymentmodel");';
                    EXCEPTION WHEN duplicate_table THEN
                        -- pass
                    END;

                    EXECUTE 'INSERT INTO ' || tablename || ' VALUES (($1).*);' USING NEW;
                    RETURN NEW;
                END;

$BODY$;

ALTER FUNCTION public.betik_app_payment_paymentmodel_insert_child()
    OWNER TO postgres_user;
</code>```

Body:
We have two models. I'm implementing partitioning on the PaymentModel. It gives an error when I want to add to the BuyerModel table linked to this table;

insert or update on table "betik_app_payment_buyermodel" violates
foreign key constraint
"betik_app_payment_bu_payment_id_d7022880_fk_betik_app" DETAIL:  Key
(payment_id)=(2) is not present in table
"betik_app_payment_paymentmodel".

models.py

@architect.install('partition', type='range', subtype='date', constraint='month', column='dt')
class PaymentModel(models.Model):
    class Meta:
        app_label = 'betik_app_payment'
        indexes = [
            models.Index(fields=['user_email'])
        ]

    payment_status = models.PositiveIntegerField(default=1)
    price = MoneyField(max_digits=20, decimal_places=2)
    dt = models.DateTimeField()
    user_email = models.EmailField(null=True, blank=True)
    token = models.CharField(max_length=255, null=True, blank=True)

class BuyerModel(models.Model):
    class Meta:
        app_label = 'betik_app_payment'
        indexes = [
            models.Index(fields=['name', 'surname'])
        ]

    payment = models.OneToOneField(to='betik_app_payment.PaymentModel', on_delete=models.CASCADE,related_name='buyer')
    name = models.CharField(max_length=100)
    surname = models.CharField(max_length=100)
    email = models.EmailField(null=True, blank=True)
    ip = models.GenericIPAddressField(null=True, blank=True)

main.py

from datetime import datetime
from djmoney.money import Money

buyer_name="Name"
buyer_surname="Surname"
buyer_email="developer@betik.com.tr"
buyer_ip="10.0.0.1"
price= Money("100.00","TRY")

payment_instance = PaymentModel.objects.create(
        price=price,
        dt=datetime.now(),
        user_email=buyer_email
    )

# raise error at here
buyer_instance = BuyerModel.objects.create(
        payment=payment_instance,
        name=buyer_name,
        surname=buyer_surname,
        email=buyer_email,
        ip=buyer_ip
    )

using library:

money
partition

I'm looking at the tables in the database with the pgadmin tool and the partition has been applied successfully.

data added in both tables. But BuyerModel table is empty

PaymentModel table has two triggers. These triggers are created automatically by the architect library. Maybe there is an error here?;

after_insert_betik_app_payment_paymentmodel_trigger.

-- FUNCTION: public.betik_app_payment_paymentmodel_delete_master()

-- DROP FUNCTION IF EXISTS public.betik_app_payment_paymentmodel_delete_master();

CREATE OR REPLACE FUNCTION public.betik_app_payment_paymentmodel_delete_master()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
                BEGIN
                    DELETE FROM ONLY "betik_app_payment_paymentmodel" WHERE id = NEW.id;
                    RETURN NEW;
                END;

$BODY$;

ALTER FUNCTION public.betik_app_payment_paymentmodel_delete_master()
    OWNER TO postgres_user;

before_insert_betik_app_payment_paymentmodel_trigger.

-- FUNCTION: public.betik_app_payment_paymentmodel_insert_child()

-- DROP FUNCTION IF EXISTS public.betik_app_payment_paymentmodel_insert_child();

CREATE OR REPLACE FUNCTION public.betik_app_payment_paymentmodel_insert_child()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF SECURITY DEFINER
AS $BODY$
                DECLARE
                    match "betik_app_payment_paymentmodel"."dt"%TYPE;
                    tablename VARCHAR;
                    checks TEXT;

                BEGIN
                    IF NEW."dt" IS NULL THEN
                        tablename := 'betik_app_payment_paymentmodel_null';
                        checks := '"dt" IS NULL';
                    ELSE
                        match := DATE_TRUNC('month', NEW."dt");
                        tablename := 'betik_app_payment_paymentmodel_' || TO_CHAR(NEW."dt", '"y"YYYY"m"MM');
                        checks := '"dt" >= ''' || match || ''' AND "dt" < ''' || (match + INTERVAL '1 month') || '''';
                    END IF;

                    BEGIN
                        EXECUTE 'CREATE TABLE IF NOT EXISTS ' || tablename || ' (
                            CHECK (' || checks || '),
                            LIKE "betik_app_payment_paymentmodel" INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES
                        ) INHERITS ("betik_app_payment_paymentmodel");';
                    EXCEPTION WHEN duplicate_table THEN
                        -- pass
                    END;

                    EXECUTE 'INSERT INTO ' || tablename || ' VALUES (($1).*);' USING NEW;
                    RETURN NEW;
                END;

$BODY$;

ALTER FUNCTION public.betik_app_payment_paymentmodel_insert_child()
    OWNER TO postgres_user;


问:
Angular http calls for local server getting redirect to https
I am running python flask application on my local.

Developing angular UI on local environment, One of the call is getting redirect from http to https. Rest of the calls are working fine.

Any suggestions?


问:
Failed to load the engine in FileReaderView Flutter. Error in android platform only
```<code>import 'package:flutter/material.dart';
import 'package:flutter_filereader/flutter_filereader.dart';
import 'package:path/path.dart';

class FileViewerScreen extends StatefulWidget {
  final String filePath;

  const FileViewerScreen({super.key, required this.filePath});

  @override
  State<FileViewerScreen> createState() => _FileViewerScreenState();
}

class _FileViewerScreenState extends State<FileViewerScreen> {
  @override
  Widget build(BuildContext context) {
    final name = basename(widget.filePath);
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text(name),
        ),
        body: FileReaderView(
          filePath: widget.filePath,
        ),
      ),
    );
  }
}
</code>```

Using FilReader Packaage. Not open/view any kind of file. Getting "引擎加载失败,请退出重试"(Failed to load the engine) error.

View files in flutter project.

Body:
import 'package:flutter/material.dart';
import 'package:flutter_filereader/flutter_filereader.dart';
import 'package:path/path.dart';

class FileViewerScreen extends StatefulWidget {
  final String filePath;

  const FileViewerScreen({super.key, required this.filePath});

  @override
  State<FileViewerScreen> createState() => _FileViewerScreenState();
}

class _FileViewerScreenState extends State<FileViewerScreen> {
  @override
  Widget build(BuildContext context) {
    final name = basename(widget.filePath);
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text(name),
        ),
        body: FileReaderView(
          filePath: widget.filePath,
        ),
      ),
    );
  }
}

Using FilReader Packaage. Not open/view any kind of file. Getting "引擎加载失败,请退出重试"(Failed to load the engine) error.

View files in flutter project.


问:
gitlab server with external nginx
I can't start nginx on my home server for several web-services like GitLab and another service. I prepared configuration, but it's not work:

```<code>server {
    listen 443;
    server_name mywebsite.space *.mywebsite.space;

    location / {
        proxy_pass https://my-another-local-ip:443;
    }
}
upstream gitlab-workhorse {
    server unix:/var/opt/gitlab/gitlab-workhorse/socket fail_timeout=0;
}
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name gitlab.mywebsite.space;
    server_tokens off;
    root /opt/gitlab/embedded/service/gitlab-rails/public;
    ssl on;
    ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4";
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;
    ssl_certificate /etc/ssl/my-certs/mywebsite.space.crt;
    ssl_certificate_key /etc/ssl/my-certs/mywebsite.space.key;
    location / {
       client_max_body_size 0;
       gzip off;
       proxy_read_timeout      300;
       proxy_connect_timeout   300;
       proxy_redirect          off;
       proxy_http_version 1.1;
       proxy_set_header    Host                $host;
       proxy_set_header    X-Real-IP           $remote_addr;
       proxy_set_header    X-Forwarded-Ssl     on;
       proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
       proxy_set_header    X-Forwarded-Proto   $scheme;
       proxy_pass http://gitlab-workhorse;
  }
}
</code>```

and in gitlab.rb I set:

```<code>registry_external_url 'https://gitlab.mywebsite.space'
gitlab_rails['registry_enabled'] = true
registry_nginx['enable'] = false
registry['enable'] = true
</code>```

At out nginx I see next log:

```<code>× nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since ....; 1s ago
       Docs: man:nginx(8)
    Process: 15834 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 15835 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=1/FAILURE)
        CPU: 21ms

дек 29 13:58:34 home-server systemd[1]: Starting A high performance web server and a reverse proxy server...
дек 29 13:58:34 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:34 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:35 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:35 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:36 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:36 home-server nginx[15835]: nginx: [emerg] still could not bind()
дек 29 13:58:36 home-server systemd[1]: nginx.service: Control process exited, code=exited, status=1/FAILURE
дек 29 13:58:36 home-server systemd[1]: nginx.service: Failed with result 'exit-code'.
дек 29 13:58:36 home-server systemd[1]: Failed to start A high performance web server and a reverse proxy server.
</code>```

I don't know what I done wrong

Title: gitlab server with external nginx

Body:
I can't start nginx on my home server for several web-services like GitLab and another service. I prepared configuration, but it's not work:

server {
    listen 443;
    server_name mywebsite.space *.mywebsite.space;

    location / {
        proxy_pass https://my-another-local-ip:443;
    }
}
upstream gitlab-workhorse {
    server unix:/var/opt/gitlab/gitlab-workhorse/socket fail_timeout=0;
}
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name gitlab.mywebsite.space;
    server_tokens off;
    root /opt/gitlab/embedded/service/gitlab-rails/public;
    ssl on;
    ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4";
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;
    ssl_certificate /etc/ssl/my-certs/mywebsite.space.crt;
    ssl_certificate_key /etc/ssl/my-certs/mywebsite.space.key;
    location / {
       client_max_body_size 0;
       gzip off;
       proxy_read_timeout      300;
       proxy_connect_timeout   300;
       proxy_redirect          off;
       proxy_http_version 1.1;
       proxy_set_header    Host                $host;
       proxy_set_header    X-Real-IP           $remote_addr;
       proxy_set_header    X-Forwarded-Ssl     on;
       proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
       proxy_set_header    X-Forwarded-Proto   $scheme;
       proxy_pass http://gitlab-workhorse;
  }
}

and in gitlab.rb I set:

registry_external_url 'https://gitlab.mywebsite.space'
gitlab_rails['registry_enabled'] = true
registry_nginx['enable'] = false
registry['enable'] = true

At out nginx I see next log:

× nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since ....; 1s ago
       Docs: man:nginx(8)
    Process: 15834 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 15835 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=1/FAILURE)
        CPU: 21ms

дек 29 13:58:34 home-server systemd[1]: Starting A high performance web server and a reverse proxy server...
дек 29 13:58:34 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:34 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:35 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:35 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:36 home-server nginx[15835]: nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Unknown error)
дек 29 13:58:36 home-server nginx[15835]: nginx: [emerg] still could not bind()
дек 29 13:58:36 home-server systemd[1]: nginx.service: Control process exited, code=exited, status=1/FAILURE
дек 29 13:58:36 home-server systemd[1]: nginx.service: Failed with result 'exit-code'.
дек 29 13:58:36 home-server systemd[1]: Failed to start A high performance web server and a reverse proxy server.

I don't know what I done wrong


问:
Are there any disadvantages in setting a lower java compliance level than the available java sdk?
When updating a large java project from one LTS version (java 1.x) to the next (java 17), one may set the java compliance level of the compiler of the new javac compiler to match older versions of the standard, so that the compiled bytecode can be run with older java runtime environments that may be installed on the user devices. This advantage is plausible to me, but is there any downsides to doing this?

I have updated my java version in my project, but are unsure of the consequences of setting a lower compliance level for the compiler.


问:
Assign picture to a cell if picture exists for the value looked up in another cell, vba
I want to assign pictures from a folder to a cell next to the cell with values.
But if I don't have a picture I want it left blank, for example I enclosed a picture..
In the picture you can see that the nail should be right below the screw, but since error occured my code went to the next cell and placed it..

[]

```<code>Sub Pictures()

Dim profile_pic As Picture
Dim pic_location As String
Dim profile_name As String

    Columns("C:C").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.ColumnWidth = 8.86
    Range("A9", Range("L9").End(xlDown)).Select
    Selection.RowHeight = 50
    Range("C8").Select
    ActiveCell.FormulaR1C1 = "Slika artikla"
    Range("C9").Select

For i = 9 To Range("A9").End(xlDown).row

profile_name = Worksheets("1").Cells(i, 1).Value
pic_location = "C:\Picture\" & Worksheets("1").Cells(i, 1).Value & ".png"

With Worksheets("1").Cells(i, 3)

    On Error Resume Next

        Set profile_pic = ActiveSheet.Pictures.Insert(pic_location)

        profile_pic.Top = .Top
        profile_pic.Left = .Left
        profile_pic.ShapeRange.LockAspectRatio = msoTrue
        profile_pic.Placement = xlMoveAndSize
        profile_pic.ShapeRange.Width = 50
        profile_pic.ShapeRange.Height = 50

    On Error GoTo 0

End With
Next

Range("a8").Select

End Sub
</code>```

Hoping it would work..
I want a list of pictures next to a list of values that I have.

So if I have a pictures (225, 226, 228) I want my list to be like:

225 Picture225
226 Picture226
227 no picture
228 Picture228

Body:
I want to assign pictures from a folder to a cell next to the cell with values.
But if I don't have a picture I want it left blank, for example I enclosed a picture..
In the picture you can see that the nail should be right below the screw, but since error occured my code went to the next cell and placed it..

[]

Sub Pictures()

Dim profile_pic As Picture
Dim pic_location As String
Dim profile_name As String

    Columns("C:C").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.ColumnWidth = 8.86
    Range("A9", Range("L9").End(xlDown)).Select
    Selection.RowHeight = 50
    Range("C8").Select
    ActiveCell.FormulaR1C1 = "Slika artikla"
    Range("C9").Select

For i = 9 To Range("A9").End(xlDown).row

profile_name = Worksheets("1").Cells(i, 1).Value
pic_location = "C:\Picture\" & Worksheets("1").Cells(i, 1).Value & ".png"

With Worksheets("1").Cells(i, 3)

    On Error Resume Next

        Set profile_pic = ActiveSheet.Pictures.Insert(pic_location)

        profile_pic.Top = .Top
        profile_pic.Left = .Left
        profile_pic.ShapeRange.LockAspectRatio = msoTrue
        profile_pic.Placement = xlMoveAndSize
        profile_pic.ShapeRange.Width = 50
        profile_pic.ShapeRange.Height = 50

    On Error GoTo 0

End With
Next

Range("a8").Select

End Sub

Hoping it would work..
I want a list of pictures next to a list of values that I have.

So if I have a pictures (225, 226, 228) I want my list to be like:

225 Picture225
226 Picture226
227 no picture
228 Picture228


问:
Browser tab close/refresh alert in angular
I want to patch an API that fetches the date and time from users activity of browser tab close or refresh event. In my API request body, I am passing eventIDs. So, for an example, eventID 1 for tab close and eventID 2 for tab refresh. Now, I want to use the same method, lets say eventID 3 and 4 for 'leave' and 'cancel' options on Alert box that pops up after refreshing or clicking on tab close. As the code i have used for the alert pop up is

```<code>('window:beforeunload', ['$event'])
  unloadNotification($event: any) {
    console.log($event)
    if (this.hasUnsavedData()) {
      $event.returnValue = "true";
    }
  }
</code>```

I am unable to get events for either of them. How can i get the event for at least one between 'leave'or'cancel' so i could patch the API eventID

```<code>('window:beforeunload', ['$event'])
  unloadNotification($event: any) {
    console.log($event)
    if (this.hasUnsavedData()) {
      $event.returnValue = "true";
    }
  }
</code>```
```<code>hasUnsavedData() {
    return true;
  }
</code>```

Body:
I want to patch an API that fetches the date and time from users activity of browser tab close or refresh event. In my API request body, I am passing eventIDs. So, for an example, eventID 1 for tab close and eventID 2 for tab refresh. Now, I want to use the same method, lets say eventID 3 and 4 for 'leave' and 'cancel' options on Alert box that pops up after refreshing or clicking on tab close. As the code i have used for the alert pop up is

('window:beforeunload', ['$event'])
  unloadNotification($event: any) {
    console.log($event)
    if (this.hasUnsavedData()) {
      $event.returnValue = "true";
    }
  }

I am unable to get events for either of them. How can i get the event for at least one between 'leave'or'cancel' so i could patch the API eventID

('window:beforeunload', ['$event'])
  unloadNotification($event: any) {
    console.log($event)
    if (this.hasUnsavedData()) {
      $event.returnValue = "true";
    }
  }

hasUnsavedData() {
    return true;
  }


问:
Flyway DB Schema History issues
I'm using flyway 8.5.13 with springboot version 2.7.1 for db migrations. Migrations run successfully, but at times it inserts the new script in flyway_schema_history table with type='Delete' and also randomly marks some of the old scripts as DELETE.

I run repair but as for DELETE also success flag is marked as 1 so repair doesn't help here. To re-run the script, i've to manually remove the entries from flyway_schema_history table which are marked as 'DELETE'. Once these rows are removed manually same script executes successfully. If there is any problem with the migration script then after just deletion of row it should not work again.

Here is the screenshot for your reference

Please suggest.

Thank you,
Jagdish

Tried to run flyway repair script, but that doesn't help much because successful flag is always set to 1. Repair only helps if script is not executed successfully and marked as 0 in the flyway_schema_history table.

Title: Flyway DB Schema History issues


问:
Get soft deleted records using Nestjs and TypeOrmQueryService
I am trying to get soft deleted records (deletedAt column) when using query from TypeOrmQueryService but looks like there is no way to do that. I know that I can use withDeleted if I use find or findOne but I cannot switch to these methods or use a query builder since it would require a lot of changed in the front-end.

```<code>@QueryService(Patient)
export class PatientQueryService extends TypeOrmQueryService<Patient> {
    constructor(@InjectRepository(Patient) repo: Repository<Patient>) {
        super(repo);
    }

    async getOnePatient(currentUser: User, patientId: number) {

        const result = await super.query({
            paging: { limit: 1 },
            filter: { id: { eq: 1 } },
        });

    }
}
</code>```

Body:
I am trying to get soft deleted records (deletedAt column) when using query from TypeOrmQueryService but looks like there is no way to do that. I know that I can use withDeleted if I use find or findOne but I cannot switch to these methods or use a query builder since it would require a lot of changed in the front-end.

@QueryService(Patient)
export class PatientQueryService extends TypeOrmQueryService<Patient> {
    constructor(@InjectRepository(Patient) repo: Repository<Patient>) {
        super(repo);
    }

    async getOnePatient(currentUser: User, patientId: number) {

        const result = await super.query({
            paging: { limit: 1 },
            filter: { id: { eq: 1 } },
        });

    }
}


问:
What is the proper value for Redis io-threads config in Kubernetes?
I want to deploy Redis on Kubernetes. This Redis should handle a huge amount of commands and we are enabling io-threads config in our Redis.

Based on the request and limit resource values in Kubernetes, what should I have considered as io-threads config?

For example, I want to set 9 core CPU request for this Redis instance and our Kubernetes cluster will guarantee 3 core request for it. What is the proper value for this config? I should set io-threads to 2 or I can set it to more than the request core like 5 or 6?

I have tried both 4 and 5, but there was no change in CPU usage and latency of executed commands and I just want to make sure higher values than CPU requests are fine for Redis.


问:
Android on ADB returns "DEVICE NOT FOUND" in Recovery
I am experiencing this issue where I am unable to get ADB to recognize my device when its at Recovery screen. It works during normal mode, as well as Sideload mode, but not at recovery. Other guides have suggested me to update drivers, but I am using Ubuntu 22.10.
Can someone please help me?</p>


问:
Why my png function appear to not create any image?
I am trying to create a png watermark from text input. I use same function for jpeg and everything works perfectly fine.

I use imagestring(). In the code below I try to make two images, one of them is watermark and second one is resized dafault image.

I uplode photos through my form and they correctly appear in the default photos folder. None of the functions below return an image.

$destination_w is a path to the folder with watermarks. $destination_m is a path to the folder with miniatures. $_SESSION['mime'] and $_SESSION['image'] store correct values as I have tried to var_dump them and they appear in html which is rendered after this functions. Problem is that images do not exist, so they are not visible on my page.

This function is stored in watermark.inc.php file which is included after saving the photos to the default folder and their info in database.

```<code>else if ($_SESSION['mime'] === 'image/png'){
$img = imagecreatefrompng($source.'/'.$_SESSION['image']);
$blackcolor = imagecolorallocate($img, 0, 0, 0);
imagestring($img, 3,15, 30, $_SESSION['watermark'], $blackcolor);
imagepng($img, $destination_w.'/'.$_SESSION['image'], 100);
imagedestroy($img);

$img = imagecreatefrompng($source.'/'.$_SESSION['image']);
list($width, $height) = getimagesize($source.'/'.$_SESSION['image']);

$thumb = imagecreatetruecolor(200, 125);

//MINIATURES
imagecopyresized($thumb, $img, 0, 0, 0, 0, 200, 125, $width, $height);
imagepng($thumb, $destination_m.'/'.$_SESSION['image'], 100);
imagedestroy($img);
imagedestroy($thumb);
</code>```

};

Body:
I am trying to create a png watermark from text input. I use same function for jpeg and everything works perfectly fine.

I use imagestring(). In the code below I try to make two images, one of them is watermark and second one is resized dafault image.

I uplode photos through my form and they correctly appear in the default photos folder. None of the functions below return an image.

$destination_w is a path to the folder with watermarks. $destination_m is a path to the folder with miniatures. $_SESSION['mime'] and $_SESSION['image'] store correct values as I have tried to var_dump them and they appear in html which is rendered after this functions. Problem is that images do not exist, so they are not visible on my page.

This function is stored in watermark.inc.php file which is included after saving the photos to the default folder and their info in database.

else if ($_SESSION['mime'] === 'image/png'){
$img = imagecreatefrompng($source.'/'.$_SESSION['image']);
$blackcolor = imagecolorallocate($img, 0, 0, 0);
imagestring($img, 3,15, 30, $_SESSION['watermark'], $blackcolor);
imagepng($img, $destination_w.'/'.$_SESSION['image'], 100);
imagedestroy($img);

$img = imagecreatefrompng($source.'/'.$_SESSION['image']);
list($width, $height) = getimagesize($source.'/'.$_SESSION['image']);

$thumb = imagecreatetruecolor(200, 125);

//MINIATURES
imagecopyresized($thumb, $img, 0, 0, 0, 0, 200, 125, $width, $height);
imagepng($thumb, $destination_m.'/'.$_SESSION['image'], 100);
imagedestroy($img);
imagedestroy($thumb);

};


问:
yamldump() inserts unneeded newlines for arrays
yaml.dump() produces yaml like this:

xpack:
  security:
    authc:
      realms:
        active_directory.active_directory:
          domain_name: abc
          order: 2
          ssl:
            verification_mode: none
          unmapped_groups_as_roles: false
          url: abc
xpack.notification.email.account:
  work:
    email_defaults:
      from: abc
    profile: mail
    smtp:
      auth: false
      host: abc
      port: 25
      starttls.enable: true
reindex.remote.whitelist:
- asrp:3200
```
<p>Notice the last key <code>reindex.remote.whitelist</code>. It is an array with values in newlines. What I want instead is like this:</p>
<pre class="lang-yaml prettyprint-override"><code>xpack:
  security:
    authc:
      realms:
        active_directory.active_directory:
          domain_name: abc
          order: 2
          ssl:
            verification_mode: none
          unmapped_groups_as_roles: false
          url: abc
xpack.notification.email.account:
  work:
    email_defaults:
      from: abc
    profile: mail
    smtp:
      auth: false
      host: abc
      port: 25
      starttls.enable: true
reindex.remote.whitelist: ["apsrp:3200"]
</code>```

I know it's not a bug, I just have a requirement to not have newlines for arrays in yaml.

Body:
yaml.dump() produces yaml like this:

xpack:
  security:
    authc:
      realms:
        active_directory.active_directory:
          domain_name: abc
          order: 2
          ssl:
            verification_mode: none
          unmapped_groups_as_roles: false
          url: abc
xpack.notification.email.account:
  work:
    email_defaults:
      from: abc
    profile: mail
    smtp:
      auth: false
      host: abc
      port: 25
      starttls.enable: true
reindex.remote.whitelist:
- asrp:3200

Notice the last key reindex.remote.whitelist. It is an array with values in newlines. What I want instead is like this:

xpack:
  security:
    authc:
      realms:
        active_directory.active_directory:
          domain_name: abc
          order: 2
          ssl:
            verification_mode: none
          unmapped_groups_as_roles: false
          url: abc
xpack.notification.email.account:
  work:
    email_defaults:
      from: abc
    profile: mail
    smtp:
      auth: false
      host: abc
      port: 25
      starttls.enable: true
reindex.remote.whitelist: ["apsrp:3200"]

I know it's not a bug, I just have a requirement to not have newlines for arrays in yaml.


问:
SSIS package creates a file when it cannot find one
SSIS package created in VS 2019.
The package Imports an Excel file & fails if file not found (as expected).
This runs fine from SSIS application window.
However, when triggered from SQL Server Agent (SSMS 18.8) job, an empty excel file is created with a random hex sheet name if it cannot find the file it was looking for; the job fails with an error.

Has anyone experienced this?


问:
MsBuild: Fail the Build when referenced Projects outside of the solution have Code Analaysis warnings
In one of our .net Projects we have a Build/Publish discrepancy. The Build succeeds but the publish fails.

The reason for that:

We have a lot of shared Projects which are just dependencies but are not included in the solution.

MSBuild is smart enough to build them when the others are builded, but it ignores Code Analysis warnings / errors when building the dependencies.

One way to fix this issue would be to include all the shared Projects in all the solutions we use them but if possible we would like to not do that because it increases maintenance work when adding a new Shared project.

Is there a way to tell MSBuild to fail when the referenced projects has a CA warning / error?


问:
AWS crawler - Table,schema is created but data is not populated?
Trying to Run Athena crawler so table is created in Athena but only schema is populated but data is not there. what will be reason for that ?

I am trying to Run Athena crawler -(AWS glue Crawler) Taking Input file form s3 Bucket(Parquet format) and  run crawler.so table is created in Athena but only schema is populated and data is not there. what will be reason for that ?

I have assigned proper IAM rule

Having small parquet file stored in s3 path

Database selected, output location selected.

Crawler is run properly, table is created in database only data is not populated ??


问:
How to add text on button click in angular-editor?
Here I have made a demo for angular-editor but in this on click text is add anywhere in document.

I want to add text on click only inside angular-editor.

Button Click code to add text.

```<code>fnSetPlaceHolder(_value: string) {
    var sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      var range = sel.getRangeAt(0);
      range.insertNode(document.createTextNode(_value));
    }
  }
</code>```

Is there any solution to add text only in angular-editor?

Body:
Here I have made a demo for angular-editor but in this on click text is add anywhere in document.

I want to add text on click only inside angular-editor.

Button Click code to add text.

fnSetPlaceHolder(_value: string) {
    var sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      var range = sel.getRangeAt(0);
      range.insertNode(document.createTextNode(_value));
    }
  }

Is there any solution to add text only in angular-editor?