问:
How can I fix "SSL routines:ssl3_read_bytes:sslv3 alert handshake failure" in my firebase function?
I'm trying to use a Firebase function to invalidate the merchantToken provided by apple using this api endpoint: https://developer.apple.com/documentation/merchanttokennotificationservices/invalidate_a_merchant_token?changes=latest_minor&language=objc_2

But I keep getting this error "SSL routines:ssl3_read_bytes:sslv3 alert handshake failure"
Here is my function

```<code>
``
import * as functions from "firebase-functions";
import * as request from "request-promise";

interface ErrorResponse {
  errorMessage: string;
  httpResponseCode: number;
  statusCode: number;
}

export const unlinkMerchantToken = functions.https.onCall(async (data, context) => {
  // Set the options for the POST request
  const options = {
    method: "POST",
    uri: "https://apple-pay-gateway.apple.com/v1/merchantId/{merchantId}/merchantToken/unlink",
    body: {
      data: data,
    },
    headers: {
      "Content-Type": "application/json",
      "x-request-id": String(Math.random()),
    },
    json: true,
  };

  // Make the POST request
  try {
    const response = await request(options);
    if (response.statusCode >= 201 && response.statusCode < 300) {
      // The request was successful
      return response.body;
    } else if (response.statusCode == 200) {
      return response.body;
    } else {
      // The request was not successful
      const errorResponse: ErrorResponse = response.body;
      throw new functions.https.HttpsError("unknown", errorResponse.errorMessage, errorResponse);
    }
  } catch (error) {
    functions.logger.error(error);
    throw new functions.https.HttpsError("unknown", JSON.stringify(error));
  }
});

``

</code>```

I tried using different https request libraries but I get the same error.

Body:
I'm trying to use a Firebase function to invalidate the merchantToken provided by apple using this api endpoint: https://developer.apple.com/documentation/merchanttokennotificationservices/invalidate_a_merchant_token?changes=latest_minor&language=objc_2

But I keep getting this error "SSL routines:ssl3_read_bytes:sslv3 alert handshake failure"
Here is my function

``
import * as functions from "firebase-functions";
import * as request from "request-promise";

interface ErrorResponse {
  errorMessage: string;
  httpResponseCode: number;
  statusCode: number;
}

export const unlinkMerchantToken = functions.https.onCall(async (data, context) => {
  // Set the options for the POST request
  const options = {
    method: "POST",
    uri: "https://apple-pay-gateway.apple.com/v1/merchantId/{merchantId}/merchantToken/unlink",
    body: {
      data: data,
    },
    headers: {
      "Content-Type": "application/json",
      "x-request-id": String(Math.random()),
    },
    json: true,
  };

  // Make the POST request
  try {
    const response = await request(options);
    if (response.statusCode >= 201 && response.statusCode < 300) {
      // The request was successful
      return response.body;
    } else if (response.statusCode == 200) {
      return response.body;
    } else {
      // The request was not successful
      const errorResponse: ErrorResponse = response.body;
      throw new functions.https.HttpsError("unknown", errorResponse.errorMessage, errorResponse);
    }
  } catch (error) {
    functions.logger.error(error);
    throw new functions.https.HttpsError("unknown", JSON.stringify(error));
  }
});

``

I tried using different https request libraries but I get the same error.


来源: stackexchange

问:
Error in the extraction of the moviepy subclip function
I am doing a project in which I need to extract the audio from a video and then transcribe that audio using google speech recognizer. The problem comes that when extracting the audio from the video, instead of extracting the piece that I want to extract, it extracts the entire audio so I can not transcribe that because the audios are 8 minutes and the maximum that google allows is 3. I attach the code below in case it is helpful.</p>
```<code>import numpy
from numpy import clip
import speech_recognition as sr
import moviepy.editor as mp
from moviepy.editor import *

#lectura de video
clip = mp.VideoFileClip("video.mp4")

clip_final=clip.subclip(0,100)

#extraemos el audio
clip_final.audio.write_audiofile("video.wav")

#iniciamos el speechrecognition
r = sr.Recognizer()

#leemos el archivo audio extraido
audio = sr.AudioFile("video.wav")
print("audio extraido")

#lectura de audio
with audio as source:
    r.adjust_for_ambient_noise(source)
    clean_file = r.record(source)

print("lectura terminada")
#reconocemos la voz del audio
result = r.recognize_google(clean_file,language="es-ES")
#result = r.recognize_ibm(clean_file, username="apkikey", password= "your API Key")

print("")
print(result)
#escribimos el texto en un nuevo archivo txt
with open('video.txt','a+') as file:
    file.write("RECOGNIZED SPEECH: \n")
    file.write(result)
    #file.write(" "+result)

print("\nEscritura terminada")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am doing a project in which I need to extract the audio from a video and then transcribe that audio using google speech recognizer. The problem comes that when extracting the audio from the video, instead of extracting the piece that I want to extract, it extracts the entire audio so I can not transcribe that because the audios are 8 minutes and the maximum that google allows is 3. I attach the code below in case it is helpful.

import numpy
from numpy import clip
import speech_recognition as sr
import moviepy.editor as mp
from moviepy.editor import *

#lectura de video
clip = mp.VideoFileClip("video.mp4")

clip_final=clip.subclip(0,100)

#extraemos el audio
clip_final.audio.write_audiofile("video.wav")

#iniciamos el speechrecognition
r = sr.Recognizer()

#leemos el archivo audio extraido
audio = sr.AudioFile("video.wav")
print("audio extraido")

#lectura de audio
with audio as source:
    r.adjust_for_ambient_noise(source)
    clean_file = r.record(source)

print("lectura terminada")
#reconocemos la voz del audio
result = r.recognize_google(clean_file,language="es-ES")
#result = r.recognize_ibm(clean_file, username="apkikey", password= "your API Key")

print("")
print(result)
#escribimos el texto en un nuevo archivo txt
with open('video.txt','a+') as file:
    file.write("RECOGNIZED SPEECH: \n")
    file.write(result)
    #file.write(" "+result)

print("\nEscritura terminada")


问:
Why nebular behaves different across various browsers?
I am using a nebular theme for my angular application. It works fine for laptops as expected.

But when comes to mobile devices, The padding behaves differently for different browsers.

For Example, I am using a REDMI 9 power mobile to view my application with various browsers,

1) Chrome browser:

```<code>     The border-spacing is not displayed as expected as below:
</code>```

2) OperaMini Browser ::

```<code>    In operaMini, the application spacing is fine as expected like below image:
</code>```

NOTE:

If I use another mobile like Redmi Note 8 pro  to view the same application It works fine even in the chrome browser itself as in the below image.

So I am very confused about how to solve this issue. Someone, please guide me to solve or at least what happens? Thanks in advance

Body:
I am using a nebular theme for my angular application. It works fine for laptops as expected.

But when comes to mobile devices, The padding behaves differently for different browsers.

For Example, I am using a REDMI 9 power mobile to view my application with various browsers,

1) Chrome browser:

     The border-spacing is not displayed as expected as below:

2) OperaMini Browser ::

    In operaMini, the application spacing is fine as expected like below image:

NOTE:

If I use another mobile like Redmi Note 8 pro  to view the same application It works fine even in the chrome browser itself as in the below image.

So I am very confused about how to solve this issue. Someone, please guide me to solve or at least what happens? Thanks in advance


问:
Pentaho Data Integration (PDI) does not finish the job
I created one simple transformation in PDI. For windows scheduler I created Windows batch file for running this transformation (in bat file):

```<code>CALL %PDI_HOME%\Kitchen.bat /level:Error /file:"C:\Users\sbrbot\my.kjb" >> %logfile%
</code>```

I put this bat file in Windows scheduler and it was working fine for long time. Suddenly it does not want to finish. It comes to one point and runs forever:

```<code>C:\pentaho\pdi>"C:\Program Files\Java\jre1.8.0_351\bin\java.exe"   "-Xms1g" "-Xmx3g" "-Djava.library.path=libswt\win64;/bin" "-Djava.endorsed.dirs=C:\Program Files\Java\jre1.8.0_351\jre\lib\endorsed;C:\Program Files\Java\jre1.8.0_351\lib\endorsed;C:\pentaho\pdi\system\karaf\lib\endorsed"  "-DKETTLE_HOME=" "-DKETTLE_REPOSITORY=" "-DKETTLE_USER=" "-DKETTLE_PASSWORD=" "-DKETTLE_PLUGIN_PACKAGES=" "-DKETTLE_LOG_SIZE_LIMIT=" "-DKETTLE_JNDI_ROOT=" -jar launcher\launcher.jar -lib ..\libswt\win64  -main org.pentaho.di.kitchen.Kitchen -initialDir "C:\Windows\system32"\ /level:Error /file:"C:\Users\sbrbot\my.kjb"
09:30:11,569 INFO  [KarafBoot] Checking to see if org.pentaho.clean.karaf.cache is enabled
09:30:14,780 INFO  [KarafInstance]
*******************************************************************************
*** Karaf Instance Number: 1 at C:\pentaho\pdi\.\system\karaf\caches\kitche ***
***   n\data-1                                                              ***
*** Karaf Port:8802                                                         ***
*** OSGI Service Port:9051                                                  ***
*******************************************************************************
09:30:27,974 INFO  [DriverManager] Installing driver kars.
09:30:27,989 INFO  [DriverManager] 0 drivers will be installed.
09:30:27,989 INFO  [DriverManager] Finished installing drivers kars.
</code>```

When I run the same batch file manually then it finishes fine!!!

```<code>C:\pentaho\pdi>"C:\Program Files\Java\jre1.8.0_351\bin\java.exe"   "-Xms1g" "-Xmx3g" "-Djava.library.path=libswt\win64;/bin" "-Djava.endorsed.dirs=C:\Program Files\Java\jre1.8.0_351\jre\lib\endorsed;C:\Program Files\Java\jre1.8.0_351\lib\endorsed;C:\pentaho\pdi\system\karaf\lib\endorsed"  "-DKETTLE_HOME=" "-DKETTLE_REPOSITORY=" "-DKETTLE_USER=" "-DKETTLE_PASSWORD=" "-DKETTLE_PLUGIN_PACKAGES=" "-DKETTLE_LOG_SIZE_LIMIT=" "-DKETTLE_JNDI_ROOT=" -jar launcher\launcher.jar -lib ..\libswt\win64  -main org.pentaho.di.kitchen.Kitchen -initialDir "C:\Users\sbrbot\Documents\Pentaho\BOC"\ /level:Error /file:"C:\Users\sbrbot\my.kjb"
10:54:31,591 INFO  [KarafBoot] Checking to see if org.pentaho.clean.karaf.cache is enabled
10:54:34,819 INFO  [KarafInstance]
*******************************************************************************
*** Karaf Instance Number: 1 at C:\pentaho\pdi\.\system\karaf\caches\kitche ***
***   n\data-1                                                              ***
*** Karaf Port:8802                                                         ***
*** OSGI Service Port:9051                                                  ***
*******************************************************************************
10:54:43,444 INFO  [DriverManager] Installing driver kars.
10:54:43,444 INFO  [DriverManager] 0 drivers will be installed.
10:54:43,444 INFO  [DriverManager] Finished installing drivers kars.
2022/12/27 10:58:53 - Carte - Installing timer to purge stale objects after 1440 minutes.
</code>```

I have no idea what's going on.

Body:
I created one simple transformation in PDI. For windows scheduler I created Windows batch file for running this transformation (in bat file):

CALL %PDI_HOME%\Kitchen.bat /level:Error /file:"C:\Users\sbrbot\my.kjb" >> %logfile%

I put this bat file in Windows scheduler and it was working fine for long time. Suddenly it does not want to finish. It comes to one point and runs forever:

C:\pentaho\pdi>"C:\Program Files\Java\jre1.8.0_351\bin\java.exe"   "-Xms1g" "-Xmx3g" "-Djava.library.path=libswt\win64;/bin" "-Djava.endorsed.dirs=C:\Program Files\Java\jre1.8.0_351\jre\lib\endorsed;C:\Program Files\Java\jre1.8.0_351\lib\endorsed;C:\pentaho\pdi\system\karaf\lib\endorsed"  "-DKETTLE_HOME=" "-DKETTLE_REPOSITORY=" "-DKETTLE_USER=" "-DKETTLE_PASSWORD=" "-DKETTLE_PLUGIN_PACKAGES=" "-DKETTLE_LOG_SIZE_LIMIT=" "-DKETTLE_JNDI_ROOT=" -jar launcher\launcher.jar -lib ..\libswt\win64  -main org.pentaho.di.kitchen.Kitchen -initialDir "C:\Windows\system32"\ /level:Error /file:"C:\Users\sbrbot\my.kjb"
09:30:11,569 INFO  [KarafBoot] Checking to see if org.pentaho.clean.karaf.cache is enabled
09:30:14,780 INFO  [KarafInstance]
*******************************************************************************
*** Karaf Instance Number: 1 at C:\pentaho\pdi\.\system\karaf\caches\kitche ***
***   n\data-1                                                              ***
*** Karaf Port:8802                                                         ***
*** OSGI Service Port:9051                                                  ***
*******************************************************************************
09:30:27,974 INFO  [DriverManager] Installing driver kars.
09:30:27,989 INFO  [DriverManager] 0 drivers will be installed.
09:30:27,989 INFO  [DriverManager] Finished installing drivers kars.

When I run the same batch file manually then it finishes fine!!!

C:\pentaho\pdi>"C:\Program Files\Java\jre1.8.0_351\bin\java.exe"   "-Xms1g" "-Xmx3g" "-Djava.library.path=libswt\win64;/bin" "-Djava.endorsed.dirs=C:\Program Files\Java\jre1.8.0_351\jre\lib\endorsed;C:\Program Files\Java\jre1.8.0_351\lib\endorsed;C:\pentaho\pdi\system\karaf\lib\endorsed"  "-DKETTLE_HOME=" "-DKETTLE_REPOSITORY=" "-DKETTLE_USER=" "-DKETTLE_PASSWORD=" "-DKETTLE_PLUGIN_PACKAGES=" "-DKETTLE_LOG_SIZE_LIMIT=" "-DKETTLE_JNDI_ROOT=" -jar launcher\launcher.jar -lib ..\libswt\win64  -main org.pentaho.di.kitchen.Kitchen -initialDir "C:\Users\sbrbot\Documents\Pentaho\BOC"\ /level:Error /file:"C:\Users\sbrbot\my.kjb"
10:54:31,591 INFO  [KarafBoot] Checking to see if org.pentaho.clean.karaf.cache is enabled
10:54:34,819 INFO  [KarafInstance]
*******************************************************************************
*** Karaf Instance Number: 1 at C:\pentaho\pdi\.\system\karaf\caches\kitche ***
***   n\data-1                                                              ***
*** Karaf Port:8802                                                         ***
*** OSGI Service Port:9051                                                  ***
*******************************************************************************
10:54:43,444 INFO  [DriverManager] Installing driver kars.
10:54:43,444 INFO  [DriverManager] 0 drivers will be installed.
10:54:43,444 INFO  [DriverManager] Finished installing drivers kars.
2022/12/27 10:58:53 - Carte - Installing timer to purge stale objects after 1440 minutes.

I have no idea what's going on.


问:
Creating a report for ansible loop output
I have 3 hosts and 4(varies according to requirements) loop items.So after registering the output i get below result

We are running playbook on localhost

```<code>HOSTS file

[server]
MAIN_RUNNING_HOST API_key=XXX
SECOND_RUNNING_HOST API_key=YYY

[loop_object]
HOSTNAME1
HOSTNAME2
HOSTNAME3
HOSTNAME4
</code>```
```<code>- name: All output of one host
  debug:
    msg: "{{execution.results}}"
</code>```

Output :-

```<code>ok: [localhost] => {
    "msg": [
        {
            "access_control_allow_methods": "POST, GET, OPTIONS, DELETE, PUT",
            "content": "{\n    \"error\": \"Could not remove hosts. Failed hosts may not exist.\",\n    \"hosts\": [\n        \n    ],\n    \"failed\": [\n        \"HOSTNAME1\"\n    ]\n}\n",
            "invocation": {
                "module_args": {
                    "attributes": null,
                    "validate_certs": true
                }
            },
            "item": "HOSTNAME1",
            "json": {
                "error": "Could not remove hosts. Failed hosts may not exist.",
                "failed": [
                    "HOSTNAME1"
                ],
                "hosts": []
            },
            "msg": "OK (148 bytes)",
            "status": 200,
            "url": "http://MAIN_RUNNING_HOST/nagiosxi/api/v1/config/host/HOSTNAME1?apikey=XXXXX&pretty=1&applyconfig=1",
        },
        {
            "access_control_allow_methods": "POST, GET, OPTIONS, DELETE, PUT",
            "content": "{\n    \"error\": \"Could not remove hosts. Failed hosts may not exist.\",\n    \"hosts\": [\n        \n    ],\n    \"failed\": [\n        \"HOSTNAME2\"\n    ]\n}\n",

            "invocation": {
                "module_args": {
                    "attributes": null,
                    "validate_certs": true
                }
            },
            "item": "HOSTNAME2",
            "json": {
                "error": "Could not remove hosts. Failed hosts may not exist.",
                "failed": [
                    "HOSTNAME2"
                ],
                "hosts": []
            },
            "msg": "OK (148 bytes)",
            "status": 200,
            "url": "http://MAIN_RUNNING_HOST/nagiosxi/api/v1/config/host/HOSTNAME2?apikey=XXXXX&pretty=1&applyconfig=1",
        },
        {
            "access_control_allow_methods": "POST, GET, OPTIONS, DELETE, PUT",
            "content": "{\n    \"error\": \"Could not remove hosts. Failed hosts may not exist.\",\n    \"hosts\": [\n        \n    ],\n    \"failed\": [\n        \"HOSTNAME3\"\n    ]\n}\n",

            "invocation": {
                "module_args": {
                    "attributes": null,
                    "validate_certs": true
                }
            },
            "item": "HOSTNAME3",
            "json": {
                "failed": [],
                "hosts": [
                    "HOSTNAME3"
                ],
                "success": "Removed hosts from the system. Config applied Nagios Core was restarted."
            },
            "msg": "OK (172 bytes)",
            "status": 200,
             "url": "http://MAIN_RUNNING_HOST/nagiosxi/api/v1/config/host/HOSTNAME3?apikey=XXXXX&pretty=1&applyconfig=1",
        },
        {
            "access_control_allow_methods": "POST, GET, OPTIONS, DELETE, PUT",
            "content": "{\n    \"error\": \"Could not remove hosts. Failed hosts may not exist.\",\n    \"hosts\": [\n        \n    ],\n    \"failed\": [\n        \"HOSTNAME4\"\n    ]\n}\n",
            "invocation": {
                "module_args": {
                    "attributes": null,

                    "validate_certs": true
                }
            },
            "item": "HOSTNAME4",
            "json": {
                "error": "Could not remove hosts. Failed hosts may not exist.",
                "failed": [
                    "HOSTNAME4"
                ],
                "hosts": []
            },
            "msg": "OK (148 bytes)",
            "url": "http://MAIN_RUNNING_HOST/nagiosxi/api/v1/config/host/HOSTNAME4?apikey=XXXXX&pretty=1&applyconfig=1",
        }
    ]
}

</code>```

There is only HOSTNAME 3 in this MAIN_RUNNING_HOST

in the CSV file expected output

```<code>
MAIN_RUNNING_OUTPUT -- HOSTNAME1 -- Not Found
MAIN_RUNNING_OUTPUT -- HOSTNAME2 -- Not Found
MAIN_RUNNING_OUTPUT -- HOSTNAME3 -- Found
MAIN_RUNNING_OUTPUT -- HOSTNAME4 -- Not Found
SECOND_RUNNING_HOST -- HOSTNAME1 -- Not Found
SECOND_RUNNING_HOST -- HOSTNAME2 -- Not Found
SECOND_RUNNING_HOST -- HOSTNAME3 -- Not Found
SECOND_RUNNING_HOST -- HOSTNAME4 -- Found
</code>```

I tried belowthing to get the result

```<code>- name: Show the error message if it is occured
  debug: "var=execution.results.{{item}}.json."
  with_sequence: "0-{{groups['loop_object']|length - 1}}"
  register: linux_host_remove_hosts
</code>```

This will only show the output at console .. not sure how to get it done in csv format. Can anyone help me with the required output in the required csv format?

Body:
I have 3 hosts and 4(varies according to requirements) loop items.So after registering the output i get below result

We are running playbook on localhost

HOSTS file

[server]
MAIN_RUNNING_HOST API_key=XXX
SECOND_RUNNING_HOST API_key=YYY

[loop_object]
HOSTNAME1
HOSTNAME2
HOSTNAME3
HOSTNAME4

- name: All output of one host
  debug:
    msg: "{{execution.results}}"

Output :-

ok: [localhost] => {
    "msg": [
        {
            "access_control_allow_methods": "POST, GET, OPTIONS, DELETE, PUT",
            "content": "{\n    \"error\": \"Could not remove hosts. Failed hosts may not exist.\",\n    \"hosts\": [\n        \n    ],\n    \"failed\": [\n        \"HOSTNAME1\"\n    ]\n}\n",
            "invocation": {
                "module_args": {
                    "attributes": null,
                    "validate_certs": true
                }
            },
            "item": "HOSTNAME1",
            "json": {
                "error": "Could not remove hosts. Failed hosts may not exist.",
                "failed": [
                    "HOSTNAME1"
                ],
                "hosts": []
            },
            "msg": "OK (148 bytes)",
            "status": 200,
            "url": "http://MAIN_RUNNING_HOST/nagiosxi/api/v1/config/host/HOSTNAME1?apikey=XXXXX&pretty=1&applyconfig=1",
        },
        {
            "access_control_allow_methods": "POST, GET, OPTIONS, DELETE, PUT",
            "content": "{\n    \"error\": \"Could not remove hosts. Failed hosts may not exist.\",\n    \"hosts\": [\n        \n    ],\n    \"failed\": [\n        \"HOSTNAME2\"\n    ]\n}\n",

            "invocation": {
                "module_args": {
                    "attributes": null,
                    "validate_certs": true
                }
            },
            "item": "HOSTNAME2",
            "json": {
                "error": "Could not remove hosts. Failed hosts may not exist.",
                "failed": [
                    "HOSTNAME2"
                ],
                "hosts": []
            },
            "msg": "OK (148 bytes)",
            "status": 200,
            "url": "http://MAIN_RUNNING_HOST/nagiosxi/api/v1/config/host/HOSTNAME2?apikey=XXXXX&pretty=1&applyconfig=1",
        },
        {
            "access_control_allow_methods": "POST, GET, OPTIONS, DELETE, PUT",
            "content": "{\n    \"error\": \"Could not remove hosts. Failed hosts may not exist.\",\n    \"hosts\": [\n        \n    ],\n    \"failed\": [\n        \"HOSTNAME3\"\n    ]\n}\n",

            "invocation": {
                "module_args": {
                    "attributes": null,
                    "validate_certs": true
                }
            },
            "item": "HOSTNAME3",
            "json": {
                "failed": [],
                "hosts": [
                    "HOSTNAME3"
                ],
                "success": "Removed hosts from the system. Config applied Nagios Core was restarted."
            },
            "msg": "OK (172 bytes)",
            "status": 200,
             "url": "http://MAIN_RUNNING_HOST/nagiosxi/api/v1/config/host/HOSTNAME3?apikey=XXXXX&pretty=1&applyconfig=1",
        },
        {
            "access_control_allow_methods": "POST, GET, OPTIONS, DELETE, PUT",
            "content": "{\n    \"error\": \"Could not remove hosts. Failed hosts may not exist.\",\n    \"hosts\": [\n        \n    ],\n    \"failed\": [\n        \"HOSTNAME4\"\n    ]\n}\n",
            "invocation": {
                "module_args": {
                    "attributes": null,

                    "validate_certs": true
                }
            },
            "item": "HOSTNAME4",
            "json": {
                "error": "Could not remove hosts. Failed hosts may not exist.",
                "failed": [
                    "HOSTNAME4"
                ],
                "hosts": []
            },
            "msg": "OK (148 bytes)",
            "url": "http://MAIN_RUNNING_HOST/nagiosxi/api/v1/config/host/HOSTNAME4?apikey=XXXXX&pretty=1&applyconfig=1",
        }
    ]
}

There is only HOSTNAME 3 in this MAIN_RUNNING_HOST

in the CSV file expected output

MAIN_RUNNING_OUTPUT -- HOSTNAME1 -- Not Found
MAIN_RUNNING_OUTPUT -- HOSTNAME2 -- Not Found
MAIN_RUNNING_OUTPUT -- HOSTNAME3 -- Found
MAIN_RUNNING_OUTPUT -- HOSTNAME4 -- Not Found
SECOND_RUNNING_HOST -- HOSTNAME1 -- Not Found
SECOND_RUNNING_HOST -- HOSTNAME2 -- Not Found
SECOND_RUNNING_HOST -- HOSTNAME3 -- Not Found
SECOND_RUNNING_HOST -- HOSTNAME4 -- Found

I tried belowthing to get the result

- name: Show the error message if it is occured
  debug: "var=execution.results.{{item}}.json."
  with_sequence: "0-{{groups['loop_object']|length - 1}}"
  register: linux_host_remove_hosts

This will only show the output at console .. not sure how to get it done in csv format. Can anyone help me with the required output in the required csv format?


问:
IS it possible to write a function in SASS that can detects a property in a class of an element?
I want to write an RTL component in SASS for an existing source code of a website. instead of going through all codes to manually change relevant properties of elements (e.g, margin, padding, left-right positioning, etc), I would like write a function to detects them all and change them accordingly, would you give me guidance if there is a solution to this?

I went through some documents such as this and this, but my problem is writing the function in SASS itself.


问:
reactivate a disabled draggable div jquery
I have a div and after dropping it at a new location, this action will be triggered:

```<code>function handleActionDrop(event, ui) {

    // can not be dragged
    ui.draggable.draggable('disable');

    // only one is allowed to be dropped
    $(this).droppable('disable');

    // set to the new position
    ui.draggable.position({ of: $(this), my: 'left top', at: 'left top' });

    // disable the revert of the selected div
    ui.draggable.draggable('option', 'revert', false);
}
</code>```

After I double click on that div, the div will be moved back to the initial position (done). However, if I set that div to have the same behavior that it can be dragged, then it does not work. I tried to do it like this: $(theDiv).draggable();

Is there any way to reset the div to have the same behavior as the starting state? or is there a way to reactivate the disabled draggable div?

Thanks in advance.

ContentLicense: CC BY-SA 3.0

Body:
I have a div and after dropping it at a new location, this action will be triggered:

function handleActionDrop(event, ui) {

    // can not be dragged
    ui.draggable.draggable('disable');

    // only one is allowed to be dropped
    $(this).droppable('disable');

    // set to the new position
    ui.draggable.position({ of: $(this), my: 'left top', at: 'left top' });

    // disable the revert of the selected div
    ui.draggable.draggable('option', 'revert', false);
}

After I double click on that div, the div will be moved back to the initial position (done). However, if I set that div to have the same behavior that it can be dragged, then it does not work. I tried to do it like this: $(theDiv).draggable();

Is there any way to reset the div to have the same behavior as the starting state? or is there a way to reactivate the disabled draggable div?

Thanks in advance.


问:
How can I load graphql schema from external file with graphql/go library?
I am using this library https://github.com/graphql-go/graphql to build graphql application in go. All the examples in this lib uses go code to define graphql schema, see below example:

```<code>fields := graphql.Fields{
        "hello": &graphql.Field{
            Type: graphql.String,
            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                return "world", nil
            },
        },
    }
</code>```

But I'd like to define the graphql schema in an external file *.schema in gql format. How can I let the lib load schema from a file?

I know there are other libraries build on top of this library who can load external schema file. But I don't want to bring any transport layer dependencies. I am looking for a solution with this library only.

Body:
I am using this library https://github.com/graphql-go/graphql to build graphql application in go. All the examples in this lib uses go code to define graphql schema, see below example:

fields := graphql.Fields{
        "hello": &graphql.Field{
            Type: graphql.String,
            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                return "world", nil
            },
        },
    }

But I'd like to define the graphql schema in an external file *.schema in gql format. How can I let the lib load schema from a file?

I know there are other libraries build on top of this library who can load external schema file. But I don't want to bring any transport layer dependencies. I am looking for a solution with this library only.


问:
Gift in cart for order amount in Woocommerce
I need a code that with 150 subtotal add a gift in cart. I have the following code:
`

```<code>/** Gift in Cart */
// Add free gifted product for specific cart subtotal
add_action( 'woocommerce_before_calculate_totals', 'check_free_gifted_product' );
function check_free_gifted_product( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $free_product_id   = 7912;
    $targeted_subtotal = 150;

    $cart_subtotal     = 0; // Initializing

    // Loop through cart items (first loop)
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
        // When free product is is cart
        if ( $free_product_id == $cart_item['product_id'] ) {
            $free_key = $cart_item_key;
            $free_qty = $cart_item['quantity'];
            $cart_item['data']->set_price(0); // Optionally set the price to zero
        } else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    // If subtotal match and free product is not already in cart, add it
    if ( ! isset($free_key) && $cart_subtotal >= $targeted_subtotal ) {
        $cart->add_to_cart( $free_product_id );
    }
    // If subtotal doesn't match and free product is already in cart, remove it
    elseif ( isset($free_key) && $cart_subtotal < $targeted_subtotal ) {
        $cart->remove_cart_item( $free_key );
    }
    // Keep free product quantity to 1.
    elseif ( isset($free_qty) && $free_qty > 1 ) {
        $cart->set_quantity( $free_key, 1 );
    }
}
</code>```

`

When I apply a discount and the subtotal of order is less than subtotal targeted the gift is removed by the order in checkout but the gift should remain also if I apply a discount.

I modify the code in this way but it doesn't work:

`

```<code>add_action( 'woocommerce_before_calculate_totals', 'check_free_gifted_product' );
function check_free_gifted_product( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $free_product_id   = 7912;
    $targeted_subtotal = 150;

    $cart_subtotal     = 0; // Initializing
    $applied_coupons   = WC()->cart->get_applied_coupons(); // Get applied coupon codes
    $free_product_in_cart = false; // Flag to check if free product is in cart

    // Loop through cart items (first loop)
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
        // When free product is is cart
        if ( $free_product_id == $cart_item['product_id'] ) {
            $free_product_in_cart = true;
            $free_qty = $cart_item['quantity'];
            $cart_item['data']->set_price(0); // Optionally set the price to zero
        } else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    // Store the original cart subtotal before applying the coupon discounts
    $original_subtotal = $cart_subtotal;

    // Loop through applied coupon codes and apply discounts to the cart subtotal
    foreach ( $applied_coupons as $code ) {
        $coupon = new WC_Coupon( $code );
        $discount_amount = $coupon->get_discount_amount( $cart_subtotal );
        $cart_subtotal -= $discount_amount;
    }

    // If original subtotal match and free product is not already in cart, add it
    if ( ! $free_product_in_cart && $original_subtotal >= $targeted_subtotal ) {
        $cart->add_to_cart( $free_product_id );
    }
    // If original subtotal doesn't match and free product is already in cart, remove it
    elseif ( $free_product_in_cart && $original_subtotal < $targeted_subtotal ) {
        $cart->remove_cart_item( $free_product_id );
    }
    // Keep free product quantity to 1.
    elseif ( $free_product_in_cart && $free_qty > 1 ) {
        $cart->set_quantity( $free_product_id, 1 );
    }
}
</code>```

`

Body:
I need a code that with 150 subtotal add a gift in cart. I have the following code:
`

/** Gift in Cart */
// Add free gifted product for specific cart subtotal
add_action( 'woocommerce_before_calculate_totals', 'check_free_gifted_product' );
function check_free_gifted_product( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $free_product_id   = 7912;
    $targeted_subtotal = 150;

    $cart_subtotal     = 0; // Initializing

    // Loop through cart items (first loop)
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
        // When free product is is cart
        if ( $free_product_id == $cart_item['product_id'] ) {
            $free_key = $cart_item_key;
            $free_qty = $cart_item['quantity'];
            $cart_item['data']->set_price(0); // Optionally set the price to zero
        } else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    // If subtotal match and free product is not already in cart, add it
    if ( ! isset($free_key) && $cart_subtotal >= $targeted_subtotal ) {
        $cart->add_to_cart( $free_product_id );
    }
    // If subtotal doesn't match and free product is already in cart, remove it
    elseif ( isset($free_key) && $cart_subtotal < $targeted_subtotal ) {
        $cart->remove_cart_item( $free_key );
    }
    // Keep free product quantity to 1.
    elseif ( isset($free_qty) && $free_qty > 1 ) {
        $cart->set_quantity( $free_key, 1 );
    }
}

`

When I apply a discount and the subtotal of order is less than subtotal targeted the gift is removed by the order in checkout but the gift should remain also if I apply a discount.

I modify the code in this way but it doesn't work:

`

add_action( 'woocommerce_before_calculate_totals', 'check_free_gifted_product' );
function check_free_gifted_product( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $free_product_id   = 7912;
    $targeted_subtotal = 150;

    $cart_subtotal     = 0; // Initializing
    $applied_coupons   = WC()->cart->get_applied_coupons(); // Get applied coupon codes
    $free_product_in_cart = false; // Flag to check if free product is in cart

    // Loop through cart items (first loop)
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
        // When free product is is cart
        if ( $free_product_id == $cart_item['product_id'] ) {
            $free_product_in_cart = true;
            $free_qty = $cart_item['quantity'];
            $cart_item['data']->set_price(0); // Optionally set the price to zero
        } else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    // Store the original cart subtotal before applying the coupon discounts
    $original_subtotal = $cart_subtotal;

    // Loop through applied coupon codes and apply discounts to the cart subtotal
    foreach ( $applied_coupons as $code ) {
        $coupon = new WC_Coupon( $code );
        $discount_amount = $coupon->get_discount_amount( $cart_subtotal );
        $cart_subtotal -= $discount_amount;
    }

    // If original subtotal match and free product is not already in cart, add it
    if ( ! $free_product_in_cart && $original_subtotal >= $targeted_subtotal ) {
        $cart->add_to_cart( $free_product_id );
    }
    // If original subtotal doesn't match and free product is already in cart, remove it
    elseif ( $free_product_in_cart && $original_subtotal < $targeted_subtotal ) {
        $cart->remove_cart_item( $free_product_id );
    }
    // Keep free product quantity to 1.
    elseif ( $free_product_in_cart && $free_qty > 1 ) {
        $cart->set_quantity( $free_product_id, 1 );
    }
}

`


问:
What is the optimal way to assemble trees from query?
I have a table with a tree alike data organization (at the example below the First. Second, and Third are the nodes with subnodes - list of Id for the Third value):

```<code>+----+-------+--------+-------+
| Id | First | Second | Third |
+----+-------+--------+-------+
| 1  |   1   |   1    |   1   |
| 2  |   1   |   1    |   2   |
| 3  |   1   |   1    |   2   |
| 4  |   1   |   2    |   1   |
| 5  |   1   |   2    |   2   |
| 6  |   1   |   2    |   3   |
...
+----+-------+--------+-------+
</code>```

The Id, First, Second and Third are the ids, that I need to transform into a tree, like:

```<code>[
    "1": [                   (First)
        "1": [               (Second)
            "1": [ 1 ],      (Third with list of `Id`
            "2": [ 2, 3 ]
        ],
        "2": [
            "1": [ 4 ],
            "2": [ 5 ],
            "3": [ 6 ]
        ]
    ]
]
</code>```

What is the optimal approach for querying and assembling trees from that kind of data? I assume that a good option is to retrieve the groupped data from the db already, but I could not find any suitable example...

On the other hand it seems to be normal to retrieve the plain sql result and group the data into the tree afterwards.

Can anyone give a good example of that?

Body:
I have a table with a tree alike data organization (at the example below the First. Second, and Third are the nodes with subnodes - list of Id for the Third value):

+----+-------+--------+-------+
| Id | First | Second | Third |
+----+-------+--------+-------+
| 1  |   1   |   1    |   1   |
| 2  |   1   |   1    |   2   |
| 3  |   1   |   1    |   2   |
| 4  |   1   |   2    |   1   |
| 5  |   1   |   2    |   2   |
| 6  |   1   |   2    |   3   |
...
+----+-------+--------+-------+

The Id, First, Second and Third are the ids, that I need to transform into a tree, like:

[
    "1": [                   (First)
        "1": [               (Second)
            "1": [ 1 ],      (Third with list of `Id`
            "2": [ 2, 3 ]
        ],
        "2": [
            "1": [ 4 ],
            "2": [ 5 ],
            "3": [ 6 ]
        ]
    ]
]

What is the optimal approach for querying and assembling trees from that kind of data? I assume that a good option is to retrieve the groupped data from the db already, but I could not find any suitable example...

On the other hand it seems to be normal to retrieve the plain sql result and group the data into the tree afterwards.

Can anyone give a good example of that?


问:
C# Toolbox full of same TableAdapterManagers
So im currently working on an "old" C# .Net-Framework 4.6.2 software project from someone else and he was working with TableAdaptermanager. I get that a TableAdapterManager is generated together with a DataSet so all good. He used the TableAdapterManager.UpdateAll Command which i also want to use to commit Data to the Database but the Toolbox list is full of TabelAdapterManagers. This isnt particular bad but all have the same names so i dont know which manager belongs to which dataset. I can only see it when i throw them into the designer (Look at the pictures)

Has anyone an idea how to change their names or anything else so i can tell the difference and directly see what TableAdapterManager im looking at?

Edit: I found a way to add them manually in any FormDesigner.CS ("private *.DataSets.*TableAdapters.TableAdapterManager anyNameHere;" but still i want to use the Toolbox

Screenshot of my Toolbox

Screenshot of how i can see the difference only here when added to Designer and looking at the properties

I was aready Looking for an option to rename TableAdapterManager in the DataSet.Designer.CS or other files but didnt see any option to do so


问:
What is difference between an array with dynamic allocation and an array with static allocation
I created an array like int* p=new int[5] and try to assign value for each i.e p[0]=1,p[1]=2... . The program got compiled successfully. But when created an array like int* p[5] and try to assign value for each I got error.

```<code>#include <iostream>
using namespace std;
int main() {

    int *ptr=new int[5];
    ptr[0] = 1;

}
</code>```

Compilation Successful.

```<code>#include <iostream>
using namespace std;
int main() {

    int *ptr[2];
    ptr[0] = 1;

}
</code>```

Compilation unsuccessful.
Why is that?

Body:
I created an array like int* p=new int[5] and try to assign value for each i.e p[0]=1,p[1]=2... . The program got compiled successfully. But when created an array like int* p[5] and try to assign value for each I got error.

#include <iostream>
using namespace std;
int main() {

    int *ptr=new int[5];
    ptr[0] = 1;

}

Compilation Successful.

#include <iostream>
using namespace std;
int main() {

    int *ptr[2];
    ptr[0] = 1;

}

Compilation unsuccessful.
Why is that?


问:
How to request a permission of type System.Net.WebPermission in SQL Server CLR?
I have created a sqlproj for SQL Server CLR to allows SQL Server call web API, the code like this:

public partial class SqlServerClrClient
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString Query(string url, string jobName, string sql)
    {
        var jobNameBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(jobName));
        var sqlBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(sql));
        var param =
            $"{{\"Id\":\"{Guid.NewGuid()}\",\"JobNameBase64\":\"{jobNameBase64}\",\"SqlBase64\":\"{sqlBase64}\",\"CreatedUtcTime\":\"{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}\"}}";
        var postData = "cmdParam=" + param;
        var bytes = Encoding.UTF8.GetBytes(postData);

        var httpRequest = WebRequest.CreateHttp(url);
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        httpRequest.ContentLength = bytes.Length;
        using (var stream = httpRequest.GetRequestStream())
            stream.Write(bytes, 0, bytes.Length);

        using (var httpResponse = httpRequest.GetResponse())
        {
            var responseStream = httpResponse.GetResponseStream();
            if (responseStream is null)
                return SqlString.Null;
            using (var streamReader = new StreamReader(responseStream, Encoding.UTF8))
                return streamReader.ReadToEnd();
        }
    }
}
```
<p>And I have turn on the TRUSTWORTHY like this</p>
<pre class="lang-sql prettyprint-override"><code>ALTER DATABASE TESTDB SET TRUSTWORTHY ON
</code>```

But when I call it the SQL Server throws an error

Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "GatewayQuery":
System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
System.Security.SecurityException:
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
   at System.Security.CodeAccessPermission.Demand()
   at System.Net.HttpWebRequest.CheckConnectPermission(Uri uri, Boolean needExecutionContext)
   at System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint)
   at System.Net.HttpRequestCreator.Create(Uri Uri)
   at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
   at System.Net.WebRequest.CreateHttp(Uri requestUri)
   at CIPGatewaySqlServerClrClient.Query(String url, String jobName, String sql)
```

How can I solve this problem?

The TRUSTWORTHY has been turn on.

Body:
I have created a sqlproj for SQL Server CLR to allows SQL Server call web API, the code like this:

public partial class SqlServerClrClient
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString Query(string url, string jobName, string sql)
    {
        var jobNameBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(jobName));
        var sqlBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(sql));
        var param =
            $"{{\"Id\":\"{Guid.NewGuid()}\",\"JobNameBase64\":\"{jobNameBase64}\",\"SqlBase64\":\"{sqlBase64}\",\"CreatedUtcTime\":\"{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}\"}}";
        var postData = "cmdParam=" + param;
        var bytes = Encoding.UTF8.GetBytes(postData);

        var httpRequest = WebRequest.CreateHttp(url);
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        httpRequest.ContentLength = bytes.Length;
        using (var stream = httpRequest.GetRequestStream())
            stream.Write(bytes, 0, bytes.Length);

        using (var httpResponse = httpRequest.GetResponse())
        {
            var responseStream = httpResponse.GetResponseStream();
            if (responseStream is null)
                return SqlString.Null;
            using (var streamReader = new StreamReader(responseStream, Encoding.UTF8))
                return streamReader.ReadToEnd();
        }
    }
}

And I have turn on the TRUSTWORTHY like this

ALTER DATABASE TESTDB SET TRUSTWORTHY ON

But when I call it the SQL Server throws an error

Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "GatewayQuery":
System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
System.Security.SecurityException:
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
   at System.Security.CodeAccessPermission.Demand()
   at System.Net.HttpWebRequest.CheckConnectPermission(Uri uri, Boolean needExecutionContext)
   at System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint)
   at System.Net.HttpRequestCreator.Create(Uri Uri)
   at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
   at System.Net.WebRequest.CreateHttp(Uri requestUri)
   at CIPGatewaySqlServerClrClient.Query(String url, String jobName, String sql)

How can I solve this problem?

The TRUSTWORTHY has been turn on.


问:
Not getting the right indentation in YAML using PYYAML
While using PYAML for creating a YAML I am not getting the expected indentation.

1- Using the below I am getting:

```<code>data2 = {'rule_dimensions': ['consistency', 'correctness', 'duplication','completeness',
                              'conformance','integrity']}
print(yaml.dump(data2,default_flow_style= False,sort_keys=False,indent=3,allow_unicode=True))
</code>```

Output:

```<code>rule_dimensions:
- consistency
- correctness
- duplication
- completeness
- conformance
- integrity
</code>```

2- Using this I am getting:

```<code>data2 = {'rule_dimensions': [['consistency', 'correctness', 'duplication','completeness',
                              'conformance','integrity']]}
print(yaml.dump(data2,default_flow_style= False,sort_keys=False,indent=3,allow_unicode=True))
</code>```

Output

```<code>rule_dimensions:
-  - consistency
   - correctness
   - duplication
   - completeness
   - conformance
   - integrity
</code>```

What is the right options to to get the below

Expected output with indentation:

```<code>rule_dimensions:
  - consistency
  - correctness
  - duplication
  - completeness
  - conformance
  - integrity
</code>```

Body:
While using PYAML for creating a YAML I am not getting the expected indentation.

1- Using the below I am getting:

data2 = {'rule_dimensions': ['consistency', 'correctness', 'duplication','completeness',
                              'conformance','integrity']}
print(yaml.dump(data2,default_flow_style= False,sort_keys=False,indent=3,allow_unicode=True))

Output:

rule_dimensions:
- consistency
- correctness
- duplication
- completeness
- conformance
- integrity

2- Using this I am getting:

data2 = {'rule_dimensions': [['consistency', 'correctness', 'duplication','completeness',
                              'conformance','integrity']]}
print(yaml.dump(data2,default_flow_style= False,sort_keys=False,indent=3,allow_unicode=True))

Output

rule_dimensions:
-  - consistency
   - correctness
   - duplication
   - completeness
   - conformance
   - integrity

What is the right options to to get the below

Expected output with indentation:

rule_dimensions:
  - consistency
  - correctness
  - duplication
  - completeness
  - conformance
  - integrity


问:
How to fix error code 110 in agora? unity
i am using agora voice for sound system in unity. but I am getting an error with the code error 110. sdk is up to date.

I read the agora docs, did the sdk update.

I get and use token from railway.app but it says invalid token

here is my code:

```<code>    IEnumerator
FetchToken(string url, string channel, string userId, int TimeToLive) /* , Action<string> callback = null */
{
    int role = 1;
    UnityWebRequest request =
        UnityWebRequest
            .Get(string
                .Format("{0}/rtc/{1}/{2}/uid/{3}/?expiry={4}",
                url,
                channel,
                role,
                userId,
                TimeToLive));

    yield return request.SendWebRequest();
    if (request.isNetworkError || request.isHttpError)
    {
        Debug.Log(request.error);

        /* callback(null); */
        yield break;
    }
    AgoraToken tokenInfo =
        JsonUtility.FromJson<AgoraToken>(request.downloadHandler.text);

    /* callback(tokenInfo.rtcToken); */
    fetchedToken = tokenInfo.rtcToken;
}
</code>```

Body:
i am using agora voice for sound system in unity. but I am getting an error with the code error 110. sdk is up to date.

I read the agora docs, did the sdk update.

I get and use token from railway.app but it says invalid token

here is my code:

    IEnumerator
FetchToken(string url, string channel, string userId, int TimeToLive) /* , Action<string> callback = null */
{
    int role = 1;
    UnityWebRequest request =
        UnityWebRequest
            .Get(string
                .Format("{0}/rtc/{1}/{2}/uid/{3}/?expiry={4}",
                url,
                channel,
                role,
                userId,
                TimeToLive));

    yield return request.SendWebRequest();
    if (request.isNetworkError || request.isHttpError)
    {
        Debug.Log(request.error);

        /* callback(null); */
        yield break;
    }
    AgoraToken tokenInfo =
        JsonUtility.FromJson<AgoraToken>(request.downloadHandler.text);

    /* callback(tokenInfo.rtcToken); */
    fetchedToken = tokenInfo.rtcToken;
}


问:
Hibernate Upgrade to v6 (Spring Boot 3) - "Named type [interface java.util.List] did not implement BasicType nor UserType"
After upgrading to Spring Boot 3 / Hibernate 6, I am getting exceptions during Spring application / test startup.

java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@15ec3c0c testClass = ....

Caused by: jakarta.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is java.lang.IllegalArgumentException: Named type [interface java.util.List] did not implement BasicType nor UserType

Problem can be traced / debugged down to a List<String> entity property, which is using an AttributeConverter for storing it as a comma-separated string in the (MySQL) DB (TEXT field).

The converter:

```<code>@Converter
class StringListToStringConverter : AttributeConverter<List<String>, String> {
....
}
</code>```

The entity:

```<code>@MappedSuperclass
abstract class MyInstance<T>(
...

@Column(name = "iface_ids", columnDefinition = "TEXT")
@Convert(converter = StringListToStringConverter::class)
var interfaceIds: List<String> = emptyList()

...
)
</code>```

This has been working nicely before with Spring Boot 2.7.x / Hibernate 5.x.

Do you think there is another solution than writing a custom type (and thus removing/replacing the AttributeConverter) in this case?

Kind Regards,
dom

Expecting it to actually work OOTB, the AttributeConverter solution looks so clean&simple for this purpose compared to a custom type implementation that I don't really want to change that.

Body:
After upgrading to Spring Boot 3 / Hibernate 6, I am getting exceptions during Spring application / test startup.

java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@15ec3c0c testClass = ....

Caused by: jakarta.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is java.lang.IllegalArgumentException: Named type [interface java.util.List] did not implement BasicType nor UserType

Problem can be traced / debugged down to a List<String> entity property, which is using an AttributeConverter for storing it as a comma-separated string in the (MySQL) DB (TEXT field).

The converter:

@Converter
class StringListToStringConverter : AttributeConverter<List<String>, String> {
....
}

The entity:

@MappedSuperclass
abstract class MyInstance<T>(
...

@Column(name = "iface_ids", columnDefinition = "TEXT")
@Convert(converter = StringListToStringConverter::class)
var interfaceIds: List<String> = emptyList()

...
)

This has been working nicely before with Spring Boot 2.7.x / Hibernate 5.x.

Do you think there is another solution than writing a custom type (and thus removing/replacing the AttributeConverter) in this case?

Kind Regards,
dom

Expecting it to actually work OOTB, the AttributeConverter solution looks so clean&simple for this purpose compared to a custom type implementation that I don't really want to change that.


问:
FIrebase react hooks only when a statement is true
I'm trying to make a Context API that supplies a connected user (not in Firebase Auth) and its respective DB entry in Firestore. I'm using Magic links as the auth method.

Here's my Provider:

const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [signer, setSigner] = useState<ethers.Signer | null>(null);
  const [address, setAddress] = useState<string | null>(null);
  const [balance, setBalance] = useState<string | null>(null);
  const [userDoc, dbLoading] = useCollection(
    query(
      collection(firestore, "users"),
      where("walletAddress", "==", address ?? "") // issue is here <----
    )
  );
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isConnected, setIsConnected] = useState<boolean>(false);

  useEffect(() => {
    if (!dbLoading && userDoc?.empty) {
      addDoc(collection(firestore, "users"), {
        walletAddress: address,
      });
    }

    setIsLoading(false);
  }, [dbLoading]);

  const connect = () => {
    setIsLoading(true);

    provider
      .listAccounts()
      .then((accounts) => {
        if (accounts.length > 0) {
          const signer = provider.getSigner(accounts[0]);
          setSigner(signer);
          signer.getAddress().then((address) => {
            setAddress(address);
          });
          signer.getBalance().then((balance) => {
            setBalance(balance.toString());
          });
          setIsConnected(true);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const disconnect = () => {
    setIsLoading(true);

    magic.connect
      .disconnect()
      .then(() => {
        setAddress(null);
        setBalance(null);
        setIsConnected(false);
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <AuthContext.Provider
      value={{
        userDoc: userDoc?.docs[0]?.data() ?? {},
        address,
        balance,
        isLoading: isLoading || dbLoading,
        isConnected,
        connect,
        disconnect,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
```

So the problem I'm having is quite straight forward: when the user is not logged in, it creates a new entry with 'walletAddress' of null. Before, I had the same Auth Provider as above, just stripped of all the Firestore logic. But after running into some issues when creating Route Guards, I decided to put it all into a single Provider. Is there a simple solution to this, or do I need to go back to two providers and work from there?

Body:
I'm trying to make a Context API that supplies a connected user (not in Firebase Auth) and its respective DB entry in Firestore. I'm using Magic links as the auth method.

Here's my Provider:

const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [signer, setSigner] = useState<ethers.Signer | null>(null);
  const [address, setAddress] = useState<string | null>(null);
  const [balance, setBalance] = useState<string | null>(null);
  const [userDoc, dbLoading] = useCollection(
    query(
      collection(firestore, "users"),
      where("walletAddress", "==", address ?? "") // issue is here <----
    )
  );
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isConnected, setIsConnected] = useState<boolean>(false);

  useEffect(() => {
    if (!dbLoading && userDoc?.empty) {
      addDoc(collection(firestore, "users"), {
        walletAddress: address,
      });
    }

    setIsLoading(false);
  }, [dbLoading]);

  const connect = () => {
    setIsLoading(true);

    provider
      .listAccounts()
      .then((accounts) => {
        if (accounts.length > 0) {
          const signer = provider.getSigner(accounts[0]);
          setSigner(signer);
          signer.getAddress().then((address) => {
            setAddress(address);
          });
          signer.getBalance().then((balance) => {
            setBalance(balance.toString());
          });
          setIsConnected(true);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const disconnect = () => {
    setIsLoading(true);

    magic.connect
      .disconnect()
      .then(() => {
        setAddress(null);
        setBalance(null);
        setIsConnected(false);
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <AuthContext.Provider
      value={{
        userDoc: userDoc?.docs[0]?.data() ?? {},
        address,
        balance,
        isLoading: isLoading || dbLoading,
        isConnected,
        connect,
        disconnect,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

So the problem I'm having is quite straight forward: when the user is not logged in, it creates a new entry with 'walletAddress' of null. Before, I had the same Auth Provider as above, just stripped of all the Firestore logic. But after running into some issues when creating Route Guards, I decided to put it all into a single Provider. Is there a simple solution to this, or do I need to go back to two providers and work from there?


问:
in laravel hasMany() relation is working but belongsTO not working
i have two tables 1: users 2: roles

as for migration of users table like this

`

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->foreignId('role_id')->constrained()->onDelete('cascade');
            $table->string('name');
            $table->string('username');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('profile_image')->default('user.png');
            $table->text('about')->nullable();;
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

</code>```

`

as for roles table migration

`

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('role_title');
            $table->string('role_slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
};

</code>```

`

User mode

`

```<code><?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Role;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    public function role(){

        return $this->belongsTo(Role::class);
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

}

</code>```

`

Role model

`

```<code><?php

namespace App\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Role extends Model
{
    use HasFactory;

    public function users(){
        return $this->hasMany(User::class);
    }
}

</code>```

`

so i have tried

App\Models\Role::find(1)->users;
so it is returning

`

```<code> Illuminate\Database\Eloquent\Collection {#4831
    all: [
      App\Models\User {#4829
        id: 2,
        role_id: 1,
        name: "zahid",
        username: "admin",
        email: "admin@gmail.com",
        email_verified_at: null,
        #password: "$2y$10$6Up.B4.0gytPsVWOT/f0eeG4yk.u466FDRNf34yYZwxbwyKJh8o8u",
        updated_at: null,
      },
    ],
  }
</code>```

`

and
App\Models\User::find(2)->roles;
it is returning null

please tell me where is my fault in code why my belogsTo not working. i want for one use lke jone or nike  contains only one role lke author or admin or writer etc. but one role lke admin or it could be contain multiple users lke multiple user can be admin or author.

is in my logic any fault or in code above.

plz help me. and thank for advaced for all helpfull code loves.

Body:
i have two tables 1: users 2: roles

as for migration of users table like this

`

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->foreignId('role_id')->constrained()->onDelete('cascade');
            $table->string('name');
            $table->string('username');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('profile_image')->default('user.png');
            $table->text('about')->nullable();;
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

`

as for roles table migration

`

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('role_title');
            $table->string('role_slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
};

`

User mode

`

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Role;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    public function role(){

        return $this->belongsTo(Role::class);
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

}

`

Role model

`

<?php

namespace App\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Role extends Model
{
    use HasFactory;

    public function users(){
        return $this->hasMany(User::class);
    }
}

`

so i have tried

App\Models\Role::find(1)->users;
so it is returning

`

 Illuminate\Database\Eloquent\Collection {#4831
    all: [
      App\Models\User {#4829
        id: 2,
        role_id: 1,
        name: "zahid",
        username: "admin",
        email: "admin@gmail.com",
        email_verified_at: null,
        #password: "$2y$10$6Up.B4.0gytPsVWOT/f0eeG4yk.u466FDRNf34yYZwxbwyKJh8o8u",
        updated_at: null,
      },
    ],
  }

`

and
App\Models\User::find(2)->roles;
it is returning null

please tell me where is my fault in code why my belogsTo not working. i want for one use lke jone or nike  contains only one role lke author or admin or writer etc. but one role lke admin or it could be contain multiple users lke multiple user can be admin or author.

is in my logic any fault or in code above.

plz help me. and thank for advaced for all helpfull code loves.