问:
FT2232HQ synchronous FIFO mode is much slower than it should be in Ubuntu
I'm working on a project which needs to collect data from FPGA. I'm using an FTDI FT2232H UART/FIFO IC. According to the datasheet, the chip can transfer up to 40 Mbytes/s in single-channel synchronous FIFO mode. However, when I use the Linux system (Ubuntu 20.04), the transfer speed I get is only 10 Mbytes/s.

This is the C++ code I use:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include "ftd2xx.h"
#include <iostream>
#include <chrono>
#define BUF_SIZE 0x10

#define MAX_DEVICES 1000
#define OneSector 8
int main(int argc, char *argv[]){
    system("sudo rmmod ftdi_sio");
    system("sudo rmmod usbserial");
    system("setserial /dev/ttyUSB0 low_latency");
    system("setserial /dev/ttyUSB1 low_latency");

    FT_STATUS ftStatus;
    FT_HANDLE ftHandle0;
    FT_HANDLE ftHandle1;
    UCHAR Mask = 0xFF;
    UCHAR Mode;
    UCHAR LatencyTimer = 2; //our default setting is 16
    int retCode = EXIT_FAILURE;
    DWORD libVersion = 0;
    static FT_PROGRAM_DATA Data;
    char *BufPtrs[3]; // pointer to array of 3 pointers
    char Buffer1[64]; // buffer for description of first device
    char Buffer2[64]; // buffer for description of second device

    BufPtrs[0] = Buffer1;
    BufPtrs[1] = Buffer2;
    BufPtrs[2] = NULL; // last entry should be NULL

    UCHAR rxBuffer[65536] = {0};
    // memset(rxBuffer,0,1028);
    DWORD byteCount;
    auto start = std::chrono::high_resolution_clock::now();
    auto stop = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    double mbps;
    double secondsElapsed;
    // DWORD devIndex = 0; // first device
    // char Buffer[64]; // more than enough room!

    DWORD RxBytes = 8;
    DWORD BytesReceived;
    DWORD numDevs;
    // char RxBuffer[OneSector];
    ftStatus = FT_GetLibraryVersion(&libVersion);
    if (ftStatus == FT_OK)
    {
        printf("D2xx Library version = 0x%x\n", (unsigned int)libVersion);
    }
    else
    {
        printf("Error reading library version.\n");
        return 1;
    }

    ftStatus = FT_ListDevices(BufPtrs,&numDevs,FT_LIST_ALL|FT_OPEN_BY_DESCRIPTION);
    if (ftStatus == FT_OK) {
    // FT_ListDevices OK, product descriptions are in Buffer1 and Buffer2, and
    // numDevs contains the number of devices connected
    if(numDevs<=0){
        goto exit;
    }
    printf("%s\n", Buffer1);
    printf("%s\n", Buffer2);
    printf("Number of ports: %d\n", numDevs);
    }
    else {
    // FT_ListDevices failed
    }
    ftStatus = FT_Open(0, &ftHandle0);
    if(ftStatus != FT_OK) {
        printf("FT_Open(%d) failed\n", 0);}
    else{
        printf("Port 0 FT_Open succeeded.  Handle is %p\n", ftHandle0);}

    Data.Signature1 = 0x00000000;
    Data.Signature2 = 0xffffffff;
    Data.Manufacturer = (char *)malloc(256); /* E.g "deponce" */
    Data.ManufacturerId = (char *)malloc(256); /* E.g. "FT" */
    Data.Description = (char *)malloc(256); /* E.g. "USB HS Serial Converter" */
    Data.SerialNumber = (char *)malloc(256); /* E.g. "FT000001" if fixed, or NULL */
    if (Data.Manufacturer == NULL ||
        Data.ManufacturerId == NULL ||
        Data.Description == NULL ||
        Data.SerialNumber == NULL)
    {
        printf("Failed to allocate memory.\n");
        retCode = 1;
        goto exit;
    }
    ftStatus = FT_EE_Read(ftHandle0, &Data);
    if(ftStatus != FT_OK) {
        printf("FT_EE_Read failed\n");
        retCode = 1;
        goto exit;
    }
    printf("FT_EE_Read succeeded.\n\n");
    printf("Signature1 = %d\n", (int)Data.Signature1);
    printf("Signature2 = %d\n", (int)Data.Signature2);
    printf("Version = %d\n", (int)Data.Version);
    printf("VendorId = 0x%04X\n", Data.VendorId);
    printf("ProductId = 0x%04X\n", Data.ProductId);
    printf("Manufacturer = %s\n", Data.Manufacturer);
    printf("ManufacturerId = %s\n", Data.ManufacturerId);
    Mode = 0x40;
    if(FT_SetBitMode(ftHandle0, Mask, Mode) == FT_OK){
        printf("set bit mode succeeded\n");}
    else{
        printf("set bit mode failed\n"); retCode=1; goto exit;}

    ftStatus = FT_SetLatencyTimer(ftHandle0, LatencyTimer);
    FT_SetUSBParameters(ftHandle0, 0x40000, 0x40000);
    FT_SetFlowControl(ftHandle0, FT_FLOW_RTS_CTS, 0x0, 0x0);
    FT_Purge(ftHandle0, FT_PURGE_RX);
    ftStatus = FT_SetTimeouts(ftHandle0, 500, 500);
    if(ftStatus == FT_OK){std::cout<<"set FT_SetTimeouts success."<<std::endl;}
    start = std::chrono::high_resolution_clock::now();
    for(int i = 0; i < 16384; i++){
        std::cout<<i<<std::endl;
        if(FT_Read(ftHandle0, rxBuffer, 65536, &byteCount) != FT_OK || byteCount != 65536) {
                        printf("Error while reading from the device. Exiting.\r\n");
                        goto exit;
                    }
    }
    std::cout<<std::endl;
    stop = std::chrono::high_resolution_clock::now();
    duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    std::cout << "Read 1GB from the FTDI in : "
    << duration.count()/1000000. << " seconds" << std::endl;
    mbps = 1024 / (duration.count()/1000000.);
    printf("Average read speed: %0.1f Mbps.\r\n", mbps);
    exit:
        return retCode;
}
```
<p>Here is the VHDL code:</p>
<pre class="lang-vhdl prettyprint-override"><code>library IEEE;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;
entity test_syn_fifo is
port
(
    CLK60M: in std_logic;
    CLK50M: in std_logic;
    TXE   : in std_logic;
    DATA  : buffer std_logic_vector (7 downto 0):="00000000";
    WR    : buffer std_logic:='1';
    );
end entity;

architecture Behavioral of test_syn_fifo is
    begin
    process(CLK60M,TXE, WR)
    begin
        if(CLK60M ='1'and CLK60M'event)then
            if(TXE='0')then
                DATA <= DATA+1;
                WR<='0';
            else
                DATA <= DATA;
                WR<='1';
            end if;
        else
            DATA <= DATA;

        end if;
    end process;

end Behavioral;
</code>```

Could you give me some suggestions on how to speed up in the Linux?

Body:
I'm working on a project which needs to collect data from FPGA. I'm using an FTDI FT2232H UART/FIFO IC. According to the datasheet, the chip can transfer up to 40 Mbytes/s in single-channel synchronous FIFO mode. However, when I use the Linux system (Ubuntu 20.04), the transfer speed I get is only 10 Mbytes/s.

This is the C++ code I use:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include "ftd2xx.h"
#include <iostream>
#include <chrono>
#define BUF_SIZE 0x10

#define MAX_DEVICES 1000
#define OneSector 8
int main(int argc, char *argv[]){
    system("sudo rmmod ftdi_sio");
    system("sudo rmmod usbserial");
    system("setserial /dev/ttyUSB0 low_latency");
    system("setserial /dev/ttyUSB1 low_latency");

    FT_STATUS ftStatus;
    FT_HANDLE ftHandle0;
    FT_HANDLE ftHandle1;
    UCHAR Mask = 0xFF;
    UCHAR Mode;
    UCHAR LatencyTimer = 2; //our default setting is 16
    int retCode = EXIT_FAILURE;
    DWORD libVersion = 0;
    static FT_PROGRAM_DATA Data;
    char *BufPtrs[3]; // pointer to array of 3 pointers
    char Buffer1[64]; // buffer for description of first device
    char Buffer2[64]; // buffer for description of second device

    BufPtrs[0] = Buffer1;
    BufPtrs[1] = Buffer2;
    BufPtrs[2] = NULL; // last entry should be NULL

    UCHAR rxBuffer[65536] = {0};
    // memset(rxBuffer,0,1028);
    DWORD byteCount;
    auto start = std::chrono::high_resolution_clock::now();
    auto stop = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    double mbps;
    double secondsElapsed;
    // DWORD devIndex = 0; // first device
    // char Buffer[64]; // more than enough room!

    DWORD RxBytes = 8;
    DWORD BytesReceived;
    DWORD numDevs;
    // char RxBuffer[OneSector];
    ftStatus = FT_GetLibraryVersion(&libVersion);
    if (ftStatus == FT_OK)
    {
        printf("D2xx Library version = 0x%x\n", (unsigned int)libVersion);
    }
    else
    {
        printf("Error reading library version.\n");
        return 1;
    }

    ftStatus = FT_ListDevices(BufPtrs,&numDevs,FT_LIST_ALL|FT_OPEN_BY_DESCRIPTION);
    if (ftStatus == FT_OK) {
    // FT_ListDevices OK, product descriptions are in Buffer1 and Buffer2, and
    // numDevs contains the number of devices connected
    if(numDevs<=0){
        goto exit;
    }
    printf("%s\n", Buffer1);
    printf("%s\n", Buffer2);
    printf("Number of ports: %d\n", numDevs);
    }
    else {
    // FT_ListDevices failed
    }
    ftStatus = FT_Open(0, &ftHandle0);
    if(ftStatus != FT_OK) {
        printf("FT_Open(%d) failed\n", 0);}
    else{
        printf("Port 0 FT_Open succeeded.  Handle is %p\n", ftHandle0);}

    Data.Signature1 = 0x00000000;
    Data.Signature2 = 0xffffffff;
    Data.Manufacturer = (char *)malloc(256); /* E.g "deponce" */
    Data.ManufacturerId = (char *)malloc(256); /* E.g. "FT" */
    Data.Description = (char *)malloc(256); /* E.g. "USB HS Serial Converter" */
    Data.SerialNumber = (char *)malloc(256); /* E.g. "FT000001" if fixed, or NULL */
    if (Data.Manufacturer == NULL ||
        Data.ManufacturerId == NULL ||
        Data.Description == NULL ||
        Data.SerialNumber == NULL)
    {
        printf("Failed to allocate memory.\n");
        retCode = 1;
        goto exit;
    }
    ftStatus = FT_EE_Read(ftHandle0, &Data);
    if(ftStatus != FT_OK) {
        printf("FT_EE_Read failed\n");
        retCode = 1;
        goto exit;
    }
    printf("FT_EE_Read succeeded.\n\n");
    printf("Signature1 = %d\n", (int)Data.Signature1);
    printf("Signature2 = %d\n", (int)Data.Signature2);
    printf("Version = %d\n", (int)Data.Version);
    printf("VendorId = 0x%04X\n", Data.VendorId);
    printf("ProductId = 0x%04X\n", Data.ProductId);
    printf("Manufacturer = %s\n", Data.Manufacturer);
    printf("ManufacturerId = %s\n", Data.ManufacturerId);
    Mode = 0x40;
    if(FT_SetBitMode(ftHandle0, Mask, Mode) == FT_OK){
        printf("set bit mode succeeded\n");}
    else{
        printf("set bit mode failed\n"); retCode=1; goto exit;}

    ftStatus = FT_SetLatencyTimer(ftHandle0, LatencyTimer);
    FT_SetUSBParameters(ftHandle0, 0x40000, 0x40000);
    FT_SetFlowControl(ftHandle0, FT_FLOW_RTS_CTS, 0x0, 0x0);
    FT_Purge(ftHandle0, FT_PURGE_RX);
    ftStatus = FT_SetTimeouts(ftHandle0, 500, 500);
    if(ftStatus == FT_OK){std::cout<<"set FT_SetTimeouts success."<<std::endl;}
    start = std::chrono::high_resolution_clock::now();
    for(int i = 0; i < 16384; i++){
        std::cout<<i<<std::endl;
        if(FT_Read(ftHandle0, rxBuffer, 65536, &byteCount) != FT_OK || byteCount != 65536) {
                        printf("Error while reading from the device. Exiting.\r\n");
                        goto exit;
                    }
    }
    std::cout<<std::endl;
    stop = std::chrono::high_resolution_clock::now();
    duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    std::cout << "Read 1GB from the FTDI in : "
    << duration.count()/1000000. << " seconds" << std::endl;
    mbps = 1024 / (duration.count()/1000000.);
    printf("Average read speed: %0.1f Mbps.\r\n", mbps);
    exit:
        return retCode;
}

Here is the VHDL code:

library IEEE;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;
entity test_syn_fifo is
port
(
    CLK60M: in std_logic;
    CLK50M: in std_logic;
    TXE   : in std_logic;
    DATA  : buffer std_logic_vector (7 downto 0):="00000000";
    WR    : buffer std_logic:='1';
    );
end entity;

architecture Behavioral of test_syn_fifo is
    begin
    process(CLK60M,TXE, WR)
    begin
        if(CLK60M ='1'and CLK60M'event)then
            if(TXE='0')then
                DATA <= DATA+1;
                WR<='0';
            else
                DATA <= DATA;
                WR<='1';
            end if;
        else
            DATA <= DATA;

        end if;
    end process;

end Behavioral;

Could you give me some suggestions on how to speed up in the Linux?


来源: stackexchange

问:
Angular insert a char-limit: Property 'invalid' does not exist on type 'HTMLTextAreaElement'. Did you mean 'oninvalid'?
I want to add a character limit and I did this:

but it shows an error by "invalid" last line

```<code><mat-form-field class="fbinput" appearance="outline" style="white-space: pre-wrap;" [formGroup]="myForm" >
  <textarea
    [(ngModel)]="enteredContent"
    id="content"
    matInput rows="6"
    name="content"
    required
    [maxlength]="maxChars"
    formControlName="wordLimitation"
    placeholder="{{'Feedback.notizEingeben' | translate}}"
    #content
    ngModel="content"

      >
  </textarea>
  <mat-error *ngIf="content.invalid">{{'Warnung.feedbackEingeben' | translate}}</mat-error>
</code>```

before the code was like this and had no errors

What can i do??

```<code><mat-form-field class="fbinput" appearance="outline" style="white-space: pre-wrap;">
  <textarea
    [(ngModel)]="enteredContent"
    id="content"
    matInput rows="6"
    name="content"
    required
    placeholder="{{'Feedback.notizEingeben' | translate}}"
    #content="ngModel">
  </textarea>
  <mat-error *ngIf="content.invalid">{{'Warnung.feedbackEingeben' | translate}}</mat-error>
</mat-form-field>

</mat-form-field>

</code>```

What can i do??
can someone help

ContentLicense: CC BY-SA 4.0

Body:
I want to add a character limit and I did this:

but it shows an error by "invalid" last line

<mat-form-field class="fbinput" appearance="outline" style="white-space: pre-wrap;" [formGroup]="myForm" >
  <textarea
    [(ngModel)]="enteredContent"
    id="content"
    matInput rows="6"
    name="content"
    required
    [maxlength]="maxChars"
    formControlName="wordLimitation"
    placeholder="{{'Feedback.notizEingeben' | translate}}"
    #content
    ngModel="content"

      >
  </textarea>
  <mat-error *ngIf="content.invalid">{{'Warnung.feedbackEingeben' | translate}}</mat-error>

before the code was like this and had no errors

What can i do??

<mat-form-field class="fbinput" appearance="outline" style="white-space: pre-wrap;">
  <textarea
    [(ngModel)]="enteredContent"
    id="content"
    matInput rows="6"
    name="content"
    required
    placeholder="{{'Feedback.notizEingeben' | translate}}"
    #content="ngModel">
  </textarea>
  <mat-error *ngIf="content.invalid">{{'Warnung.feedbackEingeben' | translate}}</mat-error>
</mat-form-field>

</mat-form-field>

What can i do??
can someone help


问:
RedirectMatch rule to remove amp param
I want to remove the AMP param from the URLs of my site and recirect the request to the original URl: /url_example/?amp=1 => /url_example/

I'm trying with RedirectMatch as follows:

```<code>RedirectMatch 301 ^(.*)\/(\?amp\=1)$ https://www.example.com/$1/
</code>```

But the URL does not change... what am I doing wrong?

Title: RedirectMatch rule to remove amp param

Body:
I want to remove the AMP param from the URLs of my site and recirect the request to the original URl: /url_example/?amp=1 => /url_example/

I'm trying with RedirectMatch as follows:

RedirectMatch 301 ^(.*)\/(\?amp\=1)$ https://www.example.com/$1/

But the URL does not change... what am I doing wrong?


问:
disable going to previous page after clicking a link
what I want to do; I don't want the user to come back from the page they went to when they clicked on a link. i.e. the back button should be completely disabled. I will put the exit button for the page that should go later. I tried window.location.replace but it didn't work

if you can go to the page from this link to understand what i want to do
https://awenarts.com/wer

Click on the news and click on any link on the page you go to. (arrow shape) What can I do to avoid returning to this page, namely disabling browser navigation completely.

href

```<code><a href="javascript:delay('pages/news-style-1/news.html')" >
</code>```

function that works when clicked

```<code>function delay (URL) {

    setTimeout( function() {
        window.location = URL
    }, 1000);

    var deneme = body.getBoundingClientRect().bottom * -1;
    tPage.classList.add('transition-close');
    body.classList.add('stop-scroll');
    tPage.style.display = "block";
    tPage.style.top = deneme + "px";
}
</code>```

current

how can I do that

Body:
what I want to do; I don't want the user to come back from the page they went to when they clicked on a link. i.e. the back button should be completely disabled. I will put the exit button for the page that should go later. I tried window.location.replace but it didn't work

if you can go to the page from this link to understand what i want to do
https://awenarts.com/wer

Click on the news and click on any link on the page you go to. (arrow shape) What can I do to avoid returning to this page, namely disabling browser navigation completely.

href

function that works when clicked

function delay (URL) {

    setTimeout( function() {
        window.location = URL
    }, 1000);

    var deneme = body.getBoundingClientRect().bottom * -1;
    tPage.classList.add('transition-close');
    body.classList.add('stop-scroll');
    tPage.style.display = "block";
    tPage.style.top = deneme + "px";
}

current

how can I do that


问:
Laraberg Gutenberg block validation error
I am trying to create a custom block to just show the code snippet on the frontend side. So, everything seem fine, content saved to the database as expected (escaped html) and showing on the front-end also as expected. But when try to edit the post, it throw an error. My ultimate goal is to use enlighterjs to show highlighted code snippets on the front-end side of my website.

```<code>Block validation: Block validation failed for `gutenberg-enlighter/enlighter-editable` (

Content generated by `save` function:

<code><strong>Hi from strong</strong></code>

Content retrieved from post body:

<code><strong>Hi from strong</strong></code>
</code>```
```<code>attributes: {
                        content: {
                            type: 'string',
                            selector: 'code.EnlighterJSRAW',
                            source: 'html',
                        },
}
</code>```

I have tried source as text but didn't solve my issue.

Updated: 21 Jan 2023
My issue is resolved now.
I have changed the edit and save method to below code:

```<code>edit: function (props) {
            return el('pre', blockProps,
                            el(RichText, {
                                tagName: 'code',
                                key: 'l24',
                                value: props.attributes.content,
                                preserveWhiteSpace: true,
                                __unstablePastePlainText: true,
                                onChange: content => props.setAttributes({
                                    content: content
                                }),
                                placeholder: "Insert Sourcecode..",
                            })
                        )
         },

         save: function (props) {
            const cssClasses = 'EnlighterJSRAW' + (props.className ? ' ' + props.className : '');

                // escape content if exist
                //console.log(props.attributes.content)
                const content = props.attributes.content.replace(/(\r\n|\r|\n)/g, '<br>');

                return el(RichText.Content,
                    Object.assign(blockProps, {
                        tagName: 'pre',
                        className: cssClasses,
                        value: content
                    }),
                );
         }
</code>```

Attributes are same :

```<code>attributes: {
                content: {
                    type: 'string',
                    selector: 'pre.EnlighterJSRAW',
                    source: 'html',
                },
</code>```

Body:
I am trying to create a custom block to just show the code snippet on the frontend side. So, everything seem fine, content saved to the database as expected (escaped html) and showing on the front-end also as expected. But when try to edit the post, it throw an error. My ultimate goal is to use enlighterjs to show highlighted code snippets on the front-end side of my website.

Block validation: Block validation failed for `gutenberg-enlighter/enlighter-editable` (

Content generated by `save` function:

Hi from strong

Content retrieved from post body:

Hi from strong

attributes: {
                        content: {
                            type: 'string',
                            selector: 'code.EnlighterJSRAW',
                            source: 'html',
                        },
}

I have tried source as text but didn't solve my issue.

Updated: 21 Jan 2023
My issue is resolved now.
I have changed the edit and save method to below code:

edit: function (props) {
            return el('pre', blockProps,
                            el(RichText, {
                                tagName: 'code',
                                key: 'l24',
                                value: props.attributes.content,
                                preserveWhiteSpace: true,
                                __unstablePastePlainText: true,
                                onChange: content => props.setAttributes({
                                    content: content
                                }),
                                placeholder: "Insert Sourcecode..",
                            })
                        )
         },

         save: function (props) {
            const cssClasses = 'EnlighterJSRAW' + (props.className ? ' ' + props.className : '');

                // escape content if exist
                //console.log(props.attributes.content)
                const content = props.attributes.content.replace(/(\r\n|\r|\n)/g, '
');

                return el(RichText.Content,
                    Object.assign(blockProps, {
                        tagName: 'pre',
                        className: cssClasses,
                        value: content
                    }),
                );
         }

Attributes are same :

attributes: {
                content: {
                    type: 'string',
                    selector: 'pre.EnlighterJSRAW',
                    source: 'html',
                },


问:
Write to journalctl -u [SERVICE] -f, from a different script
There is a service that I follow along with using the command

journalctl -u [servicename] -f

I'm hoping to add to the log trace I see from this command using an outside script/service. Is this possible?

I tried echoing directly to a log file for the service
I tried systemd-cat with the same service name using the -t flag


问:
How can I send the message in dm when he receives a degree
It won't let me send the message when a member gets an automatic rank.

```<code>client.on('messageCreate', async (message) => {
  // the ID of the guild the message.author is a member of
  let guildId = '1037086287548649503';
  let roleId = '1037086287699652627';

  try {
     let guild = await client.guilds.fetch(guildId);
     let member = await guild.members.fetch(message.author.id);

  if (member.roles.cache.has(roleId)) {
     console.log('User is an admin');
  }
  } catch (err) {
    console.log(err);
  }
})
</code>```

And this is the error in the console.

```<code>DiscordAPIError[10013]: Unknown User
 at SequentialHandler.runRequest (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\node_modules\discord.js\node_modules\@discordjs\rest\dist\index.js:659:15)
 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
 at async SequentialHandler.queueRequest (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\node_modules\discord.js\node_modules\@discordjs\rest\dist\index.js:458:14)
 at async REST.request (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\node_modules\discord.js\node_modules\@discordjs\rest\dist\index.js:902:22)
 at async GuildMemberManager._fetchSingle (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\node_modules\discord.js\src\managers\GuildMemberManager.js:489:18)
 at async MainClient.<anonymous> (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\nanospace.js:51:24) {
 requestBody: { files: undefined, json: undefined },
 rawError: { message: 'Unknown User', code: 10013 },
 code: 10013,
 status: 404,
 method: 'GET',
 url: 'https://discord.com/api/v10/guilds/1037086287548649503/members/1046173097801298022'
}
</code>```

In short, I want him to receive a message in dm when he receives a ror offered by the Patreon bot.

Body:
It won't let me send the message when a member gets an automatic rank.

client.on('messageCreate', async (message) => {
  // the ID of the guild the message.author is a member of
  let guildId = '1037086287548649503';
  let roleId = '1037086287699652627';

  try {
     let guild = await client.guilds.fetch(guildId);
     let member = await guild.members.fetch(message.author.id);

  if (member.roles.cache.has(roleId)) {
     console.log('User is an admin');
  }
  } catch (err) {
    console.log(err);
  }
})

And this is the error in the console.

DiscordAPIError[10013]: Unknown User
 at SequentialHandler.runRequest (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\node_modules\discord.js\node_modules\@discordjs\rest\dist\index.js:659:15)
 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
 at async SequentialHandler.queueRequest (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\node_modules\discord.js\node_modules\@discordjs\rest\dist\index.js:458:14)
 at async REST.request (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\node_modules\discord.js\node_modules\@discordjs\rest\dist\index.js:902:22)
 at async GuildMemberManager._fetchSingle (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\node_modules\discord.js\src\managers\GuildMemberManager.js:489:18)
 at async MainClient.<anonymous> (C:\Users\MihaiT\OneDrive\Desktop\Rovy
Manager\nanospace.js:51:24) {
 requestBody: { files: undefined, json: undefined },
 rawError: { message: 'Unknown User', code: 10013 },
 code: 10013,
 status: 404,
 method: 'GET',
 url: 'https://discord.com/api/v10/guilds/1037086287548649503/members/1046173097801298022'
}

In short, I want him to receive a message in dm when he receives a ror offered by the Patreon bot.


问:
java.lang.NumberFormatException: empty String
so I got this error on Android studio

```<code>
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androids.pmob4/com.androids.pmob4.MainActivity}: java.lang.NumberFormatException: empty String
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.androids.pmob4.MainActivity$3.init(MainActivity.java:82)
at com.androids.pmob4.MainActivity.onCreate(MainActivity.java:81)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

</code>```

Here's the code of the MainActivity.java

```<code>
package com.androids.pmob4;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
Button btsn;
EditText txtlat,txtlong;
String JsonURL = "https://lpmobilediff.000webhostapp.com/";
// Mendefiniskan Volley request queue yang akanmenangani URL request
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestQueue = Volley.newRequestQueue(this);
setContentView(R.layout.activity_main);
btsn = findViewById(R.id.btns);
txtlat = (EditText) findViewById(R.id.txtlat);
txtlong = (EditText) findViewById(R.id.txtlong);

        JsonArrayRequest arrayreq = new
                JsonArrayRequest(JsonURL,
                //parameter kedua adalah Listener overrides dengan method //onResponse() dan melewatkan JSONArray sebagai parameter

                new Response.Listener<JSONArray>() {
                    //mengambil response dari JSON request

                    @Override

                    public void onResponse(JSONArray response) {

                        try {

//                            for (int i = 0; i  response.length(); i++) {

//mengambil tiap JSON object didalam JSON array
JSONObject jsonObject = response.getJSONObject(1);
// menyimpan ke dalam string dengan nama "idemp" and"namaemp",
// dan convert dalam bentuk javascript objects
String idemp = jsonObject.getString("employee_id");
String namaemp = jsonObject.getString("employee_name");
TextView textView = findViewById(R.id.textView);
textView.setText(idemp+", "+namaemp+"");
//                            }
}
catch (JSONException e) {
// jika ada error json, print ke log
e.printStackTrace();
}
}
},
// parameter terakhir overrides adalah method onErrorResponse()dan // melewatkan VolleyError sebagai sebuah parameter
new Response.ErrorListener() {
@Override
// handle error yang disebabkan Volley
public void onErrorResponse(VolleyError error)
{
Log.e("Volley", "Error");
}
}
);
// Add JSON array request "arrayreq" ke request queue
requestQueue.add(arrayreq);
btsn.setOnClickListener(new View.OnClickListener() {
double doublat = Double.parseDouble(txtlat.getText().toString());
double doublong = Double.parseDouble(txtlong.getText().toString());
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MapsActivity.class);
intent.putExtra("INPUT_TEXTLAT", doublat);
intent.putExtra("INPUT_TEXTLONG", doublong);
startActivity(intent);
} });
}
}
</code>```

The problem is in this part

```<code>       requestQueue.add(arrayreq);
        btsn.setOnClickListener(new View.OnClickListener() {
      double doublat = Double.parseDouble(txtlat.getText().toString());
     double doublong = Double.parseDouble(txtlong.getText().toString());
           @Override
            public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, MapsActivity.class);
              intent.putExtra("INPUT_TEXTLAT", doublat);                 intent.putExtra("INPUT_TEXTLONG", doublong);
           startActivity(intent);             } });     }
</code>```

I tried to take value of edit text and parse it to double and then intent it to other class but then this error happens, it does works with string but when I parse it to Double the error occured, Does anyone have a solution for this?

Body:
so I got this error on Android studio

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androids.pmob4/com.androids.pmob4.MainActivity}: java.lang.NumberFormatException: empty String
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.androids.pmob4.MainActivity$3.init(MainActivity.java:82)
at com.androids.pmob4.MainActivity.onCreate(MainActivity.java:81)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Here's the code of the MainActivity.java

package com.androids.pmob4;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
Button btsn;
EditText txtlat,txtlong;
String JsonURL = "https://lpmobilediff.000webhostapp.com/";
// Mendefiniskan Volley request queue yang akanmenangani URL request
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestQueue = Volley.newRequestQueue(this);
setContentView(R.layout.activity_main);
btsn = findViewById(R.id.btns);
txtlat = (EditText) findViewById(R.id.txtlat);
txtlong = (EditText) findViewById(R.id.txtlong);

        JsonArrayRequest arrayreq = new
                JsonArrayRequest(JsonURL,
                //parameter kedua adalah Listener overrides dengan method //onResponse() dan melewatkan JSONArray sebagai parameter

                new Response.Listener<JSONArray>() {
                    //mengambil response dari JSON request

                    @Override

                    public void onResponse(JSONArray response) {

                        try {

//                            for (int i = 0; i  response.length(); i++) {

//mengambil tiap JSON object didalam JSON array
JSONObject jsonObject = response.getJSONObject(1);
// menyimpan ke dalam string dengan nama "idemp" and"namaemp",
// dan convert dalam bentuk javascript objects
String idemp = jsonObject.getString("employee_id");
String namaemp = jsonObject.getString("employee_name");
TextView textView = findViewById(R.id.textView);
textView.setText(idemp+", "+namaemp+"");
//                            }
}
catch (JSONException e) {
// jika ada error json, print ke log
e.printStackTrace();
}
}
},
// parameter terakhir overrides adalah method onErrorResponse()dan // melewatkan VolleyError sebagai sebuah parameter
new Response.ErrorListener() {
@Override
// handle error yang disebabkan Volley
public void onErrorResponse(VolleyError error)
{
Log.e("Volley", "Error");
}
}
);
// Add JSON array request "arrayreq" ke request queue
requestQueue.add(arrayreq);
btsn.setOnClickListener(new View.OnClickListener() {
double doublat = Double.parseDouble(txtlat.getText().toString());
double doublong = Double.parseDouble(txtlong.getText().toString());
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MapsActivity.class);
intent.putExtra("INPUT_TEXTLAT", doublat);
intent.putExtra("INPUT_TEXTLONG", doublong);
startActivity(intent);
} });
}
}

The problem is in this part

       requestQueue.add(arrayreq);
        btsn.setOnClickListener(new View.OnClickListener() {
      double doublat = Double.parseDouble(txtlat.getText().toString());
     double doublong = Double.parseDouble(txtlong.getText().toString());
           @Override
            public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, MapsActivity.class);
              intent.putExtra("INPUT_TEXTLAT", doublat);                 intent.putExtra("INPUT_TEXTLONG", doublong);
           startActivity(intent);             } });     }

I tried to take value of edit text and parse it to double and then intent it to other class but then this error happens, it does works with string but when I parse it to Double the error occured, Does anyone have a solution for this?


问:
Error while running emulator. Cant find executable
```<code>2023-01-02 00:30:42,727 [  57060]   INFO -   Emulator: Pixel 6 Pro API 31 - Android emulator version 31.3.14.0 (build_id 9322596) (CL:N/A)
2023-01-02 00:30:42,728 [  57061]   INFO -   Emulator: Pixel 6 Pro API 31 - emulator: INFO: Found systemPath C:\Users\16466\AppData\Local\Android\Sdk\system-images\android-31\google_apis\x86_64\
2023-01-02 00:30:42,745 [  57078]  ERROR -   Emulator: Pixel 6 Pro API 31 - can't find the emulator executable.
2023-01-02 00:30:42,746 [  57079]  ERROR -   Emulator: Pixel 6 Pro API 31 - Android Studio Dolphin | 2021.3.1 Patch 1  Build #AI-213.7172.25.2113.9123335
2023-01-02 00:30:42,746 [  57079]  ERROR -   Emulator: Pixel 6 Pro API 31 - JDK: 11.0.13; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o.
2023-01-02 00:30:42,746 [  57079]  ERROR -   Emulator: Pixel 6 Pro API 31 - OS: Windows 10
2023-01-02 00:30:42,746 [  57079]  ERROR -   Emulator: Pixel 6 Pro API 31 - Last Action:
2023-01-02 00:30:42,747 [  57080]   INFO -   Emulator: Pixel 6 Pro API 31 -
2023-01-02 00:30:42,754 [  57087]   INFO -   Emulator: Pixel 6 Pro API 31 - Process finished with exit code -1
2023-01-02 00:30:42,756 [  57089]  ERROR -   Emulator: Pixel 6 Pro API 31 - Emulator terminated with exit code -1
</code>```

Getting the following error while starting the emulator on android studio. Has anyone faced a similar error?

I tried to restart the system, change the image for android, and even created new emulators. Nothing seems to work

Body:
2023-01-02 00:30:42,727 [  57060]   INFO -   Emulator: Pixel 6 Pro API 31 - Android emulator version 31.3.14.0 (build_id 9322596) (CL:N/A)
2023-01-02 00:30:42,728 [  57061]   INFO -   Emulator: Pixel 6 Pro API 31 - emulator: INFO: Found systemPath C:\Users\16466\AppData\Local\Android\Sdk\system-images\android-31\google_apis\x86_64\
2023-01-02 00:30:42,745 [  57078]  ERROR -   Emulator: Pixel 6 Pro API 31 - can't find the emulator executable.
2023-01-02 00:30:42,746 [  57079]  ERROR -   Emulator: Pixel 6 Pro API 31 - Android Studio Dolphin | 2021.3.1 Patch 1  Build #AI-213.7172.25.2113.9123335
2023-01-02 00:30:42,746 [  57079]  ERROR -   Emulator: Pixel 6 Pro API 31 - JDK: 11.0.13; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o.
2023-01-02 00:30:42,746 [  57079]  ERROR -   Emulator: Pixel 6 Pro API 31 - OS: Windows 10
2023-01-02 00:30:42,746 [  57079]  ERROR -   Emulator: Pixel 6 Pro API 31 - Last Action:
2023-01-02 00:30:42,747 [  57080]   INFO -   Emulator: Pixel 6 Pro API 31 -
2023-01-02 00:30:42,754 [  57087]   INFO -   Emulator: Pixel 6 Pro API 31 - Process finished with exit code -1
2023-01-02 00:30:42,756 [  57089]  ERROR -   Emulator: Pixel 6 Pro API 31 - Emulator terminated with exit code -1

Getting the following error while starting the emulator on android studio. Has anyone faced a similar error?

I tried to restart the system, change the image for android, and even created new emulators. Nothing seems to work


问:
How can I adjust a values as page scrolls in flutter
I have created a listview with a scroll controller, I am able to get offset values via _scrollController.offset now I want to be able to move from

```<code>  double initialPointX = 0.5;
  double initialPointY = 0.0;
  double hDrag = 20;
  double vDrag = -20;
</code>```

to here

```<code>  double initialPointX = 0.0;
  double initialPointY = 0.0;
  double hDrag = 0.0;
  double vDrag = 0.0;
</code>```

while scrolling down and back to the first values while scrolling back up.

I hope to get ideas and answers.

for context: I am trying to animate an object while scrolling to and from.

Body:
I have created a listview with a scroll controller, I am able to get offset values via _scrollController.offset now I want to be able to move from

  double initialPointX = 0.5;
  double initialPointY = 0.0;
  double hDrag = 20;
  double vDrag = -20;

to here

  double initialPointX = 0.0;
  double initialPointY = 0.0;
  double hDrag = 0.0;
  double vDrag = 0.0;

while scrolling down and back to the first values while scrolling back up.

I hope to get ideas and answers.

for context: I am trying to animate an object while scrolling to and from.


问:
Storing dynamic keys of a document in an Array in MongoDB
I want to create a generic request document that can take different parameters to be consumed by the same endpoint. Example below is in prisma syntax I hope it is self documenting enough.

```<code>model Request {
    id                     String                @id @default(auto()) @map("_id") @db.ObjectId
    params                 String[]
    dynamicValues          JSON
}
</code>```

2 example docs for ref

```<code>{
  id: "123",
  params: ["dog_name", "cat_name"],
  dynamicValues: {
    "dog_name": "bob",
    "cat_name": "alice",
  }
}
</code>```

```<code>{
  id: "123",
  params: ["restaurant_location", "time"],
  dynamicValues: {
    "restaurant_location": "paris",
    "time": Date("1-1-23"),
  }
}
</code>```

Some context

I am using prisma, and currently create a new model for each "request type" very annoying and I would like to create even more in the future.

These requests are sent to a message queue to be consumed by a BE service.

Wanted to know what y'all think about this situation, if this is best practice or not. If there are other suggestions or thoughts on this, Thanks!

Body:
I want to create a generic request document that can take different parameters to be consumed by the same endpoint. Example below is in prisma syntax I hope it is self documenting enough.

model Request {
    id                     String                @id @default(auto()) @map("_id") @db.ObjectId
    params                 String[]
    dynamicValues          JSON
}

2 example docs for ref

{
  id: "123",
  params: ["dog_name", "cat_name"],
  dynamicValues: {
    "dog_name": "bob",
    "cat_name": "alice",
  }
}

{
  id: "123",
  params: ["restaurant_location", "time"],
  dynamicValues: {
    "restaurant_location": "paris",
    "time": Date("1-1-23"),
  }
}

Some context

I am using prisma, and currently create a new model for each "request type" very annoying and I would like to create even more in the future.

These requests are sent to a message queue to be consumed by a BE service.

Wanted to know what y'all think about this situation, if this is best practice or not. If there are other suggestions or thoughts on this, Thanks!


问:
How can I write on a existing excel sheet and get the pdf output from a flutter app?
I have an excel sheet formatted properly for creating invoices. I just edit the fields as I need and finally save as pdf to get a printable Invoice. Now I want to create an mobile app with flutter to do the task. I'll add all functionality to my app to pass data, the app has to set it on the excel sheet and get a pdf out for me. But how can I do this. I'm not finding any suitable way or package for it. I found gsheets for accessing google sheets and do the exactly what I want. But gsheet can't fulfil my demand. And also final pdf output can't be properly done in google sheet as Excel.
Can anybody help?

Any suitable package or any idea to implement the process.


问:
Android How to click to switch animation
I have an animation in imageview, I want to switch the second animation
After the second animation running once, then return to the previous

I add a OnClickListener and tried setOneShot(true) and if (ad.isRunning() == false)
but it only runnind oneshot and then stop running

This is my code

```<code>anim_doll = (ImageView) findViewById(R.id.anim_doll);
ad = (AnimationDrawable) anim_doll.getDrawable();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ad.start();
            }
        }, 300);

anim_doll.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        anim_doll.setImageResource(R.drawable.doll_touch);
        // 核心实现代码
        ad = (AnimationDrawable) anim_doll.getDrawable();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                ad.start();
                ad.setOneShot(true);

                if (ad.isRunning() == false) {
                    anim_doll.setImageResource(R.drawable.doll_normal);
                }
            }
        }, 300);
    }
});
</code>```

Body:
I have an animation in imageview, I want to switch the second animation
After the second animation running once, then return to the previous

I add a OnClickListener and tried setOneShot(true) and if (ad.isRunning() == false)
but it only runnind oneshot and then stop running

This is my code

anim_doll = (ImageView) findViewById(R.id.anim_doll);
ad = (AnimationDrawable) anim_doll.getDrawable();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ad.start();
            }
        }, 300);

anim_doll.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        anim_doll.setImageResource(R.drawable.doll_touch);
        // 核心实现代码
        ad = (AnimationDrawable) anim_doll.getDrawable();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                ad.start();
                ad.setOneShot(true);

                if (ad.isRunning() == false) {
                    anim_doll.setImageResource(R.drawable.doll_normal);
                }
            }
        }, 300);
    }
});


问:
Extract bezier curve info from a TTF file (ttfquery won't install)
I saw this post: Retrieving bounding box and bezier curve data for all glyphs in a .ttf font file in python

about how to retrieve the bezier curve data from a TTF file. The reason I want this is so that I can make animations of letters being drawn in matplotlib. The problem is that the package ttfquery won't install. My guess is that my python version is too new (3.9) and that package is pretty old.

```<code>C:\Users\Chris>pip install TTFQuery
Collecting TTFQuery
  Downloading TTFQuery-1.0.5.tar.gz (17 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [7 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "C:\Users\Chris\AppData\Local\Temp\pip-install-djyaq0d_\ttfquery_678fb4fdd4004a81b1bc72c29a99b35f\setup.py", line 11
          except ImportError, err:
                            ^
      SyntaxError: invalid syntax
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

Is there another way to obtain that sort of info from a TTF file? Alternatively, is there a way to specifically obtain the stroke order of Japanese characters that can be downloaded for free?

I ultimately want to make animations such as this one. Is there some free tool/ data online for that sort of purpose or do I have to install an earlier python version and use that instead?

Body:
I saw this post: Retrieving bounding box and bezier curve data for all glyphs in a .ttf font file in python

about how to retrieve the bezier curve data from a TTF file. The reason I want this is so that I can make animations of letters being drawn in matplotlib. The problem is that the package ttfquery won't install. My guess is that my python version is too new (3.9) and that package is pretty old.

C:\Users\Chris>pip install TTFQuery
Collecting TTFQuery
  Downloading TTFQuery-1.0.5.tar.gz (17 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [7 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "C:\Users\Chris\AppData\Local\Temp\pip-install-djyaq0d_\ttfquery_678fb4fdd4004a81b1bc72c29a99b35f\setup.py", line 11
          except ImportError, err:
                            ^
      SyntaxError: invalid syntax
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Is there another way to obtain that sort of info from a TTF file? Alternatively, is there a way to specifically obtain the stroke order of Japanese characters that can be downloaded for free?

I ultimately want to make animations such as this one. Is there some free tool/ data online for that sort of purpose or do I have to install an earlier python version and use that instead?


问:
How to connect Nodejs with AWS APIGateway external websocket endpoints
I have a stateless API, where I am doing, simply login in with authentication, authorization, and CRUD. I have 20+ routes, where I have deployed it in a single lambda function.

The sample code looks like this - https://github.com/codeztech-atique/Basic_Authentication_With_Nodejs

Below is the separate lambda function ---

Now, I have created a WebSockets, in AWS API Gateway, my WebSocket URL.

WebSocket URL:  wss://efd342kq5e.execute-api.us-west-1.amazonaws.com/production

Connection URL: https://efd342kq5e.execute-api.us-west-1.amazonaws.com/production/@connections

I have done the logic, Each and every time, I have connected from -- https://www.piesocket.com/websocket-tester
I am doing insert to dynamodb table, when the id disconnected I am removing from dynamodb.

Screenshot --

Followed by this video -- https://www.youtube.com/watch?v=DzpGfyB0iKk

Now --- I wanted to call these 2 endpoint in the

Frontend WebSocket URL: wss://efd342kq5e.execute-api.us-west-1.amazonaws.com/production

Backend connection URL: https://efd342kq5e.execute-api.us-west-1.amazonaws.com/production/@connections

From my single lambda function. How can I integrate the logic?

Adding https://www.piesocket.com/websocket-tester Screenshot -


问:
AWS emr serverless --py-files with zipped project package cannot find deps .py files
I am doing a use case where I zipped up my python project files to S3 with structure such as:

```<code>Project1

 --bin
  ---mymain.py
 --libs
  ---mylibs using in mymain.py
</code>```

I submitted using --py-files=s3://bucket/filename.zip to EMR serverless job. The job failed with unable to find mylibs.

I went over the emr serverless using libs doc, but it only covered external libs.  Other than that there are no documentation about using project file for emr serverless out there at all.  Has anyone done this use case before?

I tried creating pyspark_venvsource per external libs doc, but it was still having issue finding the path to ./environment/bin.

Body:
I am doing a use case where I zipped up my python project files to S3 with structure such as:

Project1

 --bin
  ---mymain.py
 --libs
  ---mylibs using in mymain.py

I submitted using --py-files=s3://bucket/filename.zip to EMR serverless job. The job failed with unable to find mylibs.

I went over the emr serverless using libs doc, but it only covered external libs.  Other than that there are no documentation about using project file for emr serverless out there at all.  Has anyone done this use case before?

I tried creating pyspark_venvsource per external libs doc, but it was still having issue finding the path to ./environment/bin.


问:
Visual Studio 2022 Community gone crash what should i do?
my Visual Studio reacts like this and when i open properties so it restart automatically

I have used Visual Studio 2022 Community for 3 months but suddenly Visual Studio crash as shown in the screenshot and also shows the error

The program '[11392] API.exe' has exited with code 4294967295
(0xffffffff).

when I run the project. I tried also to update and repair it to solve this, but the still issue persists.


问:
What is this R error in bipartite package: 'length(x) = 2 > 1' in coercion to 'logical(1)'
Trying to compute c and z statistics using the bipartite package in R and plot the two on a graph (c on the x-axis and z on the y-axis). I have a plant-pollinator network and I am trying to determine the most important plants in the network using the following code:

```<code>#calculating c and z values. c = connection z = participation
#insects
cz.insects <- czvalues(all.mod, weighted=TRUE, level="higher")
#plants
cz.plants <- czvalues(all.mod, weighted=TRUE, level="lower")
</code>```

When I use the function czvalues() I get 6 identical warning messages and am wondering what I am doing wrong:

```<code>1: In dim(slot(moduleWebObject, "originalWeb")) == 0 || dim(slot(moduleWebObject,  :
  'length(x) = 2 > 1' in coercion to 'logical(1)'
</code>```

Thanks!

I am not sure what to do because I researched the warning message and do not know how to fit it. I notice that some of the data points return as NA on the z-values. For example, look at the head() of my czvalues output. the z-values return a number of NAs.

```<code>> head(cz.plants)

$c
      ACMI       ASFA       BADE       CECY       CEIN       COAR       CRAT       CRIN
0.34113810 0.17572333 0.09283695 0.10081873 0.49398836 0.69166726 0.00000000 0.50696682
      DICO       ERCO       FRAL       HISC       LONU       LOTR       LUSU       SEIN
0.69485228 0.60391999 0.34644387 0.06568726 0.16474358 0.18742946 0.29405213 0.15277778
      TOPA       TOVE       TRGR       VISA
0.59259259 0.00000000 0.48000000 0.00000000

$z
      ACMI       ASFA       BADE       CECY       CEIN       COAR       CRAT       CRIN
        NA         NA  0.7071068         NA         NA -0.7572719 -0.7071068  0.7071068
      DICO       ERCO       FRAL       HISC       LONU       LOTR       LUSU       SEIN
-0.3762842  1.1335561  1.1532389         NA         NA -0.5263202         NA         NA
      TOPA       TOVE       TRGR       VISA
-0.6269187         NA -0.7071068         NA
</code>```

Body:
Trying to compute c and z statistics using the bipartite package in R and plot the two on a graph (c on the x-axis and z on the y-axis). I have a plant-pollinator network and I am trying to determine the most important plants in the network using the following code:

#calculating c and z values. c = connection z = participation
#insects
cz.insects <- czvalues(all.mod, weighted=TRUE, level="higher")
#plants
cz.plants <- czvalues(all.mod, weighted=TRUE, level="lower")

When I use the function czvalues() I get 6 identical warning messages and am wondering what I am doing wrong:

1: In dim(slot(moduleWebObject, "originalWeb")) == 0 || dim(slot(moduleWebObject,  :
  'length(x) = 2 > 1' in coercion to 'logical(1)'

Thanks!

I am not sure what to do because I researched the warning message and do not know how to fit it. I notice that some of the data points return as NA on the z-values. For example, look at the head() of my czvalues output. the z-values return a number of NAs.

> head(cz.plants)

$c
      ACMI       ASFA       BADE       CECY       CEIN       COAR       CRAT       CRIN
0.34113810 0.17572333 0.09283695 0.10081873 0.49398836 0.69166726 0.00000000 0.50696682
      DICO       ERCO       FRAL       HISC       LONU       LOTR       LUSU       SEIN
0.69485228 0.60391999 0.34644387 0.06568726 0.16474358 0.18742946 0.29405213 0.15277778
      TOPA       TOVE       TRGR       VISA
0.59259259 0.00000000 0.48000000 0.00000000

$z
      ACMI       ASFA       BADE       CECY       CEIN       COAR       CRAT       CRIN
        NA         NA  0.7071068         NA         NA -0.7572719 -0.7071068  0.7071068
      DICO       ERCO       FRAL       HISC       LONU       LOTR       LUSU       SEIN
-0.3762842  1.1335561  1.1532389         NA         NA -0.5263202         NA         NA
      TOPA       TOVE       TRGR       VISA
-0.6269187         NA -0.7071068         NA


问:
HealthKit KCALs not Increasing
I am saving calories burned to healthKit central repository but the issue is it does not increment the total amount of KCAL in the fitness app . Saving workout works well i can see the time duration and the calories burned but its not added into the total MOVE/KCALs. I can see the MOVE are incremented.</p>
```<code>    class func savingWorkout(duration : Double , burnedEnergy : Double , completion: @escaping (Result<Bool, Error>) -> ()) {

    let healthKitStore = HKHealthStore()
    let totalEnergyBurned = HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: burnedEnergy)

    let finish = Date() // Now
    let start = finish.addingTimeInterval(-duration) // 1 hour ago

    let metadata = [
        HKMetadataKeyGroupFitness : false,
        HKMetadataKeyIndoorWorkout : true,
        HKMetadataKeyCoachedWorkout : true
    ]

    let workout = HKWorkout(
        activityType: .functionalStrengthTraining,
        start: start,
        end: finish,
        workoutEvents: nil,
        totalEnergyBurned: totalEnergyBurned,
        totalDistance: nil,
        device: nil,
        metadata: metadata
    )

    guard let energyBurnedType =
        HKObjectType.quantityType(forIdentifier:
            HKQuantityTypeIdentifier.activeEnergyBurned) else {
        fatalError("*** Unable to create an energy burned type ***")
    }

    let energyBurnedPerInterval = HKQuantity(unit: HKUnit.kilocalorie(),
                                             doubleValue: burnedEnergy)

    let energyBurnedPerIntervalSample =
        HKQuantitySample(type: energyBurnedType,
                         quantity: energyBurnedPerInterval,
                         start: start,
                         end: finish) as HKSample

    //3.  Save the same to HealthKit
     healthKitStore.save(energyBurnedPerIntervalSample) { (success, error) in

      if let error = error {
        print("Error Saving calories burned: \(error.localizedDescription)")
      } else {
        print("Calories saved")
      }
    }

        healthKitStore.save(workout) { result , error in
            if let error = error {
                completion(.failure(error))
                return
            }
           print("workout saved into HealthKit successfully ")
    }

}
</code>```

Title: HealthKit KCALs not Increasing

Body:
I am saving calories burned to healthKit central repository but the issue is it does not increment the total amount of KCAL in the fitness app . Saving workout works well i can see the time duration and the calories burned but its not added into the total MOVE/KCALs. I can see the MOVE are incremented.

    class func savingWorkout(duration : Double , burnedEnergy : Double , completion: @escaping (Result<Bool, Error>) -> ()) {

    let healthKitStore = HKHealthStore()
    let totalEnergyBurned = HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: burnedEnergy)

    let finish = Date() // Now
    let start = finish.addingTimeInterval(-duration) // 1 hour ago

    let metadata = [
        HKMetadataKeyGroupFitness : false,
        HKMetadataKeyIndoorWorkout : true,
        HKMetadataKeyCoachedWorkout : true
    ]

    let workout = HKWorkout(
        activityType: .functionalStrengthTraining,
        start: start,
        end: finish,
        workoutEvents: nil,
        totalEnergyBurned: totalEnergyBurned,
        totalDistance: nil,
        device: nil,
        metadata: metadata
    )

    guard let energyBurnedType =
        HKObjectType.quantityType(forIdentifier:
            HKQuantityTypeIdentifier.activeEnergyBurned) else {
        fatalError("*** Unable to create an energy burned type ***")
    }

    let energyBurnedPerInterval = HKQuantity(unit: HKUnit.kilocalorie(),
                                             doubleValue: burnedEnergy)

    let energyBurnedPerIntervalSample =
        HKQuantitySample(type: energyBurnedType,
                         quantity: energyBurnedPerInterval,
                         start: start,
                         end: finish) as HKSample

    //3.  Save the same to HealthKit
     healthKitStore.save(energyBurnedPerIntervalSample) { (success, error) in

      if let error = error {
        print("Error Saving calories burned: \(error.localizedDescription)")
      } else {
        print("Calories saved")
      }
    }

        healthKitStore.save(workout) { result , error in
            if let error = error {
                completion(.failure(error))
                return
            }
           print("workout saved into HealthKit successfully ")
    }

}


问:
Django RequestFactory; TypeError: get() missing 1 required positional argument;
In attempting to test the context of a view PostedQuestionPage with RequestFactory, the following error is being raised when running the test:

```<code>  File "C:\Users\..\django\test\testcases.py", line 1201, in setUpClass
    cls.setUpTestData()
  Fi..\posts\test\test_views.py", line 334, in setUpTestData
    cls.view = PostedQuestionPage.as_view()(request)
  File "C:\..\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\..\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
TypeError: get() missing 1 required positional argument: 'question_id'
</code>```

It's unclear to me as to why the error is being raised while question_id is being passed into reverse("posts:question", kwargs={'question_id': 1})?

test_views.py

```<code>class TestQuestionIPAddressHit(TestCase):
    '''Verify that a page hit is recorded from a user of a given IP address
    on a posted question.'''

    @classmethod
    def setUpTestData(cls):
        user_author = get_user_model().objects.create_user("ItsNotYou")
        user_me = get_user_model().objects.create_user("ItsMe")
        author_profile = Profile.objects.create(user=user_author)
        user_me = Profile.objects.create(user=user_me)
        question = Question.objects.create(
            title="Blah blahhhhhhhhh blahhh I'm bord blah blah zzzzzzzzzzzzz",
            body="This is zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...zzzzz",
            profile=author_profile
        )
        authenticated_user = user_me.user
        request = RequestFactory().get(
            reverse("posts:question", kwargs={"question_id": 1}),
            headers={
                "REMOTE_ADDR": "IP Address here"
            }
        )
        request.user = authenticated_user
        cls.view = PostedQuestionPage.as_view()(request)
</code>```

views.py

```<code>class PostedQuestionPage(Page):

    template_name = "posts/question.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['answer_form'] = AnswerForm
        return context

    def get(self, request, question_id):
        context = self.get_context_data()
        question = get_object_or_404(Question, id=question_id)
        if question.profile.user != request.user and not question.visible:
            raise Http404
        context |= {
            'question': question,
            'answer_count': question.answers.count()
        }

        return self.render_to_response(context)
</code>```

urls.py

```<code>posts_patterns = ([
    path("", pv.QuestionListingPage.as_view(), name="main"),
    re_path(r"questions/ask/?$", pv.AskQuestionPage.as_view(), name="ask"),
    re_path(r"questions/(?P<question_id>\d+)/edit/?$", pv.EditQuestionPage.as_view(), name="edit"),
    re_path(r"questions/(?P<question_id>\d+)/edit/answers/(?P<answer_id>\d+)/?$", pv.EditPostedAnswerPage.as_view(), name="answer_edit"),

    re_path(r"questions/(?P<question_id>\d+)/?$", pv.PostedQuestionPage.as_view(), name="question"),

    re_path(r"questions/tagged/(?P<tags>[0-9a-zA-Z\.\-#]+(?:\+[0-9a-zA-Z\.\-#]+)*)$", pv.TaggedSearchResultsPage.as_view(), name="tagged"),
    re_path(r"questions/tagged/$", pv.SearchTaggedRedirect.as_view(), name="tagged_redirect"),
    re_path(r"questions/search/$", pv.SearchMenuPage.as_view(), name="search_menu"),
    re_path(r"questions/search$", pv.SearchResultsPage.as_view(), name="search_results"),
    re_path(r"questions/?$", pv.AllQuestionsPage.as_view(), name="main_paginated"),
</code>```

Body:
In attempting to test the context of a view PostedQuestionPage with RequestFactory, the following error is being raised when running the test:

  File "C:\Users\..\django\test\testcases.py", line 1201, in setUpClass
    cls.setUpTestData()
  Fi..\posts\test\test_views.py", line 334, in setUpTestData
    cls.view = PostedQuestionPage.as_view()(request)
  File "C:\..\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\..\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
TypeError: get() missing 1 required positional argument: 'question_id'

It's unclear to me as to why the error is being raised while question_id is being passed into reverse("posts:question", kwargs={'question_id': 1})?

test_views.py

class TestQuestionIPAddressHit(TestCase):
    '''Verify that a page hit is recorded from a user of a given IP address
    on a posted question.'''

    @classmethod
    def setUpTestData(cls):
        user_author = get_user_model().objects.create_user("ItsNotYou")
        user_me = get_user_model().objects.create_user("ItsMe")
        author_profile = Profile.objects.create(user=user_author)
        user_me = Profile.objects.create(user=user_me)
        question = Question.objects.create(
            title="Blah blahhhhhhhhh blahhh I'm bord blah blah zzzzzzzzzzzzz",
            body="This is zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...zzzzz",
            profile=author_profile
        )
        authenticated_user = user_me.user
        request = RequestFactory().get(
            reverse("posts:question", kwargs={"question_id": 1}),
            headers={
                "REMOTE_ADDR": "IP Address here"
            }
        )
        request.user = authenticated_user
        cls.view = PostedQuestionPage.as_view()(request)

views.py

class PostedQuestionPage(Page):

    template_name = "posts/question.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['answer_form'] = AnswerForm
        return context

    def get(self, request, question_id):
        context = self.get_context_data()
        question = get_object_or_404(Question, id=question_id)
        if question.profile.user != request.user and not question.visible:
            raise Http404
        context |= {
            'question': question,
            'answer_count': question.answers.count()
        }

        return self.render_to_response(context)

urls.py

posts_patterns = ([
    path("", pv.QuestionListingPage.as_view(), name="main"),
    re_path(r"questions/ask/?$", pv.AskQuestionPage.as_view(), name="ask"),
    re_path(r"questions/(?P<question_id>\d+)/edit/?$", pv.EditQuestionPage.as_view(), name="edit"),
    re_path(r"questions/(?P<question_id>\d+)/edit/answers/(?P<answer_id>\d+)/?$", pv.EditPostedAnswerPage.as_view(), name="answer_edit"),

    re_path(r"questions/(?P<question_id>\d+)/?$", pv.PostedQuestionPage.as_view(), name="question"),

    re_path(r"questions/tagged/(?P<tags>[0-9a-zA-Z\.\-#]+(?:\+[0-9a-zA-Z\.\-#]+)*)$", pv.TaggedSearchResultsPage.as_view(), name="tagged"),
    re_path(r"questions/tagged/$", pv.SearchTaggedRedirect.as_view(), name="tagged_redirect"),
    re_path(r"questions/search/$", pv.SearchMenuPage.as_view(), name="search_menu"),
    re_path(r"questions/search$", pv.SearchResultsPage.as_view(), name="search_results"),
    re_path(r"questions/?$", pv.AllQuestionsPage.as_view(), name="main_paginated"),


问:
How to check if I am authenticated in the client (using JavaScript) against a ASP.NET MVC backend without performing a request?
In my SPA frontend, I want to display a login page if I am not authenticated. In my SPA, everything goes to index.html. So I need to determine if I am authenticated in JavaScript. I am using the ASP.NET cookie authentication scheme. It is set up like this:

```<code>builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        options.SlidingExpiration = true;
        options.AccessDeniedPath = "/Forbidden/";
    });
</code>```

and

```<code>app.UseCookiePolicy(new CookiePolicyOptions
{
    MinimumSameSitePolicy = SameSiteMode.Strict,
});

app.UseAuthentication();
app.UseAuthorization();
</code>```

and to sign in:

```<code>        await HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity),
            authProperties);
</code>```

The authentication cookie is HTTP only, so there's no way to read it from document.cookie. However, I thought a good idea would be to set an additional cookie which is not HTTP only, that I can access from the frontend, which simply contains a bool value; and then I could use that to determine if I am signed in or not. I.e. set two cookies: the authentication cookie (HTTP only) and a non-HTTP only cookie containing a bool value.

Is this a good idea? Is it not a good idea? If good, how can I integrate this into SignInAsync or wherever I need to integrate something?

Body:
In my SPA frontend, I want to display a login page if I am not authenticated. In my SPA, everything goes to index.html. So I need to determine if I am authenticated in JavaScript. I am using the ASP.NET cookie authentication scheme. It is set up like this:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        options.SlidingExpiration = true;
        options.AccessDeniedPath = "/Forbidden/";
    });

and

app.UseCookiePolicy(new CookiePolicyOptions
{
    MinimumSameSitePolicy = SameSiteMode.Strict,
});

app.UseAuthentication();
app.UseAuthorization();

and to sign in:

        await HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity),
            authProperties);

The authentication cookie is HTTP only, so there's no way to read it from document.cookie. However, I thought a good idea would be to set an additional cookie which is not HTTP only, that I can access from the frontend, which simply contains a bool value; and then I could use that to determine if I am signed in or not. I.e. set two cookies: the authentication cookie (HTTP only) and a non-HTTP only cookie containing a bool value.

Is this a good idea? Is it not a good idea? If good, how can I integrate this into SignInAsync or wherever I need to integrate something?


问:
Vim YouCompleteMe Java setup
I'm trying to set up Java autocompletion for Vim using the YouCompleteMe plugin. I ran the install script and got the following message saying that I need to set an option called java_binary_path:

```<code>$ python3 install.py --java-completer --clang-completer
Generating ycmd build configuration...OK
Compiling ycmd target: ycm_core...OK
Building regex module...OK
Building watchdog module...OK
Installing jdt.ls for Java support...

*** WARNING ***: jdt.ls requires Java 17. You must set the option java_binary_path to point to a working java 17.

OK
</code>```

I tried setting this in my ~/.vimrc file as follows, but now I'm getting the error E518: Unknown option: java_binary_path=/usr/local/opt/openjdk@17/bin/java:

```<code>set java_binary_path=/usr/local/opt/openjdk@17/bin/java
</code>```

Does anyone know how to set this option?

Title: Vim YouCompleteMe Java setup

Body:
I'm trying to set up Java autocompletion for Vim using the YouCompleteMe plugin. I ran the install script and got the following message saying that I need to set an option called java_binary_path:

$ python3 install.py --java-completer --clang-completer
Generating ycmd build configuration...OK
Compiling ycmd target: ycm_core...OK
Building regex module...OK
Building watchdog module...OK
Installing jdt.ls for Java support...

*** WARNING ***: jdt.ls requires Java 17. You must set the option java_binary_path to point to a working java 17.

OK

I tried setting this in my ~/.vimrc file as follows, but now I'm getting the error E518: Unknown option: java_binary_path=/usr/local/opt/openjdk@17/bin/java:

set java_binary_path=/usr/local/opt/openjdk@17/bin/java

Does anyone know how to set this option?


问:
How to pass NGRX selector to data Router
i want to implement a custom breadcrumb for my app, i have thinking pass an NGRX selector direcly inside the router data.

I have try something like this:

```<code>@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([
      {
        path: 'update/:id',
        data: {
          breadcrumb: {
            title: 'Update',
            path: [
              {
                value: 'Products',
                href: '/products'
              },
              {
                value: 'Update'
              },
              {
                selector: this.ngrxFacade.selectedName$ // <-- this on error here
              }
            ]
          }
        }
      }
    ])
})
export class MyModule {
  public ngrxFacade: NgrxFacade;

  constructor(ngrxFacade: NgrxFacade) {
    this.ngrxFacade = ngrxFacade;
  }
}
</code>```

And i have this error:

mymodulefile.js:1 Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'selectedName$')

I have search on the internet but no one seems to have try to do something like this. In this state i don't think this I want to achieve is possible, but maybe some one have an idea how to achieve this.

Body:
i want to implement a custom breadcrumb for my app, i have thinking pass an NGRX selector direcly inside the router data.

I have try something like this:

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([
      {
        path: 'update/:id',
        data: {
          breadcrumb: {
            title: 'Update',
            path: [
              {
                value: 'Products',
                href: '/products'
              },
              {
                value: 'Update'
              },
              {
                selector: this.ngrxFacade.selectedName$ // <-- this on error here
              }
            ]
          }
        }
      }
    ])
})
export class MyModule {
  public ngrxFacade: NgrxFacade;

  constructor(ngrxFacade: NgrxFacade) {
    this.ngrxFacade = ngrxFacade;
  }
}

And i have this error:

mymodulefile.js:1 Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'selectedName$')

I have search on the internet but no one seems to have try to do something like this. In this state i don't think this I want to achieve is possible, but maybe some one have an idea how to achieve this.


问:
buildroot/output/build/linux-custom/.stamp_built] Error 2 error in Buildroot
I and newbie to using Buildroot system.

I have a local kernel source directory present on developement system which i am using in Buildroot but the build fails with following error.

```<code>package/pkg-generic.mk:290: recipe for target '/home/lsys/workspace/BuildrootWork/buildroot/output/build/linux-custom/.stamp_built' failed
make[1]: *** [/home/lsys/workspace/BuildrootWork/buildroot/output/build/linux-custom/.stamp_built] Error 2
Makefile:84: recipe for target '_all' failed
make: *** [_all] Error 2
</code>```

Using the LINUX_OVERRIDE_SRCDIR="/home/lsys/workspace/BuildrootWork/kernelsource/KERNEL_3_8" i have given the path of the local kernel source directory in local.mk in Builroot directory where .config is present.

The build sucesfully works if i don't provide an override directory and kernel v5.10 builds fine.

Buildroot version : buildroot-2022.11.tar.gz from buildroot.org

override Linux kernel version : v3.8.x

board config used : config/beaglebone_defconfig

Body:
I and newbie to using Buildroot system.

I have a local kernel source directory present on developement system which i am using in Buildroot but the build fails with following error.

package/pkg-generic.mk:290: recipe for target '/home/lsys/workspace/BuildrootWork/buildroot/output/build/linux-custom/.stamp_built' failed
make[1]: *** [/home/lsys/workspace/BuildrootWork/buildroot/output/build/linux-custom/.stamp_built] Error 2
Makefile:84: recipe for target '_all' failed
make: *** [_all] Error 2

Using the LINUX_OVERRIDE_SRCDIR="/home/lsys/workspace/BuildrootWork/kernelsource/KERNEL_3_8" i have given the path of the local kernel source directory in local.mk in Builroot directory where .config is present.

The build sucesfully works if i don't provide an override directory and kernel v5.10 builds fine.

Buildroot version : buildroot-2022.11.tar.gz from buildroot.org

override Linux kernel version : v3.8.x

board config used : config/beaglebone_defconfig


问:
Persian PDF file to Word file Converter
Persian PDF to Word Converter.

I have created an application to convert the PDF file into a word file. There is a problem with Persian PDf files when I try to convert them. The application converts the pdf into a word file but the text format is not readable, It will try to put the Letters and vice versa.

Here is the code which I have written.

import os.path
from tkinter import *
from tkinter import ttk
import tkinter.filedialog as fd
from pdf2docx import Converter

def open_file():
    file_name = fd.askopenfilename()
    file_path = os.path.basename(file_name).split('/')[-1]
    change_file_type = file_path.replace('.pdf', '.docx')

    pdf_file = file_name
    docx_file = change_file_type

    cv = Converter(pdf_file)
    cv.convert(docx_file)
    cv.close()

root = Tk()
root.title('PDF2Word Converter')

label_title = ttk.Label(root, text='Welcome to PDF Converter!')
label_open_pdf = ttk.Label(root, text='Open PDF: ')
label_Developer = ttk.Label(root, text='Developer: Behrooz Sharify')

open_button = ttk.Button(root, text='Open', command=open_file)

label_title.grid(row=0, column=1, columnspan=2)
label_open_pdf.grid(row=2, column=0)
label_Developer.grid(row=3, column=1, columnspan=2)
open_button.grid(row=2, column=3)

root.geometry('296x70')
root.resizable(False, False)
root.mainloop()
```

You can refer to the picture I uploaded here for the output problem:

Title: Persian PDF file to Word file Converter

Body:
Persian PDF to Word Converter.

I have created an application to convert the PDF file into a word file. There is a problem with Persian PDf files when I try to convert them. The application converts the pdf into a word file but the text format is not readable, It will try to put the Letters and vice versa.

Here is the code which I have written.

import os.path
from tkinter import *
from tkinter import ttk
import tkinter.filedialog as fd
from pdf2docx import Converter

def open_file():
    file_name = fd.askopenfilename()
    file_path = os.path.basename(file_name).split('/')[-1]
    change_file_type = file_path.replace('.pdf', '.docx')

    pdf_file = file_name
    docx_file = change_file_type

    cv = Converter(pdf_file)
    cv.convert(docx_file)
    cv.close()

root = Tk()
root.title('PDF2Word Converter')

label_title = ttk.Label(root, text='Welcome to PDF Converter!')
label_open_pdf = ttk.Label(root, text='Open PDF: ')
label_Developer = ttk.Label(root, text='Developer: Behrooz Sharify')

open_button = ttk.Button(root, text='Open', command=open_file)

label_title.grid(row=0, column=1, columnspan=2)
label_open_pdf.grid(row=2, column=0)
label_Developer.grid(row=3, column=1, columnspan=2)
open_button.grid(row=2, column=3)

root.geometry('296x70')
root.resizable(False, False)
root.mainloop()

You can refer to the picture I uploaded here for the output problem:


问:
AR framework in Linux (ARcore and ARkit alternatives for Linux)
I want to implement a hair filter app for Linux, so for the first steps, I tried to implement and run this video project. How can I run it on my Laptop without an android or iOS?

Are there any frameworks like ARcore and ARkit for face tracking in Linux?
(It's preferred to run it on Linux because I want to run it on an embedded system.)

These are the frameworks that I can choose in Unity, but I think that all of them need a VR device so I can't use them.


问:
Mongoose findone returns wrong user when the field passed in, is not defined in schema. How can I handle this case?
I noticed a case where (accidentally) the value passed into Model.findOne was a key that is not defined in schema. I expected an error or undefined but what is happening is that for exampe when I search for a user, if the value i pass in is undefined ANY random (as it seems) and wrong user is returned.

//if I would pass in instead of:

```<code>function (req, res, next) {
  const email = req.body.email
  User.findOne({email: email})
}
</code>```

this:

```<code>function (req, res, next) {
  const email = req.body.email
  User.findOne({emaill: email})
}
</code>```

then, because 'emaill' does not exist in the schema, instead of an err, I would get another user returned.

Could someone explain to me why this happens and how I can handle it. I cant handle error and check if passed value doesnt exist in schema..

Body:
I noticed a case where (accidentally) the value passed into Model.findOne was a key that is not defined in schema. I expected an error or undefined but what is happening is that for exampe when I search for a user, if the value i pass in is undefined ANY random (as it seems) and wrong user is returned.

//if I would pass in instead of:

function (req, res, next) {
  const email = req.body.email
  User.findOne({email: email})
}

this:

function (req, res, next) {
  const email = req.body.email
  User.findOne({emaill: email})
}

then, because 'emaill' does not exist in the schema, instead of an err, I would get another user returned.

Could someone explain to me why this happens and how I can handle it. I cant handle error and check if passed value doesnt exist in schema..


问:
Unable to update data using prisma
I am using prisma to update some fields but i am getting error.
I am using unique id to update the data.
Before update i am able to get all the data from table so prisma is working on select

```<code>        const cartUpdate = await prisma.custom_checkout__c.update({
            where: {

                id: uniqueId,
            },
            data: {
                status__c: 'Checkout completed',
                coupon_code__c: coupon,
                checkout_id__c: result.subscription.id,
            }
        })
</code>```

Error is below

```<code>PrismaClientUnknownRequestError:
Invalid `prisma.custom_checkout__c.update()` invocation:

    Error occurred during query execution:
    ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E42883), message: "function get_xmlbinary() does not exist", detail: None, hint: Some("No function matches the given name and argument types. You might need to add explicit type casts."), position: Some(Internal { position: 2, query: "(get_xmlbinary() = 'base64')" }), where_: Some("PL/pgSQL function hc_custom_checkout__c_status() line 3 at IF"), schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("parse_func.c"), line: Some(629), routine: Some("ParseFuncOrColumn") }) }) })
        at RequestHandler.handleRequestError (/Users/bi
</code>```

Title: Unable to update data using prisma

Body:
I am using prisma to update some fields but i am getting error.
I am using unique id to update the data.
Before update i am able to get all the data from table so prisma is working on select

        const cartUpdate = await prisma.custom_checkout__c.update({
            where: {

                id: uniqueId,
            },
            data: {
                status__c: 'Checkout completed',
                coupon_code__c: coupon,
                checkout_id__c: result.subscription.id,
            }
        })

Error is below

PrismaClientUnknownRequestError:
Invalid `prisma.custom_checkout__c.update()` invocation:

    Error occurred during query execution:
    ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E42883), message: "function get_xmlbinary() does not exist", detail: None, hint: Some("No function matches the given name and argument types. You might need to add explicit type casts."), position: Some(Internal { position: 2, query: "(get_xmlbinary() = 'base64')" }), where_: Some("PL/pgSQL function hc_custom_checkout__c_status() line 3 at IF"), schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("parse_func.c"), line: Some(629), routine: Some("ParseFuncOrColumn") }) }) })
        at RequestHandler.handleRequestError (/Users/bi