问:
Questions about exception handling in Java specifically the purpose of the throws keyword
I had a question about the throws keyword in the code below. In the method testLoop3() I am indicating that the IndexOutOfBoundsException may be thrown with the throws keyword. But the method testLoop() is identical except it does not show that exception being thrown. What is the purpose of including throws IndexOutOfBoundsException if the exception is being sent to the calling method in both cases and the output is exactly the same? I read that the throws keyword is to make the caller of method aware of the exception and force the caller to handle it in the last line of the main() method it is not handling it.

package exceptions;

import java.util.ArrayList;

public class TestException {

  public static void main(String[] args) {

    System.out.println("------------------");
    try {
      testLoop();
    } catch (Exception e) {
      System.out.println("Exception from testLoop() passed to main= " + e);
    }
    System.out.println("After Exception");
    System.out.println("------------------");

    testLoop2();

    try {
      testLoop3();
    } catch (Exception e) {
      System.out.println("Exception from testLoop3() passed to main= " + e);
    }
    System.out.println("After Exception");

    System.out.println("------------------");
    testLoop();

    System.out.println("------------------");
    testLoop3();
  }

  private static void testLoop() {
    System.out.println("In testLoop()");
    ArrayList<Integer> arrLst = new ArrayList();
    arrLst.add(4);
    arrLst.add(6);
    arrLst.add(2);

    for(int x=0; x<5; x++)  {
      System.out.println(arrLst.get(x));
    }
  }

  private static void testLoop2() {
    System.out.println("In testLoop2()");
    ArrayList<Integer> arrLst = new ArrayList();
    arrLst.add(4);
    arrLst.add(6);
    arrLst.add(2);
    try {
      for(int x=0; x<5; x++)  {
        System.out.println(arrLst.get(x));
      }
    } catch (Exception e) {
      System.out.println("Exception = " + e);
    }
    System.out.println("After Exception");
  }

  private static void testLoop3() throws IndexOutOfBoundsException{
    System.out.println("In testLoop3()");
    ArrayList<Integer> arrLst = new ArrayList();
    arrLst.add(4);
    arrLst.add(6);
    arrLst.add(2);

    for(int x=0; x<5; x++)  {
      System.out.println(arrLst.get(x));
    }
  }
}
```
<p>Output:</p>
```------------------
In testLoop()
4
6
2
Exception from testLoop() passed to main= java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
After Exception
------------------
In testLoop2()
4
6
2
Exception = java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
After Exception
In testLoop3()
4
6
2
Exception from testLoop3() passed to main= java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
After Exception
------------------
In testLoop()
4
6
2
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:372)
    at java.base/java.util.ArrayList.get(ArrayList.java:459)
    at exceptions.TestException.testLoop(TestException.java:42)
    at exceptions.TestException.main(TestException.java:28)

```

I expected different results when calling testLoop() and testLoop3() due to the fact that testLoop3() has the thows IndexOutOfBoundsException and testLoop() does not. I excepted testLoop() not to propagate the exception to the main() method

Body:
I had a question about the throws keyword in the code below. In the method testLoop3() I am indicating that the IndexOutOfBoundsException may be thrown with the throws keyword. But the method testLoop() is identical except it does not show that exception being thrown. What is the purpose of including throws IndexOutOfBoundsException if the exception is being sent to the calling method in both cases and the output is exactly the same? I read that the throws keyword is to make the caller of method aware of the exception and force the caller to handle it in the last line of the main() method it is not handling it.

package exceptions;

import java.util.ArrayList;

public class TestException {

  public static void main(String[] args) {

    System.out.println("------------------");
    try {
      testLoop();
    } catch (Exception e) {
      System.out.println("Exception from testLoop() passed to main= " + e);
    }
    System.out.println("After Exception");
    System.out.println("------------------");

    testLoop2();

    try {
      testLoop3();
    } catch (Exception e) {
      System.out.println("Exception from testLoop3() passed to main= " + e);
    }
    System.out.println("After Exception");

    System.out.println("------------------");
    testLoop();

    System.out.println("------------------");
    testLoop3();
  }

  private static void testLoop() {
    System.out.println("In testLoop()");
    ArrayList<Integer> arrLst = new ArrayList();
    arrLst.add(4);
    arrLst.add(6);
    arrLst.add(2);

    for(int x=0; x<5; x++)  {
      System.out.println(arrLst.get(x));
    }
  }

  private static void testLoop2() {
    System.out.println("In testLoop2()");
    ArrayList<Integer> arrLst = new ArrayList();
    arrLst.add(4);
    arrLst.add(6);
    arrLst.add(2);
    try {
      for(int x=0; x<5; x++)  {
        System.out.println(arrLst.get(x));
      }
    } catch (Exception e) {
      System.out.println("Exception = " + e);
    }
    System.out.println("After Exception");
  }

  private static void testLoop3() throws IndexOutOfBoundsException{
    System.out.println("In testLoop3()");
    ArrayList<Integer> arrLst = new ArrayList();
    arrLst.add(4);
    arrLst.add(6);
    arrLst.add(2);

    for(int x=0; x<5; x++)  {
      System.out.println(arrLst.get(x));
    }
  }
}

Output:

------------------
In testLoop()
4
6
2
Exception from testLoop() passed to main= java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
After Exception
------------------
In testLoop2()
4
6
2
Exception = java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
After Exception
In testLoop3()
4
6
2
Exception from testLoop3() passed to main= java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
After Exception
------------------
In testLoop()
4
6
2
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:372)
    at java.base/java.util.ArrayList.get(ArrayList.java:459)
    at exceptions.TestException.testLoop(TestException.java:42)
    at exceptions.TestException.main(TestException.java:28)

I expected different results when calling testLoop() and testLoop3() due to the fact that testLoop3() has the thows IndexOutOfBoundsException and testLoop() does not. I excepted testLoop() not to propagate the exception to the main() method


来源: stackexchange

问:
how to stored data from API to react state?
i have try this code to save data from API, no error when i run this code, but data API not save to dataDetail from state

```<code>class DetailApi extends Component {
    constructor(){
        super()
        this.state={
            dataDetail: {},
        }
    }

    getDetail = ()=>{
        axios.get(`https://pokeapi.co/api/v2/pokemon/${this.props.nameParam.name}`)
        .then(res => {
            this.setState({
                dataDetail: res.data,
            })
            console.log(res.data)
            console.log(this.state.dataDetail)
        })
    }
</code>```

i expect api data to be stored in state

ContentLicense: CC BY-SA 4.0

Body:
i have try this code to save data from API, no error when i run this code, but data API not save to dataDetail from state

class DetailApi extends Component {
    constructor(){
        super()
        this.state={
            dataDetail: {},
        }
    }

    getDetail = ()=>{
        axios.get(`https://pokeapi.co/api/v2/pokemon/${this.props.nameParam.name}`)
        .then(res => {
            this.setState({
                dataDetail: res.data,
            })
            console.log(res.data)
            console.log(this.state.dataDetail)
        })
    }

i expect api data to be stored in state


问:
How to make the menu item have the window accessibility?
I test the window accessibility by using the application "Accessibility Insights For Windows"

However, I notice I am unable to access to the submenu as the app is using to test the accessibility issue.

I had inserted the example of the code and the output, and the output of the app that unable to show the sub menu.
example of the code and the output
output of the app that unable to show the sub menu

How should I edit the code to make the sub menu accessible??
Or
How to make the element appear in the UI Tree


问:
Test for tooltip test in typescript/jest
I want to test that the tooltip can be found and the text is equal to a specific text.

I have this code in vue:

```<code> span.mt-1(v-if='hasDescription')
  InfoTooltip(right)
    div(v-html='renderedDescription')
</code>```

The test is as below

```<code>import { createLocalVue, mount, MountOptions, Wrapper } from '@vue/test-utils';
import flushPromises from 'flush-promises';
import Vue from 'vue';
import Vuetify from 'vuetify';

import TimelineRecordDynamicField from '@/components/caseTimeline/TimelineRecordDynamicField.vue';
import InfoTooltip from '@/components/InfoTooltip.vue';
import api from '@/store/api';
import { DynamicFieldSchema, DynamicFieldValue } from '@/types';

jest.mock('@/store/api');

const localVue = createLocalVue();
const SCHEMA_FIELDS: DynamicFieldSchema = {
  key: 'The schema key',
  format: '',
  freeText: true,
  multiple: true,
  required: false,
  predefinedValues: false,
  description: 'this is a description',
};

describe('TimelineRecordDynamicField.vue', () => {
  let options: MountOptions<Vue>;
  let wrapper: Wrapper<Vue & { [key: string]: any }>;

  beforeEach(() => {
    options = {
      localVue,
      vuetify: new Vuetify(),
      sync: false,
      propsData: {
        parentTicketId: 'any ticket id',
        schema: SCHEMA_FIELDS,
      },
    };
    api.getTimelineRecordDynamicFieldSchemaValues = jest.fn().mockResolvedValue({ items: [], total: 0 });
    wrapper = mount(TimelineRecordDynamicField, options);
  });

  describe('the tooltip rendering', () => {
    it.each([[SCHEMA_FIELDS]])('shows a tooltip if the dynamic field has a description', async () => {
      const tooltip = wrapper.find(InfoTooltip);
      expect(wrapper.vm.hasDescription).toBe(true);
      expect(tooltip.exists()).toBe(true);
      expect(wrapper.vm.renderedDescription).toContain('this is a description');
    });
  });
});
</code>```

wrapper.vm.hasDescription is undefined.

What am I doing wrong here? Any help is much appreciated :)

Thanks in advance!

Body:
I want to test that the tooltip can be found and the text is equal to a specific text.

I have this code in vue:

 span.mt-1(v-if='hasDescription')
  InfoTooltip(right)
    div(v-html='renderedDescription')

The test is as below

import { createLocalVue, mount, MountOptions, Wrapper } from '@vue/test-utils';
import flushPromises from 'flush-promises';
import Vue from 'vue';
import Vuetify from 'vuetify';

import TimelineRecordDynamicField from '@/components/caseTimeline/TimelineRecordDynamicField.vue';
import InfoTooltip from '@/components/InfoTooltip.vue';
import api from '@/store/api';
import { DynamicFieldSchema, DynamicFieldValue } from '@/types';

jest.mock('@/store/api');

const localVue = createLocalVue();
const SCHEMA_FIELDS: DynamicFieldSchema = {
  key: 'The schema key',
  format: '',
  freeText: true,
  multiple: true,
  required: false,
  predefinedValues: false,
  description: 'this is a description',
};

describe('TimelineRecordDynamicField.vue', () => {
  let options: MountOptions<Vue>;
  let wrapper: Wrapper<Vue & { [key: string]: any }>;

  beforeEach(() => {
    options = {
      localVue,
      vuetify: new Vuetify(),
      sync: false,
      propsData: {
        parentTicketId: 'any ticket id',
        schema: SCHEMA_FIELDS,
      },
    };
    api.getTimelineRecordDynamicFieldSchemaValues = jest.fn().mockResolvedValue({ items: [], total: 0 });
    wrapper = mount(TimelineRecordDynamicField, options);
  });

  describe('the tooltip rendering', () => {
    it.each([[SCHEMA_FIELDS]])('shows a tooltip if the dynamic field has a description', async () => {
      const tooltip = wrapper.find(InfoTooltip);
      expect(wrapper.vm.hasDescription).toBe(true);
      expect(tooltip.exists()).toBe(true);
      expect(wrapper.vm.renderedDescription).toContain('this is a description');
    });
  });
});

wrapper.vm.hasDescription is undefined.

What am I doing wrong here? Any help is much appreciated :)

Thanks in advance!


问:
Why is a global variable initialized with a function after the main label in assembly?
This example is with clang 15 using -O3.

Check it out on Godbolt: https://godbolt.org/z/Pd31fGKTe

```<code>#include <iostream>

int hello = printf("Hello World!\n");

int main() {
    printf("main()");
}
</code>```

Output is as expected from the rules of C++ initialization.

```<code>Hello World!
main()
</code>```

What is not expected to me is the assembly code:

```<code>main:                                   # @main
        push    rax
        lea     rdi, [rip + .L.str.2]
        xor     eax, eax
        call    printf@PLT
        xor     eax, eax
        pop     rcx
        ret
_GLOBAL__sub_I_example.cpp:             # @_GLOBAL__sub_I_example.cpp
        push    rbx
        lea     rbx, [rip + std::__ioinit]
        mov     rdi, rbx
        call    std::ios_base::Init::Init()@PLT
        mov     rdi, qword ptr [rip + std::ios_base::Init::~Init()@GOTPCREL]
        lea     rdx, [rip + __dso_handle]
        mov     rsi, rbx
        call    __cxa_atexit@PLT
        lea     rdi, [rip + .L.str]
        xor     eax, eax
        call    printf@PLT
        mov     dword ptr [rip + hello], eax
        pop     rbx
        ret
hello:
        .long   0                               # 0x0

.L.str:
        .asciz  "Hello World!\n"

.L.str.2:
        .asciz  "main()"
</code>```

It seems to me that main: is not the entry point, but _GLOBAL__sub_I_example.cpp: instead. I believe this because if not I think the program would ouput main() first, but it doesn't. What confuses me is that I don't get how the code from the main: label gets called. If _GLOBAL__sub_I_example.cpp: is the entry point, then why does it return something and how does the program ever run the code with the main label.

Body:
This example is with clang 15 using -O3.

Check it out on Godbolt: https://godbolt.org/z/Pd31fGKTe

#include <iostream>

int hello = printf("Hello World!\n");

int main() {
    printf("main()");
}

Output is as expected from the rules of C++ initialization.

Hello World!
main()

What is not expected to me is the assembly code:

main:                                   # @main
        push    rax
        lea     rdi, [rip + .L.str.2]
        xor     eax, eax
        call    printf@PLT
        xor     eax, eax
        pop     rcx
        ret
_GLOBAL__sub_I_example.cpp:             # @_GLOBAL__sub_I_example.cpp
        push    rbx
        lea     rbx, [rip + std::__ioinit]
        mov     rdi, rbx
        call    std::ios_base::Init::Init()@PLT
        mov     rdi, qword ptr [rip + std::ios_base::Init::~Init()@GOTPCREL]
        lea     rdx, [rip + __dso_handle]
        mov     rsi, rbx
        call    __cxa_atexit@PLT
        lea     rdi, [rip + .L.str]
        xor     eax, eax
        call    printf@PLT
        mov     dword ptr [rip + hello], eax
        pop     rbx
        ret
hello:
        .long   0                               # 0x0

.L.str:
        .asciz  "Hello World!\n"

.L.str.2:
        .asciz  "main()"

It seems to me that main: is not the entry point, but _GLOBAL__sub_I_example.cpp: instead. I believe this because if not I think the program would ouput main() first, but it doesn't. What confuses me is that I don't get how the code from the main: label gets called. If _GLOBAL__sub_I_example.cpp: is the entry point, then why does it return something and how does the program ever run the code with the main label.


问:
vitepress:Unexpected identifier 'project'
On my computer, when I create a vitepress project on the desktop, the project is normal. But when I nest a folder outside the project, my console will report the following error. There are no problems under my friend's window computer.

My computer environment is as follows:

```<code>System:
    OS: macOS 12.6
    CPU: (8) arm64 Apple M1 Pro
    Memory: 64.11 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v16.16.0/bin/npm
  Browsers:
    Chrome: 108.0.5359.124
    Safari: 15.6.1
  npmPackages:
    vitepress: ^1.0.0-alpha.31 => 1.0.0-alpha.31
</code>```

I hope that the projects created by my vitepress can be accessed normally under the condition of nested folders

Body:
On my computer, when I create a vitepress project on the desktop, the project is normal. But when I nest a folder outside the project, my console will report the following error. There are no problems under my friend's window computer.

My computer environment is as follows:

System:
    OS: macOS 12.6
    CPU: (8) arm64 Apple M1 Pro
    Memory: 64.11 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v16.16.0/bin/npm
  Browsers:
    Chrome: 108.0.5359.124
    Safari: 15.6.1
  npmPackages:
    vitepress: ^1.0.0-alpha.31 => 1.0.0-alpha.31

I hope that the projects created by my vitepress can be accessed normally under the condition of nested folders


问:
bluetooth module blocking the rest of the program in case of connection reset or host is down
I am trying to send and receive data simultaneously using bluetooth between client and server sides. The scripts are separate and running on separate devices, on for client and one for server. Initially, the rest of my programs would get blocked in a loop if there was a connection reset or issue with the client or server connection. So I added a single thread in both codes. Now it seems to fix the issue but I am not sure whether it's the correct way to solve this problem.

I have the following codes for client and server sides.

client side:

```<code>import bluetooth
import threading

# Set the server's Bluetooth address and port number
bd_addr = "00:e0:4c:9a:f8:64"
port = 1

def client():
    while True:
        try:
            # Create a Bluetooth socket and connect to the server
            sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            sock.connect((bd_addr, port))

            # Continuously receive data from the server and print it out
            while True:
                data = sock.recv(1024)
                print("Received from server:", data.decode())

                # Prompt the user to type something to send back to the server
                txt = input("Type something to send back to the server: ")
                sock.send(txt.encode())

        except Exception as e:
            # If an error occurs, print the error message and close the socket
            # print(e)
            sock.close()

# Start the receive_data and send_data functions in separate threads
threading.Thread(target=client).start()

</code>```

server side:

```<code>import bluetooth
import threading

def server():
    while True:
        try:
            # Create a Bluetooth socket and bind it to the specified port
            server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            port = 1
            server_sock.bind(("", port))
            server_sock.listen(1)

            # Accept an incoming connection from a client
            client_sock, address = server_sock.accept()
            print("Accepted connection from", address)

            # Continuously prompt the user to type something to send to the client
            while True:
                txt = input("Type something to send to the client: ")
                client_sock.send(txt.encode())

                # Receive data from the client and print it out
                data = client_sock.recv(1024)
                print("Received from client:", data.decode())

        except Exception as e:
            # If an error occurs, print the error message and close the sockets
            # print(e)
            client_sock.close()
            server_sock.close()

# Start the receive_data and send_data functions in separate threads
threading.Thread(target=server).start()

</code>```

Is using threading this way, to prevent the rest of the program in each script getting stuck, in case of connection error on either side, correct?

Are there any other/better ways to fix the issue, such as callback function?

Body:
I am trying to send and receive data simultaneously using bluetooth between client and server sides. The scripts are separate and running on separate devices, on for client and one for server. Initially, the rest of my programs would get blocked in a loop if there was a connection reset or issue with the client or server connection. So I added a single thread in both codes. Now it seems to fix the issue but I am not sure whether it's the correct way to solve this problem.

I have the following codes for client and server sides.

client side:

import bluetooth
import threading

# Set the server's Bluetooth address and port number
bd_addr = "00:e0:4c:9a:f8:64"
port = 1

def client():
    while True:
        try:
            # Create a Bluetooth socket and connect to the server
            sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            sock.connect((bd_addr, port))

            # Continuously receive data from the server and print it out
            while True:
                data = sock.recv(1024)
                print("Received from server:", data.decode())

                # Prompt the user to type something to send back to the server
                txt = input("Type something to send back to the server: ")
                sock.send(txt.encode())

        except Exception as e:
            # If an error occurs, print the error message and close the socket
            # print(e)
            sock.close()

# Start the receive_data and send_data functions in separate threads
threading.Thread(target=client).start()

server side:

import bluetooth
import threading

def server():
    while True:
        try:
            # Create a Bluetooth socket and bind it to the specified port
            server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            port = 1
            server_sock.bind(("", port))
            server_sock.listen(1)

            # Accept an incoming connection from a client
            client_sock, address = server_sock.accept()
            print("Accepted connection from", address)

            # Continuously prompt the user to type something to send to the client
            while True:
                txt = input("Type something to send to the client: ")
                client_sock.send(txt.encode())

                # Receive data from the client and print it out
                data = client_sock.recv(1024)
                print("Received from client:", data.decode())

        except Exception as e:
            # If an error occurs, print the error message and close the sockets
            # print(e)
            client_sock.close()
            server_sock.close()

# Start the receive_data and send_data functions in separate threads
threading.Thread(target=server).start()

Is using threading this way, to prevent the rest of the program in each script getting stuck, in case of connection error on either side, correct?

Are there any other/better ways to fix the issue, such as callback function?


问:
How to create multiple many-to-many relationships in Entity Framework Core?
I read this answer here. The author adds in one of the comments saying:

... the easiest thing would be to add a PK to the UserSeries table.
Btw, keep in mind that with the "discriminator" approach, you will
have a "denormalized" model
(en.wikipedia.org/wiki/Database_normalization) which in the DB world
is something not desired. Think that if you have some properties that
are exclusive of the "Fav" relationship (for example, a column rating
saying how much you liked the series) and some other properties that
are exclusive of the "Watchlist" relationship (for example, a date you
would like to watch it), then you will have a lot of null depending on
the type of the row: fav rows will have null on the date column,
whereas watchlisted rows will have null on the fav column. That being
said, that approach however is many times being chosen because it's
really simple to make queries when all the data is in a single table.

In my case I have Book and Person entity classes:

```<code>public class Book
{
    [Key]
    public int ID { get; set; }

    [Required]
    public string Title { get; set; }

    public string? Subtitle { get; set; }

    public ICollection<PersonBook> Authors { get; set; }

    public ICollection<PersonBook> Reviewers { get; set; }

    public ICollection<PersonBook> Translators { get; set; }
}

public class Person
{
    [Key]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }

    public ICollection<PersonBook> BooksAuthored { get; set; }

    public ICollection<PersonBook> BooksReviewed { get; set; }

    public ICollection<PersonBook> BooksTranslated { get; set; }
}

public class PersonBook
{
    [ForeignKey("Book")]
    public int BookID { get; set; }

    public Book Book { get; set; }

    [ForeignKey("Person")]
    public int PersonID { get; set; }

    public Person Person { get; set; }
}
</code>```

If I go with that first solution to add a discriminator/additional attribute to PersonBook:

How to add that key while adding entities to the database?

How to overcome having a denormalized model?

Is there a third solution to this problem besides the 2 @dglozano mentioned in that post?

Body:
I read this answer here. The author adds in one of the comments saying:

... the easiest thing would be to add a PK to the UserSeries table.
Btw, keep in mind that with the "discriminator" approach, you will
have a "denormalized" model
(en.wikipedia.org/wiki/Database_normalization) which in the DB world
is something not desired. Think that if you have some properties that
are exclusive of the "Fav" relationship (for example, a column rating
saying how much you liked the series) and some other properties that
are exclusive of the "Watchlist" relationship (for example, a date you
would like to watch it), then you will have a lot of null depending on
the type of the row: fav rows will have null on the date column,
whereas watchlisted rows will have null on the fav column. That being
said, that approach however is many times being chosen because it's
really simple to make queries when all the data is in a single table.

In my case I have Book and Person entity classes:

public class Book
{
    [Key]
    public int ID { get; set; }

    [Required]
    public string Title { get; set; }

    public string? Subtitle { get; set; }

    public ICollection<PersonBook> Authors { get; set; }

    public ICollection<PersonBook> Reviewers { get; set; }

    public ICollection<PersonBook> Translators { get; set; }
}

public class Person
{
    [Key]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }

    public ICollection<PersonBook> BooksAuthored { get; set; }

    public ICollection<PersonBook> BooksReviewed { get; set; }

    public ICollection<PersonBook> BooksTranslated { get; set; }
}

public class PersonBook
{
    [ForeignKey("Book")]
    public int BookID { get; set; }

    public Book Book { get; set; }

    [ForeignKey("Person")]
    public int PersonID { get; set; }

    public Person Person { get; set; }
}

If I go with that first solution to add a discriminator/additional attribute to PersonBook:

How to add that key while adding entities to the database?

How to overcome having a denormalized model?

Is there a third solution to this problem besides the 2 @dglozano mentioned in that post?


问:
pyqt show window again when same process execute
what i want is
1.program run on system tray
2.user forgot program is already running
3.user run the program
4.showing up the program from tray already running, not new process

I already tried check that if same process running in first process, if detected, show up window and kill the second process. but i think it's not best solution

How can I do this?

```<code>class SystemTrayIcon(QSystemTrayIcon):
    def __init__(self, parent):
        QSystemTrayIcon.__init__(self, QIcon(icon_image_path + 'tray_icon5.png'))
        self.parent = parent
        menu = QMenu()
        menu.setStyleSheet('''
            font-size: 12px;
            width: 120px;
        ''')

        show_action = menu.addAction("open")
        show_action.triggered.connect(self.show_window)
        self.activated.connect(self.Activation_Reason)

        setting_action = menu.addAction("settings")
        setting_action.triggered.connect(self.show_setting)

        menu.addSeparator()

        exit_action = menu.addAction(exit"")
        exit_action.triggered.connect(self.exit_window)
        self.setContextMenu(menu)

    def Activation_Reason(self, index):
        if index == 2 :
            self.show_window()

    def show_window(self):
        self.parent.window().show()

    def exit_window(self):
        self.hide()
        QCoreApplication.instance().quit()

    def show_setting(self):
        tab_click_connector = TabClickConnector.get_instance()
        tab_click_connector.emit(3)
        self.show_window()
</code>```

Body:
what i want is
1.program run on system tray
2.user forgot program is already running
3.user run the program
4.showing up the program from tray already running, not new process

I already tried check that if same process running in first process, if detected, show up window and kill the second process. but i think it's not best solution

How can I do this?

class SystemTrayIcon(QSystemTrayIcon):
    def __init__(self, parent):
        QSystemTrayIcon.__init__(self, QIcon(icon_image_path + 'tray_icon5.png'))
        self.parent = parent
        menu = QMenu()
        menu.setStyleSheet('''
            font-size: 12px;
            width: 120px;
        ''')

        show_action = menu.addAction("open")
        show_action.triggered.connect(self.show_window)
        self.activated.connect(self.Activation_Reason)

        setting_action = menu.addAction("settings")
        setting_action.triggered.connect(self.show_setting)

        menu.addSeparator()

        exit_action = menu.addAction(exit"")
        exit_action.triggered.connect(self.exit_window)
        self.setContextMenu(menu)

    def Activation_Reason(self, index):
        if index == 2 :
            self.show_window()

    def show_window(self):
        self.parent.window().show()

    def exit_window(self):
        self.hide()
        QCoreApplication.instance().quit()

    def show_setting(self):
        tab_click_connector = TabClickConnector.get_instance()
        tab_click_connector.emit(3)
        self.show_window()


问:
how to connect ELK to Oracle DB using JDBC input plugin
how can I connect and transfer data from ORACLE DB to elasticsearch.
I installed elasticsearch logstash and kibana, but I can't find the config file to connect.
My product version is 7.17.8.


问:
Can't push due to unknown Git LFS objects (error GH008)
My LFS storage was over the limit, so deleted the repo to reset it. I created a new repo and set that as my new remote origin. Now when I push I get an error like this:

remote: error: GH008: Your push referenced at least 49 unknown Git LFS objects

It suggests I use git lfs push --all origin master which gives me the error that it was unable find a source for an object. Then it proceeds to tell me there are apparently a few missing or corrupt local objects, but they don't appear to be missing when I search for them and they seem completely fine.

I'm thinking this has got to do with me deleting the old repo but not sure exactly what. I'm not sure what exactly is different between me pushing to this new repo and the old one.

How do I fix this?


问:
Getting all xml files in a folder and subfolders
Currently I'm able to get and return files from a directory. However, it cannot get only xml files and get files from sub-folders.

Example folder:

```<code>folder
   |_ folder1
      |_file1.xml
      |_file2.xml
   |_ folder2
      |_file3.xml
 file4.xml
</code>```

Expected return:

```<code>file1.xml
file2.xml
file3.xml
file4.xml
</code>```

My current code is like this

```<code>def get_files(d):
    return [os.path.join(d, f) for f in os.listdir(d) if os.path.isfile(os.path.join(d, f))]

get_files(*filepath*)
</code>```

And the code only returns file4.xml

Body:
Currently I'm able to get and return files from a directory. However, it cannot get only xml files and get files from sub-folders.

Example folder:

folder
   |_ folder1
      |_file1.xml
      |_file2.xml
   |_ folder2
      |_file3.xml
 file4.xml

Expected return:

file1.xml
file2.xml
file3.xml
file4.xml

My current code is like this

def get_files(d):
    return [os.path.join(d, f) for f in os.listdir(d) if os.path.isfile(os.path.join(d, f))]

get_files(*filepath*)

And the code only returns file4.xml


问:
Pyqtgraph adds extra point in 3D GLViewWidget
I made an app to plot data from .log file. This app has a button, which opens second window, where I try to make a 3D simulation according to some data. In fact MainWindow displays SimulationWindow in function:

```<code>def start_model(self):
    try:
        self.simulation = SimulationWin(self.data)
        self.simulation.show()
    except AttributeError:
        print("No data to start simulation")
</code>```

My second windows class:

```<code>class SimulationWin(QtWidgets.QMainWindow, sim_viewer.Ui_MainWindow):
    def __init__(self, data):
        super().__init__()
        self.setupUi(self)
        self.data = data
        self.state = 0
        self.id = -1

        self.viewer = gl.GLViewWidget()
        self.viewer.setWindowTitle('STL Viewer')
        self.viewer.setCameraPosition(distance=10)
        g = gl.GLGridItem()
        g.setSize(20, 20, 20)
        g.setSpacing(1, 1)
        self.viewer.addItem(g)

        self.horizontalLayout_2.addWidget(self.viewer)

        self.pause_button.clicked.connect(self.start)
        self.next_button.clicked.connect(self.next)
        self.prev_button.clicked.connect(self.previous)

        self.x_data = list(self.data["vehicle_local_position"]["x"])
        self.y_data = list(self.data["vehicle_local_position"]["y"])
        self.z_data = list(self.data["vehicle_local_position"]["z"])

        self.point = gl.GLScatterPlotItem(pos=[self.x_data[0], self.y_data[0], self.z_data[0]],
                                          color=pg.glColor("#0072BD"))
        self.viewer.addItem(self.point)

        self.timer = Qt.QTimer()
        print(self.point)

    def update(self):
        self.point.setData(pos=[self.x_data[self.id], self.y_data[self.id], -self.z_data[self.id]])

    def start(self):
        self.state = 1 if self.state == 0 else 0
        if self.state:
            self.animation()
        else:
            self.timer.stop()

    def next(self):
        self.id += 1
        if self.id > len(self.x_data):
            self.id = 0
            self.timer.stop()
            print("End Of Simulation")
        else:
            self.update()

    def previous(self):
        self.id -= 1
        if self.id < 0:
            self.id = len(self.x_data)
        else:
            self.update()

    def animation(self):
        self.timer.timeout.connect(self.next)
        self.timer.start(10)
</code>```

When I open with window sometimes another extra point displays:
Extra point with coordinates (0, 0, 0)
It might start blinking and so on. Sometimes there are two or more extra points
Extra point with coordinates (0, 0, 0)

Tried to check self.viewer.items list to find extra point, but there are only Grid object and ScatterPlot object. In addition to it, I tried to print self.point.pos to find out, whether there would be coordinates of extra point. Nothing help - this point still display time by time.
Removing items from self.viewer deletes Grid and both of points

P.S. Displayed code was just an attempt to test Pyqtgraph in 3D plotting, that's why apologize me for some mistakes and so on.

Body:
I made an app to plot data from .log file. This app has a button, which opens second window, where I try to make a 3D simulation according to some data. In fact MainWindow displays SimulationWindow in function:

def start_model(self):
    try:
        self.simulation = SimulationWin(self.data)
        self.simulation.show()
    except AttributeError:
        print("No data to start simulation")

My second windows class:

class SimulationWin(QtWidgets.QMainWindow, sim_viewer.Ui_MainWindow):
    def __init__(self, data):
        super().__init__()
        self.setupUi(self)
        self.data = data
        self.state = 0
        self.id = -1

        self.viewer = gl.GLViewWidget()
        self.viewer.setWindowTitle('STL Viewer')
        self.viewer.setCameraPosition(distance=10)
        g = gl.GLGridItem()
        g.setSize(20, 20, 20)
        g.setSpacing(1, 1)
        self.viewer.addItem(g)

        self.horizontalLayout_2.addWidget(self.viewer)

        self.pause_button.clicked.connect(self.start)
        self.next_button.clicked.connect(self.next)
        self.prev_button.clicked.connect(self.previous)

        self.x_data = list(self.data["vehicle_local_position"]["x"])
        self.y_data = list(self.data["vehicle_local_position"]["y"])
        self.z_data = list(self.data["vehicle_local_position"]["z"])

        self.point = gl.GLScatterPlotItem(pos=[self.x_data[0], self.y_data[0], self.z_data[0]],
                                          color=pg.glColor("#0072BD"))
        self.viewer.addItem(self.point)

        self.timer = Qt.QTimer()
        print(self.point)

    def update(self):
        self.point.setData(pos=[self.x_data[self.id], self.y_data[self.id], -self.z_data[self.id]])

    def start(self):
        self.state = 1 if self.state == 0 else 0
        if self.state:
            self.animation()
        else:
            self.timer.stop()

    def next(self):
        self.id += 1
        if self.id > len(self.x_data):
            self.id = 0
            self.timer.stop()
            print("End Of Simulation")
        else:
            self.update()

    def previous(self):
        self.id -= 1
        if self.id < 0:
            self.id = len(self.x_data)
        else:
            self.update()

    def animation(self):
        self.timer.timeout.connect(self.next)
        self.timer.start(10)

When I open with window sometimes another extra point displays:
Extra point with coordinates (0, 0, 0)
It might start blinking and so on. Sometimes there are two or more extra points
Extra point with coordinates (0, 0, 0)

Tried to check self.viewer.items list to find extra point, but there are only Grid object and ScatterPlot object. In addition to it, I tried to print self.point.pos to find out, whether there would be coordinates of extra point. Nothing help - this point still display time by time.
Removing items from self.viewer deletes Grid and both of points

P.S. Displayed code was just an attempt to test Pyqtgraph in 3D plotting, that's why apologize me for some mistakes and so on.


问:
How to customize the countdown time in rewarded video ads?
I want the countdown time of Rewarded Video Admob to be fixed at 30 seconds, is it possible?

On google admob documentation, the countdown time ranges from 5 to 30s
https://support.google.com/admob/answer/7372450?hl=en


问:
Restrict sending emails when cell values are not entered
I'd want emails not to trigger when a condition is met when there aren't any values in a row.

Current scenario:

I have a condition which prompts an alert message (YES/NO) whenever a value is entered in cell 5 in (column 5). And when I click YES, an email is triggered with the help of installable trigger, but even when there is no data in a specific row, when I update value in cell 5, and click on YES button on alert prompt, email is sent. I want to restrict; email should be sent only when there is a value even if I press YES button on alert prompt.

I have an Installable trigger set and it works basis on the alert option set - YES/NO.

```<code>function sendMailEdit(e) {
if (e.range.columnStart != 6 || e.range.isBlank()|| !["Approved", "Rejected", "Duplicate"].includes(e.range.getValue())) return;
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var trix = sheet.getSheetByName('Response');
var status = trix.getRange(e.range.rowStart, 1, 1, 6).getValue();
var sh=SpreadsheetApp.getUi();
var response = sh.alert(
"Please confirm","Do you want to proceed?", sh.ButtonSet.YES_NO);
if (response == sh.Button.YES){
if (e.range.columnStart == 6 || e.value == "Approved" || e.value == "Rejected" || e.value == "Duplicate")
{
const rData = e.source.getActiveSheet().getRange(e.range.rowStart, 1, 1, 6).getValues();
    let EmployeeName = rData[0][2];
    let Reviewer = rData[0][4];
    let Status = rData[0][5];
    Logger.log(Status);
    var ccmail = "tesing123@gmail.com";
    var UpdateEmail =

 ('<html>' +
           '<body>' +
            '<head>' +
            '<style>table, th,tr{border: 2px solid black;}</style>' +
            '</head>' +
            '<tr style="background-color:#d3ecdc;"><td width=500 height=auto; colspan=6><br>Hi ' + EmployeeName + ',<br><br> Your suggestion has been ' + Status + ' by ' + Reviewer + '<br> you can check the comments here <br><br>Regards,<br>"Rajanee"<br><br></td></tr>' +
           '</body>' +
           '</html>')

     MailApp.sendEmail({
     to: EmployeeName,
     subject: 'Idea Status!',
     htmlBody: UpdateEmail,
     name: 'Ideas',
     cc: ccmail
    });
}}}
</code>```

Body:
I'd want emails not to trigger when a condition is met when there aren't any values in a row.

Current scenario:

I have a condition which prompts an alert message (YES/NO) whenever a value is entered in cell 5 in (column 5). And when I click YES, an email is triggered with the help of installable trigger, but even when there is no data in a specific row, when I update value in cell 5, and click on YES button on alert prompt, email is sent. I want to restrict; email should be sent only when there is a value even if I press YES button on alert prompt.

I have an Installable trigger set and it works basis on the alert option set - YES/NO.

function sendMailEdit(e) {
if (e.range.columnStart != 6 || e.range.isBlank()|| !["Approved", "Rejected", "Duplicate"].includes(e.range.getValue())) return;
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var trix = sheet.getSheetByName('Response');
var status = trix.getRange(e.range.rowStart, 1, 1, 6).getValue();
var sh=SpreadsheetApp.getUi();
var response = sh.alert(
"Please confirm","Do you want to proceed?", sh.ButtonSet.YES_NO);
if (response == sh.Button.YES){
if (e.range.columnStart == 6 || e.value == "Approved" || e.value == "Rejected" || e.value == "Duplicate")
{
const rData = e.source.getActiveSheet().getRange(e.range.rowStart, 1, 1, 6).getValues();
    let EmployeeName = rData[0][2];
    let Reviewer = rData[0][4];
    let Status = rData[0][5];
    Logger.log(Status);
    var ccmail = "tesing123@gmail.com";
    var UpdateEmail =

 ('' +
           '' +
            '' +
            '' +
            '' +
            '

Hi ' + EmployeeName + ',

 Your suggestion has been ' + Status + ' by ' + Reviewer + '
 you can check the comments here

Regards,
"Rajanee"

' +
           '' +
           '')

     MailApp.sendEmail({
     to: EmployeeName,
     subject: 'Idea Status!',
     htmlBody: UpdateEmail,
     name: 'Ideas',
     cc: ccmail
    });
}}}


问:
Socket Not working if we import controller from inversify but if we import the controller from inversify-socket-util it is work

Socket Not working if we import controller from inversify but if we import the controller from inversify-socket-util it is works.

unable to apply middleware in controller if we import controller from inversify-socket-util

not works rest of the controller if we import controller from inversify-socket-util

(e.g)
socket not work mentioned in 1st issue above
import { interfaces, controller, httpGet, request, response, httpPost } from "inversify-express-utils";
@controller('/following', SITE_MAINTENANCE)

socket will work but rest of the code dont and occurs 2 and 3rd issue above
import { interfaces, httpGet, request, response, httpPost } from "inversify-express-utils";
import {
controller
} from "inversify-socket-utils";

@controller('/following')

currently I have used inversify-express-util for my whole app. so that I try to implement inversify-socket-util package.

is there any working code for inversify-socket-util kindly share for the reference

I need any working example code for socket using inversify-socket-util package with some controller class.


问:
How to pass a templated function as argument to another function
I have the following class:

```<code>class myClass
{
private:
    /* data */
public:
    myClass(/* args */);
    ~myClass();
    template<class T>
    static bool testFun1(const T &args);
    static bool testFun2(const int &args);

    void callerFun();

    template<class CallbackReturn = void, typename handlerReturn = bool, class ...Args>
    static handlerReturn errorHandler(myClass *obj, CallbackReturn (*callback)(const Args &...obj) = nullptr, const Args &...param);
};
</code>```

I want to pass both "testFun1" and "testFun2" as arguments to "errorHandler" method.

I know how to pass "testFun2" :

```<code>myClass::errorHandler(this, &myClass::testFun2, 23);
</code>```

However, when I try something like the following, the program won't compile:

```<code>myClass::errorHandler(this, &myClass::testFun1<int, char, bool>, (int) 23, 'c', true);
</code>```

This is the compilation time error:

```<code>error: cannot convert ‘<unresolved overloaded function type>’ to ‘void (*)(const int&, const char&, const bool&)’
   48 |     myClass::errorHandler(this, &myClass::testFun1<int, char, bool>, (int) 23, 'c', true);
</code>```

Thanks in advance

Body:
I have the following class:

class myClass
{
private:
    /* data */
public:
    myClass(/* args */);
    ~myClass();
    template<class T>
    static bool testFun1(const T &args);
    static bool testFun2(const int &args);

    void callerFun();

    template<class CallbackReturn = void, typename handlerReturn = bool, class ...Args>
    static handlerReturn errorHandler(myClass *obj, CallbackReturn (*callback)(const Args &...obj) = nullptr, const Args &...param);
};

I want to pass both "testFun1" and "testFun2" as arguments to "errorHandler" method.

I know how to pass "testFun2" :

myClass::errorHandler(this, &myClass::testFun2, 23);

However, when I try something like the following, the program won't compile:

myClass::errorHandler(this, &myClass::testFun1<int, char, bool>, (int) 23, 'c', true);

This is the compilation time error:

error: cannot convert ‘<unresolved overloaded function type>’ to ‘void (*)(const int&, const char&, const bool&)’
   48 |     myClass::errorHandler(this, &myClass::testFun1<int, char, bool>, (int) 23, 'c', true);

Thanks in advance


问:
How to use kill -9 -1 or pkill -u <OS username for application services> command in bash script
I was developed oracle application services auto down script. Script is running successfully. But after running script I need to kill the process.

I tried it using kill -9 -1 and  pkill -u <OS username for application services> both commands. But I did not get expected results.

. <env path> run

sh


问:
Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it). Here have to add that flag
```<code>const { addAfterLoader, loaderByName } = require("@craco/craco");

module.exports = {
  webpack: {
    configure(webpackConfig) {
      addAfterLoader(webpackConfig, loaderByName("babel-loader"), {
        test: /\.mdx?$/,
        loader: require.resolve("@mdx-js/loader"),
      });
      return webpackConfig;
    },
  },
};

</code>```

Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
File was processed with these loaders:

./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js

./node_modules/babel-loader/lib/index.js

./node_modules/source-map-loader/dist/cjs.js

Where I have to add topLevelAwait this flag in between these codes.

Body:
const { addAfterLoader, loaderByName } = require("@craco/craco");

module.exports = {
  webpack: {
    configure(webpackConfig) {
      addAfterLoader(webpackConfig, loaderByName("babel-loader"), {
        test: /\.mdx?$/,
        loader: require.resolve("@mdx-js/loader"),
      });
      return webpackConfig;
    },
  },
};

Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
File was processed with these loaders:

./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js

./node_modules/babel-loader/lib/index.js

./node_modules/source-map-loader/dist/cjs.js

Where I have to add topLevelAwait this flag in between these codes.


问:
I have data from useQuery hook but I cannot use it
I have this issue in two different files and I cannot seem to find a solution to either of them. I do not know how to use the onSuccess properly and so I resorted to setting state data inside the onSuccess. What I would like is to be able to map through the data that was returned from the useQuery hook.

```<code>const [ticker, setTicker] = useState(props.router.query.stock)
const [stockCurrentPrice, setStockCurrentPrice] = useState(parseFloat(props.router.query.currentPrice))
const [listDocs, setListDocs] = useState([])
async function fetchDocs() {
        try {
            const loc = getLoc()
            const queryCollection = query(collection(db, loc), where("stockTicker", "==", ticker))
            const snapshot = await getDocs(queryCollection);
            let arr = []
            snapshot.forEach(doc => {
                // console.log(doc.data())
                arr.push(doc.data())
            })
            return arr
        } catch (error) {
            console.log(error)
        }
    }

    const {data, status} = useQuery({queryKey: [pid, db], queryFn: () => fetchDocs(),
    onSuccess: (collectedData) => {
        setListDocs(collectedData)
        return collectedData
    }})

</code>```

the rendering of the components

```<code>
{listDocs?.map((doc) => {
                                if (doc.ticker !== undefined) {
                                return (<tr key={doc.stockTicker} className="bg-black flex flex-col flex-no wrap sm:table-row rounded-lg sm:rounded-none mb-2 sm:mb-0">
                                    <td className="p-3 text-left">Type</td>
                                    <td className="p-3 text-left">Shares</td>
                                    <td className="p-3 text-left">Price</td>
                                    <td className="p-3 text-left">Return</td>
                                    <td className="p-3 text-left" width="110px">Actions</td>
                                </tr>)
                                }
                            })}
</code>```

For some reason, when I try to map either listDocs or data, it still returns undefined. But if I print it out or even render the information in a JSON string format, it renders perfectly fine. Why is that?

Body:
I have this issue in two different files and I cannot seem to find a solution to either of them. I do not know how to use the onSuccess properly and so I resorted to setting state data inside the onSuccess. What I would like is to be able to map through the data that was returned from the useQuery hook.

const [ticker, setTicker] = useState(props.router.query.stock)
const [stockCurrentPrice, setStockCurrentPrice] = useState(parseFloat(props.router.query.currentPrice))
const [listDocs, setListDocs] = useState([])
async function fetchDocs() {
        try {
            const loc = getLoc()
            const queryCollection = query(collection(db, loc), where("stockTicker", "==", ticker))
            const snapshot = await getDocs(queryCollection);
            let arr = []
            snapshot.forEach(doc => {
                // console.log(doc.data())
                arr.push(doc.data())
            })
            return arr
        } catch (error) {
            console.log(error)
        }
    }

    const {data, status} = useQuery({queryKey: [pid, db], queryFn: () => fetchDocs(),
    onSuccess: (collectedData) => {
        setListDocs(collectedData)
        return collectedData
    }})

the rendering of the components

{listDocs?.map((doc) => {
                                if (doc.ticker !== undefined) {
                                return (

                                    Type
                                    Shares
                                    Price
                                    Return
                                    Actions

)
                                }
                            })}

For some reason, when I try to map either listDocs or data, it still returns undefined. But if I print it out or even render the information in a JSON string format, it renders perfectly fine. Why is that?


问:
How to analyze memory consumption when running application inside container
I am running a RxJava-Micronaut with application and sqlite database inside the container. This application is having a scheduled job which process half millions string records from database (it calls other api in the batch of 200 records during that process) . We are loading all these records in one shot using RxJava Flowable and using BackPressure Drop Strategy. There is no OutOfMemoryError.

I am trying to understand memory consumption by container. Container memory limit has been set to 512M.

My Docker file is having below JVM params

```<code>EXPOSE 8080
CMD java -Dcom.sun.management.jmxremote -Xms200m -Xmx235m -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:+HeapDumpOnOutOfMemoryError -XX:+ExitOnOutOfMemoryError -XX:HeapDumpPath=/var/data/heapdump.hprof -Dmicronaut.environments=${CONFIG_ENV} -XX:+PrintCommandLineFlags -jar myapp.jar
</code>```

Here I have Jvm min and max to 200M and 235M respectively.

What here I am looking is to understand all components which is contributing to container memory consumption.

When I check the docker stats for the container, it shows memory usage around 450M out of 512 even if the schedule job inside docker is not running. How can I check what all is contributing to this memory usage.

As suggested I have checked inside the container and found java process is consuming that much memory (439M)

How to investigate further here. I believe heap dump will show details or memory occupied in heap which in my case max is 235M. What else might be contributing to 437M? How can I check that ?

Thanks

Body:
I am running a RxJava-Micronaut with application and sqlite database inside the container. This application is having a scheduled job which process half millions string records from database (it calls other api in the batch of 200 records during that process) . We are loading all these records in one shot using RxJava Flowable and using BackPressure Drop Strategy. There is no OutOfMemoryError.

I am trying to understand memory consumption by container. Container memory limit has been set to 512M.

My Docker file is having below JVM params

EXPOSE 8080
CMD java -Dcom.sun.management.jmxremote -Xms200m -Xmx235m -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:+HeapDumpOnOutOfMemoryError -XX:+ExitOnOutOfMemoryError -XX:HeapDumpPath=/var/data/heapdump.hprof -Dmicronaut.environments=${CONFIG_ENV} -XX:+PrintCommandLineFlags -jar myapp.jar

Here I have Jvm min and max to 200M and 235M respectively.

What here I am looking is to understand all components which is contributing to container memory consumption.

When I check the docker stats for the container, it shows memory usage around 450M out of 512 even if the schedule job inside docker is not running. How can I check what all is contributing to this memory usage.

As suggested I have checked inside the container and found java process is consuming that much memory (439M)

How to investigate further here. I believe heap dump will show details or memory occupied in heap which in my case max is 235M. What else might be contributing to 437M? How can I check that ?

Thanks


问:
How to create session key on behalf or public key identifier
I got this description for SKey block in documentation for generating XML request

Element: Skey (mandatory): Value of this element is base-64 encoded
value of encrypted 256-bit AES session key. Session key must be
dynamically generated for every transaction (session key must not be
reused) and must not be stored anywhere except in memory. See next
chapter for encryption details.

Attributes: ci – (mandatory) Public key certificate identifier using
which “skey” was encrypted. UIDAI may have multiple public keys in
field at the same time. Value of this attribute is the certificate
expiration date in the format “YYYYMMDD”. Expiry date of the
certificate can be obtained from the certificate itself

And I want something like this:-

```<code>        A00<?xml version="1.0" encoding="UTF-8"?><Auth xmlns="http://www.uidai.gov.in/authentication/uid-auth-request/2.0" ac="public" lk="Mssshhhhhhhhhhhhhhhhhhhhhhhhsssssssssssfff" rc="Y" sa="public" tid="" txn="AuthDemoClient:PUBLIC:20180601103742966" uid="1111111111111111" ver="2.5"><Uses bio="n" otp="n" pa="n" pfa="n" pi="y" pin="n"/><Meta dc="" dpId="" mc="" mi="" rdsId="" rdsVer=""/>

    <Skey ci="20201030">lrsFAH8bGjpEetiMEb7AFQBBOZeP0I6L21nY7weKKYE0/SakC7E6jlQXjNtSCH8IISIb3EorbdwsCWFGq9z/TILQs0JmB15fKAopTZx6/mNkGjuTLk1t6tjTValJxXmWq8/F8IHcjuM70yWwwMmuwJRuxZPOkoFFjSBUqFVkSVKtBYQobTUEWL7i/PEyMIQyDRfQy/SMTdYDqFQStnBQofvBcj0UbUT2I9g0+2VEwwFKuiZZ8KEuYvy+SE9YvnOncARtqxp1jveeyPkpuA2QymiDnpfcV/mjBnqCHdeVBHM1tB3YIUCtO9rNHqfUP13iI0eWRwQeYrsKctRDmLkB0g==</Skey>

    <Data type="X">MjAxOC0wNi0wMVQxMDozNzo0MRq5ZwZTA2ddEuSXZNj5oofGkQ01abbLy0+3SGV6CbrRFSRb8Ve/6a+IOxAE5Zswij3GYebGAw4XeXAOI88Vxd2zxO//ZFq6loq5o0TbSIRg/oBJ7hpa5J2P20nGeMKsaygSvmsY9M3DFTAcjy3Dkq5RalwW+zELM58l9VgyQXhTVO0fqzgH2XNrYPsBfSpfI1Uwx4t1OCjhdyJJWnDG8c3JADzbA4smISjw//K38qUumUjIaRClwnx61xdj0992hwTN7fNK5iDkN78g8NppKQz+mY/zMJRPjJAJK6Ead+ioiwMquPVAfwdHS7hUC5XIqXSKYjpyd3soeM0kkS81d3vrnUuFFmkJp/Q==</Data>

<Hmac>9nkUcE3nYbs22zXa9zX0PAUn0hNG3lo/vKfEy3x5ELeHUfXpXcR3y92x1ZEmM5K0</Hmac>

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>NMemaHgaMX0aO51Mbq1jKsOsCG0=</DigestValue></Reference></SignedInfo><SignatureValue>izR4i53yCpzlO3AVcgtmSj87H5AzEya4NZTGwPe3Pq3wPOgtwvXsHVzM4GBoo/8MaDzyJpYxstXmcmdZvcd2ljCg0byJ4hOZepd7w0OYbudDICD5wVObaLGGcWJm5mIoeusy/3rOf/SIF/UxUUNe/9Ao4IBKuAq7iAuE2+B7vECeGfeDNEBtqgrKByAHAMoz6tV0QeeShfPFIvuEWXuMSzaJGDspGSy6sn/ktgYm7kNLqELklFjmJQUSbJ/S9BO3Z2O6gXVGa+/A7vBkHGwfBOo7fOA9sqjHLWG3VjfKU4x/Qpl2Nlwqo36UH1PuoV40sPsKLYWJvmzPA3ldjeNywA==</SignatureValue><KeyInfo><X509Data><X509SubjectName>CN=DS NSDL E GOVERNANCE INFRASTRUCTURE LIMITED 3,2.5.4.51=#133331535420464c4f4f522054494d455320544f574552204b414d414c41204d494c4c5320434f4d504f554e44205342204d415247,STREET=MUMBAI,ST=MAHARASHTRA,2.5.4.17=#1306343030303133,OU=PAN TIN AND UID OPERATIONS,O=NSDL E GOVERNANCE INFRASTRUCTURE LIMITED,C=IN</X509SubjectName><X509Certificate>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</X509Certificate></X509Data></KeyInfo></Signature>
</Auth>
</code>```

Body:
I got this description for SKey block in documentation for generating XML request

Element: Skey (mandatory): Value of this element is base-64 encoded
value of encrypted 256-bit AES session key. Session key must be
dynamically generated for every transaction (session key must not be
reused) and must not be stored anywhere except in memory. See next
chapter for encryption details.

Attributes: ci – (mandatory) Public key certificate identifier using
which “skey” was encrypted. UIDAI may have multiple public keys in
field at the same time. Value of this attribute is the certificate
expiration date in the format “YYYYMMDD”. Expiry date of the
certificate can be obtained from the certificate itself

And I want something like this:-

        A00<?xml version="1.0" encoding="UTF-8"?><Auth xmlns="http://www.uidai.gov.in/authentication/uid-auth-request/2.0" ac="public" lk="Mssshhhhhhhhhhhhhhhhhhhhhhhhsssssssssssfff" rc="Y" sa="public" tid="" txn="AuthDemoClient:PUBLIC:20180601103742966" uid="1111111111111111" ver="2.5"><Uses bio="n" otp="n" pa="n" pfa="n" pi="y" pin="n"/><Meta dc="" dpId="" mc="" mi="" rdsId="" rdsVer=""/>

    <Skey ci="20201030">lrsFAH8bGjpEetiMEb7AFQBBOZeP0I6L21nY7weKKYE0/SakC7E6jlQXjNtSCH8IISIb3EorbdwsCWFGq9z/TILQs0JmB15fKAopTZx6/mNkGjuTLk1t6tjTValJxXmWq8/F8IHcjuM70yWwwMmuwJRuxZPOkoFFjSBUqFVkSVKtBYQobTUEWL7i/PEyMIQyDRfQy/SMTdYDqFQStnBQofvBcj0UbUT2I9g0+2VEwwFKuiZZ8KEuYvy+SE9YvnOncARtqxp1jveeyPkpuA2QymiDnpfcV/mjBnqCHdeVBHM1tB3YIUCtO9rNHqfUP13iI0eWRwQeYrsKctRDmLkB0g==</Skey>

    <Data type="X">MjAxOC0wNi0wMVQxMDozNzo0MRq5ZwZTA2ddEuSXZNj5oofGkQ01abbLy0+3SGV6CbrRFSRb8Ve/6a+IOxAE5Zswij3GYebGAw4XeXAOI88Vxd2zxO//ZFq6loq5o0TbSIRg/oBJ7hpa5J2P20nGeMKsaygSvmsY9M3DFTAcjy3Dkq5RalwW+zELM58l9VgyQXhTVO0fqzgH2XNrYPsBfSpfI1Uwx4t1OCjhdyJJWnDG8c3JADzbA4smISjw//K38qUumUjIaRClwnx61xdj0992hwTN7fNK5iDkN78g8NppKQz+mY/zMJRPjJAJK6Ead+ioiwMquPVAfwdHS7hUC5XIqXSKYjpyd3soeM0kkS81d3vrnUuFFmkJp/Q==</Data>

<Hmac>9nkUcE3nYbs22zXa9zX0PAUn0hNG3lo/vKfEy3x5ELeHUfXpXcR3y92x1ZEmM5K0</Hmac>

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>NMemaHgaMX0aO51Mbq1jKsOsCG0=</DigestValue></Reference></SignedInfo><SignatureValue>izR4i53yCpzlO3AVcgtmSj87H5AzEya4NZTGwPe3Pq3wPOgtwvXsHVzM4GBoo/8MaDzyJpYxstXmcmdZvcd2ljCg0byJ4hOZepd7w0OYbudDICD5wVObaLGGcWJm5mIoeusy/3rOf/SIF/UxUUNe/9Ao4IBKuAq7iAuE2+B7vECeGfeDNEBtqgrKByAHAMoz6tV0QeeShfPFIvuEWXuMSzaJGDspGSy6sn/ktgYm7kNLqELklFjmJQUSbJ/S9BO3Z2O6gXVGa+/A7vBkHGwfBOo7fOA9sqjHLWG3VjfKU4x/Qpl2Nlwqo36UH1PuoV40sPsKLYWJvmzPA3ldjeNywA==</SignatureValue><KeyInfo><X509Data><X509SubjectName>CN=DS NSDL E GOVERNANCE INFRASTRUCTURE LIMITED 3,2.5.4.51=#133331535420464c4f4f522054494d455320544f574552204b414d414c41204d494c4c5320434f4d504f554e44205342204d415247,STREET=MUMBAI,ST=MAHARASHTRA,2.5.4.17=#1306343030303133,OU=PAN TIN AND UID OPERATIONS,O=NSDL E GOVERNANCE INFRASTRUCTURE LIMITED,C=IN</X509SubjectName><X509Certificate>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</X509Certificate></X509Data></KeyInfo></Signature>
</Auth>


问:
cant display images on Flutter web
i am creating a flutter web project and i am facing a problem than when i try to load images from REST APIs and show them in flutter mobile app, it works fine but on Flutter Web it doesn't show me pics. I used some packeges like ImageNetwork and ExtendedImageNetwork from flutter pub dev. ImageNetwork shows me Images succusfully but this causes some Web rendering issues. like when i hot reload then images remain visible for a while even hot reload has been started. i have attached a output giff file to show my problem.
is there any other solution for rendering images on flutter web then do suggest me.

Title: cant display images on Flutter web


问:
Telugu Text is not displaying properly in itext generated pdf
I am creating a small Bilingual application in Telugu and English languages using Java and Spring Boot. Here, I have to generate Pdf both Telugu and English Languages. So, I am Generating a pdf Using itext Library. This pdf has both Telugu and English Languages. but, The problem is English is appearing Properly in the PDF but Telugu Language is not displaying properly

I've tried with multiple .ttf telugu fonts. but the telugu text is not displaying properly.

example: the Telugu text that I want to show is వ్యవసాయ శాఖ
but the output that I am getting is "Please refer the below image"

So, anyone Please guide me to solve this issue. Thank You.

Below I am Attching the Code Please, check.

1.Code

public class samplepdf {

    public void export(HttpServletRequest request, HttpServletResponse response)
                    throws DocumentException, ParseException, java.io.IOException, SAXException, ParserConfigurationException
    {

        ByteArrayOutputStream baos = null;
        baos = new ByteArrayOutputStream();

        //Create Document
        Document doc  = new Document();

        //Pass 2 things ---> What to render & where to render
        PdfWriter instance2 = PdfWriter.getInstance(doc, response.getOutputStream());

        Paragraph bottom = new Paragraph();
        bottom.add(Chunk.NEWLINE);
        bottom.setAlignment(Element.ALIGN_BOTTOM);
        bottom.setAlignment(Element.ALIGN_CENTER);

        //Open the document to start the work
        doc.open();

          Paragraph  paragraph2 = new Paragraph();
          //String fontpath = request.getServletContext().getRealPath("/static/TeluguFonts/NotoSansTelugu-Light.ttf");
          //String fontpath = request.getServletContext().getRealPath("/static/TeluguFonts/Chathura Light.ttf");
          //String fontpath = request.getServletContext().getRealPath("/static/TeluguFonts/Gidugu.ttf");
          //String fontpath = request.getServletContext().getRealPath("/static/TeluguFonts/akshar.ttf");
          //String fontpath = request.getServletContext().getRealPath("/static/TeluguFonts/gautami.ttf");
          //String fontpath = request.getServletContext().getRealPath("/static/TeluguFonts/Chathura Light.ttf");
          String fontpath = request.getServletContext().getRealPath("/static/TeluguFonts/NotoSansTelugu-VariableFont.ttf");
          BaseFont bf_cjk1 = BaseFont.createFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
          Font cjk1 = new Font(bf_cjk1, 12,Font.NORMAL);
          paragraph2.setFont(cjk1);
          paragraph2.add(Chunk.NEWLINE);
          paragraph2.add("వ్యవసాయ శాఖ");
          paragraph2.add(Chunk.NEWLINE);
          paragraph2.add(Chunk.NEWLINE);
          doc.add(paragraph2);

        //Here, Closing the document.
            doc.close();
            try {
                ServletOutputStream os = response.getOutputStream();
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
}
```


问:
OKR Board for Jira Error on link issue to KR: maximum number of expressions in a list is 1000
When I try to link an issue to KR I get an error:

```<code>
There was a SQL exception thrown by the Active Objects library: Database: - name: Oracle - version: Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production - minor version:0 - major version:19 Driver: - name: Oracle JDBC driver - version:12.2.0.1.0 java.sql.SQLSyntaxErrorException: ORA-01795: maximum number of expressions in a list is 1000

</code>```

by reviewing the log file I found OKR plugin generates one SELECT command that has one WHERE clause with more than 1000 numbers in IN condition:

```<code>
SELECT  .......  FROM ........ ....... WHERE OBJECTIVE."ISS" = :1 AND OBJECTIVE."DELETED" = 0 AND (OBJECTIVE."ID" in (20,71,79,92,93,105, ...........,1683,1684,1687)

</code>```

I use Jira version 8.5.7 and OKR Board Plugin version [f.3.0.0, b.6.1.2] and use Oracle for the database

How can I solve my problem?

Thanks.

Body:
When I try to link an issue to KR I get an error:

There was a SQL exception thrown by the Active Objects library: Database: - name: Oracle - version: Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production - minor version:0 - major version:19 Driver: - name: Oracle JDBC driver - version:12.2.0.1.0 java.sql.SQLSyntaxErrorException: ORA-01795: maximum number of expressions in a list is 1000

by reviewing the log file I found OKR plugin generates one SELECT command that has one WHERE clause with more than 1000 numbers in IN condition:

SELECT  .......  FROM ........ ....... WHERE OBJECTIVE."ISS" = :1 AND OBJECTIVE."DELETED" = 0 AND (OBJECTIVE."ID" in (20,71,79,92,93,105, ...........,1683,1684,1687)

I use Jira version 8.5.7 and OKR Board Plugin version [f.3.0.0, b.6.1.2] and use Oracle for the database

How can I solve my problem?

Thanks.


问:
vuesax table element styles disappear
If you go to page 2 and go to page 1 again, the table that disappeared appears in white.
disappeared 'element.style {}' is not returned. Is there any way to keep this? I tried to control it by adding a class, but it failed. I think it's probably because it's v-if, not v-show, but I don't know how to properly fix vuesax.

```<code>     <template #tbody>
    <vs-tr
      :key="i"
      v-for="(exchangedatasT, i) in $vs.getPage(exchangedatas1, page, max)"
      :data="exchangedatasT"
      class="tableColor"
      :class="{
        lastDay: todayGo2 !== new Date().toISOString().substring(0, 10),
      }"
    >
      <vs-td
        ><p>{{ exchangedatasT.Machinecd }}</p></vs-td
      >
      <vs-td
        ><p>{{ exchangedatasT.Exchangedt }}</p></vs-td
      >
      <vs-td
        ><p>{{ exchangedatasT.ExchangeItemnm }}</p></vs-td
      >
      <vs-td
        ><p>{{ exchangedatasT.Specnm }}</p></vs-td
      >
      <vs-td class="pointer" :id="[`e${i}`]" @click="click2(i)">
        <p>
          <span :id="[`s${i}`]"></span>
          {{ exchangedatasT.CntDay }}
        </p>
      </vs-td>
      <vs-td
        ><p>{{ exchangedatasT.ExchangeUser }}</p></vs-td
      >
      <!-- <vs-td>{{ exchangedatasT.Remark }}</vs-td> -->
    </vs-tr>
  </template>
</code>```

```<code>    created() {
    const vm = this;
    axios
      //소모품 항목
      .post(``, {
        Machinecd: "Test",
        Exchangedt: vm.todayGo2,
      })
      .then((response) => {
        const entries = Object.values(response.data);
        vm.exchangedatas1 = entries;
        console.log(response.data);
        for (let i = 0; i < Object.keys(response.data).length; i++) {
          this.ExchangeUser = response.data[i].ExchangeUser;
          this.CntDay = response.data[i].CntDay;
          setTimeout(() => {
            if (response.data[i].CntDay == 99999) {
              document.getElementById(`e${i}`).style.background = "#ceecc5";
              document.getElementById(`e${i}`).style.color = "#176f24";
              document.getElementById(
                `s${i}`
              ).innerHTML = `<span>교체 완료 : </span>`;
            } else if (response.data[i].CntDay > 20) {
              document.getElementById(`e${i}`).style.background = "#ceecc5";
              document.getElementById(`e${i}`).style.color = "#176f24";
              document.getElementById(
                `s${i}`
              ).innerHTML = `<span>점검 완료 : </span>`;
            } else if (response.data[i].CntDay > 10) {
              document.getElementById(`e${i}`).style.background = "#ffe079";
              document.getElementById(`e${i}`).style.color = "#db751c";
              document.getElementById(
                `s${i}`
              ).innerHTML = `<span>미점검 : </span>`;
            } else {
              document.getElementById(`e${i}`).style.background = "#e96666";
              document.getElementById(`e${i}`).style.color = "#ffffff";
              document.getElementById(
                `s${i}`
              ).innerHTML = `<span>미점검 : </span>`;
            }
          }, 1);
        }
      })
      .catch((error) => {
        console.error(error);
      });
  },
</code>```

Title: vuesax table element styles disappear

Body:
If you go to page 2 and go to page 1 again, the table that disappeared appears in white.
disappeared 'element.style {}' is not returned. Is there any way to keep this? I tried to control it by adding a class, but it failed. I think it's probably because it's v-if, not v-show, but I don't know how to properly fix vuesax.

     <template #tbody>
    <vs-tr
      :key="i"
      v-for="(exchangedatasT, i) in $vs.getPage(exchangedatas1, page, max)"
      :data="exchangedatasT"
      class="tableColor"
      :class="{
        lastDay: todayGo2 !== new Date().toISOString().substring(0, 10),
      }"
    >
      <vs-td
        >
{{ exchangedatasT.Machinecd }}
</vs-td
      >
      <vs-td
        >
{{ exchangedatasT.Exchangedt }}
</vs-td
      >
      <vs-td
        >
{{ exchangedatasT.ExchangeItemnm }}
</vs-td
      >
      <vs-td
        >
{{ exchangedatasT.Specnm }}
</vs-td
      >
      <vs-td class="pointer" :id="[`e${i}`]" @click="click2(i)">

          <span :id="[`s${i}`]">
          {{ exchangedatasT.CntDay }}

      </vs-td>
      <vs-td
        >
{{ exchangedatasT.ExchangeUser }}
</vs-td
      >

    </vs-tr>
  </template>

    created() {
    const vm = this;
    axios
      //소모품 항목
      .post(``, {
        Machinecd: "Test",
        Exchangedt: vm.todayGo2,
      })
      .then((response) => {
        const entries = Object.values(response.data);
        vm.exchangedatas1 = entries;
        console.log(response.data);
        for (let i = 0; i < Object.keys(response.data).length; i++) {
          this.ExchangeUser = response.data[i].ExchangeUser;
          this.CntDay = response.data[i].CntDay;
          setTimeout(() => {
            if (response.data[i].CntDay == 99999) {
              document.getElementById(`e${i}`).style.background = "#ceecc5";
              document.getElementById(`e${i}`).style.color = "#176f24";
              document.getElementById(
                `s${i}`
              ).innerHTML = `<span>교체 완료 : </span>`;
            } else if (response.data[i].CntDay > 20) {
              document.getElementById(`e${i}`).style.background = "#ceecc5";
              document.getElementById(`e${i}`).style.color = "#176f24";
              document.getElementById(
                `s${i}`
              ).innerHTML = `<span>점검 완료 : </span>`;
            } else if (response.data[i].CntDay > 10) {
              document.getElementById(`e${i}`).style.background = "#ffe079";
              document.getElementById(`e${i}`).style.color = "#db751c";
              document.getElementById(
                `s${i}`
              ).innerHTML = `<span>미점검 : </span>`;
            } else {
              document.getElementById(`e${i}`).style.background = "#e96666";
              document.getElementById(`e${i}`).style.color = "#ffffff";
              document.getElementById(
                `s${i}`
              ).innerHTML = `<span>미점검 : </span>`;
            }
          }, 1);
        }
      })
      .catch((error) => {
        console.error(error);
      });
  },


问:
When using UIGraphicsBeginImageContextWithOptions, the text color cannot be adjusted
hi i am a beginner in speed writing
I refer to this writing method and apply it in my segment controller
I am using swift 5.7 method
This can be successfully used and executed with

But i have a problem that i can't change the color of my text and icon
I try to add something in "string.draw" but it dosen't work

The method I use is as follows

```<code>class func textEmbededImage(image: UIImage, string: String, color: UIColor, imageAlignment: Int = 0) -> UIImage {
    let font = UIFont.systemFont(ofSize: 13.0)
    let expectedTextSize: CGSize = (string as NSString).size(withAttributes: [NSAttributedString.Key.font: font])
    let width: CGFloat = expectedTextSize.width + image.size.width + 5.0
    let height: CGFloat = max(expectedTextSize.height, image.size.width)
    let size: CGSize = CGSize(width: width, height: height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    let context: CGContext = UIGraphicsGetCurrentContext()!
    context.setFillColor(color.cgColor)

    let fontTopPosition: CGFloat = (height - expectedTextSize.height) / 2.0
    let textOrigin: CGFloat = (imageAlignment == 0) ? image.size.width + 5 : 0
    let textPoint: CGPoint = CGPoint.init(x: textOrigin, y: fontTopPosition)
    string.draw(at: textPoint, withAttributes: [.font : font , .foregroundColor : UIColor.gray])
    let flipVertical: CGAffineTransform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)
    context.concatenate(flipVertical)

    let alignment: CGFloat =  (imageAlignment == 0) ? 0.0 : expectedTextSize.width + 5.0
    context.draw(image.cgImage!, in: CGRect.init(x: alignment, y: ((height - image.size.height) / 2.0), width: image.size.width, height: image.size.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext(
    return newImage!
}
</code>```

and i use like this

```<code>    customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "QQQ", color: .red),forSegmentAt: 0)
    customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "AAA", color: .white),forSegmentAt: 1)
    customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "BBB", color: .red),forSegmentAt: 2)
</code>```

but this doesn't work for
I went into debug view hierarchy xcode to try to find the problem
debug view hierarchy
But what puzzles me even more is that what I see on the right layer is the gray color I set, but what I see on the screen is the blue color set by the system

How can I solve it

In addition, I also want to ask, how to make different text colors to achieve the effect when selecting

Body:
hi i am a beginner in speed writing
I refer to this writing method and apply it in my segment controller
I am using swift 5.7 method
This can be successfully used and executed with

But i have a problem that i can't change the color of my text and icon
I try to add something in "string.draw" but it dosen't work

The method I use is as follows

class func textEmbededImage(image: UIImage, string: String, color: UIColor, imageAlignment: Int = 0) -> UIImage {
    let font = UIFont.systemFont(ofSize: 13.0)
    let expectedTextSize: CGSize = (string as NSString).size(withAttributes: [NSAttributedString.Key.font: font])
    let width: CGFloat = expectedTextSize.width + image.size.width + 5.0
    let height: CGFloat = max(expectedTextSize.height, image.size.width)
    let size: CGSize = CGSize(width: width, height: height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    let context: CGContext = UIGraphicsGetCurrentContext()!
    context.setFillColor(color.cgColor)

    let fontTopPosition: CGFloat = (height - expectedTextSize.height) / 2.0
    let textOrigin: CGFloat = (imageAlignment == 0) ? image.size.width + 5 : 0
    let textPoint: CGPoint = CGPoint.init(x: textOrigin, y: fontTopPosition)
    string.draw(at: textPoint, withAttributes: [.font : font , .foregroundColor : UIColor.gray])
    let flipVertical: CGAffineTransform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)
    context.concatenate(flipVertical)

    let alignment: CGFloat =  (imageAlignment == 0) ? 0.0 : expectedTextSize.width + 5.0
    context.draw(image.cgImage!, in: CGRect.init(x: alignment, y: ((height - image.size.height) / 2.0), width: image.size.width, height: image.size.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext(
    return newImage!
}

and i use like this

    customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "QQQ", color: .red),forSegmentAt: 0)
    customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "AAA", color: .white),forSegmentAt: 1)
    customSegment.setImage(UIImage.textEmbededImage(image: UIImage.add, string: "BBB", color: .red),forSegmentAt: 2)

but this doesn't work for
I went into debug view hierarchy xcode to try to find the problem
debug view hierarchy
But what puzzles me even more is that what I see on the right layer is the gray color I set, but what I see on the screen is the blue color set by the system

How can I solve it

In addition, I also want to ask, how to make different text colors to achieve the effect when selecting


问:
Rust compiler error: future cannot be sent between threads safely required for the cast from X to Y
I have seen other questions about similar errors with implementing send, but my error message is different. This is the error message:

```<code>future cannot be sent between threads safely
required for the cast from `impl warp::Future<Output = Result<std::string::String, std::string::String>>` to the object type `dyn warp::Future<Output = Result<std::string::String, std::string::String>> + std::marker::Send`
</code>```

I'm getting this on a function on an implementation of an async_trait. Here's the impl:

```<code>use std::borrow::Borrow;

use async_trait::async_trait;
use mongodb::{
    bson::{doc, oid::ObjectId, Document},
    error::Error,
    options::FindOneOptions,
    results::InsertOneResult,
    Client,
};
use serde::{de::DeserializeOwned, Serialize};

pub struct MessagesRepository<'a> {
    pub(crate) client: &'a Client,
}

#[async_trait]
impl<'a> super::Repository<'a> for MessagesRepository<'a> {
    fn with_client(client: &'a Client) -> Self {
        MessagesRepository { client: client }
    }

    async fn find_one<'b, T: DeserializeOwned + Sync + Send + Unpin>(
        &self,
        filter: Document,
        find_one_options: FindOneOptions,
    ) -> Result<Option<T>, Error> {
        let collection = self
            .client
            .database("App")
            .collection::<T>("Messages");

        collection.find_one(filter, find_one_options).await
    }

    async fn insert_one<'b, T: DeserializeOwned + Sync + Send + Unpin + Serialize>(
        &self,
        new_document: impl Borrow<T>,
    ) -> Result<String, String> {
        let collection = self
            .client
            .database("App")
            .collection::<T>("Messages");

        let result = collection.insert_one(new_document, None).await;

        match result {
            Ok(_) => Ok("Success".to_string()),
            Err(_) => Err("Error".to_string()),
        }
    }
}
</code>```

This is the trait:

```<code>use std::borrow::Borrow;

use async_trait::async_trait;
use mongodb::{
    bson::Document, error::Error, options::FindOneOptions, results::InsertOneResult, Client,
};
use serde::{de::DeserializeOwned, Serialize};

#[async_trait]
pub trait Repository<'a> {
    fn with_client(client: &'a Client) -> Self;
    async fn find_one<'b, T: DeserializeOwned + Sync + Send + Unpin>(
        &self,
        filter: Document,
        find_one_options: FindOneOptions,
    ) -> Result<Option<T>, Error>;

    async fn insert_one<'b, T: DeserializeOwned + Sync + Send + Unpin + Serialize>(
        &self,
        new_document: impl Borrow<T>,
    ) -> Result<String, String>;
}

</code>```

Anyone have any ideas? I'm using the mongodb rust driver. Thanks!

Body:
I have seen other questions about similar errors with implementing send, but my error message is different. This is the error message:

future cannot be sent between threads safely
required for the cast from `impl warp::Future<Output = Result<std::string::String, std::string::String>>` to the object type `dyn warp::Future<Output = Result<std::string::String, std::string::String>> + std::marker::Send`

I'm getting this on a function on an implementation of an async_trait. Here's the impl:

use std::borrow::Borrow;

use async_trait::async_trait;
use mongodb::{
    bson::{doc, oid::ObjectId, Document},
    error::Error,
    options::FindOneOptions,
    results::InsertOneResult,
    Client,
};
use serde::{de::DeserializeOwned, Serialize};

pub struct MessagesRepository<'a> {
    pub(crate) client: &'a Client,
}

#[async_trait]
impl<'a> super::Repository<'a> for MessagesRepository<'a> {
    fn with_client(client: &'a Client) -> Self {
        MessagesRepository { client: client }
    }

    async fn find_one<'b, T: DeserializeOwned + Sync + Send + Unpin>(
        &self,
        filter: Document,
        find_one_options: FindOneOptions,
    ) -> Result<Option<T>, Error> {
        let collection = self
            .client
            .database("App")
            .collection::<T>("Messages");

        collection.find_one(filter, find_one_options).await
    }

    async fn insert_one<'b, T: DeserializeOwned + Sync + Send + Unpin + Serialize>(
        &self,
        new_document: impl Borrow<T>,
    ) -> Result<String, String> {
        let collection = self
            .client
            .database("App")
            .collection::<T>("Messages");

        let result = collection.insert_one(new_document, None).await;

        match result {
            Ok(_) => Ok("Success".to_string()),
            Err(_) => Err("Error".to_string()),
        }
    }
}

This is the trait:

use std::borrow::Borrow;

use async_trait::async_trait;
use mongodb::{
    bson::Document, error::Error, options::FindOneOptions, results::InsertOneResult, Client,
};
use serde::{de::DeserializeOwned, Serialize};

#[async_trait]
pub trait Repository<'a> {
    fn with_client(client: &'a Client) -> Self;
    async fn find_one<'b, T: DeserializeOwned + Sync + Send + Unpin>(
        &self,
        filter: Document,
        find_one_options: FindOneOptions,
    ) -> Result<Option<T>, Error>;

    async fn insert_one<'b, T: DeserializeOwned + Sync + Send + Unpin + Serialize>(
        &self,
        new_document: impl Borrow<T>,
    ) -> Result<String, String>;
}

Anyone have any ideas? I'm using the mongodb rust driver. Thanks!


问:
How to make raw Bootstrap Tooltip working in React
I have used Bootstrap (bundled with Popper) in my project to show a Tooltip when you hover on a button. I use the code from Bootstrap docs. However the tooltip is not visible.

```<code><li className="nav-item">
    <button type="button" className="btn grad-text"
            data-bs-toggle="tooltip" data-bs-placement="top"
            title="Meet the Algorithms"
    >
        <i className="fas fa-solid fa-laptop-code fa-lg"></i>
    </button>
</li>
</code>```

The above code here shows title on bottom on hover. That was visible even before I added

```<code>data-bs-toggle="tooltip" data-bs-placement="top"
</code>```

to my <button> element. Below is the screenshot of the same.

I am using raw Bootstrap not React-Bootstrap and the version I am using is 5.2.3

Can anyone help me with how to show the tooltip like Bootstrap Tooltip over here. Thank you.

Body:
I have used Bootstrap (bundled with Popper) in my project to show a Tooltip when you hover on a button. I use the code from Bootstrap docs. However the tooltip is not visible.

    <button type="button" className="btn grad-text"
            data-bs-toggle="tooltip" data-bs-placement="top"
            title="Meet the Algorithms"
    >

    </button>

The above code here shows title on bottom on hover. That was visible even before I added

data-bs-toggle="tooltip" data-bs-placement="top"

to my <button> element. Below is the screenshot of the same.

I am using raw Bootstrap not React-Bootstrap and the version I am using is 5.2.3

Can anyone help me with how to show the tooltip like Bootstrap Tooltip over here. Thank you.


问:
How to Concat Two Metric Value in One Value using promql?
I want to concat two metrices to display the dashboard

Example : metrice 1 value:

```<code>21
</code>```

metrics 2 value:

```<code>100
</code>```

Excpeted Output: "21/100"

Body:
I want to concat two metrices to display the dashboard

Example : metrice 1 value:

21

metrics 2 value:

100

Excpeted Output: "21/100"


问:
Vue.js - temporarily highlight table row with transition
I am working on a simple view with Vue.js that does the CRUD actions and to improve UX I want to highlight the recently added/modified record row for 1-2 seconds.

However, no solution of mine seems to work. The background color is changed as expected, however, that happens without any transition.

Would greatly appreciate any hint!

Here's my component (replaced irrelevant bits with ...):

```<code><template>
    <v-container>
        <h2>Sponsors</h2>
        <v-table>
            <thead>
            <tr>
                <th>Name</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="sponsor in sponsors" :key="sponsor.id" :class="{highlight: lastSponsorId === sponsor.id }">
                <td>{{ sponsor.name }}</td>
                <td>
                    <div class="btn-group">
                        <v-btn depressed color="success" @click="openEditDialog(sponsor)">Edit</v-btn>
                        <v-btn color="error" @click="deleteSponsor(sponsor)">Delete</v-btn>
                    </div>
                </td>
            </tr>
            </tbody>
        </v-table>
    </v-container>
</template>

<script>
....

export default {
    name: 'SponsorsIndex',
    components: {
        SponsorModal,
        ConfirmationDialog
    },
    ...
    watch: {
        ...
        lastSponsorId (val) {
            if (val !== null) {
                setTimeout(() => {
                    this.$store.dispatch('sponsors/resetLastSponsor');
                }, 1 * 1000);
            }
        },
    },
....
}
</script>

<style>
tr {
    background-color: white;
}
.highlight {
    background-color: blue;
    color: white;
    transition-property: background-color;
    transition: background-color 2s;
}
</style>
</code>```

UPDATE
I was able to achieve fade-out of the background with the following CSS

```<code>tr {
    transition: 1s all ease;
}
tr.highlight {
    background-color: #76b5c5;
    color: white;
}
</code>```

However, it only fades out but does not fade-in

Body:
I am working on a simple view with Vue.js that does the CRUD actions and to improve UX I want to highlight the recently added/modified record row for 1-2 seconds.

However, no solution of mine seems to work. The background color is changed as expected, however, that happens without any transition.

Would greatly appreciate any hint!

Here's my component (replaced irrelevant bits with ...):

<template>
    <v-container>

Sponsors

        <v-table>

                Name
                Actions

                {{ sponsor.name }}

                        <v-btn depressed color="success" @click="openEditDialog(sponsor)">Edit</v-btn>
                        <v-btn color="error" @click="deleteSponsor(sponsor)">Delete</v-btn>

        </v-table>
    </v-container>
</template>

UPDATE
I was able to achieve fade-out of the background with the following CSS

tr {
    transition: 1s all ease;
}
tr.highlight {
    background-color: #76b5c5;
    color: white;
}

However, it only fades out but does not fade-in