问:
C# UWP: The parameter is incorrect - NavigationView
I'm building a UWP in C# with Visual Studio, and need to hide and show a NavigationView, named 'navigationView' as required.
I am using the property .IsPaneVisible to achieve this, but am encountering a strange bug:

I can set IsPaneVisible = true or false in the xaml document, but if I set navigationView.IsPaneVisible = false; in the related C# document, and run a debug build of the app from Visual Studio, the app crashes with the error

System.ArgumentException: 'The parameter is incorrect.

Even stranger, if I run the same debug build, but launched directly, outside Visual Studio, the app functions normally without crashing at this line.

Does anyone have an idea of why this might be happening or how I could fix it?

Here's the xaml code:

```<code><Page
    x:Class="Sheet_Music_Reader.Views.ShellPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    xmlns:behaviors="using:Sheet_Music_Reader.Behaviors"
    xmlns:winui="using:Microsoft.UI.Xaml.Controls"
    xmlns:helpers="using:Sheet_Music_Reader.Helpers"
    xmlns:views="using:Sheet_Music_Reader.Views"
    Loaded="OnLoaded"
    mc:Ignorable="d">
    <Page.Resources>
        <!--This top margin is the height of the custom TitleBar-->
        <Thickness x:Key="NavigationViewContentMargin">0,48,0,0</Thickness>
        <Thickness x:Key="NavigationViewContentGridBorderThickness">0</Thickness>
        <SolidColorBrush x:Key="NavigationViewContentBackground" Color="Transparent"></SolidColorBrush>
    </Page.Resources>

    <Grid>
        <Border x:Name="AppTitleBar"
                IsHitTestVisible="True"
                VerticalAlignment="Top"
                Background="Transparent"
                Height="40"
                Canvas.ZIndex="1"
                Margin="48,8,0,0">
            <StackPanel Orientation="Horizontal">
                <Image x:Name="AppFontIcon"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Center"
                    Source="Assets/Square44x44Logo.png"
                    Width="16"
                    Height="16"/>
                <TextBlock x:Name="AppTitle"
                    Text="enScore"
                    VerticalAlignment="Center"
                    Margin="12,0,0,0"
                    Style="{ThemeResource CaptionTextBlockStyle}"/>
            </StackPanel>
        </Border>

        <winui:NavigationView
            IsBackButtonVisible="Visible"
            IsBackEnabled="{x:Bind IsBackEnabled, Mode=OneWay}"
            SelectedItem="{x:Bind Selected, Mode=OneWay}"
            ItemInvoked="OnItemInvoked"
            IsSettingsVisible="True"
            IsTitleBarAutoPaddingEnabled="False"
            DisplayModeChanged="NavigationViewControl_DisplayModeChanged"
            Canvas.ZIndex="0"
            x:Name="navigationView">
            <winui:NavigationView.MenuItems>

                <winui:NavigationViewItem x:Uid="Shell_Main" Icon="Copy" helpers:NavHelper.NavigateTo="views:MainPage" />

            </winui:NavigationView.MenuItems>

            <i:Interaction.Behaviors>
                <behaviors:NavigationViewHeaderBehavior
                DefaultHeader="{x:Bind Selected.Content, Mode=OneWay}">
                    <behaviors:NavigationViewHeaderBehavior.DefaultHeaderTemplate>
                        <DataTemplate>
                            <Grid x:Name="headerGrid">
                                <TextBlock
                                Text="{Binding}"
                                Style="{ThemeResource TitleTextBlockStyle}"
                                Margin="{StaticResource SmallLeftRightMargin}" />
                                <Button Style="{ThemeResource ButtonRevealStyle}"  Content="Refresh Library Contents" HorizontalAlignment="Right" Margin="0,45,8,0" Click="RefreshLibrary"/>
                                <Button Style="{ThemeResource ButtonRevealStyle}" Content="Import PDF To Current Folder" HorizontalAlignment="Right" Margin="0,-35,140,0" Click="AddScore"/>
                                <Button Style="{ThemeResource ButtonRevealStyle}" Content="Add New Folder" HorizontalAlignment="Right" Margin="0,-35,8,0" Click="AddFolderAsync"/>
                                <ToggleButton Style="{ThemeResource ToggleButtonRevealStyle}"  x:FieldModifier="public" x:Name="tbtndelete" Content="Delete Items" HorizontalAlignment="Right" Margin="0,45,191,0" Tapped="DeleteItem"/>
                            </Grid>
                        </DataTemplate>
                    </behaviors:NavigationViewHeaderBehavior.DefaultHeaderTemplate>
                </behaviors:NavigationViewHeaderBehavior>
            </i:Interaction.Behaviors>
            <Grid>
                <Frame x:Name="shellFrame" />
            </Grid>
        </winui:NavigationView>

    </Grid>

</Page>
</code>```

答:
Try to change the placement of the menu with:

```<code>PaneDisplayMode="Top"
</code>```

For my case with Microsoft.UI.Xaml.Controls for Microsoft.WindowsAppSDK v1.0.0.
the showing/hidding of menu bar works fine.

Left, LeftMinimal, LeftCompact crashes the app.
I know you may expect the menu on the left, but still on the top is not that bad idea ;-) At least it works.. Greetz.

Body:
I'm building a UWP in C# with Visual Studio, and need to hide and show a NavigationView, named 'navigationView' as required.
I am using the property .IsPaneVisible to achieve this, but am encountering a strange bug:

I can set IsPaneVisible = true or false in the xaml document, but if I set navigationView.IsPaneVisible = false; in the related C# document, and run a debug build of the app from Visual Studio, the app crashes with the error

System.ArgumentException: 'The parameter is incorrect.

Even stranger, if I run the same debug build, but launched directly, outside Visual Studio, the app functions normally without crashing at this line.

Does anyone have an idea of why this might be happening or how I could fix it?

Here's the xaml code:

<Page
    x:Class="Sheet_Music_Reader.Views.ShellPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    xmlns:behaviors="using:Sheet_Music_Reader.Behaviors"
    xmlns:winui="using:Microsoft.UI.Xaml.Controls"
    xmlns:helpers="using:Sheet_Music_Reader.Helpers"
    xmlns:views="using:Sheet_Music_Reader.Views"
    Loaded="OnLoaded"
    mc:Ignorable="d">
    <Page.Resources>

        <Thickness x:Key="NavigationViewContentMargin">0,48,0,0</Thickness>
        <Thickness x:Key="NavigationViewContentGridBorderThickness">0</Thickness>
        <SolidColorBrush x:Key="NavigationViewContentBackground" Color="Transparent"></SolidColorBrush>
    </Page.Resources>

    <Grid>
        <Border x:Name="AppTitleBar"
                IsHitTestVisible="True"
                VerticalAlignment="Top"
                Background="Transparent"
                Height="40"
                Canvas.ZIndex="1"
                Margin="48,8,0,0">
            <StackPanel Orientation="Horizontal">
                <Image x:Name="AppFontIcon"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Center"
                    Source="Assets/Square44x44Logo.png"
                    Width="16"
                    Height="16"/>
                <TextBlock x:Name="AppTitle"
                    Text="enScore"
                    VerticalAlignment="Center"
                    Margin="12,0,0,0"
                    Style="{ThemeResource CaptionTextBlockStyle}"/>
            </StackPanel>
        </Border>

        <winui:NavigationView
            IsBackButtonVisible="Visible"
            IsBackEnabled="{x:Bind IsBackEnabled, Mode=OneWay}"
            SelectedItem="{x:Bind Selected, Mode=OneWay}"
            ItemInvoked="OnItemInvoked"
            IsSettingsVisible="True"
            IsTitleBarAutoPaddingEnabled="False"
            DisplayModeChanged="NavigationViewControl_DisplayModeChanged"
            Canvas.ZIndex="0"
            x:Name="navigationView">
            <winui:NavigationView.MenuItems>

                <winui:NavigationViewItem x:Uid="Shell_Main" Icon="Copy" helpers:NavHelper.NavigateTo="views:MainPage" />

            </winui:NavigationView.MenuItems>

                <behaviors:NavigationViewHeaderBehavior
                DefaultHeader="{x:Bind Selected.Content, Mode=OneWay}">
                    <behaviors:NavigationViewHeaderBehavior.DefaultHeaderTemplate>
                        <DataTemplate>
                            <Grid x:Name="headerGrid">
                                <TextBlock
                                Text="{Binding}"
                                Style="{ThemeResource TitleTextBlockStyle}"
                                Margin="{StaticResource SmallLeftRightMargin}" />
                                <Button Style="{ThemeResource ButtonRevealStyle}"  Content="Refresh Library Contents" HorizontalAlignment="Right" Margin="0,45,8,0" Click="RefreshLibrary"/>
                                <Button Style="{ThemeResource ButtonRevealStyle}" Content="Import PDF To Current Folder" HorizontalAlignment="Right" Margin="0,-35,140,0" Click="AddScore"/>
                                <Button Style="{ThemeResource ButtonRevealStyle}" Content="Add New Folder" HorizontalAlignment="Right" Margin="0,-35,8,0" Click="AddFolderAsync"/>
                                <ToggleButton Style="{ThemeResource ToggleButtonRevealStyle}"  x:FieldModifier="public" x:Name="tbtndelete" Content="Delete Items" HorizontalAlignment="Right" Margin="0,45,191,0" Tapped="DeleteItem"/>
                            </Grid>
                        </DataTemplate>
                    </behaviors:NavigationViewHeaderBehavior.DefaultHeaderTemplate>
                </behaviors:NavigationViewHeaderBehavior>

            <Grid>
                <Frame x:Name="shellFrame" />
            </Grid>
        </winui:NavigationView>

    </Grid>

</Page>

Body:
Try to change the placement of the menu with:

PaneDisplayMode="Top"

For my case with Microsoft.UI.Xaml.Controls for Microsoft.WindowsAppSDK v1.0.0.
the showing/hidding of menu bar works fine.

Left, LeftMinimal, LeftCompact crashes the app.
I know you may expect the menu on the left, but still on the top is not that bad idea ;-) At least it works.. Greetz.


来源: stackexchange

问:
Subscribing to a Websockets topic in Svelte
Previously, I've used Stomp for Websockets on the client side, subscribing to a particular topic.  For example:

```<code>    const url = "ws://localhost:8080";

    //const socket = new SockJS(url);
    const socket = new WebSocket(url);
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function () {
        stompClient.subscribe('/topic/someTopic.*', function (output) {
            //parse the message
        });

        setConnected(true);
    }, function (err) {
        alert('Error: ' + err);
    });
</code>```

In Svelte and Node Websockets, I see ways of connecting such as:

```<code>let socket
onMount(() => {
  socket = new WebSocket("ws://localhost:8000/chat")
  socket.addEventListener("open", ()=> {
    console.log("Opened")
  })
})
</code>```

However, how would I subscribe to a particular topic?  Is there an alternative that would offer this?

答:
You can execute every javascript you want in a svelte component, just be sure that the DOM is yet rendered by calling it in the onMount:

```

ContentLicense: CC BY-SA 4.0

Body:
Previously, I've used Stomp for Websockets on the client side, subscribing to a particular topic.  For example:

    const url = "ws://localhost:8080";

    //const socket = new SockJS(url);
    const socket = new WebSocket(url);
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function () {
        stompClient.subscribe('/topic/someTopic.*', function (output) {
            //parse the message
        });

        setConnected(true);
    }, function (err) {
        alert('Error: ' + err);
    });

In Svelte and Node Websockets, I see ways of connecting such as:

let socket
onMount(() => {
  socket = new WebSocket("ws://localhost:8000/chat")
  socket.addEventListener("open", ()=> {
    console.log("Opened")
  })
})

However, how would I subscribe to a particular topic?  Is there an alternative that would offer this?

Body:
You can execute every javascript you want in a svelte component, just be sure that the DOM is yet rendered by calling it in the onMount:

<script>
  import { onMount } from 'svelte';
  const URL = "ws://localhost:8080";

  const subscribeToTopic = () => {
    //const socket = new SockJS(URL);
    const socket = new WebSocket(URL);
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function () {
        stompClient.subscribe('/topic/someTopic.*', function (output) {
            //parse the message
        });

        setConnected(true);
    }, function (err) {
        alert('Error: ' + err);
    });
  }

  onMount(() => {
    subscribeToTopic();
  });

</script>


问:
How to get Atlassian Bamboo repository caching to work with docker?
Atlassian Bamboo repository caching causes issue with docker:

```<code>error: object directory $BAMBOO_HOME/xml-data/build-dir/_git-repositories-cache/8454c6d4af76ff5751c9e2ecf0bd2d2371695eec/.git/objects does not exist; check .git/objects/info/alternates
error: Could not read d55f59e8de25d61533151b43092751e40269b31d
</code>```

Note that we don't use docker agent because of permission issues, and the need for elevated privilege and capabilities.

答:
The cache directory has to be added to docker as a volume using Bamboo's $bamboo_git_cache_directory environment variable:

```<code>docker run --rm -v $bamboo_git_cache_directory:$bamboo_git_cache_directory -v $(pwd):/workspace python:3.9 ...
</code>```

Body:
Atlassian Bamboo repository caching causes issue with docker:

error: object directory $BAMBOO_HOME/xml-data/build-dir/_git-repositories-cache/8454c6d4af76ff5751c9e2ecf0bd2d2371695eec/.git/objects does not exist; check .git/objects/info/alternates
error: Could not read d55f59e8de25d61533151b43092751e40269b31d

Note that we don't use docker agent because of permission issues, and the need for elevated privilege and capabilities.

Body:
The cache directory has to be added to docker as a volume using Bamboo's $bamboo_git_cache_directory environment variable:

docker run --rm -v $bamboo_git_cache_directory:$bamboo_git_cache_directory -v $(pwd):/workspace python:3.9 ...


问:
PostgreSQL Job Scheduler on Azure DB for PostgreSQL
In Azure Database for PostgreSQL, how do I install a pgAgent?
As, its a PaaS only, I will not have access to the Server. In that case, if I need a pgAgent to install, how do I do it?</p>

答: As per azure docs, it seems PgCron is available in flexible server type.</p>


问:
Text doesn't break in special case
I have a problem that the text doesn't break in a popup made with Vue.js which is included in the header like this:

The text breaks normally if I include the popup into the main screen, but doesn't if I include it into the header. I have also drawn border around the
 element which contains the text and the border is drawn correctly.

Here is the sample code: https://codesandbox.io/s/cold-feather-3zi3d?file=/src/components/BasicModal.vue

答:
You could add the following style rule :

```<code>white-space: pre-wrap;
</code>```

in :

```<code><p slot="modal-paragraph" style="border-style: solid;whitespace:pre-wrap">
</code>```

Title: Text doesn't break in special case

Body:
You could add the following style rule :

white-space: pre-wrap;

in :

<p slot="modal-paragraph" style="border-style: solid;whitespace:pre-wrap">


问:
How can i get the ActualWidth of Grid.Column, after changing its width using *?
In my c# wpf code i used to change programmaticaly the width of a grid column, like this :

```<code> mycolumn.Width = new GridLength(1, GridUnitType.Star);
</code>```

But later in code, when i try to get the "ActualWidth", at first time, the value of ActualWidth (that is in pixel) it's always 0. The value is updated later by the parent window, for some reason i don't know.

```<code>double myWidthInPixels = myColumn.ActualWidth;
</code>```

myWidthInPixels is set to 0, for the first time i ask it.

How to solve?

答:
The solution for me was this :</p>
```<code>double myWidthInPixels = Convert.ToDouble(myColumn.GetValue(WidthProperty));
</code>```

Body:
In my c# wpf code i used to change programmaticaly the width of a grid column, like this :

 mycolumn.Width = new GridLength(1, GridUnitType.Star);

But later in code, when i try to get the "ActualWidth", at first time, the value of ActualWidth (that is in pixel) it's always 0. The value is updated later by the parent window, for some reason i don't know.

double myWidthInPixels = myColumn.ActualWidth;

myWidthInPixels is set to 0, for the first time i ask it.

How to solve?

Body:
The solution for me was this :

double myWidthInPixels = Convert.ToDouble(myColumn.GetValue(WidthProperty));


问:
ContainsKey Thread Safe
In the following code:

```<code>public class StringCache
{
    private readonly object lockobj = new object();

    private readonly Dictionary<int, string> cache = new Dictionary<int, string>();

    public string GetMemberInfo(int key)
    {
        if (cache.ContainsKey(key))
            return cache[key];
        lock (lockobj)
        {
            if (!cache.ContainsKey(key))
                cache[key] = GetString(key);
        }
        return cache[key];
    }

    private static string GetString(int key)
    {
        return "Not Important";
    }
}
</code>```

1) Is ContainsKey thread safe?  IOW, what happens if that method is executing when another thread is adding something to the dictionary?
2) For the first return cache[key], is there any chance that it could return a garbled value?

TIA,

MB

答:
No, ContainsKey is not thread-safe if you're writing values while you're trying to read.

Yes, there is a chance you could get back invalid results -- but you'll probably start seeing exceptions first.

Take a look at the ReaderWriterLockSlim for locking in situations like this -- it's built to do this kind of stuff.

OwnerDisplayName: MBeckius

ContentLicense: CC BY-SA 2.5

Title: ContainsKey Thread Safe

Body:
In the following code:

public class StringCache
{
    private readonly object lockobj = new object();

    private readonly Dictionary<int, string> cache = new Dictionary<int, string>();

    public string GetMemberInfo(int key)
    {
        if (cache.ContainsKey(key))
            return cache[key];
        lock (lockobj)
        {
            if (!cache.ContainsKey(key))
                cache[key] = GetString(key);
        }
        return cache[key];
    }

    private static string GetString(int key)
    {
        return "Not Important";
    }
}

1) Is ContainsKey thread safe?  IOW, what happens if that method is executing when another thread is adding something to the dictionary?
2) For the first return cache[key], is there any chance that it could return a garbled value?

TIA,

MB

OwnerDisplayName: jsw


问:
UTF-8 to Unicode Code Points
Is there a function that will change UTF-8 to Unicode leaving non special characters as normal letters and numbers?

ie the German word "tchüß" would be rendered as something like "tch\20AC\21AC" (please note that I am making the Unicode codes up).

EDIT: I am experimenting with the following function, but although this one works well with ASCII 32-127, it seems to fail for double byte chars:

```<code>function strToHex ($string)
{
    $hex = '';
    for ($i = 0; $i < mb_strlen ($string, "utf-8"); $i++)
    {
        $id = ord (mb_substr ($string, $i, 1, "utf-8"));
        $hex .= ($id <= 128) ? mb_substr ($string, $i, 1, "utf-8") : "&#" . $id . ";";
}

    return ($hex);
}
</code>```

Any ideas?

EDIT 2: Found solution: The PHP ord() function does not work for double byte chars. Use instead: http://nl.php.net/manual/en/function.ord.php#78032

答:
For a readable-form I would go with JSON. It's not required to escape non-ASCII characters in JSON, but PHP does:</p>

```<code>echo json_encode("tchüß");

"tch\u00fc\u00df"
</code>```

ContentLicense: CC BY-SA 3.0

Title: UTF-8 to Unicode Code Points

Body:
Is there a function that will change UTF-8 to Unicode leaving non special characters as normal letters and numbers?

ie the German word "tchüß" would be rendered as something like "tch\20AC\21AC" (please note that I am making the Unicode codes up).

EDIT: I am experimenting with the following function, but although this one works well with ASCII 32-127, it seems to fail for double byte chars:

function strToHex ($string)
{
    $hex = '';
    for ($i = 0; $i < mb_strlen ($string, "utf-8"); $i++)
    {
        $id = ord (mb_substr ($string, $i, 1, "utf-8"));
        $hex .= ($id <= 128) ? mb_substr ($string, $i, 1, "utf-8") : "&#" . $id . ";";
}

    return ($hex);
}

Any ideas?

EDIT 2: Found solution: The PHP ord() function does not work for double byte chars. Use instead: http://nl.php.net/manual/en/function.ord.php#78032

Body:
For a readable-form I would go with JSON. It's not required to escape non-ASCII characters in JSON, but PHP does:

echo json_encode("tchüß");

"tch\u00fc\u00df"


问:
How do I manipulate an argument with mockito
I am using junit to run a few unit tests. One of these calls a method in an object that I mock using mockito like;

```<code>@Mock
private MyClass myClass;
</code>```

I then set up mockito to do something like

```<code>Mockito.when(myClass.foo(Mockito.any()).thenReturn(bar);
</code>```

Now myClass.foo actually takes another one of my classes (say class Person) as an argument and what I would like to do is something like this

```<code>Mockito.when(myClass.foo(Person parson)).thenDo(person.setName("Name")).thenReturn(bar);
</code>```

That is of course pseudo code but I hope it illustrates what I am trying to do. Is this possible?

答:
You need to use thenAnswer or its twin doAnswer method.

See Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

If your answers become too complicated, consider using a fake instead of a mock.

Body:
I am using junit to run a few unit tests. One of these calls a method in an object that I mock using mockito like;

@Mock
private MyClass myClass;

I then set up mockito to do something like

Mockito.when(myClass.foo(Mockito.any()).thenReturn(bar);

Now myClass.foo actually takes another one of my classes (say class Person) as an argument and what I would like to do is something like this

Mockito.when(myClass.foo(Person parson)).thenDo(person.setName("Name")).thenReturn(bar);

That is of course pseudo code but I hope it illustrates what I am trying to do. Is this possible?


问:
java static method for abstract class
I have a java abstract class that declares the extended class as "JsonSerializable"

public abstract class JsonSerializable {
    private final String path;

    public JsonSerializable(String path) {
        this.path = path;
    }
}
```
<p>Now, if I try to "load" a class that extends <code>JsonSerializable</code> I need to get the "filepath" for the class I want to load.
The way I am currently doing this is as follows:</p>
<pre class="lang-java prettyprint-override"><code>private static <T extends JsonSerializable> T getNew(Class<T> tClass) throws [...] {
        return tClass.getDeclaredConstructor().newInstance();
}
</code>```

But what if the constructing of a new class (of the type I am trying to load) has some side effects (e.g. upon initialization, the class "registers" itself inside another one) or if there IS no constructor with no arguments?

Is there any better way to do this? I don't want to create a "FileRegistry" class that just holds the file paths for each class.

答:
IMHO this looks more like a use case for an annotation @JsonSerializable(path="some.path") on the classes that you want to load.

The code could look like this:

```<code>// JsonSerializable.java
import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonSerializable {
    String path();
}
</code>```

The annotation would be used on a class like this:

```<code>// Options.java
@JsonSerializable(path="filepath.ending")
public class Options {
    private String example_property;
    private int example_property2;

    public Options() {
    }
}
</code>```

And the code that reads the annotation would then be:

```<code>private static <T> T getNew(Class<T> tClass) throws Exception {
    JsonSerializable annotation = tClass.getAnnotation(JsonSerializable.class);
    System.out.println(annotation.path()); // Just to show how the path is read
    // here you would insert code to read the class the way you need
    return tClass.getDeclaredConstructor().newInstance();
}
</code>```

Title: java static method for abstract class

Body:
I have a java abstract class that declares the extended class as "JsonSerializable"

public abstract class JsonSerializable {
    private final String path;

    public JsonSerializable(String path) {
        this.path = path;
    }
}

Now, if I try to "load" a class that extends JsonSerializable I need to get the "filepath" for the class I want to load.
The way I am currently doing this is as follows:

private static <T extends JsonSerializable> T getNew(Class<T> tClass) throws [...] {
        return tClass.getDeclaredConstructor().newInstance();
}

But what if the constructing of a new class (of the type I am trying to load) has some side effects (e.g. upon initialization, the class "registers" itself inside another one) or if there IS no constructor with no arguments?

Is there any better way to do this? I don't want to create a "FileRegistry" class that just holds the file paths for each class.

Body:
IMHO this looks more like a use case for an annotation @JsonSerializable(path="some.path") on the classes that you want to load.

The code could look like this:

// JsonSerializable.java
import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonSerializable {
    String path();
}

The annotation would be used on a class like this:

// Options.java
@JsonSerializable(path="filepath.ending")
public class Options {
    private String example_property;
    private int example_property2;

    public Options() {
    }
}

And the code that reads the annotation would then be:

private static <T> T getNew(Class<T> tClass) throws Exception {
    JsonSerializable annotation = tClass.getAnnotation(JsonSerializable.class);
    System.out.println(annotation.path()); // Just to show how the path is read
    // here you would insert code to read the class the way you need
    return tClass.getDeclaredConstructor().newInstance();
}


问:
How come two docker images have the same image ID and same tag, but different digests?
When I docker pull hello-world, I got the image with a digest of f9dfddf63636d84ef479d645ab5885156ae030f611a56f3a7ac7f2fdd86d7e4e

```<code>$ docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
Digest: sha256:f9dfddf63636d84ef479d645ab5885156ae030f611a56f3a7ac7f2fdd86d7e4e
Status: Image is up to date for hello-world:latest
docker.io/library/hello-world:latest
</code>```

I was using a Mac, but when I docker inspect hello-world:latest, I saw the os/arch is linux/amd64

```<code>    ...
    "Architecture": "amd64",
    "Os": "linux",
    ...
</code>```

So I went to https://hub.docker.com/_/hello-world/?tab=tags and found strangely enough, the latest hello-world for linux/amd64 is at https://hub.docker.com/layers/hello-world/library/hello-world/latest/images/sha256-92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a?context=explore with a digest of 92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a

So I pulled down this image as well

```<code>$ docker pull hello-world@sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a
sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a: Pulling from library/hello-world
Digest: sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a
Status: Downloaded newer image for hello-world@sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a
docker.io/library/hello-world@sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a
</code>```

Surprisingly, I ended up with two images with the same tag, same image ID, but different digests.

```<code>$ docker image ls --digests
REPOSITORY                    TAG                 DIGEST                                                                    IMAGE ID            CREATED             SIZE
hello-world                   latest              sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a   fce289e99eb9        15 months ago       1.84kB
hello-world                   latest              sha256:f9dfddf63636d84ef479d645ab5885156ae030f611a56f3a7ac7f2fdd86d7e4e   fce289e99eb9        15 months ago       1.84kB
</code>```

Are these two images the same one? How can I uniquely address an image if I want consistency across my team?

答:
-> This is how manifest works with docker. Config.digest file remains same for both images as they are pointing towards same configuration of layers.

->The digest used for docker pull represents the digest of image manifest which is stored in a registry. This digest is considered the root of a hash chain since the manifest itself contains the hash of the content which will be downloaded and imported into docker.

->See the schema 2 spec for a description of this manifest https://docs.docker.com/registry/spec/manifest-v2-2/. The image id used within docker can be found in this manifest as config.digest. This config represents the image configuration which will be used within docker.

->So you could say the manifest is the envelope and image is what is inside. The manifest digest will always be different than the image id BUT for any given manifest the same image id should always be produced.

->As it is a hash chain, we cannot guarantee that the manifest digest will always be the same for a given image id.

-> In most cases it should usually produce the same digest, we just cannot guarantee it but do a best effort. The possible difference in manifest digest is because we do not store gzipped blobs locally and exporting of layers may produce a different digest, even though the uncompressed content should remain the same.

->The image id itself verifies that uncompressed content is the same, this is what we mean when we say the image id is now a content addressable identifier.

Body:
When I docker pull hello-world, I got the image with a digest of f9dfddf63636d84ef479d645ab5885156ae030f611a56f3a7ac7f2fdd86d7e4e

$ docker pull hello-world
Using default tag: latest
latest: Pulling from library/hello-world
Digest: sha256:f9dfddf63636d84ef479d645ab5885156ae030f611a56f3a7ac7f2fdd86d7e4e
Status: Image is up to date for hello-world:latest
docker.io/library/hello-world:latest

I was using a Mac, but when I docker inspect hello-world:latest, I saw the os/arch is linux/amd64

    ...
    "Architecture": "amd64",
    "Os": "linux",
    ...

So I went to https://hub.docker.com/_/hello-world/?tab=tags and found strangely enough, the latest hello-world for linux/amd64 is at https://hub.docker.com/layers/hello-world/library/hello-world/latest/images/sha256-92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a?context=explore with a digest of 92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a

So I pulled down this image as well

$ docker pull hello-world@sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a
sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a: Pulling from library/hello-world
Digest: sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a
Status: Downloaded newer image for hello-world@sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a
docker.io/library/hello-world@sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a

Surprisingly, I ended up with two images with the same tag, same image ID, but different digests.

$ docker image ls --digests
REPOSITORY                    TAG                 DIGEST                                                                    IMAGE ID            CREATED             SIZE
hello-world                   latest              sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a   fce289e99eb9        15 months ago       1.84kB
hello-world                   latest              sha256:f9dfddf63636d84ef479d645ab5885156ae030f611a56f3a7ac7f2fdd86d7e4e   fce289e99eb9        15 months ago       1.84kB

Are these two images the same one? How can I uniquely address an image if I want consistency across my team?


问:
Apache Camel smtp component hangs the whole bus if mailserver is down
I have what I think is a very common scenario. I have an invoice system that is managed via Apache Camel. When something goes wrong I would like to have an email alert sent to the administrator.

After reading about Camel exception handling I came up with this: (inside my Spring XML)

```<code><!-- General retrasmission policy set to 3 times -->
        <errorHandler id="deadChannel" type="DeadLetterChannel"
            deadLetterUri="direct:invoice-error">
            <redeliveryPolicy maximumRedeliveries="2"
                redeliveryDelay="1000" backOffMultiplier="2" useExponentialBackOff="true" />
        </errorHandler>

        <!-- Problematic invoices create email alerts to the administrator -->
        <route id="invoices-with-errors">
            <from uri="direct:invoice-error" />
            <bean ref="emailAlert" method="handleProblematicInvoice" />
            <to
                uri="smtp://{{errormail.host}}?to={{errormail.to}}&subject={{errormail.subject}}&from={{errormail.from}};debugMode=true;connectionTimeout=5000" />
        </route>
</code>```

This works OK for my use case. When any exception is thrown an email is sent
indeed to the defined address.

However in order to test for corner cases I stopped the internal email server to see what
happens. I expected Camel to attempt an email send and stop trying after 5 seconds (as set in the connectionTimout option in the smpt URL above)

In reallity however the WHOLE Camel application hangs! This is simply unacceptable!
I cannot guarantee that the mail server will be up 100%.

Am I missing something here? Should I drop the idea of email alerts altogether or does Camel need another special option for NOT hanging when the mail server is down?

Answer

The line

```<code>debugMode=true;connectionTimeout=5000
</code>```

should be

```<code>debugMode=true&connectionTimeout=5000
</code>```

答:
Camel uses the Java Mail API, and thus is under its mercy how long time it takes to send an email or figure out something is wrong.

You can use the wireTap to async send the email. Then the error handler thread will not appear to block for a longer time
http://camel.apache.org/wire-tap

Body:
I have what I think is a very common scenario. I have an invoice system that is managed via Apache Camel. When something goes wrong I would like to have an email alert sent to the administrator.

After reading about Camel exception handling I came up with this: (inside my Spring XML)

        <errorHandler id="deadChannel" type="DeadLetterChannel"
            deadLetterUri="direct:invoice-error">
            <redeliveryPolicy maximumRedeliveries="2"
                redeliveryDelay="1000" backOffMultiplier="2" useExponentialBackOff="true" />
        </errorHandler>

        <route id="invoices-with-errors">
            <from uri="direct:invoice-error" />
            <bean ref="emailAlert" method="handleProblematicInvoice" />
            <to
                uri="smtp://{{errormail.host}}?to={{errormail.to}}&subject={{errormail.subject}}&from={{errormail.from}};debugMode=true;connectionTimeout=5000" />
        </route>

This works OK for my use case. When any exception is thrown an email is sent
indeed to the defined address.

However in order to test for corner cases I stopped the internal email server to see what
happens. I expected Camel to attempt an email send and stop trying after 5 seconds (as set in the connectionTimout option in the smpt URL above)

In reallity however the WHOLE Camel application hangs! This is simply unacceptable!
I cannot guarantee that the mail server will be up 100%.

Am I missing something here? Should I drop the idea of email alerts altogether or does Camel need another special option for NOT hanging when the mail server is down?

Answer

The line

debugMode=true;connectionTimeout=5000

should be

debugMode=true&connectionTimeout=5000


问:
How to snap a point in the normal 3d grid to a point on a sphere coordinate
So I need to snap any floating point in 3D space to the nearest point on a sphere, the size of the sphere also needs to change as the point gets further from the origin, idk if that made sense or I'm just thinking about something incorrectly, but I made a picture of it in blender:

In the picture I have green dots which represent the possible places(there are more of them) that any point in space could snap to.. So how can I make any point in space snap to the closest green dot? And IK I could just loop through those points to check the closest one, but there are gonna be MANY of these points so its not a solution and so any point has to find its closest green dot without distance checks. An example of how this could work if I didn't need it to be on a sphere is this,
So lets say I have point x, and I want to snap it to its closest green dot(here the green dot isn't a point on a sphere but actually a point on a "cartesian" grid), so to snap point x I just do round(x / gridSize) * gridSize; and that snaps x to its closest grid point, but in my case I need it on a sphere, so how can I convert that to snap to a spehre? IDK if I'm making any sesne.

答:
compute spherical coordinates a,b,r of point-center

where a=<0,2*PI> is longitude, b=<-PI/2,+PI/2> is latitude and r>=0 is radius

r=snapping_sphere_radius

snap a angle a= 2*PI*round(a*n/(2*PI))/n

where n is number snapping points on equator

snap b angle b= PI*round(b*m/PI)/m

where m is number of snapping circles (layers of sphere) usually m=n/2 ...

recompute Cartesian position of point from spherical (a,b,r) and add center


问:
How to get Profile photo from MSAL in Angular
I am getting the users Name and Email from MSAL graph, but I don't know how to get their profile photo from Microsoft account.

This is how I am getting name and email, it is working perfectly.

```<code>getName () : string {
      if (this.authService.instance.getActiveAccount() == null) {
        return 'unknown'
      }

      return this.authService.instance.getActiveAccount().name
    }
    getEmail () : string {
      if (this.authService.instance.getActiveAccount() == null) {
        return 'unknown'
      }

      return this.authService.instance.getActiveAccount().username
    }

    callProfile () {
      this.http.get("https://graph.microsoft.com/v1.0/me").subscribe( resp  => {
        this.apiResponse = JSON.stringify(resp)
      })
    }
</code>```

答:
You can checkout the Graph-Explorer (https://developer.microsoft.com/en-us/graph/graph-explorer) where you can explore what options there are on the me endpoint.

You will see the endpoint "https://graph.microsoft.com/v1.0/me/photo/$value" will return the photo.

Here an example with the fetch api in js:

const response = await fetch('https://graph.microsoft.com/v1.0/me/photo/$value', {
            headers: { Authorization: 'Bearer eyjo...' },
    });
    const pictureBlob = await response.blob();
    console.log(pictureBlob);
```

Body:
I am getting the users Name and Email from MSAL graph, but I don't know how to get their profile photo from Microsoft account.

This is how I am getting name and email, it is working perfectly.

getName () : string {
      if (this.authService.instance.getActiveAccount() == null) {
        return 'unknown'
      }

      return this.authService.instance.getActiveAccount().name
    }
    getEmail () : string {
      if (this.authService.instance.getActiveAccount() == null) {
        return 'unknown'
      }

      return this.authService.instance.getActiveAccount().username
    }

    callProfile () {
      this.http.get("https://graph.microsoft.com/v1.0/me").subscribe( resp  => {
        this.apiResponse = JSON.stringify(resp)
      })
    }


问:
How can I use custom tokenizer in opennmt transformer
I'm tring to transformer for translation with opennmt-py.

And I already have the tokenizer trained by sentencepiece(unigram).

But I don't know how to use my custom tokenizer in training config yaml.

I'm refering the site of opennmt-docs (https://opennmt.net/OpenNMT-py/examples/Translation.html).

Here are my code and the error .

```<code># original_ko_en.yaml
## Where is the vocab(s)
src_vocab: /workspace/tokenizer/t_50k.vocab
tgt_vocab: /workspace/tokenizer/t_50k.vocab

# Corpus opts:
data:
   corpus_1:
       path_src: /storage/genericdata_basemodel/train.ko
       path_tgt: /storage/genericdata_basemodel/train.en
       transforms: [sentencepiece]
       weight: 1
   valid:
       path_src: /storage/genericdata_basemodel/valid.ko
       path_tgt: /storage/genericdata_basemodel/valid.en
       transforms: [sentencepiece]

#### Subword
src_subword_model: /workspace/tokenizer/t_50k.model
tgt_subword_model: /workspace/tokenizer/t_50k.model
src_subword_nbest: 1
src_subword_alpha: 0.0
tgt_subword_nbest: 1
tgt_subword_alpha: 0.0

# filter
# src_seq_length: 200
# tgt_seq_length: 200

# silently ignore empty lines in the data
skip_empty_level: silent

# Train on a single GPU
world_size: 1
gpu_ranks: [0]

# General opts
save_model: /storage/models/opennmt_v1/opennmt
keep_checkpoint: 100
save_checkpoint_steps: 10000
average_decay: 0.0005
seed: 1234
train_steps: 500000
valid_steps: 20000
warmup_steps: 8000
report_every: 1000

# Model
decoder_type: transformer
encoder_type: transformer
layers: 6
heads: 8
word_vec_size: 512
rnn_size: 512
transformer_ff: 2048
dropout: 0.1
label_smoothing: 0.1

# Optimization
optim: adam
adam_beta1: 0.9
adam_beta2: 0.998
decay_method: noam
learning_rate: 2.0
max_grad_norm: 0.0
normalization: tokens
param_init: 0.0
param_init_glorot: 'true'
position_encoding: 'true'

# Batching
batch_size: 4096
batch_type: tokens
accum_count: 8
max_generator_batches: 2

# Visualization
tensorboard: True
tensorboard_log_dir: /workspace/runs/onmt1
</code>```

and When I typing < onmt_train -config xxx.yaml >

So, the questions are two.

my sentencepiece tokenizer embedding is float. How can i resolve the int error?

When training stopped by accident or I want to train more some model.pt
what is the command to start training from the some model.pt ?

I'll look forward to any opinion.
Thanks.

答:
I got the answers.

we can use tools/spm_to_vocab in onmt.

train_from argument is the one.

Body:
I'm tring to transformer for translation with opennmt-py.

And I already have the tokenizer trained by sentencepiece(unigram).

But I don't know how to use my custom tokenizer in training config yaml.

I'm refering the site of opennmt-docs (https://opennmt.net/OpenNMT-py/examples/Translation.html).

Here are my code and the error .

# original_ko_en.yaml
## Where is the vocab(s)
src_vocab: /workspace/tokenizer/t_50k.vocab
tgt_vocab: /workspace/tokenizer/t_50k.vocab

# Corpus opts:
data:
   corpus_1:
       path_src: /storage/genericdata_basemodel/train.ko
       path_tgt: /storage/genericdata_basemodel/train.en
       transforms: [sentencepiece]
       weight: 1
   valid:
       path_src: /storage/genericdata_basemodel/valid.ko
       path_tgt: /storage/genericdata_basemodel/valid.en
       transforms: [sentencepiece]

#### Subword
src_subword_model: /workspace/tokenizer/t_50k.model
tgt_subword_model: /workspace/tokenizer/t_50k.model
src_subword_nbest: 1
src_subword_alpha: 0.0
tgt_subword_nbest: 1
tgt_subword_alpha: 0.0

# filter
# src_seq_length: 200
# tgt_seq_length: 200

# silently ignore empty lines in the data
skip_empty_level: silent

# Train on a single GPU
world_size: 1
gpu_ranks: [0]

# General opts
save_model: /storage/models/opennmt_v1/opennmt
keep_checkpoint: 100
save_checkpoint_steps: 10000
average_decay: 0.0005
seed: 1234
train_steps: 500000
valid_steps: 20000
warmup_steps: 8000
report_every: 1000

# Model
decoder_type: transformer
encoder_type: transformer
layers: 6
heads: 8
word_vec_size: 512
rnn_size: 512
transformer_ff: 2048
dropout: 0.1
label_smoothing: 0.1

# Optimization
optim: adam
adam_beta1: 0.9
adam_beta2: 0.998
decay_method: noam
learning_rate: 2.0
max_grad_norm: 0.0
normalization: tokens
param_init: 0.0
param_init_glorot: 'true'
position_encoding: 'true'

# Batching
batch_size: 4096
batch_type: tokens
accum_count: 8
max_generator_batches: 2

# Visualization
tensorboard: True
tensorboard_log_dir: /workspace/runs/onmt1

and When I typing < onmt_train -config xxx.yaml >

So, the questions are two.

my sentencepiece tokenizer embedding is float. How can i resolve the int error?

When training stopped by accident or I want to train more some model.pt
what is the command to start training from the some model.pt ?

I'll look forward to any opinion.
Thanks.


问:
Format SQL in a string (in python or any language)
Is there a cli tool that can be used to format SQL code inside strings in a given .py file? Example:

```<code>import foo

query = """SELECT please, format, me

FROM    i-am-an-unformatted-query

"""

some_client.query(query)

</code>```

could for example yield

```<code>import foo

query = """
SELECT
    please,
    format,
    me
FROM i-am-an-unformatted-query"""

some_client.query(query)
</code>```

ie, formatting would only occur inside the query string.

Does such a tool exist? The once I've looked at only format standalone files. I would prefer not having discussions about SQL formatting with my colleagues but align around a tool, much like we do with for example black for python formatting.

答:
According to answer https://stackoverflow.com/a/44335609/687896, in Python you can use package sqlparse:

>>> import sqlparse
>>> sql = """SELECT please, format, me

FROM    i-am-an-unformatted-query

"""

>>> sql_formatted = sqlparse.format(sql, reindent=True, keyword_case='upper')
>>> print(sql_formatted)
SELECT please,
       format,
       me
FROM i-am-an-unformatted-query
```

Body:
Is there a cli tool that can be used to format SQL code inside strings in a given .py file? Example:

import foo

query = """SELECT please, format, me

FROM    i-am-an-unformatted-query

"""

some_client.query(query)

could for example yield

import foo

query = """
SELECT
    please,
    format,
    me
FROM i-am-an-unformatted-query"""

some_client.query(query)

ie, formatting would only occur inside the query string.

Does such a tool exist? The once I've looked at only format standalone files. I would prefer not having discussions about SQL formatting with my colleagues but align around a tool, much like we do with for example black for python formatting.


问:
How to add a circle to ListView
I have a listview.I want to put texts and a circle filled with specific color in listview items.Text are different but circle should have one color only.Anyone having idea how to do it?</p>

答: you can use a shapedrawable for the view of circle and create your own custom adapter (for example see link http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List4.html</p>

Title: How to add a circle to ListView


问:
Element ui's form validation isn't working on vue 2 composition api
I'm making a form that can be validated using element UI's form validation on vue 2 composition API environment.

A form is nesting the table inside, so its structure is quite complicated.

```<code>...
<div>
    <el-form
      ref="smKeyInfoForm"
      :model="formData"
      :rules="formRules">
      <el-table
        :data="tableData"
        ...
      >
        <el-table-column
          v-for="option in tableOptions"
          :key="option.prop"
          :prop="option.prop"
          ...
        >
          <template slot-scope="scope">
            <el-form-item :prop="scope.row[option.prop].prop">
                  <el-input
                    v-model="formData[scope.row[option.prop].prop]"
                  />
...
<script lang="ts">
...
const formRules: { [key: string]: FormRule[]} = {
  smName: [{ required: true, trigger: 'blur' }],
  clientId: [{ required: true, trigger: 'blur' }],
  ...
}
...
const formData = {
      smName: '',
      clientId: '',
...
}).then(() => {
        (smKeyInfoForm.value as unknown as ElForm).validate(async (valid) => {
          if (valid) {
...
</code>```

SomethingTab.vue

When I validate a form without the required field (ex. smName = ''), the 'valid' value of the validator returns true.

By checking with Chrome DevTools Vue extensions, I found that all props of el-form-item are normally registered, and v-model is connected to an adequate field.

How can I fix this validation problem?

答:
I found that it's caused when switching table's element from plain div to form-item and vice versa.

```<code>...
<div v-else-if="scope.row[option.prop].type === 'radios'">
                  <el-radio-group v-model="formData[scope.row[option.prop].prop]">
                    <el-radio
                      v-for="radioOption in scope.row[option.prop].options"
                      :key="radioOption.value"
                      :label="radioOption.value"
                    >
                      {{ radioOption.label }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div v-else>
                  {{ scope.row[option.prop] }}
                </div>
              </div>
            </el-form-item>
</code>```

The form shows 'divs' in show-mode and other form elements like radios in edit mode. I guess that form validation didn't work normally when switching into form-element.

So I add key to form and I change it when I toggle the show-edit mode and it works.

```<code>...
 <el-form
      ...
      :key="formReRenderKey"
      :model="formData"
      :rules="formRules">
...
    const onClickBtn = () => {
        ...
        isOnModification.value = true

        formReRenderKey.value++
...
</code>```

Body:
I'm making a form that can be validated using element UI's form validation on vue 2 composition API environment.

A form is nesting the table inside, so its structure is quite complicated.

...

    <el-form
      ref="smKeyInfoForm"
      :model="formData"
      :rules="formRules">
      <el-table
        :data="tableData"
        ...
      >
        <el-table-column
          v-for="option in tableOptions"
          :key="option.prop"
          :prop="option.prop"
          ...
        >
          <template slot-scope="scope">
            <el-form-item :prop="scope.row[option.prop].prop">
                  <el-input
                    v-model="formData[scope.row[option.prop].prop]"
                  />
...

Body:
I found that it's caused when switching table's element from plain div to form-item and vice versa.

...
<div v-else-if="scope.row[option.prop].type === 'radios'">
                  <el-radio-group v-model="formData[scope.row[option.prop].prop]">
                    <el-radio
                      v-for="radioOption in scope.row[option.prop].options"
                      :key="radioOption.value"
                      :label="radioOption.value"
                    >
                      {{ radioOption.label }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div v-else>
                  {{ scope.row[option.prop] }}
                </div>
              </div>
            </el-form-item>

The form shows 'divs' in show-mode and other form elements like radios in edit mode. I guess that form validation didn't work normally when switching into form-element.

So I add key to form and I change it when I toggle the show-edit mode and it works.

...
 <el-form
      ...
      :key="formReRenderKey"
      :model="formData"
      :rules="formRules">
...
    const onClickBtn = () => {
        ...
        isOnModification.value = true

        formReRenderKey.value++
...


问:
Issue when trying to interact with an API in Vuejs?
datalist.js

import axios from "axios";

export const datalist = () => {
  return axios.get("myapiurl/name...").then((response) => response);
};```
</div>
</div>
</p>
<p><strong>HelloWorld.vue</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
  <div>
    <div v-for="item in items" :key="item.DttID">
      <router-link
        :to="{
          name: 'UserWithID',
          params: { id: item.DepaD },
          query: { DepaD: item.DepaID },
        }"
      >
        <div class="bt-color">{{ item.DepaName }}</div>
      </router-link>
    </div>
    <br /><br /><br />
    <User />
  </div>
</template>

<script>
import User from "./User.vue";
import { datalist } from "./datalist";
export default {
  name: "HelloWorld",
  components: {
    User,
  },
  data() {
    return {
      items: datalist,
    };
  },
  mounted() {
    datalist().then((r) => {
      this.items = r.data;
    });
  },
};
</script></code>```

User.vue

<template>

      {{ item.Accv }}

</template>

```

Error with the code is,

[Vue warn]: Error in render: "TypeError: this.lists.filter is not a function"
TypeError: this.lists.filter is not a function

The above error i am getting in User.vue component in the line number '20'

From the api which is in, datalist.js file, i think i am not fetching data correctly. or in the list filter there is problem in User.vue?

答:
Since your datalist function returns a Promise, you need to wait for it to complete. To do this, simply modify your component code as follows:

```<code>import { datalist } from "./datalist";
export default {
  name: "User",
  data() {
    return {
      // empty array on initialization
      lists: [],
    };
  },
  computed: {
    user: function() {
      return this.lists.filter((item) => {
        if (item.DeploymentID === this.$route.params.id) {
          return item;
        }
      });
    },
  },
  // asynchronous function - because internally we are waiting for datalist() to complete
  async-mounted() {
    this.users = await datalist() // or datalist().then(res => this.users = res) - then async is not needed
  }
};
</code>```

now there will be no errors when initializing the component, since initially lists is an empty array but after executing the request it will turn into what you need.

Body:
datalist.js

import axios from "axios";

export const datalist = () => {
  return axios.get("myapiurl/name...").then((response) => response);
};

HelloWorld.vue

<template>

      <router-link
        :to="{
          name: 'UserWithID',
          params: { id: item.DepaD },
          query: { DepaD: item.DepaID },
        }"
      >

{{ item.DepaName }}

      </router-link>

    <User />

</template>

User.vue

<template>

      {{ item.Accv }}

</template>

Error with the code is,

[Vue warn]: Error in render: "TypeError: this.lists.filter is not a function"
TypeError: this.lists.filter is not a function

The above error i am getting in User.vue component in the line number '20'

From the api which is in, datalist.js file, i think i am not fetching data correctly. or in the list filter there is problem in User.vue?

Body:
Since your datalist function returns a Promise, you need to wait for it to complete. To do this, simply modify your component code as follows:

import { datalist } from "./datalist";
export default {
  name: "User",
  data() {
    return {
      // empty array on initialization
      lists: [],
    };
  },
  computed: {
    user: function() {
      return this.lists.filter((item) => {
        if (item.DeploymentID === this.$route.params.id) {
          return item;
        }
      });
    },
  },
  // asynchronous function - because internally we are waiting for datalist() to complete
  async-mounted() {
    this.users = await datalist() // or datalist().then(res => this.users = res) - then async is not needed
  }
};

now there will be no errors when initializing the component, since initially lists is an empty array but after executing the request it will turn into what you need.


问:
Replacing multiple special characters in oracle
I have a requirement in oracle to replace the special characters at first and last position of the column data.

Requirement: only [][.,$'*&!%^{}-?] and alphanumberic characters are allowed to stay in the address data and rest of the characters has to be replaced with space.I have tried in below way in different probabilities but its not working as expected. Please help me in resolving this.

SELECT emp_address,
       REGEXP_REPLACE(
         emp_address,
         '^[^[[][.,$'\*&!%^{}-?\]]]|[^[[][.,$'\*&!%^{}-?\]]]$'
       ) AS simplified_emp_address
FROM   table_name
```

答:
As per the regular expression operators and metasymbols documentation:

Put ] as the first character of the (negated) character group;

- as the last; and

Do not put . immediately after [ or it can be matched as the start of a coalition element [..] if there is a second . later in the expression.

Also:

Double up the single quote (to escape it, so it does not terminate the string literal); and

Include the non-special characters a-zA-Z0-9 in the capture group too otherwise they will be matched.

Which gives you the regular expression:

SELECT emp_address,
       REGEXP_REPLACE(
         emp_address,
         '^[^][,.$''\*&!%^{}?a-zA-Z0-9-]|[^][,.$''\*&!%^{}?a-zA-Z0-9-]$'
       ) AS simplified_emp_address
FROM   table_name
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE table_name (emp_address) AS
SELECT '"test1"' FROM DUAL UNION ALL
SELECT '$test2$' FROM DUAL UNION ALL
SELECT '[test3]' FROM DUAL UNION ALL
SELECT 'test4' FROM DUAL UNION ALL
SELECT '|test5|' FROM DUAL;
</code>```

Outputs:

EMP_ADDRESS
SIMPLIFIED_EMP_ADDRESS

"test1"
test1

$test2$
$test2$

[test3]
[test3]

test4
test4

|test5|
test5

db<>fiddle here

Body:
As per the regular expression operators and metasymbols documentation:

Put ] as the first character of the (negated) character group;

- as the last; and

Do not put . immediately after [ or it can be matched as the start of a coalition element [..] if there is a second . later in the expression.

Also:

Double up the single quote (to escape it, so it does not terminate the string literal); and

Include the non-special characters a-zA-Z0-9 in the capture group too otherwise they will be matched.

Which gives you the regular expression:

SELECT emp_address,
       REGEXP_REPLACE(
         emp_address,
         '^[^][,.$''\*&!%^{}?a-zA-Z0-9-]|[^][,.$''\*&!%^{}?a-zA-Z0-9-]$'
       ) AS simplified_emp_address
FROM   table_name

Which, for the sample data:

CREATE TABLE table_name (emp_address) AS
SELECT '"test1"' FROM DUAL UNION ALL
SELECT '$test2$' FROM DUAL UNION ALL
SELECT '[test3]' FROM DUAL UNION ALL
SELECT 'test4' FROM DUAL UNION ALL
SELECT '|test5|' FROM DUAL;

Outputs:

EMP_ADDRESS
SIMPLIFIED_EMP_ADDRESS

"test1"
test1

$test2$
$test2$

[test3]
[test3]

test4
test4

|test5|
test5

db<>fiddle here


问:
HttpOnly cookies are not sent with request to server
I've created API in node express and I'm running it on port :8000, I am consuming APIs through simple CRA on port :3000. I've created registration and login with setting httpOnly cookie. Furthermore, I've put middleware to check each endpoint in order to verify if it has that token.
When I test through Thunder/Postman everything works, after logging in I get the cookie in response, I set that cookie as auth token and make request to get data and I get the data.

When I log in through the React Frontend it succeeds and I can see in network tab that I have received the cookie in response. But when I make a request to protected endpoint, the request does not have a cookie in it (I log incoming requests on server and compare ones made with Thunder/Postman client and via app in Browser).

I use axios, and I've put {withCredentials: true} it doesn't work. I've used withAxios hook and it doesn't work either.

SERVER

index.js

```<code>...
const app = express()
app.use(cors({
    credentials: true,
    origin: 'http://localhost:3000',
}));
...
</code>```

controllers/User.js

```<code>...
const loginUser = async(req, res) => {
    const body = req.body
    const user = await User.findOne({ email: body.email })
        if(user) {
        const token = generateToken(user)
        const userObject = {
            userId: user._id,
            userEmail: user.email,
            userRole: user.role
        }
        const validPassword = await bcrypt.compare(body.password, user.password)
        if(validPassword) {
            res.set('Access-Control-Allow-Origin', req.headers.origin);
            res.set('Access-Control-Allow-Credentials', 'true');
            res.set(
                'Access-Control-Expose-Headers',
                'date, etag, access-control-allow-origin, access-control-allow-credentials'
            )
            res.cookie('auth-token', token, {
            httpOnly: true,
            sameSite: 'strict'
            })
            res.status(200).json(userObject)
        } else {
            res.status(400).json({ error: "Invalid password" })
        }
    } else {
        res.status(401).json({ error: "User doesn't exist" })
    }
}
...
</code>```

middleware.js

```<code>...
exports.verify = (req, res, next) => {
    const token = req.headers.authorization
    if(!token) res.status(403).json({ error: "please provide a token" })
    else {
        jwt.verify(token.split(" ")[1], tokenSecret, (err, value) => {
            if(err) res.status(500).json({error: "failed to authenticate token"})
            req.user = value.data
            next()
         })
    }
}
...
</code>```

router.js

```<code>...
router.get('/bills', middleware.verify, getBills)

router.post('/login', loginUser)
...
</code>```

CLIENT

src/components/LoginComponent.js

```<code>...
const loginUser = (e) => {
        setLoading(true)
        e.preventDefault()
        let payload = {email: email, password: password}
        axios.post('http://localhost:8000/login', payload).then(res => res.status === 200
        ? (setLoading(false), navigate('/listbills')) : navigate('/register'))
    }
...
</code>```

src/components/ListBills.js

```<code>...
useEffect(() => {
        fetch('http://localhost:8000/bills', {
            method: 'get',
            headers: {'Content-Type': 'application/json'},
            credentials: 'include',
        })
            .then(response => {console.log(response)}).catch(err => console.log(err));
    }, [])
...
</code>```

I've also tried:

```<code>axios.get('http://localhost:8000/bills',{withCredentials: true})
  .then((data) => console.log(data))
  .then((result) => console.log(result))
  .catch((err) => console.log('[Control Error ] ', err))
    }
</code>```

and

```<code>const [{ data, loading, error }, refetch] = useAxios(
  'http://localhost:8000/bills',{
  withCredentials: true,
  headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}})
</code>```

Console.log error:

After I login I get this in Network tab:

However when I want to access the list:

=== UPDATE ===

So the cause of the issue is not having the httpOnly cookie passed in the request header. This is the log of the middleware I am using:

```<code>token undefined
req headers auth undefined
req headers {
  host: 'localhost:8000',
  connection: 'keep-alive',
  'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
  'sec-ch-ua-mobile': '?0',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
  'sec-ch-ua-platform': '"macOS"',
  'content-type': 'application/json',
  accept: '*/*',
  origin: 'http://localhost:3000',
  'sec-fetch-site': 'same-site',
  'sec-fetch-mode': 'cors',
  'sec-fetch-dest': 'empty',
  referer: 'http://localhost:3000/',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9,hr;q=0.8,sr;q=0.7,bs;q=0.6,de;q=0.5,fr;q=0.4,it;q=0.3'
}
</code>```

token is read from headers.authorization but from the log of the headers it doesn't exist so my requests fail to be authorized.

Still not working.

答:
After reading everything on CORS and httpOnly cookies I've managed to get it working.
First I removed sameSite and added domain prop according to documentation in controllers/User.js on SERVER

```<code>res.cookie('auth-token', token, {
    httpOnly: true,
    domain: 'http://localhost:3000'
})
</code>```

Then I got a little yellow triangle in the console request view, it said that domain was invalid. Then I just changed domain to origin and the cookie appeared in the request log of the headers

```<code>res.cookie('auth-token', token, {
    httpOnly: true,
    origin: 'http://localhost:3000',
})
</code>```

The cookie was not in the Authorization property of the headers but in the cookie so I had to change the code in the middleware.js since it expected format bearer xxyyzz but receiving auth-token=xxyyzz, it looks like this now:

```<code>exports.verify = (req, res, next) => {
    const token = req.headers.cookie
    if(!token) res.status(403).json({ error: "please provide a token" })
    else {
        jwt.verify(token.split("=")[1], tokenSecret, (err, value) => {
            if(err) res.status(500).json({error: "failed to authenticate token"})
            req.user = value.data
            next()
         })
    }
}
</code>```

Body:
I've created API in node express and I'm running it on port :8000, I am consuming APIs through simple CRA on port :3000. I've created registration and login with setting httpOnly cookie. Furthermore, I've put middleware to check each endpoint in order to verify if it has that token.
When I test through Thunder/Postman everything works, after logging in I get the cookie in response, I set that cookie as auth token and make request to get data and I get the data.

When I log in through the React Frontend it succeeds and I can see in network tab that I have received the cookie in response. But when I make a request to protected endpoint, the request does not have a cookie in it (I log incoming requests on server and compare ones made with Thunder/Postman client and via app in Browser).

I use axios, and I've put {withCredentials: true} it doesn't work. I've used withAxios hook and it doesn't work either.

SERVER

index.js

...
const app = express()
app.use(cors({
    credentials: true,
    origin: 'http://localhost:3000',
}));
...

controllers/User.js

...
const loginUser = async(req, res) => {
    const body = req.body
    const user = await User.findOne({ email: body.email })
        if(user) {
        const token = generateToken(user)
        const userObject = {
            userId: user._id,
            userEmail: user.email,
            userRole: user.role
        }
        const validPassword = await bcrypt.compare(body.password, user.password)
        if(validPassword) {
            res.set('Access-Control-Allow-Origin', req.headers.origin);
            res.set('Access-Control-Allow-Credentials', 'true');
            res.set(
                'Access-Control-Expose-Headers',
                'date, etag, access-control-allow-origin, access-control-allow-credentials'
            )
            res.cookie('auth-token', token, {
            httpOnly: true,
            sameSite: 'strict'
            })
            res.status(200).json(userObject)
        } else {
            res.status(400).json({ error: "Invalid password" })
        }
    } else {
        res.status(401).json({ error: "User doesn't exist" })
    }
}
...

middleware.js

...
exports.verify = (req, res, next) => {
    const token = req.headers.authorization
    if(!token) res.status(403).json({ error: "please provide a token" })
    else {
        jwt.verify(token.split(" ")[1], tokenSecret, (err, value) => {
            if(err) res.status(500).json({error: "failed to authenticate token"})
            req.user = value.data
            next()
         })
    }
}
...

router.js

...
router.get('/bills', middleware.verify, getBills)

router.post('/login', loginUser)
...

CLIENT

src/components/LoginComponent.js

...
const loginUser = (e) => {
        setLoading(true)
        e.preventDefault()
        let payload = {email: email, password: password}
        axios.post('http://localhost:8000/login', payload).then(res => res.status === 200
        ? (setLoading(false), navigate('/listbills')) : navigate('/register'))
    }
...

src/components/ListBills.js

...
useEffect(() => {
        fetch('http://localhost:8000/bills', {
            method: 'get',
            headers: {'Content-Type': 'application/json'},
            credentials: 'include',
        })
            .then(response => {console.log(response)}).catch(err => console.log(err));
    }, [])
...

I've also tried:

axios.get('http://localhost:8000/bills',{withCredentials: true})
  .then((data) => console.log(data))
  .then((result) => console.log(result))
  .catch((err) => console.log('[Control Error ] ', err))
    }

and

const [{ data, loading, error }, refetch] = useAxios(
  'http://localhost:8000/bills',{
  withCredentials: true,
  headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}})

Console.log error:

After I login I get this in Network tab:

However when I want to access the list:

=== UPDATE ===

So the cause of the issue is not having the httpOnly cookie passed in the request header. This is the log of the middleware I am using:

token undefined
req headers auth undefined
req headers {
  host: 'localhost:8000',
  connection: 'keep-alive',
  'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
  'sec-ch-ua-mobile': '?0',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
  'sec-ch-ua-platform': '"macOS"',
  'content-type': 'application/json',
  accept: '*/*',
  origin: 'http://localhost:3000',
  'sec-fetch-site': 'same-site',
  'sec-fetch-mode': 'cors',
  'sec-fetch-dest': 'empty',
  referer: 'http://localhost:3000/',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9,hr;q=0.8,sr;q=0.7,bs;q=0.6,de;q=0.5,fr;q=0.4,it;q=0.3'
}

token is read from headers.authorization but from the log of the headers it doesn't exist so my requests fail to be authorized.

Still not working.

Body:
After reading everything on CORS and httpOnly cookies I've managed to get it working.
First I removed sameSite and added domain prop according to documentation in controllers/User.js on SERVER

res.cookie('auth-token', token, {
    httpOnly: true,
    domain: 'http://localhost:3000'
})

Then I got a little yellow triangle in the console request view, it said that domain was invalid. Then I just changed domain to origin and the cookie appeared in the request log of the headers

res.cookie('auth-token', token, {
    httpOnly: true,
    origin: 'http://localhost:3000',
})

The cookie was not in the Authorization property of the headers but in the cookie so I had to change the code in the middleware.js since it expected format bearer xxyyzz but receiving auth-token=xxyyzz, it looks like this now:

exports.verify = (req, res, next) => {
    const token = req.headers.cookie
    if(!token) res.status(403).json({ error: "please provide a token" })
    else {
        jwt.verify(token.split("=")[1], tokenSecret, (err, value) => {
            if(err) res.status(500).json({error: "failed to authenticate token"})
            req.user = value.data
            next()
         })
    }
}


问:
Running Scibert on GPU
I built a docker image for Scibert for CPU according to instruction here:
https://www.semi.technology/developers/weaviate/current/modules/text2vec-transformers.html#option-3-custom-build-with-a-private-or-local-model

Here the docker file:

```<code>FROM semitechnologies/transformers-inference:custom
RUN MODEL_NAME=allenai/scibert_scivocab_uncased ./download.py
</code>```

Here is the docker-compose.yaml for CPU:

```<code>version: '3.4'
services:
  weaviate:
    image: semitechnologies/weaviate:1.7.2
    restart: on-failure:0
    ports:
     - "8080:8080"
    environment:
      QUERY_DEFAULTS_LIMIT: 20
      AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
      PERSISTENCE_DATA_PATH: "./data"
      DEFAULT_VECTORIZER_MODULE: text2vec-transformers
      ENABLE_MODULES: text2vec-transformers
      TRANSFORMERS_INFERENCE_API: http://t2v-transformers:8080
  t2v-transformers:
    image: scibert-inference
    environment:
      ENABLE_CUDA: 0
</code>```

I can run it on CPU without error.
NOW, I need to run it on the GPU with this docker-compose.yaml:

```<code>version: '3.4'
services:
  weaviate:
    image: semitechnologies/weaviate:1.10.1
    restart: on-failure:0
    ports:
     - "8080:8080"
    environment:
      QUERY_DEFAULTS_LIMIT: 20
      AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
      PERSISTENCE_DATA_PATH: "./data"
      DEFAULT_VECTORIZER_MODULE: text2vec-transformers
      ENABLE_MODULES: text2vec-transformers
      TRANSFORMERS_INFERENCE_API: http://t2v-transformers:8080
  t2v-transformers:
    image: scibert-inference
    environment:
      ENABLE_CUDA: '1'
      NVIDIA_VISIBLE_DEVICES: 'all'
    deploy:
      resources:
        reservations:
          devices:
          - capabilities:
            - 'gpu'
</code>```

When I ran it on GPU, I had the following error:

```<code>weaviate_1          | {"action":"transformer_remote_wait_for_startup","error":"send check ready request: Get \"http://t2v-transformers:8080/.well-known/ready\": dial tcp: lookup t2v-transformers on 127.0.0.11:53: no such host","level":"warning","msg":"transformer remote inference service not ready","time":"2022-02-08T03:47:54Z"}
</code>```

My system specifications are as follows:

```<code>Cuda compilation tools, release 9.0, V9.0.176
Client: Docker Engine - Community
 Version:           20.10.7
 API version:       1.41
 Go version:        go1.13.15
 Git commit:        f0df350
 Built:             Wed Jun  2 11:56:47 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.7
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       b0f5bc3
  Built:            Wed Jun  2 11:54:58 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.6
  GitCommit:        d71fcd7d8303cbf684402823e425e9dd2e99285d
 runc:
  Version:          1.0.0-rc95
  GitCommit:        b9ee9c6314599f1b4a7f497e1f1f856fe433d3b7
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
docker-compose version 1.29.2, build 5becea4c
</code>```

答:
Did you set the CUDA_CORE environment variable? Weaviate is using this env variable to pinpoint the cuda device and if CUDA_CORE is not set, then it defaults to cuda:0.

If you are running this with docker-compose with gpu capabilities, you probably should pinpoint your gpu device properly. So you would have to override CUDA_CORE environment variable to something for example like this: CUDA_CORE=GPU:0 like in this example on docker page.

I don't know if your gpu device address is actually GPU:0 (bc it's not cuda:0 since it doesn't start), you can check that in your docker-compose logs.

Title: Running Scibert on GPU

Body:
I built a docker image for Scibert for CPU according to instruction here:
https://www.semi.technology/developers/weaviate/current/modules/text2vec-transformers.html#option-3-custom-build-with-a-private-or-local-model

Here the docker file:

FROM semitechnologies/transformers-inference:custom
RUN MODEL_NAME=allenai/scibert_scivocab_uncased ./download.py

Here is the docker-compose.yaml for CPU:

version: '3.4'
services:
  weaviate:
    image: semitechnologies/weaviate:1.7.2
    restart: on-failure:0
    ports:
     - "8080:8080"
    environment:
      QUERY_DEFAULTS_LIMIT: 20
      AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
      PERSISTENCE_DATA_PATH: "./data"
      DEFAULT_VECTORIZER_MODULE: text2vec-transformers
      ENABLE_MODULES: text2vec-transformers
      TRANSFORMERS_INFERENCE_API: http://t2v-transformers:8080
  t2v-transformers:
    image: scibert-inference
    environment:
      ENABLE_CUDA: 0

I can run it on CPU without error.
NOW, I need to run it on the GPU with this docker-compose.yaml:

version: '3.4'
services:
  weaviate:
    image: semitechnologies/weaviate:1.10.1
    restart: on-failure:0
    ports:
     - "8080:8080"
    environment:
      QUERY_DEFAULTS_LIMIT: 20
      AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
      PERSISTENCE_DATA_PATH: "./data"
      DEFAULT_VECTORIZER_MODULE: text2vec-transformers
      ENABLE_MODULES: text2vec-transformers
      TRANSFORMERS_INFERENCE_API: http://t2v-transformers:8080
  t2v-transformers:
    image: scibert-inference
    environment:
      ENABLE_CUDA: '1'
      NVIDIA_VISIBLE_DEVICES: 'all'
    deploy:
      resources:
        reservations:
          devices:
          - capabilities:
            - 'gpu'

When I ran it on GPU, I had the following error:

weaviate_1          | {"action":"transformer_remote_wait_for_startup","error":"send check ready request: Get \"http://t2v-transformers:8080/.well-known/ready\": dial tcp: lookup t2v-transformers on 127.0.0.11:53: no such host","level":"warning","msg":"transformer remote inference service not ready","time":"2022-02-08T03:47:54Z"}

My system specifications are as follows:

Cuda compilation tools, release 9.0, V9.0.176
Client: Docker Engine - Community
 Version:           20.10.7
 API version:       1.41
 Go version:        go1.13.15
 Git commit:        f0df350
 Built:             Wed Jun  2 11:56:47 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.7
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       b0f5bc3
  Built:            Wed Jun  2 11:54:58 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.6
  GitCommit:        d71fcd7d8303cbf684402823e425e9dd2e99285d
 runc:
  Version:          1.0.0-rc95
  GitCommit:        b9ee9c6314599f1b4a7f497e1f1f856fe433d3b7
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
docker-compose version 1.29.2, build 5becea4c


问:
Text doesn't break in special case
I have a problem that the text doesn't break in a popup made with Vue.js which is included in the header like this:

The text breaks normally if I include the popup into the main screen, but doesn't if I include it into the header. I have also drawn border around the
 element which contains the text and the border is drawn correctly.

Here is the sample code: https://codesandbox.io/s/cold-feather-3zi3d?file=/src/components/BasicModal.vue

答:
The class .header-frame is adding the css:

```<code>.header-frame {
  white-space: nowrap;
}
</code>```

This is the reason for which the text does not break when inside the header.

Try adding

```<code>white-space: pre-wrap;
</code>```

or

```<code>white-space: initial;
</code>```

Title: Text doesn't break in special case

Body:
The class .header-frame is adding the css:

.header-frame {
  white-space: nowrap;
}

This is the reason for which the text does not break when inside the header.

Try adding

white-space: pre-wrap;

or

white-space: initial;


问:
Spring boot + React JS Reset password implementation
i'm trying to implement a password reset/forgot password feature in my spring boot/react app but i'm having some problems trying to fully understand it, I'm unsure whether the approach i'm taking is correct or not.

I already have both register/login working

I created a REST endpoint: /sendForgotPasswordEmail [POST]

This finds a user via their email address they enter in the react form and sees if the account with the email exists.

If a user account is found, sends them an email with a unique token with a link to a reset password form (stuck here)

I also created a Token entity that generates a random UUID so when the user clicks forgot password and fills in the details, the email generates this link:  http://localhost:3000/reset-password/e90c4fa5-2e74-4b44-b3c4-5d6f1c616461

    @PostMapping("/sendForgotPasswordEmail")
    public ResponseEntity<?> sendForgotPasswordEmail(@Valid @RequestBody ForgotPasswordEmailRequest request) {

        User user = userService.findUserByEmailAddress(request.getForgotPasswordEmail());
        ResetPasswordToken resetPasswordToken = userService.createResetPasswordToken(user);

        if(userService.existsByEmailAddress(request.getForgotPasswordEmail())) {
            emailService.sendResetPasswordEmail(request.getForgotPasswordEmail(), resetPasswordToken.getToken());
            return ResponseEntity.ok(new ApiResponse("Please check your email for a password reset link" , true));
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
    }
```
<hr />
<ul>
<li>I created a REST endpoint: /resetPassword [POST]
<ul>
<li>Reads the token generated using @RequestParam to check whether it expired etc.</li>
<li>I have a service method called resetPassword(String email, String password) which searches for a user by their email and sets the user password to the provided password from the method.</li>
</ul>
</li>
</ul>
<pre class="lang-java prettyprint-override"><code>    @PostMapping("/resetPassword")
    public ResponseEntity<?> resetPassword(@RequestParam("token") String token, @Valid @RequestBody ForgotPasswordEmailRequest request) {
        ResetPasswordToken resetPasswordToken = userService.findByResetPasswordToken(token);

        if(resetPasswordToken == null) throw new BadRequestException("Invalid token");

        Calendar calendar = Calendar.getInstance();

        if((resetPasswordToken.getExpiredAt().getTime() - calendar.getTime().getTime()) <= 0) {
            throw new BadRequestException("Link expired. Generate new link from http://localhost:3000/signup");
        }

        userService.resetPassword(request.getForgotPasswordEmail(), request.getNewPassword());

        return ResponseEntity.ok(token);
    }
</code>```

UserServiceImpl.java (Methods related to the reset token)

    @Override
    public ResetPasswordToken createResetPasswordToken(User user) {
        ResetPasswordToken resetPasswordToken = new ResetPasswordToken(user);
        return resetPasswordTokenRepository.save(resetPasswordToken);
    }

    @Override
    public ResetPasswordToken findByResetPasswordToken(String token) {
        return resetPasswordTokenRepository.findByToken(token);
    }

    @Override
    public void resetPassword(String emailAddress, String password) {
        User user = findUserByEmailAddress(emailAddress);

        user.setPassword(passwordEncoder.encode(password));

    }

```
<hr />
<p><strong>ForgotPasswordEmailRequest.java</strong></p>
<pre class="lang-java prettyprint-override"><code>public class ForgotPasswordEmailRequest {

    private String forgotPasswordEmail;

    private String newPassword;

    // constructors / getters and setters

}

</code>```

The thing i'd like clarity on is how exactly to go about doing this and making sure i can successfully redirect a user to the reset password page, and they can change it from there.
I'm unsure where my controller methods are missing something or where i'm going wrong.

When the user reaches the reset password form after being sent an email, what's the process that needs to happen on the front + backend from there.

I'd appreciate any help.

答:
Usually the flow is like this:

on frontend side: user clicks 'remind password' where he only provides email address -> that sends POST request with email to backend

backend accepts the email, generates token and sends the email with unique url, as you mentioned above,

after user checks mail, clicks the link (GET method), you need to have on the frontend side URL with for example GET /password-recovery endpoint, that parses the token from the params, validates in the backend if token is still active and allows to change password on another form. So 2 additional backend requests for token validation and password change.

Body:
i'm trying to implement a password reset/forgot password feature in my spring boot/react app but i'm having some problems trying to fully understand it, I'm unsure whether the approach i'm taking is correct or not.

I already have both register/login working

I created a REST endpoint: /sendForgotPasswordEmail [POST]

This finds a user via their email address they enter in the react form and sees if the account with the email exists.

If a user account is found, sends them an email with a unique token with a link to a reset password form (stuck here)

I also created a Token entity that generates a random UUID so when the user clicks forgot password and fills in the details, the email generates this link:  http://localhost:3000/reset-password/e90c4fa5-2e74-4b44-b3c4-5d6f1c616461

    @PostMapping("/sendForgotPasswordEmail")
    public ResponseEntity<?> sendForgotPasswordEmail(@Valid @RequestBody ForgotPasswordEmailRequest request) {

        User user = userService.findUserByEmailAddress(request.getForgotPasswordEmail());
        ResetPasswordToken resetPasswordToken = userService.createResetPasswordToken(user);

        if(userService.existsByEmailAddress(request.getForgotPasswordEmail())) {
            emailService.sendResetPasswordEmail(request.getForgotPasswordEmail(), resetPasswordToken.getToken());
            return ResponseEntity.ok(new ApiResponse("Please check your email for a password reset link" , true));
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
    }

I created a REST endpoint: /resetPassword [POST]

Reads the token generated using @RequestParam to check whether it expired etc.

I have a service method called resetPassword(String email, String password) which searches for a user by their email and sets the user password to the provided password from the method.

    @PostMapping("/resetPassword")
    public ResponseEntity<?> resetPassword(@RequestParam("token") String token, @Valid @RequestBody ForgotPasswordEmailRequest request) {
        ResetPasswordToken resetPasswordToken = userService.findByResetPasswordToken(token);

        if(resetPasswordToken == null) throw new BadRequestException("Invalid token");

        Calendar calendar = Calendar.getInstance();

        if((resetPasswordToken.getExpiredAt().getTime() - calendar.getTime().getTime()) <= 0) {
            throw new BadRequestException("Link expired. Generate new link from http://localhost:3000/signup");
        }

        userService.resetPassword(request.getForgotPasswordEmail(), request.getNewPassword());

        return ResponseEntity.ok(token);
    }

UserServiceImpl.java (Methods related to the reset token)

    @Override
    public ResetPasswordToken createResetPasswordToken(User user) {
        ResetPasswordToken resetPasswordToken = new ResetPasswordToken(user);
        return resetPasswordTokenRepository.save(resetPasswordToken);
    }

    @Override
    public ResetPasswordToken findByResetPasswordToken(String token) {
        return resetPasswordTokenRepository.findByToken(token);
    }

    @Override
    public void resetPassword(String emailAddress, String password) {
        User user = findUserByEmailAddress(emailAddress);

        user.setPassword(passwordEncoder.encode(password));

    }

ForgotPasswordEmailRequest.java

public class ForgotPasswordEmailRequest {

    private String forgotPasswordEmail;

    private String newPassword;

    // constructors / getters and setters

}

The thing i'd like clarity on is how exactly to go about doing this and making sure i can successfully redirect a user to the reset password page, and they can change it from there.
I'm unsure where my controller methods are missing something or where i'm going wrong.

When the user reaches the reset password form after being sent an email, what's the process that needs to happen on the front + backend from there.

I'd appreciate any help.


问:
Efficient way to get indexes of matched items using Lists
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

```<code>ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}
</code>```

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

答:
If you had to use an ArrayList, you could create a HashSet from the ArrayList.  This would make the call to contains O(1).  It would take O(n) to create the HastSet.  If you could start with a HashSet, that would be best.

```<code>public static void main(String[] args)
{
    List listA = new ArrayList();
    listA.add(1);
    listA.add(2);
    listA.add(3);
    listA.add(4);
    List listB = new ArrayList();
    listB.add(2);
    listB.add(4);
    Set hashset = new HashSet(listA);

    for(int i = 0; i < listB.size(); i++)
    {
        if(hashset.contains(listB.get(i)))
        {
            listC.add(i);
            System.out.println(i);
        }
    }
}
</code>```

Body:
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

Body:
If you had to use an ArrayList, you could create a HashSet from the ArrayList.  This would make the call to contains O(1).  It would take O(n) to create the HastSet.  If you could start with a HashSet, that would be best.

public static void main(String[] args)
{
    List listA = new ArrayList();
    listA.add(1);
    listA.add(2);
    listA.add(3);
    listA.add(4);
    List listB = new ArrayList();
    listB.add(2);
    listB.add(4);
    Set hashset = new HashSet(listA);

    for(int i = 0; i < listB.size(); i++)
    {
        if(hashset.contains(listB.get(i)))
        {
            listC.add(i);
            System.out.println(i);
        }
    }
}


问:
To check if IEnumerable is not null before checking for Any() in c#
I was in a situation where I got a statement that checks if the collection is actually null before going into checking for Any() (having any elements at all) .

```<code>if(myIEnumerableCollection?.Any() ?? false)
   {
      // do this logic
   }
</code>```

I know that myIEnumerableCollection is checked and if it is null(c# 6 syntax, correct me if I am wrong)  , the argument null exception is thrown . I wanted to get an understanding of this statement as what it is evaluating , as the syntax is a bit confusing to read.

My understanding is that :

Check the collection for not null and should be false.

Chained with Any() for any elements in the sequence if the first condition is not
true(myIEnumerableCollection? not null) .

If the expression myIEnumerableCollection?.Any() is true ( this is where I am
getting confused how is it evaluating to true )  go inside the if logic
else evaluate to false.

Any links or references or explanation will help. I am getting a bit rusty and it might look like a very basic question, my concern was with the readability of the expression.

Thank you.

答: The ?. or null conditional operator syntax skips evaluation of the rest of the expression and evaluates null if the left side value is null. So myIEnumerableCollection?.Any() will give a type of bool? i.e. either null, true, or false. The ?? false, or null coalescing operator, convert the null-case to false.

Body:
I was in a situation where I got a statement that checks if the collection is actually null before going into checking for Any() (having any elements at all) .

if(myIEnumerableCollection?.Any() ?? false)
   {
      // do this logic
   }

I know that myIEnumerableCollection is checked and if it is null(c# 6 syntax, correct me if I am wrong)  , the argument null exception is thrown . I wanted to get an understanding of this statement as what it is evaluating , as the syntax is a bit confusing to read.

My understanding is that :

Check the collection for not null and should be false.

Chained with Any() for any elements in the sequence if the first condition is not
true(myIEnumerableCollection? not null) .

If the expression myIEnumerableCollection?.Any() is true ( this is where I am
getting confused how is it evaluating to true )  go inside the if logic
else evaluate to false.

Any links or references or explanation will help. I am getting a bit rusty and it might look like a very basic question, my concern was with the readability of the expression.

Thank you.