问:
mse doesn't match using SimpleRNN in Keras
I have the following dataset:

input_train = [[[0], [1], [1], [0], [0], [0], [0], [1], [0], [1]]]

output_train = [[0, 1, 2, 2, 2, 2, 2, 3, 3, 4]]

As you can see, the value in output_train[t] (t in range 0-9) is equal to the sum from i=0 to i=t of input_train[i]

This is just a simple example to see how SimpleRNN works. However, when I execute fit function mse doesn't match with the same value calculated by me. What is happening?

```<code>modelo = Sequential()
modelo.add(SimpleRNN(1, input_shape=(number_data_in_simulation,1), activation='linear', return_sequences = True))
modelo.add(Dense(units = 1, activation='linear'))
modelo.compile(optimizer=tf.keras.optimizers.Adam(0.1), loss='mse')
historial = modelo.fit(input_train, output_train, batch_size = 1, epochs=1, verbose=1)

predictions = modelo.predict(input_train, batch_size = 1, verbose = False)
mse_value = 0
number_cases = 0
for sim in range(len(output_train)):
    for example in range(len(output_train[sim])):
        mse_value = mse_value + (output_train[sim][example] - predictions[sim][example][0])**2
        number_cases += 1
print(mse_value/number_cases)
</code>```

IN TERMINAL:

2022-12-15 19:07:11.483935: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected

2022-12-15 19:07:11.483963: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (jose-HP-EliteBook-830-G7-Notebook-PC): /proc/driver/nvidia/version does not exist

2022-12-15 19:07:11.484223: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA

To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.

1/1 [==============================] - 0s 467ms/step - loss: 6.1238

5.149037324060892

I expect to have the same result.
6.1238 != 5.149037324060892
Thank you very much! :)

Body:
I have the following dataset:

input_train = [[[0], [1], [1], [0], [0], [0], [0], [1], [0], [1]]]

output_train = [[0, 1, 2, 2, 2, 2, 2, 3, 3, 4]]

As you can see, the value in output_train[t] (t in range 0-9) is equal to the sum from i=0 to i=t of input_train[i]

This is just a simple example to see how SimpleRNN works. However, when I execute fit function mse doesn't match with the same value calculated by me. What is happening?

modelo = Sequential()
modelo.add(SimpleRNN(1, input_shape=(number_data_in_simulation,1), activation='linear', return_sequences = True))
modelo.add(Dense(units = 1, activation='linear'))
modelo.compile(optimizer=tf.keras.optimizers.Adam(0.1), loss='mse')
historial = modelo.fit(input_train, output_train, batch_size = 1, epochs=1, verbose=1)

predictions = modelo.predict(input_train, batch_size = 1, verbose = False)
mse_value = 0
number_cases = 0
for sim in range(len(output_train)):
    for example in range(len(output_train[sim])):
        mse_value = mse_value + (output_train[sim][example] - predictions[sim][example][0])**2
        number_cases += 1
print(mse_value/number_cases)

IN TERMINAL:

2022-12-15 19:07:11.483935: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected

2022-12-15 19:07:11.483963: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (jose-HP-EliteBook-830-G7-Notebook-PC): /proc/driver/nvidia/version does not exist

2022-12-15 19:07:11.484223: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA

To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.

1/1 [==============================] - 0s 467ms/step - loss: 6.1238

5.149037324060892

I expect to have the same result.
6.1238 != 5.149037324060892
Thank you very much! :)


来源: stackexchange

问:
I'm trying to change my background with python but its just becoming a black screen
I want it to chose a random .png from a file and make it the background of my computer. It worked without the random file stuff, but I only get a black screen or an IndexError: list index out of range.

```<code>import ctypes
import glob, random

file_path_type = ["./backgrounds/*.png"]
images = glob.glob(random.choice(file_path_type))
random_image = random.choice(images)
print(random_image)

def changeBG(random_image):
    SPI_SETDESKWALLPAPER = 20
    ctypes.windll.user32.SystemParametersInfoW(20, 0, random_image, 2)
    return;

changeBG(random_image)
</code>```

I dont really know what to do. I have tried looking it up but I cannot find anything.

ContentLicense: CC BY-SA 4.0

Body:
I want it to chose a random .png from a file and make it the background of my computer. It worked without the random file stuff, but I only get a black screen or an IndexError: list index out of range.

import ctypes
import glob, random

file_path_type = ["./backgrounds/*.png"]
images = glob.glob(random.choice(file_path_type))
random_image = random.choice(images)
print(random_image)

def changeBG(random_image):
    SPI_SETDESKWALLPAPER = 20
    ctypes.windll.user32.SystemParametersInfoW(20, 0, random_image, 2)
    return;

changeBG(random_image)

I dont really know what to do. I have tried looking it up but I cannot find anything.


问:
Deploy yolo3 keras .h5 model to Raspberry Pi
I have trained a tiny yolo3 model with custom data on Keras and want to deploy the model onto a Raspberry Pi.
I have converted the Keras .h5 model to a int-quantized .tflite model and wanted to do inference with tflite_support.task, which is only for SSD networks it seems, so that doesn't work for yolo, raises error that it requires a metadata.

So my question now is what would be the best way to deploy a .h5 Keras model onto a Raspberry Pi, I have also tried to convert it to a frozen .pb and use opencv dnn but the conversion doesn't seem to work even following this: How to export Keras .h5 to tensorflow .pb?

Running Keras on a Raspberry Pi can't be really an option, since it would require the full tensorflow installation.
Is there a lightweight way for deployment using opencv.dnn or tflite interpreter?


问:
Jenkins- change var in stage
I have defined a var at the beginning of the pipeline and I try to change its value inside a stage but get the following error:

/home/jenkins/agent/workspace/eon-Docker-Build-Multibranch_dev@tmp/durable-d2c76925/script.sh: line 1: syntax error: bad substitution

my pipeline look something like this:

```<code>def FRONTEND_STATUS = "fail"

pipeline {
    stage{
       steps{
         script {
             FRONTEND_STATUS = 'success'
        }
</code>```

tried many syntax options but nothing works.

Title: Jenkins- change var in stage

Body:
I have defined a var at the beginning of the pipeline and I try to change its value inside a stage but get the following error:

/home/jenkins/agent/workspace/eon-Docker-Build-Multibranch_dev@tmp/durable-d2c76925/script.sh: line 1: syntax error: bad substitution

my pipeline look something like this:

def FRONTEND_STATUS = "fail"

pipeline {
    stage{
       steps{
         script {
             FRONTEND_STATUS = 'success'
        }

tried many syntax options but nothing works.


问:
How to fix this circular reference error involving Protocols and type aliases?
The below code snippet, which is taken from this Github issue, fails to compile on Xcode 14.1

```<code>enum GenericState<Mode>: Hashable where Mode: Hashable {}

// error: Circular reference
protocol P {
  associatedtype Mode: Hashable
  // (false positive error) - Type 'Self.Mode' does not conform to protocol 'Hashable'
  typealias SomeState = GenericState<Mode>

  typealias Foo = [CustomKeyPath<Self, String>]

}

struct Interface<Base> where Base: P {}
typealias CustomKeyPath<Base, T> = KeyPath<Interface<Base>, T> where Base: P
</code>```

See screenshot of errors:

So, apparently, the latest swift update has some issues with Circular references.

How should I go about fixing these errors?

Body:
The below code snippet, which is taken from this Github issue, fails to compile on Xcode 14.1

enum GenericState<Mode>: Hashable where Mode: Hashable {}

// error: Circular reference
protocol P {
  associatedtype Mode: Hashable
  // (false positive error) - Type 'Self.Mode' does not conform to protocol 'Hashable'
  typealias SomeState = GenericState<Mode>

  typealias Foo = [CustomKeyPath<Self, String>]

}

struct Interface<Base> where Base: P {}
typealias CustomKeyPath<Base, T> = KeyPath<Interface<Base>, T> where Base: P

See screenshot of errors:

So, apparently, the latest swift update has some issues with Circular references.

How should I go about fixing these errors?


问:
Xamarin.Essentials ShareTextRequest some times missing text
Hi I am developing iOS/Android application with Xamarin forms

I am trying to share url  with some predefined text here is my code

```<code> await Share.RequestAsync(new ShareTextRequest
        {
            Text = "Some text",
            Uri = "url"
        });
</code>```

This is working fine in Android and can able to share text and url, and it is also working fine in some of iOS device

But some times in iOS devices(iOS 16) are missing text and sharing only url.
I tried to found the solution why text is missing some times on share
here I found similar issue https://github.com/xamarin/Essentials/issues/942

but I don't find solution, can any one help what could be the issue, how can I solve it

I am using Xamarin.Essentials 1.7.4

Body:
Hi I am developing iOS/Android application with Xamarin forms

I am trying to share url  with some predefined text here is my code

 await Share.RequestAsync(new ShareTextRequest
        {
            Text = "Some text",
            Uri = "url"
        });

This is working fine in Android and can able to share text and url, and it is also working fine in some of iOS device

But some times in iOS devices(iOS 16) are missing text and sharing only url.
I tried to found the solution why text is missing some times on share
here I found similar issue https://github.com/xamarin/Essentials/issues/942

but I don't find solution, can any one help what could be the issue, how can I solve it

I am using Xamarin.Essentials 1.7.4


问:
How can I render just a list item in react?
I am trying to render a list item like such:

```<code>export const ListItem = forwardRef(({className}: HTMLLIElement, ref: Ref<HTMLLIElement>) => {
  return <li></li>
})
</code>```

I am wondering why I am getting the follow error:

```<code>Cannot find name 'li'.ts(2304)
</code>```

Body:
I am trying to render a list item like such:

export const ListItem = forwardRef(({className}: HTMLLIElement, ref: Ref<HTMLLIElement>) => {
  return

})

I am wondering why I am getting the follow error:

Cannot find name 'li'.ts(2304)


问:
How to resolve path alias in javascript with vite.js?
I have added jsconfig.json for path alias

```<code> "baseUrl": ".",
 "paths": {
      "@/*": [ "src/*" ]
  }
</code>```

Work fine with editor but npm run gives error  Failed to resolve import "@/router"

Relative path also works fine.

module-alias plugin does not work either.

Body:
I have added jsconfig.json for path alias

 "baseUrl": ".",
 "paths": {
      "@/*": [ "src/*" ]
  }

Work fine with editor but npm run gives error  Failed to resolve import "@/router"

Relative path also works fine.

module-alias plugin does not work either.


问:
IIS 10.0 Detailed Error - 404.0 - Not Found Visual Studio 2022
I am trying to run a web API application on my local machine. When I run the project it is working without problem, but when I try for a post request it counts like this but not responding

From postman, I get this error [not returning any result from my post request](https://i.stack.imgur.com/RWKyJ.png.

Do you have any solution to this kind of problem?

I am trying to use my post method and get response.


问:
Cesium ImageryLayer Not Working on Map load
When the map loads and this component gets hit my layer doesn't show up and it doesn't make a network request to OpenSeaMap. However, if I set a timer the layer will show up after 10 seconds (arbitrary number). I tried checking if Cesium's viewer or camera were defined, before loading, but that didn't work.

I am at a loss of what a good solution is here, this clearly isn't it. Both provider objects are exactly the same when it works vs. when it doesn't.

```<code>export const TiledImageryOverlay = memo(({ urlTemplate, bounds, blackAsAlpha }: ITiledImageryOverlayProps) => {
    const boundingRectangle = bounds
        ? Rectangle.fromCartographicArray(
              bounds.map(point => Cartographic.fromDegrees(point.lon ?? 0 - 1, point.lat ?? 0))
          )
        : undefined;

    const provider = useMemo(() => {
        return new UrlTemplateImageryProvider({
            url: urlTemplate,
            rectangle: boundingRectangle
        });
    }, [urlTemplate, boundingRectangle]);

    const layerAlpha = blackAsAlpha ? new Color(0, 0, 0, 0) : undefined;

    return <ImageryLayer imageryProvider={provider} rectangle={boundingRectangle} colorToAlpha={layerAlpha} />;
});

export const TiledImageryOverlay = memo(({ urlTemplate, bounds, blackAsAlpha }: ITiledImageryOverlayProps) => {
    const [show, setShow] = useState<boolean>(false);
    const boundingRectangle = bounds
        ? Rectangle.fromCartographicArray(
              bounds.map(point => Cartographic.fromDegrees(point.lon ?? 0 - 1, point.lat ?? 0))
          )
        : undefined;
    useEffect(() => {
        setTimeout(() => {
            setShow(true);
        }, 10000);
    }, [setShow]);

    const provider = useMemo(() => {
        return new UrlTemplateImageryProvider({
            url: urlTemplate,
            rectangle: boundingRectangle
        });
    }, [urlTemplate, boundingRectangle]);

    const layerAlpha = blackAsAlpha ? new Color(0, 0, 0, 0) : undefined;

    if (!show) return null;

    return <ImageryLayer imageryProvider={provider} rectangle={boundingRectangle} colorToAlpha={layerAlpha} />;
});
</code>```

Body:
When the map loads and this component gets hit my layer doesn't show up and it doesn't make a network request to OpenSeaMap. However, if I set a timer the layer will show up after 10 seconds (arbitrary number). I tried checking if Cesium's viewer or camera were defined, before loading, but that didn't work.

I am at a loss of what a good solution is here, this clearly isn't it. Both provider objects are exactly the same when it works vs. when it doesn't.

export const TiledImageryOverlay = memo(({ urlTemplate, bounds, blackAsAlpha }: ITiledImageryOverlayProps) => {
    const boundingRectangle = bounds
        ? Rectangle.fromCartographicArray(
              bounds.map(point => Cartographic.fromDegrees(point.lon ?? 0 - 1, point.lat ?? 0))
          )
        : undefined;

    const provider = useMemo(() => {
        return new UrlTemplateImageryProvider({
            url: urlTemplate,
            rectangle: boundingRectangle
        });
    }, [urlTemplate, boundingRectangle]);

    const layerAlpha = blackAsAlpha ? new Color(0, 0, 0, 0) : undefined;

    return <ImageryLayer imageryProvider={provider} rectangle={boundingRectangle} colorToAlpha={layerAlpha} />;
});

export const TiledImageryOverlay = memo(({ urlTemplate, bounds, blackAsAlpha }: ITiledImageryOverlayProps) => {
    const [show, setShow] = useState<boolean>(false);
    const boundingRectangle = bounds
        ? Rectangle.fromCartographicArray(
              bounds.map(point => Cartographic.fromDegrees(point.lon ?? 0 - 1, point.lat ?? 0))
          )
        : undefined;
    useEffect(() => {
        setTimeout(() => {
            setShow(true);
        }, 10000);
    }, [setShow]);

    const provider = useMemo(() => {
        return new UrlTemplateImageryProvider({
            url: urlTemplate,
            rectangle: boundingRectangle
        });
    }, [urlTemplate, boundingRectangle]);

    const layerAlpha = blackAsAlpha ? new Color(0, 0, 0, 0) : undefined;

    if (!show) return null;

    return <ImageryLayer imageryProvider={provider} rectangle={boundingRectangle} colorToAlpha={layerAlpha} />;
});


问:
Beautfull DnD + React (Droppable disappearing when empty)
When there is no Draggable inside the Droppable it simply disappears
The code was taken from the official documentation example:

https://codesandbox.io/s/ql08j35j3q?file=/index.js:0-6365

I would like that even if it was empty, it would still remain there, allowing other items to be placed


问:
Uninstalling Vibrancy from Visual Studio Code
To have a good look of vs code I have downloaded the extension called "Vibrancy".
It is really reallu buggy extension I have ever downloaded. Even after uninstalling, it keeps on showing its effect.
.
To delete it permanently (in windows)

Close all tabs and windows.

press win+R

Type:- Temp and new screen pops up. Here delete all files.

After this again press win+R.

Type:- %temp%. And also delete all files.

Also Restart vs code few times


问:
adb screenrecord captures black screen
I am using adb to record the device's video.  I pull the video and it plays back a black screen.  Is there something else I need to enable?

adb shell screenrecord --time-limit 10 /sdcard/video.mp4
adb pull ./sdcard/video.mp4

Title: adb screenrecord captures black screen


问:
How to connect a "find local Path" function with mail merge function?
I have a function that starts when I open my Word document and connects it with an Excel file in the same folder.

It worked but we moved into SharePoint where mail merge doesn't work.

I have read articles about the problem. The solution is to have the sub find the local path instead of the SharePoint path.

I found code which should fix the problem but I can't figure out how to connect the local path function with my current code.

Private Sub DataSourceSet()
    On Error Resume Next
    ActiveDocument.MailMerge.OpenDataSource Name:=ActiveDocument.Path & "\Kilde.xlsx"
    ActiveDocument.MailMerge.ViewMailMergeFieldCodes = False
End Sub

Private Sub Document_Open()
    Call Instruks
    Call DataSourceSet
End Sub

Private Sub Instruks()
    MsgBox "Placer kilden i sammen folder som denne skabelon." & Chr(13) & ActiveDocument.Path & Chr(13) & Chr(13) & _
    "Kilden skal være et excelark og navngives: 'Kilde.xlsx'" & Chr(13) & Chr(13) & _
    "Gem regnearket nu - inden du trykker Ok!"
End Sub
```
<p>The function which should return the local path for the document.</p>
<pre class="lang-vb prettyprint-override"><code>Public Function GetLocalPath(ByVal Path As String) As String
    Const HKCU = &H80000001
    Dim objReg As Object, rPath As String, subKeys(), subKey
    Dim urlNamespace As String, mountPoint As String, secPart As String
    Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\." & _
                           "\root\default:StdRegProv")
    rPath = "Software\SyncEngines\Providers\OneDrive\"
    objReg.EnumKey HKCU, rPath, subKeys
    For Each subKey In subKeys
        objReg.GetStringValue HKCU, rPath & subKey, "UrlNamespace", urlNamespace
        If InStr(Path, urlNamespace) > 0 Then
            objReg.GetStringValue HKCU, rPath & subKey, "MountPoint", mountPoint
            secPart = Replace(Mid(Path, Len(urlNamespace)), "/", "\")
            Path = mountPoint & secPart
            Do Until Dir(Path, vbDirectory) <> "" Or InStr(2, secPart, "\") = 0
                secPart = Mid(secPart, InStr(2, secPart, "\"))
                Path = mountPoint & secPart
            Loop
            Exit For
        End If
    Next
    GetLocalPath = Path
End Function
</code>```

Body:
I have a function that starts when I open my Word document and connects it with an Excel file in the same folder.

It worked but we moved into SharePoint where mail merge doesn't work.

I have read articles about the problem. The solution is to have the sub find the local path instead of the SharePoint path.

I found code which should fix the problem but I can't figure out how to connect the local path function with my current code.

Private Sub DataSourceSet()
    On Error Resume Next
    ActiveDocument.MailMerge.OpenDataSource Name:=ActiveDocument.Path & "\Kilde.xlsx"
    ActiveDocument.MailMerge.ViewMailMergeFieldCodes = False
End Sub

Private Sub Document_Open()
    Call Instruks
    Call DataSourceSet
End Sub

Private Sub Instruks()
    MsgBox "Placer kilden i sammen folder som denne skabelon." & Chr(13) & ActiveDocument.Path & Chr(13) & Chr(13) & _
    "Kilden skal være et excelark og navngives: 'Kilde.xlsx'" & Chr(13) & Chr(13) & _
    "Gem regnearket nu - inden du trykker Ok!"
End Sub

The function which should return the local path for the document.

Public Function GetLocalPath(ByVal Path As String) As String
    Const HKCU = &H80000001
    Dim objReg As Object, rPath As String, subKeys(), subKey
    Dim urlNamespace As String, mountPoint As String, secPart As String
    Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\." & _
                           "\root\default:StdRegProv")
    rPath = "Software\SyncEngines\Providers\OneDrive\"
    objReg.EnumKey HKCU, rPath, subKeys
    For Each subKey In subKeys
        objReg.GetStringValue HKCU, rPath & subKey, "UrlNamespace", urlNamespace
        If InStr(Path, urlNamespace) > 0 Then
            objReg.GetStringValue HKCU, rPath & subKey, "MountPoint", mountPoint
            secPart = Replace(Mid(Path, Len(urlNamespace)), "/", "\")
            Path = mountPoint & secPart
            Do Until Dir(Path, vbDirectory) <> "" Or InStr(2, secPart, "\") = 0
                secPart = Mid(secPart, InStr(2, secPart, "\"))
                Path = mountPoint & secPart
            Loop
            Exit For
        End If
    Next
    GetLocalPath = Path
End Function


问:
Merge adjacent polygons in sf
I'm trying to merge groups of adjacent polygons, but I'm getting big multipolygons with non-adjacent areas. In the code block below plot(Matsuyama.sf) shows a large contiguous region and a few islands, but I can't extract those geometries. How do I get those areas and geometries.

```<code>library(sf)
library(tidyverse)
Matsuyama.sf <- st_read("https://geoshape.ex.nii.ac.jp/city/geojson/20210101/38/38201A1968.geojson")
Matsuyama.sf <- st_transform(Matsuyama.sf, crs=4326)
plot(Matsuyama.sf)
st_area(Matsuyama.sf)
</code>```

I can split into hundreds of polygons, but the code options below just lump them back together into one

```<code>split.sf <- st_cast(Matsuyama.sf, "POLYGON")
clumps_1.sf <- st_join(split.sf, split.sf, join = st_intersects)
clumps_2sf <- Matsuyama.sf %>% mutate(INTERSECT = st_intersects(.))

</code>```

What am I missing?

Title: Merge adjacent polygons in sf

Body:
I'm trying to merge groups of adjacent polygons, but I'm getting big multipolygons with non-adjacent areas. In the code block below plot(Matsuyama.sf) shows a large contiguous region and a few islands, but I can't extract those geometries. How do I get those areas and geometries.

library(sf)
library(tidyverse)
Matsuyama.sf <- st_read("https://geoshape.ex.nii.ac.jp/city/geojson/20210101/38/38201A1968.geojson")
Matsuyama.sf <- st_transform(Matsuyama.sf, crs=4326)
plot(Matsuyama.sf)
st_area(Matsuyama.sf)

I can split into hundreds of polygons, but the code options below just lump them back together into one

split.sf <- st_cast(Matsuyama.sf, "POLYGON")
clumps_1.sf <- st_join(split.sf, split.sf, join = st_intersects)
clumps_2sf <- Matsuyama.sf %>% mutate(INTERSECT = st_intersects(.))

What am I missing?


问:
.NET MAUI SwipeView in a CollectionView makes program crash when refreshing items only on Windows
When the content of the cart is loaded a first time, everything goes well. When I refresh it, the program crashes. On Android everything is fine.

```<code><CollectionView ItemsSource="{Binding Cart}"
                            SelectionMode="Multiple"
                            SelectedItems="{Binding SelectedItemsInCart}"
                            SelectionChanged="On_SelectionChanged"
                            EmptyView="No ingredients in your cart"
                            x:Name="collectionView"
                            HorizontalOptions="Center">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <SwipeView>
                            <SwipeView.RightItems>
                                <SwipeItems >
                                    <SwipeItem Text="Delete"
                                   IconImageSource="trash.png"
                                   BackgroundColor="LightPink"
                                   Command="{Binding RemoveFromCartCommand}"
                                   CommandParameter="{Binding}" />
                                </SwipeItems>
                            </SwipeView.RightItems>
                            <Grid RowDefinitions="auto, auto" x:DataType="model:Ingredient">
                                <Label Grid.Row="0" Text="{Binding Name}" FontAttributes="Bold" FontSize="20" HorizontalOptions="Center"/>
                                <Label Grid.Row="1" Text="{Binding Quantity}" FontSize="15" HorizontalOptions="Center"/>
                            </Grid>
                        </SwipeView>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
</code>```

And the error is not very helpful:

```<code>Unhandled exception at 0x00007FFB117CE1EF (combase.dll) in CookUs.exe: 0xC0000602: A FailFast exception has occurred. Exception handlers will not be called and the process will terminate immediately.
</code>```

Without the SwipeView, everything's fine. The SwipeView seems to simply not be supported on Windows, even disabling it if the platform is Windows still makes the program crash.

Body:
When the content of the cart is loaded a first time, everything goes well. When I refresh it, the program crashes. On Android everything is fine.

<CollectionView ItemsSource="{Binding Cart}"
                            SelectionMode="Multiple"
                            SelectedItems="{Binding SelectedItemsInCart}"
                            SelectionChanged="On_SelectionChanged"
                            EmptyView="No ingredients in your cart"
                            x:Name="collectionView"
                            HorizontalOptions="Center">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <SwipeView>
                            <SwipeView.RightItems>
                                <SwipeItems >
                                    <SwipeItem Text="Delete"
                                   IconImageSource="trash.png"
                                   BackgroundColor="LightPink"
                                   Command="{Binding RemoveFromCartCommand}"
                                   CommandParameter="{Binding}" />
                                </SwipeItems>
                            </SwipeView.RightItems>
                            <Grid RowDefinitions="auto, auto" x:DataType="model:Ingredient">

                            </Grid>
                        </SwipeView>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>

And the error is not very helpful:

Unhandled exception at 0x00007FFB117CE1EF (combase.dll) in CookUs.exe: 0xC0000602: A FailFast exception has occurred. Exception handlers will not be called and the process will terminate immediately.

Without the SwipeView, everything's fine. The SwipeView seems to simply not be supported on Windows, even disabling it if the platform is Windows still makes the program crash.


问:
LineHeight attribute on NSAttributedString is working backwards?
I was messing around with line heights but I can't understand what's going on.

How is lineHeight = 8:

and lineHeight = 28:

```<code>func attributedString(lineHeight: CGFloat) -> NSAttributedString  {
    var attributes: [NSAttributedString.Key: Any] = [:]
    let style = NSMutableParagraphStyle()
    style.minimumLineHeight = lineHeight
    attributes.updateValue(style, forKey: .paragraphStyle)

    return .init(string: self, attributes: attributes)}
</code>```

Shouldn't it be the other way around? This is messing up everything

Body:
I was messing around with line heights but I can't understand what's going on.

How is lineHeight = 8:

and lineHeight = 28:

func attributedString(lineHeight: CGFloat) -> NSAttributedString  {
    var attributes: [NSAttributedString.Key: Any] = [:]
    let style = NSMutableParagraphStyle()
    style.minimumLineHeight = lineHeight
    attributes.updateValue(style, forKey: .paragraphStyle)

    return .init(string: self, attributes: attributes)}

Shouldn't it be the other way around? This is messing up everything


问:
Why is tsc command not found in child package in yarn workspace?
I'm using yarn version 3.2.4. I have a package.json in my root that looks like this:

```<code>{
  "scripts": {
    "compile": "tsc --build",
  },
  "devDependencies": {
    "typescript": "^4.8.4"
  }
}
</code>```

In packages/foo, I have this package.json

```<code>{
  "scripts": {
    "compile": "tsc --build"
  },
  "devDependencies": {
  }
}
</code>```

When I run yarn compile from the root, tsc compiles correctly. But this fails:

```<code>cd packages/foo
yarn compile
</code>```

command not found: tsc

If I change the child packages to include typescript as a devDependency then it works.

Why aren't the devDependencies inherited from the parent package.json?

Body:
I'm using yarn version 3.2.4. I have a package.json in my root that looks like this:

{
  "scripts": {
    "compile": "tsc --build",
  },
  "devDependencies": {
    "typescript": "^4.8.4"
  }
}

In packages/foo, I have this package.json

{
  "scripts": {
    "compile": "tsc --build"
  },
  "devDependencies": {
  }
}

When I run yarn compile from the root, tsc compiles correctly. But this fails:

cd packages/foo
yarn compile

command not found: tsc

If I change the child packages to include typescript as a devDependency then it works.

Why aren't the devDependencies inherited from the parent package.json?


问:
Python canvas grid
In tkinter, if I use canvas.grid, the canvas.bind cannot work, and shows _tkinter.TclError: bad event type or keysym "button" but if I use canvas.pack, it won't. Can anyone help me figure out?

Here is a part of the code

```<code>import tkinter as tk

window = tk.Tk()
window.title("project")
window.geometry('760x560')
window.resizable(False, False)
</code>```
```<code>def mouse_click_handler(event):
    # Get the coordinates of the mouse click
    x = event.x
    y = event.y

    screen_two.canvas.create_oval(event.x - 15, event.y - 15,
                            event.x + 15, event.y + 15,
                            fill = piece_color, tags = ("show_piece"))
</code>```
```<code>canvas = tk.Canvas(window, bg = "green", width = 540, height = 540)
canvas.grid(row = 0, column = 0, rowspan = 6
for i in range(15): # draw line
        canvas.create_line(32, (35 * i + 38), 522, (35 * i + 38))
        canvas.create_line((35 * i + 32), 38, (35 * i + 32), 528)
    point_X = [3, 3, 11, 11, 7]
    point_Y = [3, 11, 3, 11, 7]
    for i in range(5): # draw dot
        canvas.create_oval(35 * point_X[i] + 28, 35 * point_Y[i] + 33,
                        35 * point_X[i] + 36, 35 * point_Y[i] + 41, fill = "black")
    count = 0
    for i in range(15):
        label1 = tk.Label(canvas, text = str(i+1), fg = "black", bg = "green")
        label2 = tk.Label(canvas, text = str(i+1), fg = "black", bg = "green")
        label1.place(x = 35 * count + 25, y = 2)
        label2.place(x = 2, y = 35 * count + 25)
        count += 1
    canvas.bind("<button-1>", mouse_click_handler)
</code>```

Title: Python canvas grid

Body:
In tkinter, if I use canvas.grid, the canvas.bind cannot work, and shows _tkinter.TclError: bad event type or keysym "button" but if I use canvas.pack, it won't. Can anyone help me figure out?

Here is a part of the code

import tkinter as tk

window = tk.Tk()
window.title("project")
window.geometry('760x560')
window.resizable(False, False)

def mouse_click_handler(event):
    # Get the coordinates of the mouse click
    x = event.x
    y = event.y

    screen_two.canvas.create_oval(event.x - 15, event.y - 15,
                            event.x + 15, event.y + 15,
                            fill = piece_color, tags = ("show_piece"))

canvas = tk.Canvas(window, bg = "green", width = 540, height = 540)
canvas.grid(row = 0, column = 0, rowspan = 6
for i in range(15): # draw line
        canvas.create_line(32, (35 * i + 38), 522, (35 * i + 38))
        canvas.create_line((35 * i + 32), 38, (35 * i + 32), 528)
    point_X = [3, 3, 11, 11, 7]
    point_Y = [3, 11, 3, 11, 7]
    for i in range(5): # draw dot
        canvas.create_oval(35 * point_X[i] + 28, 35 * point_Y[i] + 33,
                        35 * point_X[i] + 36, 35 * point_Y[i] + 41, fill = "black")
    count = 0
    for i in range(15):
        label1 = tk.Label(canvas, text = str(i+1), fg = "black", bg = "green")
        label2 = tk.Label(canvas, text = str(i+1), fg = "black", bg = "green")
        label1.place(x = 35 * count + 25, y = 2)
        label2.place(x = 2, y = 35 * count + 25)
        count += 1
    canvas.bind("<button-1>", mouse_click_handler)


问:
How do I change all the keys of a Python dictionary, if the values of said keys are nested dictionaries?
I am working on a headache of a college project in Python, and one of the functions basically has to write a dictionary (which cointains nested dictionaries) into a csv file, and later read from the said file, place it into a new dictionary, and return that new dictionary to the user.

Now, the keys of the said dictionary are of type int, but obvsiouly after being read from the file and written into the new dictionary, they turn into type str.

The unittests we were given keep failing my function because of this, as they expect the same value that was given to us originally, so I have been struggling with modifying this. Below is a (hand-crafted) example of that dictionary that I was practicing on, but still couldn't seem to get the change to take place:

```<code>dictionary = {
    "0": {
        "name": "gary",
        "last_name": "john",
        "age": 13
    },
    "1": {
        "name": "larry",
        "last_name": "boyle",
        "age": 10
    },
    "2": {
        "name": "banji",
        "last_name": "buas",
        "age": 20
    }
}

for i in dictionary.items(): #this gives us a tuple
    change = list(i) #convert tuple to list
    change[0] = int(change[0]) #change each str to int
    i = tuple(change) #convert back to tuple
</code>```

This approach only seems to work within the for-loop, but as soon as the loop ends, and I try printing out the 'new' dict, all I get is the same old one. Can anyone help with this problem?

Body:
I am working on a headache of a college project in Python, and one of the functions basically has to write a dictionary (which cointains nested dictionaries) into a csv file, and later read from the said file, place it into a new dictionary, and return that new dictionary to the user.

Now, the keys of the said dictionary are of type int, but obvsiouly after being read from the file and written into the new dictionary, they turn into type str.

The unittests we were given keep failing my function because of this, as they expect the same value that was given to us originally, so I have been struggling with modifying this. Below is a (hand-crafted) example of that dictionary that I was practicing on, but still couldn't seem to get the change to take place:

dictionary = {
    "0": {
        "name": "gary",
        "last_name": "john",
        "age": 13
    },
    "1": {
        "name": "larry",
        "last_name": "boyle",
        "age": 10
    },
    "2": {
        "name": "banji",
        "last_name": "buas",
        "age": 20
    }
}

for i in dictionary.items(): #this gives us a tuple
    change = list(i) #convert tuple to list
    change[0] = int(change[0]) #change each str to int
    i = tuple(change) #convert back to tuple

This approach only seems to work within the for-loop, but as soon as the loop ends, and I try printing out the 'new' dict, all I get is the same old one. Can anyone help with this problem?


问:
Why does my request return an ERR_BAD_REQUEST?
I am making a request from postman that returns the requested information without problem, additionally I did the test using curl and in the same way it returns the information successfully.But when doing it from axios it returns an ERR_BAD_REQUEST, the code is the following:

```<code>const axios = require('axios');
let payload = {
  "payment_method": {
    "type": "CARD",
    "installments": 2,
    "token": "tok_prod_some_token"
  }
};

let config = {
  method: 'post',
  url: 'https://hereismyurl/v1/tokens/cards',
 data:payload,
 headers: {
      "Accept": "application/json",
        "Content-Type": "application/json",
     'Authorization': 'Bearer pub_prod_some_public_key'

  },

};

axios(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
</code>```

I can't understand what I'm sending wrong in my request

Body:
I am making a request from postman that returns the requested information without problem, additionally I did the test using curl and in the same way it returns the information successfully.But when doing it from axios it returns an ERR_BAD_REQUEST, the code is the following:

const axios = require('axios');
let payload = {
  "payment_method": {
    "type": "CARD",
    "installments": 2,
    "token": "tok_prod_some_token"
  }
};

let config = {
  method: 'post',
  url: 'https://hereismyurl/v1/tokens/cards',
 data:payload,
 headers: {
      "Accept": "application/json",
        "Content-Type": "application/json",
     'Authorization': 'Bearer pub_prod_some_public_key'

  },

};

axios(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

I can't understand what I'm sending wrong in my request


问:
Changes done in the VS code not reflecting in the Apollo Sandbox in graphQL
I have been learning graphQL from few days. I am new to it. I've created a GraphQL project in VS code. For running the code I am writing 'node index.js' at first and code runs on Apollo sandbox explorer. But whenever I do any changes in the sourcecode file in VS Code, those are not reflecting on the apollo explorer. I've to Restart the vscode and again rerun it.

Please help how do I see the changes immediately without restarting the VS Code


问:
Angular component not showing template
I downloaded angular form https://angular.io/quick-start and then added a file to the app folder tutoriel.component.ts and wrote the following code

```<code>import { Component } from "@angular/core";
@Component({
    selector: 'tutoriel',
    template: '<h2>Tutoriel</h2>'
})
export class TutorielComp{

}
</code>```

and then changed this in the app.module

```<code>@NgModule({
  declarations: [
    AppComponent,
    TutorielComp
  ],
</code>```

and the class got imported import { TutorielComp } from './tutoriel.component'; The problem is when I deleted all the code in the app.component.html and wrote

<tutoriel></tutoriel>

But,It did not show.
Edit: This is my Module file

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TutorielComp } from './tutoriel.component';

@NgModule({
  declarations: [
    AppComponent,
    TutorielComp
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Title: Angular component not showing template

Body:
I downloaded angular form https://angular.io/quick-start and then added a file to the app folder tutoriel.component.ts and wrote the following code

import { Component } from "@angular/core";
@Component({
    selector: 'tutoriel',
    template: '
Tutoriel
'
})
export class TutorielComp{

}

and then changed this in the app.module

@NgModule({
  declarations: [
    AppComponent,
    TutorielComp
  ],

and the class got imported import { TutorielComp } from './tutoriel.component'; The problem is when I deleted all the code in the app.component.html and wrote

<tutoriel></tutoriel>

But,It did not show.
Edit: This is my Module file

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TutorielComp } from './tutoriel.component';

@NgModule({
  declarations: [
    AppComponent,
    TutorielComp
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Spring JPA how can I retrieve join table with a given property?
I am working on a Spring project and I am using JPA to access database. I have two tables that have @ManyToMany property. And one other table (join table) that keeps the foreign keys of those two tables. I need to retrieve the join table with a given property of one of the tables. I tried to use JPA methods and queries but I couldn't find a solution.

I have an abstract class called Course:

```<code>@Data
@NoArgsConstructor
@MappedSuperclass
public abstract class Course {
    @Id
    @GeneratedValue(generator = "UUID")
    @Column(name = "id", nullable = false)
    private UUID courseId;

    @NotBlank
    @Column(name = "course_code", nullable = false)
    private String courseCode;

    @NotBlank
    @Column(name = "course_name", nullable = false)
    private String courseName;

    @NotNull
    @Column(name = "ects", nullable = false)
    private Double ects;

    public Course(
        @JsonProperty("id") UUID id,
        @JsonProperty("courseCode") String courseCode,
        @JsonProperty("courseName") String courseName,
        @JsonProperty("ects") Double ects) {

        this.courseId = id;
        this.courseCode = courseCode;
        this.courseName = courseName;
        this.ects = ects;
    }
}

</code>```

I have two database model classes that extends Course:

```<code>@Entity
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Table(name = "uni_course")
public class UniCourse extends Course {

    @NotNull
    @Column(name = "department", nullable = false)
    @Enumerated(EnumType.STRING)
    private Department department;

    @ManyToMany
    @JoinTable(
        name = "approved_courses",
        joinColumns = @JoinColumn(name = "uni_course_id"),
        inverseJoinColumns = @JoinColumn(name = "host_course_id"))
    private Set<HostCourse> approvedCourses;

    public UniCourse(
        @JsonProperty("id") UUID id,
        @JsonProperty("courseCode") String courseCode,
        @JsonProperty("courseName") String courseName,
        @JsonProperty("ects") Double ects,
        @JsonProperty("department") Department department) {

        super(id, courseCode, courseName, ects);
        this.department = department;
        this.bilkentCredit = bilkentCredit;
    }
}

</code>```

and,

```<code>@Entity
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Table(name = "host_course")
public class HostCourse extends Course {

    @NotBlank
    @Column(name = "syllabus", nullable = false)
    private String syllabus;

    @NotBlank
    @Column(name = "web_page", nullable = true)
    private String webPage;

    @NotNull
    @Column(name = "university_id", nullable = false)
    private UUID universityId;

    @ManyToMany(mappedBy = "approvedCourses")
    private Set<UniCourse> uniCourses;

    public HostCourse(
        @JsonProperty("id") UUID id,
        @JsonProperty("courseCode") String courseCode,
        @JsonProperty("courseName") String courseName,
        @JsonProperty("ects") Double ects,
        @JsonProperty("syllabus") String syllabus,
        @JsonProperty("webPage") String webPage,
        @JsonProperty("universityId") UUID universityId) {

        super(id, courseCode, courseName, ects);
        this.syllabus = syllabus;
        this.webPage = webPage;
        this.universityId = universityId;
        this.courseApproval = courseApproval;
    }
}

</code>```

I want to get approvedCourses using universityId of HostCourse. How can I achieve this?

I tried using the findByApprovedCoursesUniversityId(UUID universityId) method and it returned the following:

```<code>{
    "data": [
        {
            "courseCode": "CS315",
            "courseName": "Programming Languages",
            "ects": 5.0,
            "department": "CS",
            "courseId": "8a890716-aaf1-40bb-81b2-e0a638b878dd",
            "approvedCourses": []
        }
    ]
    "timestamp": "2022.12.15 21.48.32",
    "status": "OK"
}
</code>```

I also want to get approved courses but it returns an empty array.

Body:
I am working on a Spring project and I am using JPA to access database. I have two tables that have @ManyToMany property. And one other table (join table) that keeps the foreign keys of those two tables. I need to retrieve the join table with a given property of one of the tables. I tried to use JPA methods and queries but I couldn't find a solution.

I have an abstract class called Course:

@Data
@NoArgsConstructor
@MappedSuperclass
public abstract class Course {
    @Id
    @GeneratedValue(generator = "UUID")
    @Column(name = "id", nullable = false)
    private UUID courseId;

    @NotBlank
    @Column(name = "course_code", nullable = false)
    private String courseCode;

    @NotBlank
    @Column(name = "course_name", nullable = false)
    private String courseName;

    @NotNull
    @Column(name = "ects", nullable = false)
    private Double ects;

    public Course(
        @JsonProperty("id") UUID id,
        @JsonProperty("courseCode") String courseCode,
        @JsonProperty("courseName") String courseName,
        @JsonProperty("ects") Double ects) {

        this.courseId = id;
        this.courseCode = courseCode;
        this.courseName = courseName;
        this.ects = ects;
    }
}

I have two database model classes that extends Course:

@Entity
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Table(name = "uni_course")
public class UniCourse extends Course {

    @NotNull
    @Column(name = "department", nullable = false)
    @Enumerated(EnumType.STRING)
    private Department department;

    @ManyToMany
    @JoinTable(
        name = "approved_courses",
        joinColumns = @JoinColumn(name = "uni_course_id"),
        inverseJoinColumns = @JoinColumn(name = "host_course_id"))
    private Set<HostCourse> approvedCourses;

    public UniCourse(
        @JsonProperty("id") UUID id,
        @JsonProperty("courseCode") String courseCode,
        @JsonProperty("courseName") String courseName,
        @JsonProperty("ects") Double ects,
        @JsonProperty("department") Department department) {

        super(id, courseCode, courseName, ects);
        this.department = department;
        this.bilkentCredit = bilkentCredit;
    }
}

and,

@Entity
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Table(name = "host_course")
public class HostCourse extends Course {

    @NotBlank
    @Column(name = "syllabus", nullable = false)
    private String syllabus;

    @NotBlank
    @Column(name = "web_page", nullable = true)
    private String webPage;

    @NotNull
    @Column(name = "university_id", nullable = false)
    private UUID universityId;

    @ManyToMany(mappedBy = "approvedCourses")
    private Set<UniCourse> uniCourses;

    public HostCourse(
        @JsonProperty("id") UUID id,
        @JsonProperty("courseCode") String courseCode,
        @JsonProperty("courseName") String courseName,
        @JsonProperty("ects") Double ects,
        @JsonProperty("syllabus") String syllabus,
        @JsonProperty("webPage") String webPage,
        @JsonProperty("universityId") UUID universityId) {

        super(id, courseCode, courseName, ects);
        this.syllabus = syllabus;
        this.webPage = webPage;
        this.universityId = universityId;
        this.courseApproval = courseApproval;
    }
}

I want to get approvedCourses using universityId of HostCourse. How can I achieve this?

I tried using the findByApprovedCoursesUniversityId(UUID universityId) method and it returned the following:

{
    "data": [
        {
            "courseCode": "CS315",
            "courseName": "Programming Languages",
            "ects": 5.0,
            "department": "CS",
            "courseId": "8a890716-aaf1-40bb-81b2-e0a638b878dd",
            "approvedCourses": []
        }
    ]
    "timestamp": "2022.12.15 21.48.32",
    "status": "OK"
}

I also want to get approved courses but it returns an empty array.


问:
Eloquent relationship
As the title suggests, I have a little problem with the relationship between my tables.

```<code>Unknown column 'table1.entity_id' in 'where clause'

select * from `table2` where `table1`.`entity_id` = `table2`.`id`
</code>```

Here is the structure of my tables:

table1

```<code>id varchar(36)
type enum()
entity_id varchar(36)
</code>```

table2

```<code>id varchar(36)
description
</code>```

table3

```<code>id varchar(36)
brand
</code>```

In the table1.entity_id column we can find the id of table2 and table3.

And these are the relationships:

Table 1

public function table2()
{
    return $this->hasMany('App/Model/Table2', 'entity_id');
}

public function table3()
{
    return $this->hasMany('App/Model/Table3', 'entity_id');
}
```
<p><code>Table 2</code></p>
<pre class="lang-php prettyprint-override"><code>public function table1()
{
    return $this->belongsTo('App/Model/Table1', 'id', 'entity_id');
}
</code>```

Table 3

public function table1()
{
    return $this->belongsTo('App/Model/Table1', 'id', 'entity_id');
}
```
<p>And when I do that :</p>
<pre class="lang-php prettyprint-override"><code>$query->orWhereHas('table2', function($query) use ($value) {
    $query->whereNotNull('description');
});
</code>```

I have this error :

```<code>Unknown column 'table1.entity_id' in 'where clause'

select * from `table2` where `table1`.`entity_id` = `table2`.`id`
</code>```

Can someone tell me what is the problem ?

Title: Eloquent relationship

Body:
As the title suggests, I have a little problem with the relationship between my tables.

Unknown column 'table1.entity_id' in 'where clause'

select * from `table2` where `table1`.`entity_id` = `table2`.`id`

Here is the structure of my tables:

table1

id varchar(36)
type enum()
entity_id varchar(36)

table2

id varchar(36)
description

table3

id varchar(36)
brand

In the table1.entity_id column we can find the id of table2 and table3.

And these are the relationships:

Table 1

public function table2()
{
    return $this->hasMany('App/Model/Table2', 'entity_id');
}

public function table3()
{
    return $this->hasMany('App/Model/Table3', 'entity_id');
}

Table 2

public function table1()
{
    return $this->belongsTo('App/Model/Table1', 'id', 'entity_id');
}

Table 3

public function table1()
{
    return $this->belongsTo('App/Model/Table1', 'id', 'entity_id');
}

And when I do that :

$query->orWhereHas('table2', function($query) use ($value) {
    $query->whereNotNull('description');
});

I have this error :

Unknown column 'table1.entity_id' in 'where clause'

select * from `table2` where `table1`.`entity_id` = `table2`.`id`

Can someone tell me what is the problem ?


问:
After last update it is not possible to go to definition using Ctrl+click
After update VSCode to 1.74.1 it is not possible to go to function definition using ctrl+click. How to do it now?

Windows 10, JavaScript

I expect it to work as before - when I ctrl+click on a function name, it should take me to its definition.


问:
How to reload the currently displayed fragment
I'm handling Login and Logout Logic in a Fragment. I want the fragment to refresh itself when the user logs in or logs out. I'm using Navigation Component for my Fragment Navigation.
I've tried several ways but none of them are working. I'm trying the following code:

```<code>val fragManager = this@WelcomeFragment.parentFragmentManager

fragManager.beginTransaction().detach(this).attach(this).commit()
</code>```

However, this code does nothing.
I've also tried doing the following:

```<code> val act = this.requireActivity() as MainActivity

val fragmentTransaction =
   act.supportFragmentManager.beginTransaction()

   fragmentTransaction.setReorderingAllowed(true)
   fragmentTransaction.detach(this).attach(this)
</code>```

Though this crashes my App. How can I refresh/reload a currently displayed fragment? Thanks.

Body:
I'm handling Login and Logout Logic in a Fragment. I want the fragment to refresh itself when the user logs in or logs out. I'm using Navigation Component for my Fragment Navigation.
I've tried several ways but none of them are working. I'm trying the following code:

val fragManager = this@WelcomeFragment.parentFragmentManager

fragManager.beginTransaction().detach(this).attach(this).commit()

However, this code does nothing.
I've also tried doing the following:

 val act = this.requireActivity() as MainActivity

val fragmentTransaction =
   act.supportFragmentManager.beginTransaction()

   fragmentTransaction.setReorderingAllowed(true)
   fragmentTransaction.detach(this).attach(this)

Though this crashes my App. How can I refresh/reload a currently displayed fragment? Thanks.


问:
Trying to open a Azure blob file using GDAL. Getting an error "does not exist in the file system, and is not recognized as a supported dataset name."
Trying to open a Azure blob file using GDAL. Getting an error "does not exist in the file system, and is not recognized as a supported dataset name."</p>
```<code>gdal.SetConfigOption('AZURE_STORAGE_ACCOUNT', "accountname")
gdal.SetConfigOption('AZURE_STORAGE_ACCESS_KEY', "Key")
gdal.SetConfigOption('AZURE_NO_SIGN_REQUEST', 'YES')
a = gdal.Open('/vsiadls/container/folder/filename.tif')

type(a)

Tried vsiaz, vsiadls
</code>```

Body:
Trying to open a Azure blob file using GDAL. Getting an error "does not exist in the file system, and is not recognized as a supported dataset name."

gdal.SetConfigOption('AZURE_STORAGE_ACCOUNT', "accountname")
gdal.SetConfigOption('AZURE_STORAGE_ACCESS_KEY', "Key")
gdal.SetConfigOption('AZURE_NO_SIGN_REQUEST', 'YES')
a = gdal.Open('/vsiadls/container/folder/filename.tif')

type(a)

Tried vsiaz, vsiadls


问:
NoClassDefFoundError: Could not initialize class javax.xml.transform.FactoryFinder when using PowerMock + Springfox
Current project is an API that uses google cloud functions. I'd like to improve the coverage using unit tests and therefore would like to use PowerMock to mock static GCP functions. However, I receive the following error:

```<code>NoClassDefFoundError: Could not initialize class javax.xml.transform.FactoryFinder
</code>```
```<code>@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
@PrepareForTest(MockedClass.class)
public class TestControllerTest {
   ... code here ...
}
</code>```

Other details: Springfox 3.0.0, Java 11, uses Lombok.

Relevant POM:

```<code><parent>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-parent</artifactId>

    <version>2.7.3</version>

    <relativePath/> <!-- lookup parent from repository -->

</parent>
</code>```
```<code><dependency>

    <groupId>org.mockito</groupId>

    <artifactId>mockito-core</artifactId>

    <version>4.5.1</version>

    <scope>test</scope>

</dependency>

<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-core</artifactId>

    <version>$(powermock.version)</version>

    <scope>test</scope>

</dependency>

<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-module-junit4</artifactId>

    <version>$(powermock.version)</version>

    <scope>test</scope>

</dependency>
<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-api-mockito2</artifactId>

    <version>${powermock.version)</version>

    <scope>test</scope>

</dependency>
<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-module-junit4-rule</artifactId>

    <version>${powermock.version}</version>

    <scope>test</scope>

</dependency>
<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-classloading-xstream</artifactId>

    <version>${powermock.version}</version>

    <scope>test</scope>

</dependency>

<!-- API, java.xml.bind module -->

<dependency>

    <groupId>jakarta.xml.bind</groupId>

    <artifactId>jakarta.xml.bind-api</artifactId>9

    <version>2.3.3</version>

</dependency>

<!---Runtime, com.sun.xml.bind-module-->

<dependency>

    <groupId>org.glassfish.jaxb</groupId>

    <artifactId>jaxb-runtime</artifactId>"

    <version>2.3.6</version>

</dependency>

<dependency>

    <groupId>javax.xml.bind</groupId>

    <artifactId>jaxb-api</artifactId>

    <version>2.3.1</version>

</dependency>
</code>```

Power mock version is 2.0.9.

I've tried adding the classes that it says is missing.
I've tried changing up the versions of powermock.
I've tried messing with jacoco.
I've tried to ignore the errors using PowerMockIgnore but that started causing other issues.
Referenced several of the popular existing answers on stackoverflow.

Tests works without powermock (but obviously cover less).

Body:
Current project is an API that uses google cloud functions. I'd like to improve the coverage using unit tests and therefore would like to use PowerMock to mock static GCP functions. However, I receive the following error:

NoClassDefFoundError: Could not initialize class javax.xml.transform.FactoryFinder

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
@PrepareForTest(MockedClass.class)
public class TestControllerTest {
   ... code here ...
}

Other details: Springfox 3.0.0, Java 11, uses Lombok.

Relevant POM:

<parent>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-parent</artifactId>

    <version>2.7.3</version>

    <relativePath/>

</parent>

<dependency>

    <groupId>org.mockito</groupId>

    <artifactId>mockito-core</artifactId>

    <version>4.5.1</version>

    <scope>test</scope>

</dependency>

<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-core</artifactId>

    <version>$(powermock.version)</version>

    <scope>test</scope>

</dependency>

<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-module-junit4</artifactId>

    <version>$(powermock.version)</version>

    <scope>test</scope>

</dependency>
<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-api-mockito2</artifactId>

    <version>${powermock.version)</version>

    <scope>test</scope>

</dependency>
<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-module-junit4-rule</artifactId>

    <version>${powermock.version}</version>

    <scope>test</scope>

</dependency>
<dependency>

    <groupId>org.powermock</groupId>

    <artifactId>powermock-classloading-xstream</artifactId>

    <version>${powermock.version}</version>

    <scope>test</scope>

</dependency>

<dependency>

    <groupId>jakarta.xml.bind</groupId>

    <artifactId>jakarta.xml.bind-api</artifactId>9

    <version>2.3.3</version>

</dependency>

<dependency>

    <groupId>org.glassfish.jaxb</groupId>

    <artifactId>jaxb-runtime</artifactId>"

    <version>2.3.6</version>

</dependency>

<dependency>

    <groupId>javax.xml.bind</groupId>

    <artifactId>jaxb-api</artifactId>

    <version>2.3.1</version>

</dependency>

Power mock version is 2.0.9.

I've tried adding the classes that it says is missing.
I've tried changing up the versions of powermock.
I've tried messing with jacoco.
I've tried to ignore the errors using PowerMockIgnore but that started causing other issues.
Referenced several of the popular existing answers on stackoverflow.

Tests works without powermock (but obviously cover less).


问:
Set filter model before set datasource for ag-grid server side row mode
I have probelm with ag-grid in Server side rowe mode in React
I want initialize filters before first api call for rows.
So on grid ready method I create filter model and set it in gridApi, next I create server side datesource

```<code>const onGridReady = useCallback((params: GridReadyEvent) => {
 const filterModel = getFilterModel()
 params.api.setFilterModel(filterModel)

 const datasource = createServerSideDatasource()
 params.api.setServerSideDatasource(datasource)

 setGridApi(params.api)
 setColumnApi(params.columnApi)
}, [])

const createServerSideDatasource: () => IServerSideDatasource = () => {
 return {
   getRows: async (params) => {
     const response = await getTableRows(params.request) //api call
     if (response.success) {
       params.success({ rowData: response.rows, rowCount: response.lastRow
     })
    } else {
      params.fail()
     }
},}}
</code>```

Ag-grid call api twice, once with empty filters, and next with my filters
I want call api only once with my filters, perhaps there is different way to set default/initialize filters in ag-grid than api.setFilterModel because I guess that put in internal event loop

setdatasource

call getRows

setFilter

trigger call getRows

Body:
I have probelm with ag-grid in Server side rowe mode in React
I want initialize filters before first api call for rows.
So on grid ready method I create filter model and set it in gridApi, next I create server side datesource

const onGridReady = useCallback((params: GridReadyEvent) => {
 const filterModel = getFilterModel()
 params.api.setFilterModel(filterModel)

 const datasource = createServerSideDatasource()
 params.api.setServerSideDatasource(datasource)

 setGridApi(params.api)
 setColumnApi(params.columnApi)
}, [])

const createServerSideDatasource: () => IServerSideDatasource = () => {
 return {
   getRows: async (params) => {
     const response = await getTableRows(params.request) //api call
     if (response.success) {
       params.success({ rowData: response.rows, rowCount: response.lastRow
     })
    } else {
      params.fail()
     }
},}}

Ag-grid call api twice, once with empty filters, and next with my filters
I want call api only once with my filters, perhaps there is different way to set default/initialize filters in ag-grid than api.setFilterModel because I guess that put in internal event loop

setdatasource

call getRows

setFilter

trigger call getRows


问:
Pyspark put columns inside an array and then in a struct
I have this code:

```<code>test_2 = test.select(struct(
        col("transaction_start_date"),
        col("transaction_end_date"),
        col("batch_time_stamp"),
        col("batch_id"),
         array(
            struct(col("vin"),
            col("number_of_outbound_calls"),
            col("number_of_inbound_calls")).alias("sad")
           ).alias("batch_data")).alias("transactionRecord"))
</code>```

The schema is:

```<code>root
 |-- transactionRecord: struct (nullable = false)
 |    |-- transaction_start_date: string (nullable = false)
 |    |-- transaction_end_date: string (nullable = false)
 |    |-- batch_time_stamp: string (nullable = false)
 |    |-- batch_id: string (nullable = false)
 |    |-- batch_data: array (nullable = false)
 |    |    |-- element: struct (containsNull = false)
 |    |    |    |-- vin: string (nullable = false)
 |    |    |    |-- number_of_outbound_calls: long (nullable = true)
 |    |    |    |-- number_of_inbound_calls: long (nullable = true)
</code>```

But i need this

```<code>root
 |-- transactionRecord: struct (nullable = false)
 |    |-- transaction_start_date: string (nullable = false)
 |    |-- transaction_end_date: string (nullable = false)
 |    |-- batch_time_stamp: string (nullable = false)
 |    |-- batch_id: string (nullable = false)
 |    |-- batch_data: array (nullable = false)
 |    |    |-- sad: struct (nullable = false)
 |    |    |    |-- vin: string (nullable = false)
 |    |    |    |-- number_of_outbound_calls: long (nullable = true)
 |    |    |    |-- number_of_inbound_calls: long (nullable = true)
</code>```

I need inside array will be a struct and put alias to this struct. I tried but I dont know the code dosent work

Body:
I have this code:

test_2 = test.select(struct(
        col("transaction_start_date"),
        col("transaction_end_date"),
        col("batch_time_stamp"),
        col("batch_id"),
         array(
            struct(col("vin"),
            col("number_of_outbound_calls"),
            col("number_of_inbound_calls")).alias("sad")
           ).alias("batch_data")).alias("transactionRecord"))

The schema is:

root
 |-- transactionRecord: struct (nullable = false)
 |    |-- transaction_start_date: string (nullable = false)
 |    |-- transaction_end_date: string (nullable = false)
 |    |-- batch_time_stamp: string (nullable = false)
 |    |-- batch_id: string (nullable = false)
 |    |-- batch_data: array (nullable = false)
 |    |    |-- element: struct (containsNull = false)
 |    |    |    |-- vin: string (nullable = false)
 |    |    |    |-- number_of_outbound_calls: long (nullable = true)
 |    |    |    |-- number_of_inbound_calls: long (nullable = true)

But i need this

root
 |-- transactionRecord: struct (nullable = false)
 |    |-- transaction_start_date: string (nullable = false)
 |    |-- transaction_end_date: string (nullable = false)
 |    |-- batch_time_stamp: string (nullable = false)
 |    |-- batch_id: string (nullable = false)
 |    |-- batch_data: array (nullable = false)
 |    |    |-- sad: struct (nullable = false)
 |    |    |    |-- vin: string (nullable = false)
 |    |    |    |-- number_of_outbound_calls: long (nullable = true)
 |    |    |    |-- number_of_inbound_calls: long (nullable = true)

I need inside array will be a struct and put alias to this struct. I tried but I dont know the code dosent work


问:
using statements are always necessary? Or It can be avoid?
I have a noob question, it is always necessary to have using(MySqlDataAdapter ...) and using(MySqlCommand)? Or This is a bad idea?

for example, I have this code:

```<code> using (MySqlConnection connection = new MySqlConnection(GlobalVariables.connectionSQL))
 {
    connection.Open();
    using (MySqlCommand cmd = new MySqlCommand(consulta, connection))
    {
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            int cantImgs = 0;
            string nument = "";

            while (reader.Read())
            {
                ObjetctList list = new ObjectList();
                list.listNumber = reader["Number"].ToString();
            }
            foreach (var list in listViewModels)
            {
                if (nument != list.listNumber )
                {
                    cantImgs++;
                }
                nument = list.listNumber ;
            }

            if (cantImgs == 0)
            {
                ViewData["EntregasInexistentes"] = "No Data.";
            }
        }
        return listViewModels;
    }
}
try
{
    using (MySqlConnection connection = new MySqlConnection(GlobalVariables.connectionSQL))
    {
        connection.Open();
        using (MySqlCommand cmd = new MySqlCommand(consulta, connection))
        {
            cmd.CommandType = System.Data.CommandType.Text;
            using (MySqlDataReader mySqlDataReader = cmd.ExecuteReader())

            return true;
        }
    }
}
</code>```

Is this Ok? Or is not necessary to have using inside a using? I know that the first statement (using (MySqlConnection connection = new MySqlConnection(GlobalVariables.connectionSQL)) is ok because I need to autommatically close the connection when is all over...

Body:
I have a noob question, it is always necessary to have using(MySqlDataAdapter ...) and using(MySqlCommand)? Or This is a bad idea?

for example, I have this code:

 using (MySqlConnection connection = new MySqlConnection(GlobalVariables.connectionSQL))
 {
    connection.Open();
    using (MySqlCommand cmd = new MySqlCommand(consulta, connection))
    {
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            int cantImgs = 0;
            string nument = "";

            while (reader.Read())
            {
                ObjetctList list = new ObjectList();
                list.listNumber = reader["Number"].ToString();
            }
            foreach (var list in listViewModels)
            {
                if (nument != list.listNumber )
                {
                    cantImgs++;
                }
                nument = list.listNumber ;
            }

            if (cantImgs == 0)
            {
                ViewData["EntregasInexistentes"] = "No Data.";
            }
        }
        return listViewModels;
    }
}
try
{
    using (MySqlConnection connection = new MySqlConnection(GlobalVariables.connectionSQL))
    {
        connection.Open();
        using (MySqlCommand cmd = new MySqlCommand(consulta, connection))
        {
            cmd.CommandType = System.Data.CommandType.Text;
            using (MySqlDataReader mySqlDataReader = cmd.ExecuteReader())

            return true;
        }
    }
}

Is this Ok? Or is not necessary to have using inside a using? I know that the first statement (using (MySqlConnection connection = new MySqlConnection(GlobalVariables.connectionSQL)) is ok because I need to autommatically close the connection when is all over...


问:
Spinner has data but doesn't have any preview text/selected text
Spinner has data but doesn't have any preview text/selected text I try various things and still doesn't show any text

Im trying to use spinner for some data and I successfully populated some list for spinner data but it doesn't show any in the spinner.

I also try various things i saw from the net and it didnt work.

Here is the link where I based my code for spinner: https://www.youtube.com/watch?v=j7P5k-dHS9Y

JAVA CODE:

```<code> public class SpinnerSample extends AppCompatActivity {
    Spinner spinner;
    boolean isSpinnerTouched = false;
    DatabaseReference databaseReference;
    String[] status = {"Not Available", "Available", "Under Maintenance"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_sample);
        spinner = findViewById(R.id.spiiner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(SpinnerSample.this, R.layout.style_spinner, status);
        adapter.setDropDownViewResource(R.layout.style_spinner);
        spinner.setAdapter(adapter);
        databaseReference = FirebaseDatabase.getInstance().getReference();
        spinner.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isSpinnerTouched = true;
                return false;
            }
        });
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String value = adapterView.getItemAtPosition(i).toString();

                if (!isSpinnerTouched) {
                    Toast.makeText(SpinnerSample.this, "No Selected", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(SpinnerSample.this, value, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
</code>```

XML CODE:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SpinnerSample">

        <Spinner
            android:id="@+id/spiiner"
            android:layout_width="240dp"
            android:background="#ff0"
            android:layout_height="40dp"
            android:textColor="#000"
            android:hint="Current Password"
            android:layout_marginTop="10dp"/>

</LinearLayout>

</code>```
```<code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:text="A"
    android:padding="20dp"
    android:layout_height="match_parent"
    android:textColor="#000"
    android:textColorHint="#1e7591">

</TextView>
</code>```

Body:
Spinner has data but doesn't have any preview text/selected text I try various things and still doesn't show any text

Im trying to use spinner for some data and I successfully populated some list for spinner data but it doesn't show any in the spinner.

I also try various things i saw from the net and it didnt work.

Here is the link where I based my code for spinner: https://www.youtube.com/watch?v=j7P5k-dHS9Y

JAVA CODE:

 public class SpinnerSample extends AppCompatActivity {
    Spinner spinner;
    boolean isSpinnerTouched = false;
    DatabaseReference databaseReference;
    String[] status = {"Not Available", "Available", "Under Maintenance"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_sample);
        spinner = findViewById(R.id.spiiner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(SpinnerSample.this, R.layout.style_spinner, status);
        adapter.setDropDownViewResource(R.layout.style_spinner);
        spinner.setAdapter(adapter);
        databaseReference = FirebaseDatabase.getInstance().getReference();
        spinner.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isSpinnerTouched = true;
                return false;
            }
        });
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String value = adapterView.getItemAtPosition(i).toString();

                if (!isSpinnerTouched) {
                    Toast.makeText(SpinnerSample.this, "No Selected", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(SpinnerSample.this, value, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

XML CODE:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SpinnerSample">

        <Spinner
            android:id="@+id/spiiner"
            android:layout_width="240dp"
            android:background="#ff0"
            android:layout_height="40dp"
            android:textColor="#000"
            android:hint="Current Password"
            android:layout_marginTop="10dp"/>

</LinearLayout>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:text="A"
    android:padding="20dp"
    android:layout_height="match_parent"
    android:textColor="#000"
    android:textColorHint="#1e7591">

</TextView>


问:
Scrolling speeds up on calling a requestanimationframe multiple times
I'm trying to create a slider with an image gallery and to make it scroll smooth using the requestAnimationFrame.
It works almost perfect except one thing. If you slide more then 2 times in any direction the scroll speeds up and it looks bad. I would like to have the same speed every time I slide to right or left.
Can anyone give me a hint of how to do that?</p>
```<code>              var currentPos = -200;
              var incrementer = .05;
              var id;

              function scrollNext() {

                incrementer += 1;
                currentPos = Math.pow(1.05, incrementer);

                item.scrollLeft += currentPos;

                id = requestAnimationFrame(scrollNext);

                if (!curr_slide.nextElementSibling) {
                  if (item.scrollLeft >= curr_slide.offsetLeft) {
                    item.scrollTo(curr_slide.offsetLeft, 0);
                    cancelAnimationFrame(id);
                  }
                  if (item.scrollLeft < curr_slide.offsetLeft) {
                    item.scrollTo(curr_slide.offsetLeft, 0);
                    cancelAnimationFrame(id);
                  }
                } else {
                  if (item.scrollLeft >= curr_slide.nextElementSibling.offsetLeft) {
                    item.scrollTo(curr_slide.nextElementSibling.offsetLeft, 0);
                    cancelAnimationFrame(id);
                  }
                }
              }

              scrollNext();
              curr_slide.nextElementSibling.classList.add('activeSlide');
              curr_dot.nextElementSibling.classList.add('currentDot');

</code>```

Body:
I'm trying to create a slider with an image gallery and to make it scroll smooth using the requestAnimationFrame.
It works almost perfect except one thing. If you slide more then 2 times in any direction the scroll speeds up and it looks bad. I would like to have the same speed every time I slide to right or left.
Can anyone give me a hint of how to do that?

              var currentPos = -200;
              var incrementer = .05;
              var id;

              function scrollNext() {

                incrementer += 1;
                currentPos = Math.pow(1.05, incrementer);

                item.scrollLeft += currentPos;

                id = requestAnimationFrame(scrollNext);

                if (!curr_slide.nextElementSibling) {
                  if (item.scrollLeft >= curr_slide.offsetLeft) {
                    item.scrollTo(curr_slide.offsetLeft, 0);
                    cancelAnimationFrame(id);
                  }
                  if (item.scrollLeft < curr_slide.offsetLeft) {
                    item.scrollTo(curr_slide.offsetLeft, 0);
                    cancelAnimationFrame(id);
                  }
                } else {
                  if (item.scrollLeft >= curr_slide.nextElementSibling.offsetLeft) {
                    item.scrollTo(curr_slide.nextElementSibling.offsetLeft, 0);
                    cancelAnimationFrame(id);
                  }
                }
              }

              scrollNext();
              curr_slide.nextElementSibling.classList.add('activeSlide');
              curr_dot.nextElementSibling.classList.add('currentDot');


问:
Why does the URL string of my API filter have a forward slash instead of an equal sign?
The request for an ID does return a record correctly, but the URL has the record being searched in front of a "/" in the address bar:

```<code>http://fastapi.localhost:8008/person/2
</code>```

Below is my request paramter for a GET request:

```<code>@app.get("/person/{id}", tags=["API Endpoint"])
async def get_persons(id: int | None = None, person: str | None = None, yesno: str | None = None):
    id_list = await Person.objects.get(pk=id)
    return id_list
</code>```

And the response_model is structured as follows:

```<code>class Person(ormar.Model):
class Meta(BaseMeta):
    tablename = str = "persons"

id: int = ormar.Integer(primary_key=True)
person: str = ormar.String(max_length=250, nullable=True)
yesno: str = ormar.String(max_length=4, nullable=True)
</code>```

Ideally, the URL would have the equal sign:

```<code>http://fastapi.localhost:8008/person=2
</code>```

Please let me know if there's any additional information I can provide and thank you in advance.

Body:
The request for an ID does return a record correctly, but the URL has the record being searched in front of a "/" in the address bar:

http://fastapi.localhost:8008/person/2

Below is my request paramter for a GET request:

@app.get("/person/{id}", tags=["API Endpoint"])
async def get_persons(id: int | None = None, person: str | None = None, yesno: str | None = None):
    id_list = await Person.objects.get(pk=id)
    return id_list

And the response_model is structured as follows:

class Person(ormar.Model):
class Meta(BaseMeta):
    tablename = str = "persons"

id: int = ormar.Integer(primary_key=True)
person: str = ormar.String(max_length=250, nullable=True)
yesno: str = ormar.String(max_length=4, nullable=True)

Ideally, the URL would have the equal sign:

http://fastapi.localhost:8008/person=2

Please let me know if there's any additional information I can provide and thank you in advance.


问:
Error: The process '/usr/local/bin/npx' failed with exit code 1
error

Hallo, I got the following message from Github while deploying to firebase :

Run failed: Deploy to Firebase Hosting on merge - master (bb2f1f1)

build_and_deploy

npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142

```<code>"status": "error",
"error": "Directory 'dist/Ghomala' for Hosting does not exist."
</code>```

```<code>"status": "error",
"error": "Directory 'dist/Ghomala' for Hosting does not exist."
</code>```

The process '/usr/local/bin/npx' failed with exit code 1
Retrying deploy with the --debug flag for better error output

i  hosting[lanye-ghomala]: beginning deploy...

Error: Directory 'dist/Ghomala' for Hosting does not exist.

The process '/usr/local/bin/npx' failed with exit code 1
Error: The process '/usr/local/bin/npx' failed with exit code 1

```<code>conclusion: 'failure',
output: ***
  title: 'Deploy preview failed',
  summary: "Error: The process '/usr/local/bin/npx' failed with exit code 1"
***
</code>```

Body:
error

Hallo, I got the following message from Github while deploying to firebase :

Run failed: Deploy to Firebase Hosting on merge - master (bb2f1f1)

build_and_deploy

npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142

"status": "error",
"error": "Directory 'dist/Ghomala' for Hosting does not exist."

"status": "error",
"error": "Directory 'dist/Ghomala' for Hosting does not exist."

The process '/usr/local/bin/npx' failed with exit code 1
Retrying deploy with the --debug flag for better error output

i  hosting[lanye-ghomala]: beginning deploy...

Error: Directory 'dist/Ghomala' for Hosting does not exist.

The process '/usr/local/bin/npx' failed with exit code 1
Error: The process '/usr/local/bin/npx' failed with exit code 1

conclusion: 'failure',
output: ***
  title: 'Deploy preview failed',
  summary: "Error: The process '/usr/local/bin/npx' failed with exit code 1"
***


问:
xpath find a CSS attribute from DOM not inline
See my code here of my scenarioI have this scenario and I need to use xpath to validate the image, and the gradient colors are present. I tried all kind of xpath combination but still getting errors or not finding it. Many other samples have the style in-line. In this case  has a "." class outside of a close tag. code in the image

Could some offer a hand?your text


问:
If I use hooks that updates like useContext, would it make it NOT a candidate for React.memo()?
For obviously pure components like

```<code>function DefinitelyPure({label}:{label:string}) {
  return <View><Text>{label</Text></View>
}
</code>```

I know I can safely make this memoized as

```<code>const DefinitelyPure= React.memo(function ({label}:{label:string}) {
  return <View><Text>{label</Text></View>
});
DefinitelyPure.displayName = "DefinitelyPure";
</code>```

However, what if I have something like

```<code>function DefinitelyPure({label}:{label:string}) {
  const theme = useTheme();
  return <View style={{backgroundColor: theme.primary.backgroundColor}}><Text>{label</Text></View>
}
</code>```

where useTheme() can change when the user switches themes in the app.  Would the memoized component know to rerender when the context changes? (I am thinking no)

I am only asking for useContext, since that one should trigger a rerender when the context changes and it's on the top level, and not other hooks like useState

Body:
For obviously pure components like

function DefinitelyPure({label}:{label:string}) {
  return <View><Text>{label</Text></View>
}

I know I can safely make this memoized as

const DefinitelyPure= React.memo(function ({label}:{label:string}) {
  return <View><Text>{label</Text></View>
});
DefinitelyPure.displayName = "DefinitelyPure";

However, what if I have something like

function DefinitelyPure({label}:{label:string}) {
  const theme = useTheme();
  return <View style={{backgroundColor: theme.primary.backgroundColor}}><Text>{label</Text></View>
}

where useTheme() can change when the user switches themes in the app.  Would the memoized component know to rerender when the context changes? (I am thinking no)

I am only asking for useContext, since that one should trigger a rerender when the context changes and it's on the top level, and not other hooks like useState


问:
Kotlin annotation changing of target
I have a annotation AggregateId that could be set on method params and properties and that I will use to retrieve some id :

```<code>@Target(AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
annotation class AggregateId
</code>```

I wrote that test case :

```<code>data class Example(
    @AggregateId
    val id: UUID
)

class AggregateIdTests {

    private val exUuid = UUID.fromString("bae30706-f949-4eb5-b091-d51a13ddc832")

    @Test
    fun test() {
        val ex = Example(id = exUuid)
        val id = resolve(ex)

        Assertions.assertThat(id).isEqualTo(exUuid)
    }

    private fun resolve(target: Any): UUID? {
        val prop = target::class.declaredMemberProperties.find {
            it.findAnnotation<AggregateId>() != null
        }

        return prop?.getter?.call(target) as UUID?
    }
}
</code>```

That actually works.
But if I add this class in the code :

```<code>class TestClass {
    fun aMethod(@AggregateId param: UUID) {

    }
}
</code>```

Suddently the AggregateId changes of target for the other class. Even though I didn't change the rest of the code. What is the explaination of this ?
(using kotlin 1.5)

Title: Kotlin annotation changing of target

Body:
I have a annotation AggregateId that could be set on method params and properties and that I will use to retrieve some id :

@Target(AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
annotation class AggregateId

I wrote that test case :

data class Example(
    @AggregateId
    val id: UUID
)

class AggregateIdTests {

    private val exUuid = UUID.fromString("bae30706-f949-4eb5-b091-d51a13ddc832")

    @Test
    fun test() {
        val ex = Example(id = exUuid)
        val id = resolve(ex)

        Assertions.assertThat(id).isEqualTo(exUuid)
    }

    private fun resolve(target: Any): UUID? {
        val prop = target::class.declaredMemberProperties.find {
            it.findAnnotation<AggregateId>() != null
        }

        return prop?.getter?.call(target) as UUID?
    }
}

That actually works.
But if I add this class in the code :

class TestClass {
    fun aMethod(@AggregateId param: UUID) {

    }
}

Suddently the AggregateId changes of target for the other class. Even though I didn't change the rest of the code. What is the explaination of this ?
(using kotlin 1.5)


问:
React. Headless UI Menu Items can't receive focus on keyboard navigation
I have a dropdown menu builth with Headless UI Menu component, but the menu links inside this dropdown are not getting focused on keyboard navigation.

my code goes something like so:

```<code>function Dropdown(parent, children) {

    return (
        <Menu as="div" className="Submenu">
            {
                ({close}) => (
                    <>
                        <Menu.Button>
                            { parent.label }
                        </Menu.Button>
                        <Menu.Items as="ul" className="subitems">
                            {
                                children.map(child => (
                                    <Menu.Item as="li" className="subitem" key={ child.id }>
                                        <Link href={ child.link }>
                                            {  child.label }
                                        </Link>
                                    </Menu.Item>
                                ))
                            }
                        </Menu.Items>
                    </>
                )
            }
        </Menu>
    );
}
</code>```

The only thing getting the focus is the
</ul that wraps the items, but once I press tab the dropdown closes and the focus goes to the next item on the parent level menu.

The final html rendered is this:

I've tried to add tabIndex={0} to the  tags, but the output stays the same.
I also tried to create a Link wrapper component ike suggested here, but it didn't work.

Body:
I have a dropdown menu builth with Headless UI Menu component, but the menu links inside this dropdown are not getting focused on keyboard navigation.

my code goes something like so:

function Dropdown(parent, children) {

    return (
        <Menu as="div" className="Submenu">
            {
                ({close}) => (
                    <>
                        <Menu.Button>
                            { parent.label }
                        </Menu.Button>
                        <Menu.Items as="ul" className="subitems">
                            {
                                children.map(child => (
                                    <Menu.Item as="li" className="subitem" key={ child.id }>
                                        <Link href={ child.link }>
                                            {  child.label }
                                        </Link>
                                    </Menu.Item>
                                ))
                            }
                        </Menu.Items>
                    </>
                )
            }
        </Menu>
    );
}

The only thing getting the focus is the
</ul that wraps the items, but once I press tab the dropdown closes and the focus goes to the next item on the parent level menu.

The final html rendered is this:

I've tried to add tabIndex={0} to the  tags, but the output stays the same.
I also tried to create a Link wrapper component ike suggested here, but it didn't work.


问:
Localdate json formatting
In a rest controller of a spring boot 3 application,

```<code>@GetMapping("/invoices")
    public Page<InvoiceDto> getInvoices(@RequestParam Long clientId, @PageableDefault(direction = Sort.Direction.DESC,sort = "dateCreation" )Pageable pageable){

....

}

public record InvoiceDto(
    long clientId,
    @JsonFormat(pattern="yyyy-MM-dd")
    LocalDate dateCreation
)
{
}
</code>```

When I do a test with postman,

for a localdate, i get

```<code>"dateCreation":[2018,2,15]
</code>```

I was thinking to get

```<code>"dateCreation":"2018-2-15"
</code>```

Title: Localdate json formatting

Body:
In a rest controller of a spring boot 3 application,

@GetMapping("/invoices")
    public Page<InvoiceDto> getInvoices(@RequestParam Long clientId, @PageableDefault(direction = Sort.Direction.DESC,sort = "dateCreation" )Pageable pageable){

....

}

public record InvoiceDto(
    long clientId,
    @JsonFormat(pattern="yyyy-MM-dd")
    LocalDate dateCreation
)
{
}

When I do a test with postman,

for a localdate, i get

"dateCreation":[2018,2,15]

I was thinking to get

"dateCreation":"2018-2-15"


问:
specify port with dns in google domains
I have a web server and a minecraft server and I need to set my minecraft servers subdomain on the same network as the web server so I need dns to do this:

mc.mydomain.net => myip:25565
www.mydomain.net => myip:80

My mc srv record looks like this "0 0 25565 myip".
Now I have the last thing working, but the minecraft server does not work.

I also tried using a srv record but that failed.

Title: specify port with dns in google domains