问:
How to get name of useWatch in table input data in react hook form
How to get index number in useWatch name. I am trying to get select data in from a mui select field which is inside a table.
I cannot find a way to access a specific select field using useWatch.
the problem using useWatch is giving name of the component, but in table grid there is multiple number of select input field with same name.

Is there any way to give index in useWatch, below i have given functionality of useWatch where i cannot access number.

```<code>const watchType: any = useWatch({
 control: methods.control,
 name: `Details.${number}.TypeID`
})
</code>```

Body:
How to get index number in useWatch name. I am trying to get select data in from a mui select field which is inside a table.
I cannot find a way to access a specific select field using useWatch.
the problem using useWatch is giving name of the component, but in table grid there is multiple number of select input field with same name.

Is there any way to give index in useWatch, below i have given functionality of useWatch where i cannot access number.

const watchType: any = useWatch({
 control: methods.control,
 name: `Details.${number}.TypeID`
})


来源: stackexchange

问:
Mocking Repository inside android activity
I have a bit of a tricky question.
first of all here is the MR for my code: https://gitlab.com/thw2/training-plan/thw-training-catalog-android-app/-/merge_requests/13

I want to test the adding of an alert to SingleAlertRepository via clicking an icon on the ListActivity.
In the ListActivity onCreate function I'm creating a TrainingListAdapter.
As I'm not so familiar with the DI in an Activity I'm creating the SingleAlertRepository in that onCreate function.
Because of that I have trouble mocking this Class.
The test I want to get run is the AddAlertTest Test.
Maybe some of you have some hints for me how to do proper DI or how to mock the function properly.

ContentLicense: CC BY-SA 4.0


问:
UseDropZone dynamic ref
I am using react-dropzone as a meant to upload files. I have a requirement where I have to use it at multiple places in a form (like inside .map) my problem is I am not able to receive the input file ref index where the file was dropped but it is always the last file index

```<code>const { getRootProps, getInputProps, inputRef } = useDropzone({
    accept: ["image/png", "image/jpg", "image/jpeg"],
    onDrop: async ([file]) => {
      const uploadedFileId = inputRef.current.id;
      console.log({ uploadedFileId });
    }
  });

  return (
    <section className="wfp--dropzone">
      {[1, 2, 3].map((el, ind) => {
        return (
          <div {...getRootProps()} key={ind}>
            <input {...getInputProps({ id: ind })} />
            <Icon className="wfp--dropzone__icon" icon={iconUpload} />
            <div>Drop files or click here to upload</div>
          </div>
        );
      })}
    </section>
  );
</code>```

In the above code, no matter which input file I select, the uploadedFileId is always 2 while the expected output as it should be giving the correct ID according to the input which was selected.

I have created a quick demo on sandbox here I am passing dynamic index as an ID to the input field but the ref is not updated according to that

Title: UseDropZone dynamic ref

Body:
I am using react-dropzone as a meant to upload files. I have a requirement where I have to use it at multiple places in a form (like inside .map) my problem is I am not able to receive the input file ref index where the file was dropped but it is always the last file index

const { getRootProps, getInputProps, inputRef } = useDropzone({
    accept: ["image/png", "image/jpg", "image/jpeg"],
    onDrop: async ([file]) => {
      const uploadedFileId = inputRef.current.id;
      console.log({ uploadedFileId });
    }
  });

  return (

      {[1, 2, 3].map((el, ind) => {
        return (

            <input {...getInputProps({ id: ind })} />
            <Icon className="wfp--dropzone__icon" icon={iconUpload} />

Drop files or click here to upload

        );
      })}

  );

In the above code, no matter which input file I select, the uploadedFileId is always 2 while the expected output as it should be giving the correct ID according to the input which was selected.

I have created a quick demo on sandbox here I am passing dynamic index as an ID to the input field but the ref is not updated according to that


问:
How to browse windows libraries in Powershel?
I feel like an idiot. For the past few days I have been working on a module that allows me to create windows libraries, add items or remove items to it. etc etc, thanks to a discovery I made that libraries are just .xml files

This whole time I was viewing the libraries in Explorer, Search Everything, Directory Opus. Which all have support for working with libraries.

Well how does does one browse a library in Powershell?
Lets say I have library called Config Files, how can I do something like:

```<code>Get-Child Items -Path "Libraries\Config Files"
</code>```

Which should Output:

```<code>C:\Users\someuser\Documents\output.json
C:\Users\someuser\ParsLib\Real Time Config.sublime-project
C:\Users\someuser\Lime\Settings.json
C:\Users\someuser\Documents\Config Notes.md
<...>
</code>```

Body:
I feel like an idiot. For the past few days I have been working on a module that allows me to create windows libraries, add items or remove items to it. etc etc, thanks to a discovery I made that libraries are just .xml files

This whole time I was viewing the libraries in Explorer, Search Everything, Directory Opus. Which all have support for working with libraries.

Well how does does one browse a library in Powershell?
Lets say I have library called Config Files, how can I do something like:

Get-Child Items -Path "Libraries\Config Files"

Which should Output:

C:\Users\someuser\Documents\output.json
C:\Users\someuser\ParsLib\Real Time Config.sublime-project
C:\Users\someuser\Lime\Settings.json
C:\Users\someuser\Documents\Config Notes.md
<...>


问:
Proving height of O(logn) using induction for modified binary tree
If I were to have a modified version of a binary tree such that the maximal difference between the right and left child nodes of every node in the tree is ≤2, my intuition tells me that similarly to a regular binary tree, this would have a height of O(log n), but how can I prove this using induction?</p>


问:
POST http://localhost:5000/api/device 404 (Not Found) even url is correct
I have a problem with axios. When i send post request axios returns me an error
POST http://localhost:5000/api/device 404 (Not Found)

But when when I send GET request everything is ok.

Could you help me

It is my code

```<code>const $authHost = axios.create({
    baseURL:process.env.REACT_APP_API_URL
})

const authInterceptor = config => {
    config.headers.authorization = `Bearer ${localStorage.getItem('token')}`
    return config
}

$authHost.interceptors.request.use(authInterceptor)
</code>```
```<code>export const createDevice = async (device) => {
    let config = {
        headers: {
           'Content-Type': 'application/json',
        }
   }
    const {data} = await $authHost.post('/api/device', device, config)
    return data
}

export const fetchDevices = async () =>{
    const {data} = await
</code>```
```<code>const addDevice = () =>{
    const formData = new FormData()
    formData.append('name', name)
    formData.append('price', `${price}`)
    formData.append('img', file)
    formData.append('brandId', devices.selectedBrand.id)
    formData.append('typeId', devices.selectedType.id)
    formData.append('info', JSON.stringify(info))
    createDevice(formData).then(data => onHide())
  }
</code>```

Body:
I have a problem with axios. When i send post request axios returns me an error
POST http://localhost:5000/api/device 404 (Not Found)

But when when I send GET request everything is ok.

Could you help me

It is my code

const $authHost = axios.create({
    baseURL:process.env.REACT_APP_API_URL
})

const authInterceptor = config => {
    config.headers.authorization = `Bearer ${localStorage.getItem('token')}`
    return config
}

$authHost.interceptors.request.use(authInterceptor)

export const createDevice = async (device) => {
    let config = {
        headers: {
           'Content-Type': 'application/json',
        }
   }
    const {data} = await $authHost.post('/api/device', device, config)
    return data
}

export const fetchDevices = async () =>{
    const {data} = await

const addDevice = () =>{
    const formData = new FormData()
    formData.append('name', name)
    formData.append('price', `${price}`)
    formData.append('img', file)
    formData.append('brandId', devices.selectedBrand.id)
    formData.append('typeId', devices.selectedType.id)
    formData.append('info', JSON.stringify(info))
    createDevice(formData).then(data => onHide())
  }


问:
Visual Studio 2017 Unit Test Automatic Setup
Adding a Native Unit Test project to a 2017 Visual Studio Solution, VS2017 Wizard does not add the Unit Test functionality automatically in the project settings ie D:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\VS\UnitTest for Include & Library directories, the path of the Project to be tested, etc.

Also, including the functions I want to test in the TestUnit project ie Component1 fails once again but this time in the linking phase, saying that it could not find the Component1 object or library.

So, currently, I have to add all this stuff manually, ie Adding the UnitTest path inside the VC++ Include/Library Directories of the Configuration Properties of the project, adding Obj Dependencies in the Linker's Input etc. That's ok but the question is Can I fix this to work automatically as I used before?

PS: This was not always the case. Before I add/uninstall some features using the VS installer, it worked just fine.


问:
Range Slider made on JS and HTML
I have created a code with 4 range slider that displays only its total in "$" symbol.
This total must not exceed 5 symbols in all 4 sliders.
The objective is that the customer will be able to have a visual appercus without knowing the amount how much his project will cost him.

Here is the code I have done so far.

```<code><div id="container">
  <label for="slider1">Titre 1</label>
  <input type="range" id="slider1" min="0" max="5" value="0">
  <br>
  <label for="slider2">Titre 2</label>
  <input type="range" id="slider2" min="0" max="5" value="0">
  <br>
  <label for="slider3">Titre 3</label>
  <input type="range" id="slider3" min="0" max="5" value="0">
  <br>
  <label for="slider4">Titre 4</label>
  <input type="range" id="slider4" min="0" max="5" value="0">
  <br>
  <div id="total">Total: <span id="dollar-signs"></span></div>
</div>

<style>
  #container {
    display: flex;
    flex-direction: column;
  }

  label {
    font-weight: bold;
  }

  #total {
    font-weight: bold;
  }

  #total.exceeded {
    color: red;
  }
</style>

<script>
  const sliders = document.querySelectorAll("#container input[type=range]");

function updateTotal() {
let total = 0;
sliders.forEach(slider => {
total += Number(slider.value);
});
const totalElement = document.getElementById("total");
const dollarSigns = document.getElementById("dollar-signs");
dollarSigns.innerHTML = "";
for (let i = 0; i < total; i++) {
if (i < 5) {
dollarSigns.innerHTML += "$";
}
}
if (total > 5) {
totalElement.classList.add("exceeded");
} else {
totalElement.classList.remove("exceeded");
}
}

sliders.forEach(slider => {
slider.addEventListener("input", updateTotal);
});

updateTotal();
</script>
</code>```

I would like someone to help me debug my script to allow the 4 slider to display a maximum of 5 $ sybols.

Currently it does it but not correctly if my 4 sliders are at their maximum it must be 5 symbols.

Title: Range Slider made on JS and HTML

Body:
I have created a code with 4 range slider that displays only its total in "$" symbol.
This total must not exceed 5 symbols in all 4 sliders.
The objective is that the customer will be able to have a visual appercus without knowing the amount how much his project will cost him.

Here is the code I have done so far.

  Titre 1
  <input type="range" id="slider1" min="0" max="5" value="0">

  Titre 2
  <input type="range" id="slider2" min="0" max="5" value="0">

  Titre 3
  <input type="range" id="slider3" min="0" max="5" value="0">

  Titre 4
  <input type="range" id="slider4" min="0" max="5" value="0">

Total:

I would like someone to help me debug my script to allow the 4 slider to display a maximum of 5 $ sybols.

Currently it does it but not correctly if my 4 sliders are at their maximum it must be 5 symbols.


问:
Vuetify v-combobox huge items list rendering
I'm using vuetify v3.

In my use case, I have a multiple lists with different sizes (the big one can reach  ~100k items) that I want to render in multiple v-combobox, I've tried this code :

```<code><v-col v-for="property in filterableProperties">
  <v-combobox v-model="filter[property.code]" :label="property.label" :items="values[property.code]"
              variant="outlined" hide-details bg-color="white" clearable/>
</v-col>
</code>```

values is an objet containing those lists.

My issue is that browser freeze when clicking on the v-combobox containing the huge list. I don't need to display all 100k items in a time, a lazy loading will do just fine. I haven't find a way to do that.

Any help ?

Body:
I'm using vuetify v3.

In my use case, I have a multiple lists with different sizes (the big one can reach  ~100k items) that I want to render in multiple v-combobox, I've tried this code :

<v-col v-for="property in filterableProperties">
  <v-combobox v-model="filter[property.code]" :label="property.label" :items="values[property.code]"
              variant="outlined" hide-details bg-color="white" clearable/>
</v-col>

values is an objet containing those lists.

My issue is that browser freeze when clicking on the v-combobox containing the huge list. I don't need to display all 100k items in a time, a lazy loading will do just fine. I haven't find a way to do that.

Any help ?


问:
Nextjs and tailwindcss background image include parameter ul
```<code>const bg_file = "https://via.placeholder.com/500"
<section
        className="bg-[url('{bg_file}')] bg-cover h-screen
  font-[Poppins] md:bg-top bg-center"
      >
</code>```

i'm trying include bg_file parameter in  bg-[url('parameter url')] but not working

how can i include custom parameter

Body:
const bg_file = "https://via.placeholder.com/500"

i'm trying include bg_file parameter in  bg-[url('parameter url')] but not working

how can i include custom parameter


问:
flow_from_directory cannot find path error in Spyder
I saw a lot of questions about the subject here but unfortunately didn't find one that solved my problem.I have the following code:

```<code>import numpy as np
from numpy import asarray
from PIL import Image
import tensorflow as tf
import keras
from keras.preprocessing.image import ImageDataGenerator
datagen =ImageDataGenerator()
train_it = datagen.flow_from_directory("C:/Users/agns1/Downloads/by_class.zip/by_class/4a/hsf_1", class_mode='binary', batch_size=10)
</code>```

the data is from MNIST data set . and the error is :

```<code>FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/Users/agns1/Downloads/by_class.zip/by_class/4a/hsf_1'
</code>```

unfortunately, I cant seem to understand what is is the problem is it because of the zip ? Thank you:)

Body:
I saw a lot of questions about the subject here but unfortunately didn't find one that solved my problem.I have the following code:

import numpy as np
from numpy import asarray
from PIL import Image
import tensorflow as tf
import keras
from keras.preprocessing.image import ImageDataGenerator
datagen =ImageDataGenerator()
train_it = datagen.flow_from_directory("C:/Users/agns1/Downloads/by_class.zip/by_class/4a/hsf_1", class_mode='binary', batch_size=10)

the data is from MNIST data set . and the error is :

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/Users/agns1/Downloads/by_class.zip/by_class/4a/hsf_1'

unfortunately, I cant seem to understand what is is the problem is it because of the zip ? Thank you:)


问:
Firebase RTDB - How to avoid CSP problems in chrome extension mv3
I have a private chrome extension that at the moment I'm publishing as private in the CWS.

I've noticed that sometimes the extension will stop working because of the CSP policy of mv3. I've used firebase RTDB using vite to include it, is there any way that I can use to avoid this problem?

Also I need to apply some rules to the database but I don't have any login or registration system. How I can setup rules correctly?


问:
Are css @keyframes possible natively with Webflow interaction?
I want to move a div and while it's moving I want to increase its opacity then decrease it. With css keyframes I'd do something like this:

```<code>.animated-element {
  animation: move-and-fade 5s ease-in-out infinite;
}

@keyframes move-and-fade {
  0% {
    transform: translateY(0px);
    opacity: 10%;
  }
  50% {
    opacity: 100%;
  }
  100% {
    transform: translateY(620px);
    opacity: 10%;
  }
}
</code>```

Is this possible natively with Webflow interaction? It seems I can only add actions with previous action or after.

I want to achieve something similar to this, where the small lines are moving on the border of the hero image.

Here's an example of my implementation in Webflow.

Body:
I want to move a div and while it's moving I want to increase its opacity then decrease it. With css keyframes I'd do something like this:

.animated-element {
  animation: move-and-fade 5s ease-in-out infinite;
}

@keyframes move-and-fade {
  0% {
    transform: translateY(0px);
    opacity: 10%;
  }
  50% {
    opacity: 100%;
  }
  100% {
    transform: translateY(620px);
    opacity: 10%;
  }
}

Is this possible natively with Webflow interaction? It seems I can only add actions with previous action or after.

I want to achieve something similar to this, where the small lines are moving on the border of the hero image.

Here's an example of my implementation in Webflow.


问:
Not able to access all the webelements from the grid in selenium
In webpage i have multiple grids like below

As you can see not all the web elements are in view. We need to scroll to see other elements.
This grid have around 20 rows and 10 columns. Number of rows will change as per scenario.
My requirement is to fetch data of all the web elements of this grid

I have written web elements as below

 @FindBy(xpath = "xpath here")
private static List<WebElement> sampleGridDate; (This should return all web elements from date column)

@FindBy(xpath = "xpath here")
private static List<WebElement> sampleGridCode; (This should return all web elements from code column)
```
<p>I am fetching data with below code</p>
<pre class="lang-java prettyprint-override"><code>
for (int i = 0; i < sampleGridDate.size(); i++) {

            scrollToViewElement(driver,sampleGridDate.get(i));
            row.setDate(sampleGridDate.get(i).getText());
            scrollToViewElement(driver,sampleGridCode.get(i));
            row.setCode(sampleGridCode.get(i).getText());

        .....so on
        }
</code>```

public static void scrollToViewElement(WebDriver driver, WebElement element) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].scrollIntoView();", element);
    }
```

**
Problems i am facing are

sampleGridDate.size() returns 16 instead of 20

this for loop runs only once as sampleGridDate is not found after first iteration (stale webelement exception)
**

How do i fix this

Body:
In webpage i have multiple grids like below

As you can see not all the web elements are in view. We need to scroll to see other elements.
This grid have around 20 rows and 10 columns. Number of rows will change as per scenario.
My requirement is to fetch data of all the web elements of this grid

I have written web elements as below

 @FindBy(xpath = "xpath here")
private static List<WebElement> sampleGridDate; (This should return all web elements from date column)

@FindBy(xpath = "xpath here")
private static List<WebElement> sampleGridCode; (This should return all web elements from code column)

I am fetching data with below code

for (int i = 0; i < sampleGridDate.size(); i++) {

            scrollToViewElement(driver,sampleGridDate.get(i));
            row.setDate(sampleGridDate.get(i).getText());
            scrollToViewElement(driver,sampleGridCode.get(i));
            row.setCode(sampleGridCode.get(i).getText());

        .....so on
        }

public static void scrollToViewElement(WebDriver driver, WebElement element) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].scrollIntoView();", element);
    }

**
Problems i am facing are

sampleGridDate.size() returns 16 instead of 20

this for loop runs only once as sampleGridDate is not found after first iteration (stale webelement exception)
**

How do i fix this


问:
How to upload a file in amazon s3 using presigned url in angular app?
I got the Amazon presigned url from my backend, and via this url, I want to upload a file to Amazon's AWS server. But every time I try to upload a file, I get an error in my Angular app. However, using the same url, I was able to update file via postman and there is no issue whatso ever.

Here is how I was making the http call:

```<code>uploadImage(bucket: BucketTypes, fileInput: HTMLInputElement, presignedUrl: string): Observable<IUploadedImage> {
    let file = fileInput.files[0];
    // const formData = new FormData();
    // formData.append('file', file);
    // const blob = new Blob([file], { 'type': 'video/mp4' });
    const headerDict = {
      'Content-Type': 'multipart/form-data',
    };

    const requestOptions = {
      headers: new HttpHeaders(headerDict),
    };
    return this.http.put<IUploadedImage>(presignedUrl, file, requestOptions );
  }
</code>```

I tried to upload the file as raw, as a blob, and as a form data. None of them are working, and every time I try, I get an HTTP response code 400.

However, with the same URL, Postman's response is working fine. While using Postman, I was using this setup. inside the http header: Content-Type: multipart/form-data and uploading the file as binary.

Surprisingly, While using axios put method, it was also working fine.

```<code>uploadImage(bucket: BucketTypes, file: File, presignedURL?: string) {

    const config = {
      headers: {
          'Content-Type': 'multipart/form-data',
      }
  };
  axios.put(presignedURL, file, config);
  }
</code>```

Now I am not sure what I have done wrong with the Angular HTTP request. can someone please tell me?

Body:
I got the Amazon presigned url from my backend, and via this url, I want to upload a file to Amazon's AWS server. But every time I try to upload a file, I get an error in my Angular app. However, using the same url, I was able to update file via postman and there is no issue whatso ever.

Here is how I was making the http call:

uploadImage(bucket: BucketTypes, fileInput: HTMLInputElement, presignedUrl: string): Observable<IUploadedImage> {
    let file = fileInput.files[0];
    // const formData = new FormData();
    // formData.append('file', file);
    // const blob = new Blob([file], { 'type': 'video/mp4' });
    const headerDict = {
      'Content-Type': 'multipart/form-data',
    };

    const requestOptions = {
      headers: new HttpHeaders(headerDict),
    };
    return this.http.put<IUploadedImage>(presignedUrl, file, requestOptions );
  }

I tried to upload the file as raw, as a blob, and as a form data. None of them are working, and every time I try, I get an HTTP response code 400.

However, with the same URL, Postman's response is working fine. While using Postman, I was using this setup. inside the http header: Content-Type: multipart/form-data and uploading the file as binary.

Surprisingly, While using axios put method, it was also working fine.

uploadImage(bucket: BucketTypes, file: File, presignedURL?: string) {

    const config = {
      headers: {
          'Content-Type': 'multipart/form-data',
      }
  };
  axios.put(presignedURL, file, config);
  }

Now I am not sure what I have done wrong with the Angular HTTP request. can someone please tell me?


问:
QuillJS: The toggle feature of inline blot buttons are not working when in fullscreen mode
I am using QuillJS 1.3. Since QuillJS natively doesn't provide / support full-screen mode / feature in toolbar, I created one and handled the full-screen logic from outside. Following is the code (I am using ReactJS):

```<code>  useEffect(() => {
    const fullScreenChangeEventHandler = () => {
      if (document.fullscreenElement) {
        setIsFullScreen(true);
      } else {
        setIsFullScreen(false);
      }
    };
    const { current } = textEditorContainerRef;
    if (current) {
      current.addEventListener('fullscreenchange', fullScreenChangeEventHandler);
    }

    return () => {
      current.removeEventListener('fullscreenchange', fullScreenChangeEventHandler);
    };
  }, []);

  const handleFullScreen = () => {
    if (!document.fullscreenElement) {
      textEditorContainerRef.current.requestFullscreen().catch((err) => {
        console.error('Failed to init the full screen for text editor ', err);
      });
    } else if (document.exitFullscreen) {
      document.exitFullscreen().catch((err) => {
        console.error('Failed to exit full screen text editor ', err);
      });
    }
  };
</code>```

Regardless of with or without ReactJS, I found this problem with official quilljs website as well. (Go to quilljs.com and open the devtool for experiment).

The problem with full-screen mode (only in chromium browser such as Chrome and Edge), is that the toggle behaviour of some of inline blots e.g. Bold, Italic, Underline and Strike do not work. That is, Once selection turns into Bold, clicking again on Bold button in toolbar doesn't reset it back. The toggle behaviour however works fine in normal mode i.e. non full-screen mode.
I have also reported an issue on quilljs repository, where you can find more or less detailed information with screen recording:
https://github.com/quilljs/quill/issues/3713

On a closer look, the issue is apparently looks like associated with inner SVG icon in toolbar buttons. I am not pretty much sure why though, but when you try to click slightly away from icon (but on the button), then toggle works just fine. Any idea what could go wrong here ?

Body:
I am using QuillJS 1.3. Since QuillJS natively doesn't provide / support full-screen mode / feature in toolbar, I created one and handled the full-screen logic from outside. Following is the code (I am using ReactJS):

  useEffect(() => {
    const fullScreenChangeEventHandler = () => {
      if (document.fullscreenElement) {
        setIsFullScreen(true);
      } else {
        setIsFullScreen(false);
      }
    };
    const { current } = textEditorContainerRef;
    if (current) {
      current.addEventListener('fullscreenchange', fullScreenChangeEventHandler);
    }

    return () => {
      current.removeEventListener('fullscreenchange', fullScreenChangeEventHandler);
    };
  }, []);

  const handleFullScreen = () => {
    if (!document.fullscreenElement) {
      textEditorContainerRef.current.requestFullscreen().catch((err) => {
        console.error('Failed to init the full screen for text editor ', err);
      });
    } else if (document.exitFullscreen) {
      document.exitFullscreen().catch((err) => {
        console.error('Failed to exit full screen text editor ', err);
      });
    }
  };

Regardless of with or without ReactJS, I found this problem with official quilljs website as well. (Go to quilljs.com and open the devtool for experiment).

The problem with full-screen mode (only in chromium browser such as Chrome and Edge), is that the toggle behaviour of some of inline blots e.g. Bold, Italic, Underline and Strike do not work. That is, Once selection turns into Bold, clicking again on Bold button in toolbar doesn't reset it back. The toggle behaviour however works fine in normal mode i.e. non full-screen mode.
I have also reported an issue on quilljs repository, where you can find more or less detailed information with screen recording:
https://github.com/quilljs/quill/issues/3713

On a closer look, the issue is apparently looks like associated with inner SVG icon in toolbar buttons. I am not pretty much sure why though, but when you try to click slightly away from icon (but on the button), then toggle works just fine. Any idea what could go wrong here ?


问:
Spring nested transaction causing high CPU usage
While processing thousands of batches (500 records in each batch) we found some high CPU usage and when we went through the code we found that we are using nested @Transactional annotation at some places and we thought this nested @Transactional could be the reason for the high peak.

But no where on internet we didn't find any previous issue someone have faced related to high CPU usage and Nested Transaction

Again when we checked our code properly we found that @Transactinal annotation that we are using at child method - Class2.java is from javax.transaction.Transactional and @Transactinal we are using at parent method - Class1.java is from  @org.springframework.transaction.annotation.Transactional

Class1.java

```<code>@org.springframework.transaction.annotation.Transactional
 public void transform() {
    for (...) {                  // loop to process each batch
      class2Obj.otherFunction();
    }
  }
</code>```

Class2.java

```<code>
  @javax.transaction.Transactional
  public void otherFunction() {
  }
</code>```

What could be the reason, is high CPU usage is because of

Only because of nested @Transactional (regardless of whether we are mixing @Transactional from different classes or not)

Not because of nested @Transactional but because of mixing @Transactional from different classes

Not at all related to @Transactional maybe due to some other reason?

Note: The reason we are pointing out at @Transactional is because, when we process less batches let's say some 100 / 50 batches we are not seeking high cpu usage

Body:
While processing thousands of batches (500 records in each batch) we found some high CPU usage and when we went through the code we found that we are using nested @Transactional annotation at some places and we thought this nested @Transactional could be the reason for the high peak.

But no where on internet we didn't find any previous issue someone have faced related to high CPU usage and Nested Transaction

Again when we checked our code properly we found that @Transactinal annotation that we are using at child method - Class2.java is from javax.transaction.Transactional and @Transactinal we are using at parent method - Class1.java is from  @org.springframework.transaction.annotation.Transactional

Class1.java

@org.springframework.transaction.annotation.Transactional
 public void transform() {
    for (...) {                  // loop to process each batch
      class2Obj.otherFunction();
    }
  }

Class2.java

  @javax.transaction.Transactional
  public void otherFunction() {
  }

What could be the reason, is high CPU usage is because of

Only because of nested @Transactional (regardless of whether we are mixing @Transactional from different classes or not)

Not because of nested @Transactional but because of mixing @Transactional from different classes

Not at all related to @Transactional maybe due to some other reason?

Note: The reason we are pointing out at @Transactional is because, when we process less batches let's say some 100 / 50 batches we are not seeking high cpu usage


问:
Tk.Button not passing name to other Tk.Button class using strvar()
I have a class of tk.Button(s) in one module and a different module that creates a tk.Tk() and fills it with afformentioned buttons.
My problem arrises when I try to call the function that creates the window and loads it with the buttons. If this is called just as a funciton everything works fine. However, if I assign the function to another tk.Button() the names (passed as the 3rd parameter in calling the button) do not get applied to the button.
I assume this has something to do with the way I'm passing the names using StrVar().</p>
```<code>#working module
import tkinter as tk
import json
from Stone_Level_Button import Stone_level_button

# load data from json file
with open("pricing_data.json", "r") as pricing_data_json:
    pricing_data = json.load(pricing_data_json)

#window no frame
window = tk.Tk()
for z,data in enumerate(pricing_data):
    window.rowconfigure(z,weight=1)
window.columnconfigure(0,weight=1)

#lsit of buttons for later?
btns = []

#make and add buttons to list
for data in pricing_data:
    btns.append(Stone_level_button(window,pricing_data, data))

#pack buttons onto window
for n,btn in enumerate(btns):
    btn.grid(row = n, column = 0, sticky = 'news')
window.mainloop()
</code>```
```<code>#nonworking module
import tkinter as tk
import json
from Stone_Level_Button import Stone_level_button

def button_do():
    # load data from json file
    with open("pricing_data.json", "r") as pricing_data_json:
        pricing_data = json.load(pricing_data_json)

    #window no frame
    window = tk.Tk()
    for z,data in enumerate(pricing_data):
        window.rowconfigure(z,weight=1)
    window.columnconfigure(0,weight=1)

    #lsit of buttons for later?
    btns = []

    #make and add buttons to list
    for data in pricing_data:
        btns.append(Stone_level_button(window,pricing_data, data))

    #pack buttons onto window
    for n,btn in enumerate(btns):
        btn.grid(row = n, column = 0, sticky = 'news')
    window.mainloop()
wndw = tk.Tk()
my_button = tk.Button(wndw,text = 'button', command=button_do)
my_button.pack()
wndw.mainloop()
</code>```
```<code>#button class
import json
import tkinter as tk

#make buttons
class Stone_level_button(tk.Button):
    def __init__(self, window, pricing_data, name="", *args, **kwargs):
        self.name = tk.StringVar()
        self.name.set(name.replace('_',' ').title())
        self.json_locator = name #this is used to parse the json data for the "name" assigned for the button

        self.pricing_data = pricing_data
        super(Stone_level_button, self).__init__(
            window, *args, textvariable=self.name, command=self.button_do, **kwargs
        )
    def focus_next_window(self,event):
        #makes it so that tab in a textbox will go to the next textbox insted of creating a tabbe dspace
        event.widget.tk_focusNext().focus()
        return("break")

    def button_do(self):

        #create new window
        self.stone_level_frame = tk.Tk()
        self.stone_level_frame.title("TextBox Input")

        self.stone_level_frame.mainloop()
</code>```
```<code>#json data
{
    "fabrication_cost": 17,
    "mark_up": 0.7,
    "stone_levels": {
        "granite1": {
            "Name": "Granite Level 1",
            "Colors": [
                "Azul Platino",
                "Blanco Tulum",
                "Caledonia",
                "Luna Pearl"
            ],
            "Price": 7.5
        },
        "granite2": {
            "Name": "Granite Level 2",
            "Colors": [
                "Fantasy Brown",
                "Gray Mist",
                "Santa Cecilia",
                "New Venetian Gold"
            ],
            "Price": 10
        },
        "granite3": {
            "Name": "Granite Level 3",
            "Colors": [
                "Nero Mist Honed",
                "Salinas White",
                "Steel Grey Polished",
                "Steel Grey Brushed"
            ],
            "Price": 12
        },
        "quartz1": {
            "Name": "Quartz Level 1",
            "Colors": [
                "Frost White",
                "Iced White",
                "Manhattan Gray",
                "Peppercorn White"
            ],
            "Price": 17
        },
        "quartz2": {
            "Name": "Quartz Level 2",
            "Colors": [
                "Carrara Grigio",
                "Carrara Mist",
                "Fossil Gray",
                "Midnight Majesty"
            ],
            "Price": 22.5
        },
        "quartz3": {
            "Name": "Quartz Level 3",
            "Colors": [
                "Babylon Gray",
                "Calacatta Classique",
                "Calacatta Vicenza",
                "Gray Lagoon"
            ],
            "Price": 25.5
        }
    },
    "edge_pricing": {
        "Roundover/Bevel": 8,
        "Half Bullnose": 10,
        "Full Bullnose": 15,
        "Ogee": 30,
        "Mitered": 50
    },
    "add_ons": {
        "trip_Charge": 250,
        "raw_Cutout": 50,
        "radii": 50,
        "arcs": 100,
        "splay": 100,
        "waterfall": 650,
        "farm_sink_cutout": 100,
        "undermount_Sink_Install": 100,
        "standard_18ga_Sink": 110,
        "upgrade_18ga_Sink": 240,
        "porcelain_Vanity_Sink": 45,
        "customer_Sink": 100
    }
}
</code>```

Body:
I have a class of tk.Button(s) in one module and a different module that creates a tk.Tk() and fills it with afformentioned buttons.
My problem arrises when I try to call the function that creates the window and loads it with the buttons. If this is called just as a funciton everything works fine. However, if I assign the function to another tk.Button() the names (passed as the 3rd parameter in calling the button) do not get applied to the button.
I assume this has something to do with the way I'm passing the names using StrVar().

#working module
import tkinter as tk
import json
from Stone_Level_Button import Stone_level_button

# load data from json file
with open("pricing_data.json", "r") as pricing_data_json:
    pricing_data = json.load(pricing_data_json)

#window no frame
window = tk.Tk()
for z,data in enumerate(pricing_data):
    window.rowconfigure(z,weight=1)
window.columnconfigure(0,weight=1)

#lsit of buttons for later?
btns = []

#make and add buttons to list
for data in pricing_data:
    btns.append(Stone_level_button(window,pricing_data, data))

#pack buttons onto window
for n,btn in enumerate(btns):
    btn.grid(row = n, column = 0, sticky = 'news')
window.mainloop()

#nonworking module
import tkinter as tk
import json
from Stone_Level_Button import Stone_level_button

def button_do():
    # load data from json file
    with open("pricing_data.json", "r") as pricing_data_json:
        pricing_data = json.load(pricing_data_json)

    #window no frame
    window = tk.Tk()
    for z,data in enumerate(pricing_data):
        window.rowconfigure(z,weight=1)
    window.columnconfigure(0,weight=1)

    #lsit of buttons for later?
    btns = []

    #make and add buttons to list
    for data in pricing_data:
        btns.append(Stone_level_button(window,pricing_data, data))

    #pack buttons onto window
    for n,btn in enumerate(btns):
        btn.grid(row = n, column = 0, sticky = 'news')
    window.mainloop()
wndw = tk.Tk()
my_button = tk.Button(wndw,text = 'button', command=button_do)
my_button.pack()
wndw.mainloop()

#button class
import json
import tkinter as tk

#make buttons
class Stone_level_button(tk.Button):
    def __init__(self, window, pricing_data, name="", *args, **kwargs):
        self.name = tk.StringVar()
        self.name.set(name.replace('_',' ').title())
        self.json_locator = name #this is used to parse the json data for the "name" assigned for the button

        self.pricing_data = pricing_data
        super(Stone_level_button, self).__init__(
            window, *args, textvariable=self.name, command=self.button_do, **kwargs
        )
    def focus_next_window(self,event):
        #makes it so that tab in a textbox will go to the next textbox insted of creating a tabbe dspace
        event.widget.tk_focusNext().focus()
        return("break")

    def button_do(self):

        #create new window
        self.stone_level_frame = tk.Tk()
        self.stone_level_frame.title("TextBox Input")

        self.stone_level_frame.mainloop()

#json data
{
    "fabrication_cost": 17,
    "mark_up": 0.7,
    "stone_levels": {
        "granite1": {
            "Name": "Granite Level 1",
            "Colors": [
                "Azul Platino",
                "Blanco Tulum",
                "Caledonia",
                "Luna Pearl"
            ],
            "Price": 7.5
        },
        "granite2": {
            "Name": "Granite Level 2",
            "Colors": [
                "Fantasy Brown",
                "Gray Mist",
                "Santa Cecilia",
                "New Venetian Gold"
            ],
            "Price": 10
        },
        "granite3": {
            "Name": "Granite Level 3",
            "Colors": [
                "Nero Mist Honed",
                "Salinas White",
                "Steel Grey Polished",
                "Steel Grey Brushed"
            ],
            "Price": 12
        },
        "quartz1": {
            "Name": "Quartz Level 1",
            "Colors": [
                "Frost White",
                "Iced White",
                "Manhattan Gray",
                "Peppercorn White"
            ],
            "Price": 17
        },
        "quartz2": {
            "Name": "Quartz Level 2",
            "Colors": [
                "Carrara Grigio",
                "Carrara Mist",
                "Fossil Gray",
                "Midnight Majesty"
            ],
            "Price": 22.5
        },
        "quartz3": {
            "Name": "Quartz Level 3",
            "Colors": [
                "Babylon Gray",
                "Calacatta Classique",
                "Calacatta Vicenza",
                "Gray Lagoon"
            ],
            "Price": 25.5
        }
    },
    "edge_pricing": {
        "Roundover/Bevel": 8,
        "Half Bullnose": 10,
        "Full Bullnose": 15,
        "Ogee": 30,
        "Mitered": 50
    },
    "add_ons": {
        "trip_Charge": 250,
        "raw_Cutout": 50,
        "radii": 50,
        "arcs": 100,
        "splay": 100,
        "waterfall": 650,
        "farm_sink_cutout": 100,
        "undermount_Sink_Install": 100,
        "standard_18ga_Sink": 110,
        "upgrade_18ga_Sink": 240,
        "porcelain_Vanity_Sink": 45,
        "customer_Sink": 100
    }
}


问:
Mocking of a function within a function not working in jest with jest.spyOn
I'm trying to write a test for a function that downloads an Excel file within my React app.

I understand that I need to mock certain functionality, but it doesn't seem to be working according to everything that I have read online.

A basic mock that works is this:

import FileSaver from 'file-saver'
import { xlsxExport } from './functions'

// other code...

test('saveAs', async () => {
    const saveAsSpy = jest.spyOn(FileSaver, 'saveAs')
    FileSaver.saveAs('test')
    expect(saveAsSpy).toHaveBeenCalledWith('test')
})
```
<p>The above works: <code>FileSaver.saveAs</code> was successfully mocked. However, I am utilising <code>FileSaver.saveAs</code> within another function that I wish to test and the mocking does not seem to transfer into that. <code>functions.ts</code> and <code>functions.tests.ts</code> below.</p>
<p><code>functions.ts</code>:</p>
<pre class="lang-js prettyprint-override"><code>import { Dictionary } from './interfaces'
import * as ExcelJS from 'exceljs'
import FileSaver from 'file-saver'

export function xlsxExport(data: Dictionary<any>[], fileName?: string, tabName?: string) {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet(tabName || 'export')

    // Get columns from first item in data
    worksheet.columns = Object.keys(data[0]).map((key: string) => ({ header: key, key: key }))

    // Write each item as a row
    for (const row of data) {
        worksheet.addRow(row)
    }

    // Download the file
    workbook.xlsx.writeBuffer().then(function (buffer) {
        const blob = new Blob([buffer], { type: 'applicationi/xlsx' })
        FileSaver.saveAs(blob, (fileName || 'excel_export') + '.xlsx')
    })
}

</code>```

functions.tests.ts

import FileSaver from 'file-saver'
import { xlsxExport } from './functions'

// ...other code

test('xlsxExport', async () => {
    const saveAsSpy = jest.spyOn(FileSaver, 'saveAs')
    xlsxExport(myArrayOfDicts, 'test_download')
    expect(saveAsSpy).toHaveBeenCalledWith('something, anything')
})
```
<p>Error:</p>
<pre class="lang-bash prettyprint-override"><code>TypeError: Cannot read properties of null (reading 'createElement')
    at Function.saveAs (C:\dev\pcig-react\node_modules\file-saver\src\FileSaver.js:92:9)
    at C:\dev\pcig-react\src\common\functions.ts:221:19
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v19.3.0
 FAIL  src/common/functions.test.ts
  ● Test suite failed to run

    Jest worker encountered 4 child process exceptions, exceeding retry limit

      at ChildProcessWorker.initialize (node_modules/jest-runner/node_modules/jest-worker/build/workers/ChildProcessWorker.js:185:21)
</code>```

It is trying to call the non-mocked FileSaver.saveAs (line 221 of my file) within xlsxExport.

How can I get it to call the mocked version?

Body:
I'm trying to write a test for a function that downloads an Excel file within my React app.

I understand that I need to mock certain functionality, but it doesn't seem to be working according to everything that I have read online.

A basic mock that works is this:

import FileSaver from 'file-saver'
import { xlsxExport } from './functions'

// other code...

test('saveAs', async () => {
    const saveAsSpy = jest.spyOn(FileSaver, 'saveAs')
    FileSaver.saveAs('test')
    expect(saveAsSpy).toHaveBeenCalledWith('test')
})

The above works: FileSaver.saveAs was successfully mocked. However, I am utilising FileSaver.saveAs within another function that I wish to test and the mocking does not seem to transfer into that. functions.ts and functions.tests.ts below.

functions.ts:

import { Dictionary } from './interfaces'
import * as ExcelJS from 'exceljs'
import FileSaver from 'file-saver'

export function xlsxExport(data: Dictionary<any>[], fileName?: string, tabName?: string) {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet(tabName || 'export')

    // Get columns from first item in data
    worksheet.columns = Object.keys(data[0]).map((key: string) => ({ header: key, key: key }))

    // Write each item as a row
    for (const row of data) {
        worksheet.addRow(row)
    }

    // Download the file
    workbook.xlsx.writeBuffer().then(function (buffer) {
        const blob = new Blob([buffer], { type: 'applicationi/xlsx' })
        FileSaver.saveAs(blob, (fileName || 'excel_export') + '.xlsx')
    })
}

functions.tests.ts

import FileSaver from 'file-saver'
import { xlsxExport } from './functions'

// ...other code

test('xlsxExport', async () => {
    const saveAsSpy = jest.spyOn(FileSaver, 'saveAs')
    xlsxExport(myArrayOfDicts, 'test_download')
    expect(saveAsSpy).toHaveBeenCalledWith('something, anything')
})

Error:

TypeError: Cannot read properties of null (reading 'createElement')
    at Function.saveAs (C:\dev\pcig-react\node_modules\file-saver\src\FileSaver.js:92:9)
    at C:\dev\pcig-react\src\common\functions.ts:221:19
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v19.3.0
 FAIL  src/common/functions.test.ts
  ● Test suite failed to run

    Jest worker encountered 4 child process exceptions, exceeding retry limit

      at ChildProcessWorker.initialize (node_modules/jest-runner/node_modules/jest-worker/build/workers/ChildProcessWorker.js:185:21)

It is trying to call the non-mocked FileSaver.saveAs (line 221 of my file) within xlsxExport.

How can I get it to call the mocked version?


问:
Angular: How to initialize google-charts component with width and height in %
I'm using the google-charts angular component and I'm passing it as a parameter [dynamic Resize]="dynamic Resize" to make the chart responsive. But the dynamic Resize just works if the width and height are with percentage and when the screen is resized, but I can't use width and height with percentage.

I tried to initialize the component with style="width: 100%; min-width: 500px; height: 500px;" but it's just
applicated when the screen is resized... How can I fix that and initialize the component with his width and height in percentage values?

the chart when I join the tab: chart before resize the screen

the chart when I resize the screen: chart after resize the screen

component.html

```<code><google-chart
    style="width: 100%; min-width: 500px; height: 500px;"
    [type]="type"
    [data]="data"
    [columns]="columnNames"
    [options]="options"
    [dynamicResize]="dynamicResize"
    [width]="width"
    [height]="height"
  ></google-chart>
</code>```

component.ts

```<code>  // Chart configurations
  type: any = 'ColumnChart'
  data = [
    ['BRAZIL', 7153282.26, 6243680.89],
    ['CANADA', 3593833.71, 4759069.35],
    ['CHILE', 1363314.23, 1108712.94],
    ['MEXICO', 982280.00, 354999.48],
    ['PANAMA', 0.00, 0.00],
    ['UNITED STATES', 7592720.00, 5820093.76],
  ];
  columnNames = ['Region', 'Budget', 'Closed'];
  options = {
    vAxis: {
      format: 'short',
      gridlines: { color: '#CCCCCC', count: '4' },
      minorGridlines: { color: 'transparent' },
    },
    legend: {
      position: 'top',
      alignment: 'center'
    },
    chartArea:{ height:'80%', width: '70%' },
  };
  dynamicResize = true;
  // this it's not working
  width: any = '100%';
  height: any = '100%';

</code>```

Body:
I'm using the google-charts angular component and I'm passing it as a parameter [dynamic Resize]="dynamic Resize" to make the chart responsive. But the dynamic Resize just works if the width and height are with percentage and when the screen is resized, but I can't use width and height with percentage.

I tried to initialize the component with style="width: 100%; min-width: 500px; height: 500px;" but it's just
applicated when the screen is resized... How can I fix that and initialize the component with his width and height in percentage values?

the chart when I join the tab: chart before resize the screen

the chart when I resize the screen: chart after resize the screen

component.html

<google-chart
    style="width: 100%; min-width: 500px; height: 500px;"
    [type]="type"
    [data]="data"
    [columns]="columnNames"
    [options]="options"
    [dynamicResize]="dynamicResize"
    [width]="width"
    [height]="height"
  ></google-chart>

component.ts

  // Chart configurations
  type: any = 'ColumnChart'
  data = [
    ['BRAZIL', 7153282.26, 6243680.89],
    ['CANADA', 3593833.71, 4759069.35],
    ['CHILE', 1363314.23, 1108712.94],
    ['MEXICO', 982280.00, 354999.48],
    ['PANAMA', 0.00, 0.00],
    ['UNITED STATES', 7592720.00, 5820093.76],
  ];
  columnNames = ['Region', 'Budget', 'Closed'];
  options = {
    vAxis: {
      format: 'short',
      gridlines: { color: '#CCCCCC', count: '4' },
      minorGridlines: { color: 'transparent' },
    },
    legend: {
      position: 'top',
      alignment: 'center'
    },
    chartArea:{ height:'80%', width: '70%' },
  };
  dynamicResize = true;
  // this it's not working
  width: any = '100%';
  height: any = '100%';


问:
Query databases with node.js
I have been trying to pull info from a database and insert into another database. They are two different connections. I was trying to write a cross query to two different sources in the same query, but it doesn't work.
I think the solution is to pull the data and save it in variable and in another query insert the resulting data.

Does anyone know how to use merge with dual to be able to insert?

I have been trying to pull info from a database and insert into another database (using oracle sql). They are two different connections. I was trying to write a cross query to two different sources in the same query, but it doesn't work.
I think the solution is to pull the data and save it in variable and in another query insert the resulting data.

Does anyone know how to use merge with dual to be able to insert?

Here is the code I'm using

```<code>console.log("starting test.js here");
import dbconfig from "../lib/database/dbconfig";
import { db_Query } from "../query";

export const testRoute = {
    method: 'GET',
    path: '/api/test',
    handler: async (req, h) =>  {

        var binds = {};

        const sql1= select value1, value2, value3 from table1 WHERE value1="a" AND value2 ="B";
        const sql2= `MERGE INTO table2 tgt using (select '" + value1 + "' value1, '"+ value2 +"' value2, '"+ value3 +"' value3,'" + " FROM DUAL)
        src on (src.value1=tgt.value1)" + " when matched then UPDATE SET "+ "tgt.value2=src.value2 + when not matched then INSERT ( " + value1, value2, value3")
        VALUES ('" + value1 +"','"+ value2 +"','"+ value3 +"' "+");
        console.log("sql1: " + sql1);
        console.log("calling db_Query");
        const { results } = await db_Query (sql1,sql2,binds);

        console.log(results.rows);

        //return rows only, no metahead
        return results.rows;

    }
}
</code>```

Title: Query databases with node.js

Body:
I have been trying to pull info from a database and insert into another database. They are two different connections. I was trying to write a cross query to two different sources in the same query, but it doesn't work.
I think the solution is to pull the data and save it in variable and in another query insert the resulting data.

Does anyone know how to use merge with dual to be able to insert?

I have been trying to pull info from a database and insert into another database (using oracle sql). They are two different connections. I was trying to write a cross query to two different sources in the same query, but it doesn't work.
I think the solution is to pull the data and save it in variable and in another query insert the resulting data.

Does anyone know how to use merge with dual to be able to insert?

Here is the code I'm using

console.log("starting test.js here");
import dbconfig from "../lib/database/dbconfig";
import { db_Query } from "../query";

export const testRoute = {
    method: 'GET',
    path: '/api/test',
    handler: async (req, h) =>  {

        var binds = {};

        const sql1= select value1, value2, value3 from table1 WHERE value1="a" AND value2 ="B";
        const sql2= `MERGE INTO table2 tgt using (select '" + value1 + "' value1, '"+ value2 +"' value2, '"+ value3 +"' value3,'" + " FROM DUAL)
        src on (src.value1=tgt.value1)" + " when matched then UPDATE SET "+ "tgt.value2=src.value2 + when not matched then INSERT ( " + value1, value2, value3")
        VALUES ('" + value1 +"','"+ value2 +"','"+ value3 +"' "+");
        console.log("sql1: " + sql1);
        console.log("calling db_Query");
        const { results } = await db_Query (sql1,sql2,binds);

        console.log(results.rows);

        //return rows only, no metahead
        return results.rows;

    }
}


问:
422 goes to console even with handler
I am making a request using ajax and laravel 9 to check the input of a field, but laravel returns the field error as error 422, which is not a big problem because I can work with it in ajax, but even using the error function it shows up in the console. How can I make the error not show up in the console?

Laravel:

public static function changeUsername(Request $request){

        $request->validate([
            'username' => 'required|string|max:255|unique:users',
        ], [
            'username.required' => 'O username não pode estar vazio',
            'username.string' => 'O username não pode conter apenas números',
            'username.max' => 'O username não pode ter mais de 255 caracteres',
            'username.unique' => 'O username já está em uso',
        ]);

        $user = User::find(Auth::user()->id);
        $user->username = $request->username;
        $user->save();

        return response()->json([
            'message' => 'Username alterado com sucesso!',
            'user' => $user
        ], 200);
    }
```
<p>Ajax:</p>
<pre class="lang-js prettyprint-override"><code> function saveUsername(username) {
        $.ajax({
            type: "POST",
            url: "{{ route('user.updateUsername') }}",
            data: {
                username: username,
                _token: "{{ csrf_token() }}"
            },
            success: function(response) {
                $('#username').children().text(username);
                showToast("Sucesso", "Username Alterado com Sucesso");
                $('.usrChangeBtn[function="load"]').hide();
                $('.usrChangeBtn[function="edit"]').show();
            },
            error: function(response) {
                showToast("Erro", response.responseJSON.message);
                $('.usrChangeBtn[function="load"]').hide();
                $('.usrChangeBtn[function="edit"]').show();
            },
            beforeSend: function() {
                $('.changeUsername').hide();
                $('#username').show();
                $('.usrChangeBtn[function="load"]').show();
            }
        });
    }
</code>```

Title: 422 goes to console even with handler

Body:
I am making a request using ajax and laravel 9 to check the input of a field, but laravel returns the field error as error 422, which is not a big problem because I can work with it in ajax, but even using the error function it shows up in the console. How can I make the error not show up in the console?

Laravel:

public static function changeUsername(Request $request){

        $request->validate([
            'username' => 'required|string|max:255|unique:users',
        ], [
            'username.required' => 'O username não pode estar vazio',
            'username.string' => 'O username não pode conter apenas números',
            'username.max' => 'O username não pode ter mais de 255 caracteres',
            'username.unique' => 'O username já está em uso',
        ]);

        $user = User::find(Auth::user()->id);
        $user->username = $request->username;
        $user->save();

        return response()->json([
            'message' => 'Username alterado com sucesso!',
            'user' => $user
        ], 200);
    }

Ajax:

 function saveUsername(username) {
        $.ajax({
            type: "POST",
            url: "{{ route('user.updateUsername') }}",
            data: {
                username: username,
                _token: "{{ csrf_token() }}"
            },
            success: function(response) {
                $('#username').children().text(username);
                showToast("Sucesso", "Username Alterado com Sucesso");
                $('.usrChangeBtn[function="load"]').hide();
                $('.usrChangeBtn[function="edit"]').show();
            },
            error: function(response) {
                showToast("Erro", response.responseJSON.message);
                $('.usrChangeBtn[function="load"]').hide();
                $('.usrChangeBtn[function="edit"]').show();
            },
            beforeSend: function() {
                $('.changeUsername').hide();
                $('#username').show();
                $('.usrChangeBtn[function="load"]').show();
            }
        });
    }


问:
Jest Unit Test for rxjs retryWhen method
I've being trying to increase the test's coverage of a project. Looking into the coverage report, I saw that retryWhen method is not being covered and since then I've been struggling.

Here's the function I'm trying to test:

launchWebHook<T>(
    webhookUrl: string,
    webhookRequest: IWebHookShape<T>,
    signedToken: string,
  ): Observable<IWebHookAxiosResponse> {
    const requestOptions = {
      headers: {}, // not empty in src code
    };
    return this.httpService.post(webhookUrl, webhookRequest, requestOptions).pipe(
      retryWhen(errors =>
        errors.pipe(
          delay(900000),
          take(3),
          scan((acc, source, index) => {
            if (index) {
              throw source;
            }
          }),
        ),
      ),
    );
  }
```
<p>And here is the test I have:</p>
<pre class="lang-js prettyprint-override"><code>const webhookUrl = 'https://webhook.com';
const webhookRequest = {} as IWebHookShape<string>;
const signedToken = 'signed';
const response = {} as AxiosResponse<any>;

(httpService.post as jest.Mock).mockResolvedValue(new Observable<AxiosResponse<any>>());
const mockPipe = jest.spyOn(Observable.prototype, 'pipe');
const retryWhen = mockPipe.mock.calls[0][1];

webhookService.launchWebHook(webhookUrl, webhookRequest, signedToken);
expect(retryWhen).toHaveBeenCalled();

</code>```

I tried using a similar implementation of this answer, but couldn't make it work.

I'm also trying to use mockFn.mock.calls based on this answer

Body:
I've being trying to increase the test's coverage of a project. Looking into the coverage report, I saw that retryWhen method is not being covered and since then I've been struggling.

Here's the function I'm trying to test:

launchWebHook<T>(
    webhookUrl: string,
    webhookRequest: IWebHookShape<T>,
    signedToken: string,
  ): Observable<IWebHookAxiosResponse> {
    const requestOptions = {
      headers: {}, // not empty in src code
    };
    return this.httpService.post(webhookUrl, webhookRequest, requestOptions).pipe(
      retryWhen(errors =>
        errors.pipe(
          delay(900000),
          take(3),
          scan((acc, source, index) => {
            if (index) {
              throw source;
            }
          }),
        ),
      ),
    );
  }

And here is the test I have:

const webhookUrl = 'https://webhook.com';
const webhookRequest = {} as IWebHookShape<string>;
const signedToken = 'signed';
const response = {} as AxiosResponse<any>;

(httpService.post as jest.Mock).mockResolvedValue(new Observable<AxiosResponse<any>>());
const mockPipe = jest.spyOn(Observable.prototype, 'pipe');
const retryWhen = mockPipe.mock.calls[0][1];

webhookService.launchWebHook(webhookUrl, webhookRequest, signedToken);
expect(retryWhen).toHaveBeenCalled();

I tried using a similar implementation of this answer, but couldn't make it work.

I'm also trying to use mockFn.mock.calls based on this answer


问:
Upload a just shooted photo from phone to Pocketbase backend with Svelte
I am trying to add a new record with photo on my Pocketbase backend but it's able to correctly upload just already taken pictures.

I'm sorry but because is a issue that happens only on mobile is difficult to get the console error

That's the code snippet:

<form on:submit|preventDefault>
    <input type="text" placeholder="Object Name" bind:value={new_object_name}/>
    <input type="file" id="new_obj_file" accept="image/jpg, image/jpeg, image/png, image/svg+xml, image/gif" bind:files={new_object_img}/>
    <button id="add_object" on:click={addObject}>add object</button>
</form>
```

I tried on android and on an iPhone and both have the same issues

Body:
I am trying to add a new record with photo on my Pocketbase backend but it's able to correctly upload just already taken pictures.

I'm sorry but because is a issue that happens only on mobile is difficult to get the console error

That's the code snippet:

<form on:submit|preventDefault>
    <input type="text" placeholder="Object Name" bind:value={new_object_name}/>
    <input type="file" id="new_obj_file" accept="image/jpg, image/jpeg, image/png, image/svg+xml, image/gif" bind:files={new_object_img}/>
    <button id="add_object" on:click={addObject}>add object</button>
</form>

I tried on android and on an iPhone and both have the same issues


问:
Codeigniter 3 - fetch data from another table where current ID
I'm working on helpdesk system.

I created two tables contacts and contacts_comments.

Now I fetch contacts details by contact ID in view page - this working correct.

and now from view page I insert comments to second table contacts_comments.

To contacts_comments I insert message and current contact(ticket) ID.

And now I try display all this comments for current ticket ID.

```<code><?php foreach ($comments as $comment): ?>
                                        <div class="d-flex mb-4">
                                            <div class="flex-shrink-0">
                                                <img src="<?php echo base_url(); ?>assets/c_admin/assets/images/users/avatar-8.jpg" alt="" class="avatar-xs rounded-circle" />
                                            </div>
                                            <div class="flex-grow-1 ms-3">
                                                <h5 class="fs-13"><?php echo $comment->ticket_client; ?> <small class="text-muted"><?php echo $comment->created_at; ?></small></h5>
                                                <p class="text-muted"><?php echo $comment->comments_message; ?></p>
                                                <a href="javascript: void(0);" class="badge text-muted bg-light"><i class="mdi mdi-reply"></i> Reply</a>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
</code>```

But this function display for me all comments from  table contacts_comments.

I try build function:

```<code>    //get comments by id
public function get_comments_by_id($id)
{
    $id = clean_number($id);
    $this->db->where('ticket_id', $id);
    $query = $this->db->get('contacts_comments');
    return $query->row();
}
</code>```

Can anyone help me how to add to this query in CI3 with result somelike:

```<code>DB WHERE  contacts.id == contacts_comments.ticket_id
</code>```

Body:
I'm working on helpdesk system.

I created two tables contacts and contacts_comments.

Now I fetch contacts details by contact ID in view page - this working correct.

and now from view page I insert comments to second table contacts_comments.

To contacts_comments I insert message and current contact(ticket) ID.

And now I try display all this comments for current ticket ID.

<?php foreach ($comments as $comment): ?>

                                                <img src="<?php echo base_url(); ?>assets/c_admin/assets/images/users/avatar-8.jpg" alt="" class="avatar-xs rounded-circle" />

<?php echo $comment->ticket_client; ?> <?php echo $comment->created_at; ?>

<?php echo $comment->comments_message; ?>

                                                 Reply

                                        <?php endforeach; ?>

But this function display for me all comments from  table contacts_comments.

I try build function:

    //get comments by id
public function get_comments_by_id($id)
{
    $id = clean_number($id);
    $this->db->where('ticket_id', $id);
    $query = $this->db->get('contacts_comments');
    return $query->row();
}

Can anyone help me how to add to this query in CI3 with result somelike:

DB WHERE  contacts.id == contacts_comments.ticket_id


问:
react-easy-crop overwrite custom styles
Could you tell me how to overwrite the custom styles in react-easy-crop library?

<Cropper
  image={headerImage}
  crop={crop}
  aspect={4 / 1}
  onCropChange={setCrop}
  onCropComplete={onCropComplete}
  style={{
    containerStyle: {
      borderRadius: "16px",
    },
    cropAreaStyle: {
      border: "2px solid #FFFFFF",
      borderRadius: "16px",
      // '& .reactEasyCrop_CropAreaGrid::after ': {
      //     top: '0'
      // }
    },
  }}
  classes={{ cropAreaClassName: cssStyle.reactEasyCrop_CropAreaGrid }}
/>;
```

I was trying to fix it with style or classes props but not handle it.

Title: react-easy-crop overwrite custom styles

Body:
Could you tell me how to overwrite the custom styles in react-easy-crop library?

<Cropper
  image={headerImage}
  crop={crop}
  aspect={4 / 1}
  onCropChange={setCrop}
  onCropComplete={onCropComplete}
  style={{
    containerStyle: {
      borderRadius: "16px",
    },
    cropAreaStyle: {
      border: "2px solid #FFFFFF",
      borderRadius: "16px",
      // '& .reactEasyCrop_CropAreaGrid::after ': {
      //     top: '0'
      // }
    },
  }}
  classes={{ cropAreaClassName: cssStyle.reactEasyCrop_CropAreaGrid }}
/>;

I was trying to fix it with style or classes props but not handle it.


问:
nginx config - can't point multiple domains
I have two domains: domain1.com and domain2.com

domain1.com is pointing to one of my docker containers no problem.
domain2.com is not working. It points to the same container as domain1, despite the different ports in proxy_pass. My default.conf file:

```<code>server {
      listen 80;
      listen [::]:80;
      server_name domain1.com;
      # Useful for Let's Encrypt
      location /.well-known/acme-challenge/ { root /usr/share/nginx/html; allow all; }
      location / { return 301 https://$host$request_uri; }
    }

    server {
      listen 443 ssl http2;
      listen [::]:443 ssl http2;
      server_name domain1.com;

      ssl_protocols TLSv1.2;
      ssl_ciphers HIGH:!MEDIUM:!LOW:!aNULL:!NULL:!SHA;
      ssl_prefer_server_ciphers on;
      ssl_session_cache shared:SSL:10m;

      ssl_certificate     /etc/letsencrypt/live/domain1.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/domain1.com/privkey.pem;

      location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_pass http://0.0.0.0:2368;
      }
    }

server {
      listen 80;
      listen [::]:80;
      server_name domain2.com;
      # Useful for Let's Encrypt
      location /.well-known/acme-challenge/ { root /usr/share/nginx/html; allow all; }
      location / { return 301 https://$host$request_uri; }
    }

    server {
      listen 443 ssl http2;
      listen [::]:443 ssl http2;
      server_name domain2.com;

      ssl_protocols TLSv1.2;
      ssl_ciphers HIGH:!MEDIUM:!LOW:!aNULL:!NULL:!SHA;
      ssl_prefer_server_ciphers on;
      ssl_session_cache shared:SSL:10m;

      ssl_certificate     /etc/letsencrypt/live/domain2.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/domain2.com/privkey.pem;

      location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_pass http://0.0.0.0:1313;
      }
    }
</code>```

Body:
I have two domains: domain1.com and domain2.com

domain1.com is pointing to one of my docker containers no problem.
domain2.com is not working. It points to the same container as domain1, despite the different ports in proxy_pass. My default.conf file:

server {
      listen 80;
      listen [::]:80;
      server_name domain1.com;
      # Useful for Let's Encrypt
      location /.well-known/acme-challenge/ { root /usr/share/nginx/html; allow all; }
      location / { return 301 https://$host$request_uri; }
    }

    server {
      listen 443 ssl http2;
      listen [::]:443 ssl http2;
      server_name domain1.com;

      ssl_protocols TLSv1.2;
      ssl_ciphers HIGH:!MEDIUM:!LOW:!aNULL:!NULL:!SHA;
      ssl_prefer_server_ciphers on;
      ssl_session_cache shared:SSL:10m;

      ssl_certificate     /etc/letsencrypt/live/domain1.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/domain1.com/privkey.pem;

      location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_pass http://0.0.0.0:2368;
      }
    }

server {
      listen 80;
      listen [::]:80;
      server_name domain2.com;
      # Useful for Let's Encrypt
      location /.well-known/acme-challenge/ { root /usr/share/nginx/html; allow all; }
      location / { return 301 https://$host$request_uri; }
    }

    server {
      listen 443 ssl http2;
      listen [::]:443 ssl http2;
      server_name domain2.com;

      ssl_protocols TLSv1.2;
      ssl_ciphers HIGH:!MEDIUM:!LOW:!aNULL:!NULL:!SHA;
      ssl_prefer_server_ciphers on;
      ssl_session_cache shared:SSL:10m;

      ssl_certificate     /etc/letsencrypt/live/domain2.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/domain2.com/privkey.pem;

      location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_pass http://0.0.0.0:1313;
      }
    }


问:
How can I Store 2 data in an array retrieve with querySelectorAll?
5 days ago I looked into scraping, and how to recover data. The first thing I did once the basics of the code was laid out, was to do a querySellectorAll to retrieve all the elements with a specific class. It worked, so I stored the first element in my array, but an array with a single element is useless! So I tried to add the 2nd element, but the 2nd element does not want to be added to the array... I would like ALL the elements stored in the array to be strings. Here is my code:

```<code>const annoncesPrice = await page.$$("p[data-test-id]").innerText;
const annonces = await page.$$("p[data-qa-id]");
for (const annonce of annonces) {

  const annonceTitle = await page.evaluate((el) => {
    if (el) {
      return el.innerText;
    }
    return "";
  }, annonce)

  results.push({
    Titre_des_annonces: annonceTitle,
    price: annoncesPrice
  });
}
console.table(results);
</code>```

I tried to unlock my code and replace it with the selector I wanted to assign to the 2nd element. It displayed what I wanted but the 2nd element was not aligned with the first element, it was placed much higher than the 2nd element. I also tried many other solutions, but all of them failed.

Body:
5 days ago I looked into scraping, and how to recover data. The first thing I did once the basics of the code was laid out, was to do a querySellectorAll to retrieve all the elements with a specific class. It worked, so I stored the first element in my array, but an array with a single element is useless! So I tried to add the 2nd element, but the 2nd element does not want to be added to the array... I would like ALL the elements stored in the array to be strings. Here is my code:

const annoncesPrice = await page.$$("p[data-test-id]").innerText;
const annonces = await page.$$("p[data-qa-id]");
for (const annonce of annonces) {

  const annonceTitle = await page.evaluate((el) => {
    if (el) {
      return el.innerText;
    }
    return "";
  }, annonce)

  results.push({
    Titre_des_annonces: annonceTitle,
    price: annoncesPrice
  });
}
console.table(results);

I tried to unlock my code and replace it with the selector I wanted to assign to the 2nd element. It displayed what I wanted but the 2nd element was not aligned with the first element, it was placed much higher than the 2nd element. I also tried many other solutions, but all of them failed.


问:
How to capture the Name of a Table in a Database when running a stored procedure on multiple tables
I am currently making a python program that will run a stored procedure which has multiple select statements for multiple different tables. I am storing the results in a dataframe and the displaying it with a treeview. I want to make it so that the user can see what table each row of the results came from. I was wondering if there is anyway that I could modify my stored procedure so that each row that is returned in the procedure also includes the table name.

Here is the stored procedure as of right now

```<code>procedure [dbo].[getUser](@username nvarchar(225))
AS
Select username,user_id,user_type
from db1.dublin_table
where username like '%' + TRIM(@username) + '%'
ORDER BY username

Select username,user_id,user_type
from db2.nyc_table
where username like '%' + TRIM(@username) + '%'
ORDER BY username

Select username,user_id,user_type
from db3.tokyo_table
where username like '%' + TRIM(@username) + '%'
ORDER BY username
</code>```

I am somewhat new to SQL stored procedures so any help is appreciated.

Body:
I am currently making a python program that will run a stored procedure which has multiple select statements for multiple different tables. I am storing the results in a dataframe and the displaying it with a treeview. I want to make it so that the user can see what table each row of the results came from. I was wondering if there is anyway that I could modify my stored procedure so that each row that is returned in the procedure also includes the table name.

Here is the stored procedure as of right now

procedure [dbo].[getUser](@username nvarchar(225))
AS
Select username,user_id,user_type
from db1.dublin_table
where username like '%' + TRIM(@username) + '%'
ORDER BY username

Select username,user_id,user_type
from db2.nyc_table
where username like '%' + TRIM(@username) + '%'
ORDER BY username

Select username,user_id,user_type
from db3.tokyo_table
where username like '%' + TRIM(@username) + '%'
ORDER BY username

I am somewhat new to SQL stored procedures so any help is appreciated.


问:
Can't connect to SQL Server in docker from Hyper-V virtual machine
I have a SQL Server instance in docker which maps its port 1433 to host 1433.

It's working and I connect to it.

Next, I have a Windows (actually, its old Windows 7) virtual machine in Hyper-V on same host. Virtual machine can see host (to be specific at ip 192.168.10.1).

But from virtual machine I can not connect to SQL Server on port 1433. I can't simply open a socket from virtual machine (have tried though python).

I've tried to stop docker container and start simple web server on 1433 port and I can easily connect to it from virtual machine. But once SQL Server appears there, something goes wrong.

Any ideas, what may be wrong or what to check (just got a humble idea that may be caused by MTU, but not yet checked - makes sense?)


问:
Unable to retrieve API keys for a Function App using ListWebAppFunctionKeysArgs
How can I retrieve API keys for a function app in Azure using ListWebAppFunctionKeysArgs?

I have the following method:

```<code>public static Output<Dictionary<string, string>?> Get(string resourceGroupName, FunctionApp functionApp)
    {
        var output =
            Output.Tuple(functionApp.Name, functionApp.Name)
                  .Apply(async tuple => {

                      var current        = Pulumi.Azure.Core.GetClientConfig.InvokeAsync().Result;
                      var subscriptionId = current.SubscriptionId;
                      var appName        = tuple.Item1;

                      var httpClient = new HttpClient();
                      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken.Value);

                      var url    = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{appName}/functions?api-version=2022-03-01";
                      var result = await httpClient.GetAsync(url);

                      if (!result.IsSuccessStatusCode) throw new Exception($"Error: Failed to retrive Azure function names from {appName}");

                      var json = await result.Content.ReadAsStringAsync();
                      var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
                      var items = root.value.Select(async v => {

                          var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
                              Name = appName,
                              FunctionName = v.properties.name,
                              ResourceGroupName = resourceGroupName
                          });

                          return data.Properties;
                      });

                      var data = items.SelectMany(v => v.Result).ToList();
                      return new Dictionary<string, string>(data);
                  });

        return output;
    }
</code>```

Here's the code that I'm struggling with:

```<code>  var json = await result.Content.ReadAsStringAsync();
  var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
  var items = root.value.Select(async v => {

      var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
          Name = appName,
          FunctionName = v.properties.name,
          ResourceGroupName = resourceGroupName
      });

      return data.Properties; // Property values are null
  });
</code>```

Here's the result:

In conclusion, how do I acquire API keys for a function app?

Body:
How can I retrieve API keys for a function app in Azure using ListWebAppFunctionKeysArgs?

I have the following method:

public static Output<Dictionary<string, string>?> Get(string resourceGroupName, FunctionApp functionApp)
    {
        var output =
            Output.Tuple(functionApp.Name, functionApp.Name)
                  .Apply(async tuple => {

                      var current        = Pulumi.Azure.Core.GetClientConfig.InvokeAsync().Result;
                      var subscriptionId = current.SubscriptionId;
                      var appName        = tuple.Item1;

                      var httpClient = new HttpClient();
                      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken.Value);

                      var url    = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{appName}/functions?api-version=2022-03-01";
                      var result = await httpClient.GetAsync(url);

                      if (!result.IsSuccessStatusCode) throw new Exception($"Error: Failed to retrive Azure function names from {appName}");

                      var json = await result.Content.ReadAsStringAsync();
                      var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
                      var items = root.value.Select(async v => {

                          var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
                              Name = appName,
                              FunctionName = v.properties.name,
                              ResourceGroupName = resourceGroupName
                          });

                          return data.Properties;
                      });

                      var data = items.SelectMany(v => v.Result).ToList();
                      return new Dictionary<string, string>(data);
                  });

        return output;
    }

Here's the code that I'm struggling with:

  var json = await result.Content.ReadAsStringAsync();
  var root = JsonConvert.DeserializeObject<JsonSupport.AzureFunctionItems.Root>(json);
  var items = root.value.Select(async v => {

      var data = await ListWebAppFunctionKeys.InvokeAsync(new ListWebAppFunctionKeysArgs {
          Name = appName,
          FunctionName = v.properties.name,
          ResourceGroupName = resourceGroupName
      });

      return data.Properties; // Property values are null
  });

Here's the result:

In conclusion, how do I acquire API keys for a function app?


问:
How do I change my python sqlite3 code so that it asks me for input when I run it in cmd.exe?
Using the sqlite3 module, I created a database of clients in the bank. The client has an id as the primary key, name and surname (as one string), account number and a passcode. I also defined the token attribute in which the token of the user accessing the account will be stored. The problem that I have come across is that when I run the program in cmd.exe or in visual studio code it just says access granted and prints out 3 tokens without asking me to input anything, how do I change the code so that it asks me for account_name and passcode input in the terminal or in cmd.exe after I run the program?

import sqlite3
import uuid

conn = sqlite3.connect("bank.db")
cursor = conn.cursor()

cursor.execute(
    "CREATE TABLE IF NOT EXISTS clients (id INTEGER PRIMARY KEY, name TEXT, account_number TEXT, code TEXT, token TEXT)"
)

cursor.execute(
    "INSERT INTO clients (name, account_number, code) VALUES (?, ?, ?)",
    ("John Smith", "123456", "5082"),
)
cursor.execute(
    "INSERT INTO clients (name, account_number, code) VALUES (?, ?, ?)",
    ("Jane Doe", "234567", "1428"),
)
cursor.execute(
    "INSERT INTO clients (name, account_number, code) VALUES (?, ?, ?)",
    ("Bob Johnson", "345678", "7195"),
)
conn.commit()

def authenticate(account_number, code):
    cursor.execute(
        "SELECT * FROM clients WHERE account_number=? AND code=?", (account_number, code)
    )
    client = cursor.fetchone()

    if not client:
        return "Error: client not found"

    token = str(uuid.uuid4())

    cursor.execute(
        "UPDATE clients SET token=? WHERE id=?", (token, client[0])
    )
    conn.commit()

    return f"Access granted. Token: {token}"

print(authenticate("123456", "5082"))
print(authenticate("234567", "1428"))
print(authenticate("345678", "7195"))
print(authenticate("999999", "xxxxxx"))

conn.close()
```


问:
java 2d graphics eraser
is there a easy way to Locate the Drawed Line in my PaintComponent Array to delete this Line.
Like a Eraser?

Here my PaintComponent Class

```<code>protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setStroke(new BasicStroke(5));
    g2d.setColor(Color.RED);
    for (Point[] p : glaslist) {
        g2d.setColor(Color.yellow);
        g2d.drawLine(p[0].x, p[0].y, p[1].x, p[1].y);
    }
    for (Point[] p : kupferlist) {
        g2d.setColor(Color.ORANGE);
        g2d.drawLine(p[0].x, p[0].y, p[1].x, p[1].y);

    }
    if (startPoint != null && endPoint != null) {

            g2d.setColor(Color.RED);
            g2d.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);

    }

    g2d.dispose();

}
</code>```

Title: java 2d graphics eraser

Body:
is there a easy way to Locate the Drawed Line in my PaintComponent Array to delete this Line.
Like a Eraser?

Here my PaintComponent Class

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setStroke(new BasicStroke(5));
    g2d.setColor(Color.RED);
    for (Point[] p : glaslist) {
        g2d.setColor(Color.yellow);
        g2d.drawLine(p[0].x, p[0].y, p[1].x, p[1].y);
    }
    for (Point[] p : kupferlist) {
        g2d.setColor(Color.ORANGE);
        g2d.drawLine(p[0].x, p[0].y, p[1].x, p[1].y);

    }
    if (startPoint != null && endPoint != null) {

            g2d.setColor(Color.RED);
            g2d.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);

    }

    g2d.dispose();

}


问:
CLLocation's longitude and latitude into one variable
```<code>import UIKit
import MapKit
import CoreLocation

class GetLocation: UIViewController, CLLocationManagerDelegate {

//    var isLocationEnabled = false

    var locationManager: CLLocationManager!

    var lat: Double = 1
    var lon: Double = 1

    var region = CLLocation(latitude: lat, longitude: lon)

    //    let geoCoder = CLGeocoder()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.locationManager = CLLocationManager()
        self.locationManager?.delegate = self

    }

    func regionManager() {
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestAlwaysAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            print("Location Enabled")
        } else {
            print("Location Not Enabled")
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location = locations[0] as CLLocation

        let latitube = location.coordinate.latitude
        let longitube = location.coordinate.longitude

        lat = latitube
        lon = longitube
    }
}
</code>```

I want to create a property with CLLocation's longitude and latitude.
I tried adding lazy before the variable.
There is no error, but the longitude and latitude results are not applied to the attributes.

I made a func and tried to use it but it's no use.
It just throws an error saying it found nil.

What is the problem? I tried to solve it by myself for a long time, but
It is too difficult for me who started studying.
I need your kind help.

CLLocation in Swift please help.

Body:
import UIKit
import MapKit
import CoreLocation

class GetLocation: UIViewController, CLLocationManagerDelegate {

//    var isLocationEnabled = false

    var locationManager: CLLocationManager!

    var lat: Double = 1
    var lon: Double = 1

    var region = CLLocation(latitude: lat, longitude: lon)

    //    let geoCoder = CLGeocoder()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.locationManager = CLLocationManager()
        self.locationManager?.delegate = self

    }

    func regionManager() {
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestAlwaysAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            print("Location Enabled")
        } else {
            print("Location Not Enabled")
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location = locations[0] as CLLocation

        let latitube = location.coordinate.latitude
        let longitube = location.coordinate.longitude

        lat = latitube
        lon = longitube
    }
}

I want to create a property with CLLocation's longitude and latitude.
I tried adding lazy before the variable.
There is no error, but the longitude and latitude results are not applied to the attributes.

I made a func and tried to use it but it's no use.
It just throws an error saying it found nil.

What is the problem? I tried to solve it by myself for a long time, but
It is too difficult for me who started studying.
I need your kind help.

CLLocation in Swift please help.


问:
Adding flickity Jquery plugin into Cargo site
I'm a little new to JS so please bear with me! I'm looking to add the Flickity carousel JQuery plugin to my cargo site, but can't get the page HTML to run the JS code. I believe my issue is in initializing the plugin in my HTML properly. Or possibly it's not valid JSON? (I'm new to JS so I'm not familiar with this). I've followed the Flickity intallation steps from here but Cargo is returning an error message and changing my attribute quotations in the class  'data-flickity' options when saving my page HTML. I can see the carousel on my page but the "gallery-cells" are not in their proper place. Any help is much appreciated!

What the data-flickity HTML should look like:

```<code>
<div class="main-carousel" data-flickity='{ "cellAlign": "left", "contain": true }'>
</code>```

What my data-flickity HTML looks like:

```<code><div class="main-gallery js-flickity" data-flickity-options="{ "cellAlign": "left", "contain": true }">
</code>```

And my my entire Div looks like:

```<code><div class="main-gallery js-flickity" data-flickity-options="{ "cellAlign": "left", "contain": true }">
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
</div>
</code>```

Body:
I'm a little new to JS so please bear with me! I'm looking to add the Flickity carousel JQuery plugin to my cargo site, but can't get the page HTML to run the JS code. I believe my issue is in initializing the plugin in my HTML properly. Or possibly it's not valid JSON? (I'm new to JS so I'm not familiar with this). I've followed the Flickity intallation steps from here but Cargo is returning an error message and changing my attribute quotations in the class  'data-flickity' options when saving my page HTML. I can see the carousel on my page but the "gallery-cells" are not in their proper place. Any help is much appreciated!

What the data-flickity HTML should look like:

What my data-flickity HTML looks like:

And my my entire Div looks like:


问:
The vbUnicode argument in StrConv is not giving me the desired output
I am trying to use the StrConv function to convert the letter H to its decimal value 72 and then from 72 back again to H.

```<code>Public Sub Testing()
    Dim Text As String, Back As String, Deci() As Byte
    Text = "H"
    Deci = StrConv(Text, vbFromUnicode)
    Debug.Print Deci(0)
    Back = StrConv(Deci(0), vbUnicode)
    Debug.Print Back
End Sub
</code>```

In the above example I am using StrConv(Text, vbFromUnicode) to get the decimal value 72 which works great.

However when I then try to go from 72 to H by using StrConv(Deci(0), vbUnicode) I do not get H but 72 with a strange character inbetween.

Is it not correct to use the argument vbUnicode here? What am I doing wrong?

Body:
I am trying to use the StrConv function to convert the letter H to its decimal value 72 and then from 72 back again to H.

Public Sub Testing()
    Dim Text As String, Back As String, Deci() As Byte
    Text = "H"
    Deci = StrConv(Text, vbFromUnicode)
    Debug.Print Deci(0)
    Back = StrConv(Deci(0), vbUnicode)
    Debug.Print Back
End Sub

In the above example I am using StrConv(Text, vbFromUnicode) to get the decimal value 72 which works great.

However when I then try to go from 72 to H by using StrConv(Deci(0), vbUnicode) I do not get H but 72 with a strange character inbetween.

Is it not correct to use the argument vbUnicode here? What am I doing wrong?


问:
Reliably determine PID of a process that updated clipboard
When I subscribe to clipboard updates using AddClipboardFormatListener() I get WM_CLIPBOARDUPDATE messages so I can retrieve the clipboard content. The problem is that I fail to retrieve PID of the process that updated the clipboard. When I call GetWindowThreadProcessId() passing the handle I got from GetClipboardOwner() I receive ERROR_INVALID_WINDOW_HANDLE (1400).

Here is the code I use:

        var msg C.MSG
        for C.GetMessageW(&msg, hwnd, 0, 0) != 0 {
            if msg.message == C.WM_CLIPBOARDUPDATE {
                owner := C.GetClipboardOwner()

                if C.OpenClipboard(hwnd) == 0 {
                    // ...
                    continue
                }

                var pid C.DWORD
                C.GetWindowThreadProcessId(owner, &pid)

                hdata := C.GetClipboardData(C.CF_UNICODETEXT)
                if hdata == C.HANDLE(C.NULL) {
                    // ...
                    C.CloseClipboard()
                    continue
                }

                wstr := C.LPWSTR(C.GlobalLock(hdata))
                content := wstrToGoStr(wstr)
                C.GlobalUnlock(hdata)
                C.CloseClipboard()

                // ...

                handler(int(pid), content)
            }
            C.TranslateMessage(&msg)
            C.DispatchMessage(&msg)
        }
```

What is the problem?

Body:
When I subscribe to clipboard updates using AddClipboardFormatListener() I get WM_CLIPBOARDUPDATE messages so I can retrieve the clipboard content. The problem is that I fail to retrieve PID of the process that updated the clipboard. When I call GetWindowThreadProcessId() passing the handle I got from GetClipboardOwner() I receive ERROR_INVALID_WINDOW_HANDLE (1400).

Here is the code I use:

        var msg C.MSG
        for C.GetMessageW(&msg, hwnd, 0, 0) != 0 {
            if msg.message == C.WM_CLIPBOARDUPDATE {
                owner := C.GetClipboardOwner()

                if C.OpenClipboard(hwnd) == 0 {
                    // ...
                    continue
                }

                var pid C.DWORD
                C.GetWindowThreadProcessId(owner, &pid)

                hdata := C.GetClipboardData(C.CF_UNICODETEXT)
                if hdata == C.HANDLE(C.NULL) {
                    // ...
                    C.CloseClipboard()
                    continue
                }

                wstr := C.LPWSTR(C.GlobalLock(hdata))
                content := wstrToGoStr(wstr)
                C.GlobalUnlock(hdata)
                C.CloseClipboard()

                // ...

                handler(int(pid), content)
            }
            C.TranslateMessage(&msg)
            C.DispatchMessage(&msg)
        }

What is the problem?