问:
WatchKit App Cannot Connect to the Internet. Works on Simulator but not on Physical Device
This is my first WatchKit App.

I am working on an app that gets an API call to an iCal file and displays the time remaining in two events.

I am working on Xcode 13.4.1 and created an iOS app with watchOS app using swift and storyboard. I set the target deployment for the iOS app to 15.5, which is the highest version of iOS that my current version of Xcode will let me set. The target deployment for the watchOS app is set to version 6.2 because I have an Apple Watch series 2, and the latest version of watchOS is 6.3. I want the app to at least work for my watch. The code for the iOS app and watch app are pretty much the same. The app works as expected on the watch and phone simulators and on my physical iPhone 8 plus. The problem is that the app does not work on my physical watch.

I created a custom class called API_Manager that handles the API call. I handle my API call as a giant string because I am getting an iCal file and parse it later on in the class. url is defined above. Here is my API call for both the phone and watch app:

```<code>public func getData() throws{
        //api call
        do{
            // real url is defined above
            let url:String = ""
            savedData = try String(contentsOf: URL(string: url)!)
        } catch{
            print("there was an error with the api call")
            throw API_Error.apiCallError
        }
        // parsing data
}
</code>```

getData() is called in the init function of the API_Manager class.

```<code>    init() throws {
        // checking internet connection
        if (!NetworkMonitor.shared.isConnected){
            throw API_Error.noInternet
        }

        do{
            try getData()
        } catch{
            throw API_Error.apiCallError
        }

    }
</code>```

I believe the root of the problem is an Internet connection. I check for an Internet connection before the API call, and if there is no Internet connection, then I throw a custom error. I used this video to create a Network_Monitor class. This is the startMonitoring() function which is called in the applicationDidFinishLaunching() in extensionDelegate of the watch app and application didFinishLaunchingWithOptions in the appDelegate.

```<code>public func startMonitoring(){
        monitor.start(queue: queue)

        monitor.pathUpdateHandler = { [weak self] path in
            self?.isConnected = path.status == .satisfied

            // getting connection type
            self?.getConnectionType(path)
        }
    }
</code>```

I created a custom error that is thrown throughout the API_Manager if things don't work as expected. Here is how I created the custom errors:

```<code>enum API_Error: Error{
    case noInternet
    case apiCallError
}

extension API_Error: CustomStringConvertible{
    public var description:String {
        switch self{
        case .noInternet:
            return "Error: No internet connection"
        case .apiCallError:
            return "There was an error with the api call"
        }

    }
}
</code>```

I created another enum that is used to display text on a label in the Interface Controller if a specific error is thrown.

```<code>enum API_Manager_Status{
        case active
        case noInternet
        case apiCallError
        case null                   // if the api manager is nill
    }
</code>```

Here is how I used the two enums in InterfaceController:
main() is called in the awake() function.

```<code>func main(){
        do{
            apiManager = try API_Manager()
            apiManagerStatus = .active
        } catch API_Error.noInternet{
            apiManagerStatus = .noInternet

        } catch API_Error.apiCallError{
            apiManagerStatus = .apiCallError

        } catch{
            apiManagerStatus = .null

        }

        if (apiManagerStatus == .noInternet){
            periodLabel.setText("Error")
            timeRemaining.setText("No Internet")
            print(API_Error.noInternet)
        } else if (apiManagerStatus == .apiCallError){
            periodLabel.setText("Error")
            timeRemaining.setText("API Call")
            print(API_Error.apiCallError)
        } else if (apiManagerStatus == .null){
            periodLabel.setText("Error")
            timeRemaining.setText("Other Error")
            print("Cought all errors")
        } else{
            // main code to display time remaining
        }
</code>```

So I guess my questions are:

Why is my Apple Watch not getting an Internet connection?

How can I fix my app if it worked on the simulators and iPhone, but not watch?

Can the Apple Watch do an API call?

Do I need to configure my app to connect with the iPhone, given that my watchOS verison is 6.2?

Sorry if this is a long question. This is my first time posting a question on Stack Overflow. I would appreciate any help. Let me know if I need to add any more information to help clear things up.

I have tried many potential solutions to fix the problem, but none have worked:

I distributed the app on Test Flight and had my dad download it. He has an Apple Watch Series 4 running on watchOS 9.2, and the app still does not work on his watch.

I have restarted my phone and watch multiple times and even tried to run the app with my phone off, so the watch could connect to wifi.

I tried to install a watchOS 9 beta profile on my watch, knowing it would not work, but I still wanted to see what would happen.

I tried setting the build target to watchOS 8.5, which is the highest my version of Xcode would allow, to see if the problem was watchOS 6.2, and if it would work on my dad's watch.

Lastly, I tried adding privacy messages in the Info.plist for both the phone and the watch app. The messages did not display when I re-downloaded the app, but it still did not fix the issue.
(the messages I used were: "Privacy - Nearby Interaction Usage Description" which does not work on watchOS 6.2, but I still kept in the info.plist, and "Privacy - Bluetooth Always Usage Description")

I know Apple Watches are supposed to use the connected phone for Internet and then wifi if a phone is not connected. My watch shows that my phone is connected, and I have tried it with just wifi. I believe my watch can still get an Internet connection because I can still use Siri and even go to the App Store on my watch, which needs an Internet connection. I would appreciate any help. Let me know if I need to add any more information to help clear things up.

Body:
This is my first WatchKit App.

I am working on an app that gets an API call to an iCal file and displays the time remaining in two events.

I am working on Xcode 13.4.1 and created an iOS app with watchOS app using swift and storyboard. I set the target deployment for the iOS app to 15.5, which is the highest version of iOS that my current version of Xcode will let me set. The target deployment for the watchOS app is set to version 6.2 because I have an Apple Watch series 2, and the latest version of watchOS is 6.3. I want the app to at least work for my watch. The code for the iOS app and watch app are pretty much the same. The app works as expected on the watch and phone simulators and on my physical iPhone 8 plus. The problem is that the app does not work on my physical watch.

I created a custom class called API_Manager that handles the API call. I handle my API call as a giant string because I am getting an iCal file and parse it later on in the class. url is defined above. Here is my API call for both the phone and watch app:

public func getData() throws{
        //api call
        do{
            // real url is defined above
            let url:String = ""
            savedData = try String(contentsOf: URL(string: url)!)
        } catch{
            print("there was an error with the api call")
            throw API_Error.apiCallError
        }
        // parsing data
}

getData() is called in the init function of the API_Manager class.

    init() throws {
        // checking internet connection
        if (!NetworkMonitor.shared.isConnected){
            throw API_Error.noInternet
        }

        do{
            try getData()
        } catch{
            throw API_Error.apiCallError
        }

    }

I believe the root of the problem is an Internet connection. I check for an Internet connection before the API call, and if there is no Internet connection, then I throw a custom error. I used this video to create a Network_Monitor class. This is the startMonitoring() function which is called in the applicationDidFinishLaunching() in extensionDelegate of the watch app and application didFinishLaunchingWithOptions in the appDelegate.

public func startMonitoring(){
        monitor.start(queue: queue)

        monitor.pathUpdateHandler = { [weak self] path in
            self?.isConnected = path.status == .satisfied

            // getting connection type
            self?.getConnectionType(path)
        }
    }

I created a custom error that is thrown throughout the API_Manager if things don't work as expected. Here is how I created the custom errors:

enum API_Error: Error{
    case noInternet
    case apiCallError
}

extension API_Error: CustomStringConvertible{
    public var description:String {
        switch self{
        case .noInternet:
            return "Error: No internet connection"
        case .apiCallError:
            return "There was an error with the api call"
        }

    }
}

I created another enum that is used to display text on a label in the Interface Controller if a specific error is thrown.

enum API_Manager_Status{
        case active
        case noInternet
        case apiCallError
        case null                   // if the api manager is nill
    }

Here is how I used the two enums in InterfaceController:
main() is called in the awake() function.

func main(){
        do{
            apiManager = try API_Manager()
            apiManagerStatus = .active
        } catch API_Error.noInternet{
            apiManagerStatus = .noInternet

        } catch API_Error.apiCallError{
            apiManagerStatus = .apiCallError

        } catch{
            apiManagerStatus = .null

        }

        if (apiManagerStatus == .noInternet){
            periodLabel.setText("Error")
            timeRemaining.setText("No Internet")
            print(API_Error.noInternet)
        } else if (apiManagerStatus == .apiCallError){
            periodLabel.setText("Error")
            timeRemaining.setText("API Call")
            print(API_Error.apiCallError)
        } else if (apiManagerStatus == .null){
            periodLabel.setText("Error")
            timeRemaining.setText("Other Error")
            print("Cought all errors")
        } else{
            // main code to display time remaining
        }

So I guess my questions are:

Why is my Apple Watch not getting an Internet connection?

How can I fix my app if it worked on the simulators and iPhone, but not watch?

Can the Apple Watch do an API call?

Do I need to configure my app to connect with the iPhone, given that my watchOS verison is 6.2?

Sorry if this is a long question. This is my first time posting a question on Stack Overflow. I would appreciate any help. Let me know if I need to add any more information to help clear things up.

I have tried many potential solutions to fix the problem, but none have worked:

I distributed the app on Test Flight and had my dad download it. He has an Apple Watch Series 4 running on watchOS 9.2, and the app still does not work on his watch.

I have restarted my phone and watch multiple times and even tried to run the app with my phone off, so the watch could connect to wifi.

I tried to install a watchOS 9 beta profile on my watch, knowing it would not work, but I still wanted to see what would happen.

I tried setting the build target to watchOS 8.5, which is the highest my version of Xcode would allow, to see if the problem was watchOS 6.2, and if it would work on my dad's watch.

Lastly, I tried adding privacy messages in the Info.plist for both the phone and the watch app. The messages did not display when I re-downloaded the app, but it still did not fix the issue.
(the messages I used were: "Privacy - Nearby Interaction Usage Description" which does not work on watchOS 6.2, but I still kept in the info.plist, and "Privacy - Bluetooth Always Usage Description")

I know Apple Watches are supposed to use the connected phone for Internet and then wifi if a phone is not connected. My watch shows that my phone is connected, and I have tried it with just wifi. I believe my watch can still get an Internet connection because I can still use Siri and even go to the App Store on my watch, which needs an Internet connection. I would appreciate any help. Let me know if I need to add any more information to help clear things up.


来源: stackexchange

问:
Issue using eventHandlers with react-leaflet and next.js
I'm trying to use eventHandlers with react-leaflet in a next.js application, but the events are never being fired.

Here is an example of the code I'm using in my Map component:

```<code>import { MapContainer, Rectangle } from "react-leaflet";

const Map = () => {
  return (
    <MapContainer center={[25, 25]} zoom={1} style={{ height: 600, width: 600 }}>
      <Rectangle
        bounds={[
          [0, 0],
          [50, 50],
        ]}
        eventHandlers={{
          click: () => console.log("clicked.."),
        }}
      />
    </MapContainer>
  );
};

export default Map;
</code>```

I've tried using this code outside of a next.js application (plane react app) and it worked as expected, but when I use it in a next.js application, the event is never fired.

Here is an example of how I'm rendering the Map component in my index.js file:

```<code>import dynamic from "next/dynamic";

const Map = dynamic(() => import("../components/Map"), {
  ssr: false,
});

export default function Home() {
  return (
    <>
      <Map />
    </>
  );
}
</code>```

I also tried using this code in a codesandbox, but I couldn't get the sandbox to work (it crashed). Also tested it on the live editor on https://react-leaflet.js.org/docs/example-popup-marker/ and replacing the marker with the rectangle component, the event is triggered on click.

Has anyone else experienced this issue and found a solution?

Thanks in advance for any help!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use eventHandlers with react-leaflet in a next.js application, but the events are never being fired.

Here is an example of the code I'm using in my Map component:

import { MapContainer, Rectangle } from "react-leaflet";

const Map = () => {
  return (
    <MapContainer center={[25, 25]} zoom={1} style={{ height: 600, width: 600 }}>
      <Rectangle
        bounds={[
          [0, 0],
          [50, 50],
        ]}
        eventHandlers={{
          click: () => console.log("clicked.."),
        }}
      />
    </MapContainer>
  );
};

export default Map;

I've tried using this code outside of a next.js application (plane react app) and it worked as expected, but when I use it in a next.js application, the event is never fired.

Here is an example of how I'm rendering the Map component in my index.js file:

import dynamic from "next/dynamic";

const Map = dynamic(() => import("../components/Map"), {
  ssr: false,
});

export default function Home() {
  return (
    <>
      <Map />
    </>
  );
}

I also tried using this code in a codesandbox, but I couldn't get the sandbox to work (it crashed). Also tested it on the live editor on https://react-leaflet.js.org/docs/example-popup-marker/ and replacing the marker with the rectangle component, the event is triggered on click.

Has anyone else experienced this issue and found a solution?

Thanks in advance for any help!


问:
Visual Studio: Cannot build an executable or dll when there is space in the path to the build tools
I have been using VS to create a DLL but when I tried to build it VS broke the path to the build tools location down to multiple pieces. I already have VS BuildTools installed on my machine. Do you guys know how to solve this ? Here are some screenshots:

I have been looking on the internet for 2 days now but I couldn't find one that work for me. I have tried some methods but it doesn't work.


问:
How to change value of file from a fish function when sudo is required?
I've tried to create the following:

```<code>function change_brightness
    set -l brightness_level $argv[1]
    if not string match -r '^[1-9][0-9]*$' $brightness_level
        echo "Expect a single non-zero integer value to be passed."
        return 1
    end
    sudo echo $brightness_level > /sys/class/backlight/amdgpu_bl0/brightness
end
</code>```

When I run this function I get the following output:

```<code>$ change_brightness 30
30
warning: An error occurred while redirecting file '/sys/class/backlight/amdgpu_bl0/brightness'
open: Permission denied

</code>```

I'm not sure why the permission is denied, but I'm not sure why 30 is being echo'd to the console either (i was just expecting this to be written to the setting file).

Edit - running from shell with sudo

The following doesn't work:

```<code>$ sudo change_brightness 30
[sudo] password for user:
sudo: change_brightness: command not found
</code>```

Solution

```<code>function change_brightness
    set -l brightness_level $argv[1]
    if not string match -r '^[1-9][0-9]*$' $brightness_level
        echo "Expect a single non-zero integer value to be passed."
        return 1
    end
    echo $brightness_level | sudo tee /sys/class/backlight/amdgpu_bl0/brightness
end
</code>```

Body:
I've tried to create the following:

function change_brightness
    set -l brightness_level $argv[1]
    if not string match -r '^[1-9][0-9]*$' $brightness_level
        echo "Expect a single non-zero integer value to be passed."
        return 1
    end
    sudo echo $brightness_level > /sys/class/backlight/amdgpu_bl0/brightness
end

When I run this function I get the following output:

$ change_brightness 30
30
warning: An error occurred while redirecting file '/sys/class/backlight/amdgpu_bl0/brightness'
open: Permission denied

I'm not sure why the permission is denied, but I'm not sure why 30 is being echo'd to the console either (i was just expecting this to be written to the setting file).

Edit - running from shell with sudo

The following doesn't work:

$ sudo change_brightness 30
[sudo] password for user:
sudo: change_brightness: command not found

Solution

function change_brightness
    set -l brightness_level $argv[1]
    if not string match -r '^[1-9][0-9]*$' $brightness_level
        echo "Expect a single non-zero integer value to be passed."
        return 1
    end
    echo $brightness_level | sudo tee /sys/class/backlight/amdgpu_bl0/brightness
end


问:
After desactivating Billing_email i still get asked for an email in checkout Woocommerce
I am working on a cash on delivery store that doesn't require to get an account

the checkout fields required are : Name / Phone Number / City / Adress

when i visit the checkout while connected i get exactly what i want but when i log out and visit it as a guest i get an extra email field

I am working on a cash on delivery store that doesn't require to get an account

the checkout fields required are : Name / Phone Number / City / Adress

I autorized the clients to make purchase without an account and i used Woocommerce Checkout Manager to customize the fields and to delete the onces i dont need (https://i.stack.imgur.com/86EYj.png)

when i am trying to checkout while i  am connected to dashboard i get exactly what i want (https://i.stack.imgur.com/5F4lY.png)

but once i try it on incognito i get an extra email field (https://i.stack.imgur.com/4XMk3.png)

any suggestions to solve this problem?


问:
Postfix disable smtp error bounce for example address not found
I have a custom bounce but the smtp message is still there

failure_template = <<EOF
Charset: us-ascii
From: No Reply no-reply@example.com
Subject: Invio fallito
$myhostname dice: Invio fallito
EOF

How do I disable or customize this message? zsdjdh@example.com smtp message: host example.com[private/dovecot-lmtp] said: 550 5.1.1
zsdjdh@example.com User doesn't exist: zsdjdh@example.com (in reply to RCPT TO command)


问:
Masm not assembling my win32 program in visual studio
Guys I been trying to asssemble my masm32 file in visual studio but the build fails each time. there isn't an issue with my program as it runs on other machines perfectly well it's only i think a problem with dependecies or sth or me not runnning this asemmbly file on some older windows version I guess but i tried everything peraps you could point me out to what the problem is

here is the output I get when I try to build it

```<code>1>------ Build started: Project: Project1, Configuration: Debug|Win32 ------
1>  Assembling childWnd.asm...
1>C:\masm32\include\winextra.inc(9722): error A2026: constant expected
1>C:\masm32\include\winextra.inc(9723): error A2026: constant expected
1>C:\Project1\childWnd.asm(80): warning A6004: procedure argument or local not referenced : hPrevInst
1>C:\Project1\childWnd.asm(80): warning A6004: procedure argument or local not referenced : CmdLine
1>C:\Project1\childWnd.asm(80): warning A6004: procedure argument or local not referenced : CmdShow
1>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\BuildCustomizations\masm.targets(70,5): error MSB3721: The command "ml.exe /c /nologo /Zi /Fo"Debug\childWnd.obj" /W3 /errorReport:prompt  /TachildWnd.asm" exited with code 1.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

PS: i did put my project folder inside my masm32 directory and it continues to fail

here is the code for my program

```<code>.386
.model flat,stdcall
option casemap:none
WinMain proto :DWORD,:DWORD,:DWORD,:DWORD

include \masm32\include\windows.inc
include \masm32\include\user32.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\user32.lib
includelib \masm32\lib\kernel32.lib

.data
ClassName db "SimpleWinClass",0
AppName  db "Our First Window",0
MenuName db "FirstMenu",0
ButtonClassName db "button",0
ButtonText db "My First Button",0
EditClassName db "edit",0
TestString db "Wow! I'm in an edit box now",0

.data?
hInstance HINSTANCE ?
CommandLine LPSTR ?
hwndButton HWND ?
hwndEdit HWND ?
buffer db 512 dup(?)                    ; buffer to store the text retrieved from the edit box

.const
ButtonID equ 1                                ; The control ID of the button control
EditID equ 2                                    ; The control ID of the edit control
IDM_HELLO equ 1
IDM_CLEAR equ 2
IDM_GETTEXT equ 3
IDM_EXIT equ 4

.code
start:
    invoke GetModuleHandle, NULL
    mov    hInstance,eax
    invoke GetCommandLine
    mov CommandLine,eax
    invoke WinMain, hInstance,NULL,CommandLine, SW_SHOWDEFAULT
    invoke ExitProcess,eax

WinMain proc hInst:HINSTANCE,hPrevInst:HINSTANCE,CmdLine:LPSTR,CmdShow:DWORD
    LOCAL wc:WNDCLASSEX
    LOCAL msg:MSG
    LOCAL hwnd:HWND
    mov   wc.cbSize,SIZEOF WNDCLASSEX
    mov   wc.style, CS_HREDRAW or CS_VREDRAW
    mov   wc.lpfnWndProc, OFFSET WndProc
    mov   wc.cbClsExtra,NULL
    mov   wc.cbWndExtra,NULL
    push  hInst
    pop   wc.hInstance
    mov   wc.hbrBackground,COLOR_BTNFACE+1
    mov   wc.lpszMenuName,OFFSET MenuName
    mov   wc.lpszClassName,OFFSET ClassName
    invoke LoadIcon,NULL,IDI_APPLICATION
    mov   wc.hIcon,eax
    mov   wc.hIconSm,eax
    invoke LoadCursor,NULL,IDC_ARROW
    mov   wc.hCursor,eax
    invoke RegisterClassEx, addr wc
    invoke CreateWindowEx,WS_EX_CLIENTEDGE,ADDR ClassName, \
                        ADDR AppName, WS_OVERLAPPEDWINDOW,\
                        CW_USEDEFAULT, CW_USEDEFAULT,\
                        300,200,NULL,NULL, hInst,NULL
    mov   hwnd,eax
    invoke ShowWindow, hwnd,SW_SHOWNORMAL
    invoke UpdateWindow, hwnd
    .WHILE TRUE
        invoke GetMessage, ADDR msg,NULL,0,0
        .BREAK .IF (!eax)
        invoke TranslateMessage, ADDR msg
        invoke DispatchMessage, ADDR msg
    .ENDW
    mov     eax,msg.wParam
    ret
WinMain endp

WndProc proc hWnd:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM
    .IF uMsg==WM_DESTROY
        invoke PostQuitMessage,NULL
    .ELSEIF uMsg==WM_CREATE
        invoke CreateWindowEx,WS_EX_CLIENTEDGE, ADDR EditClassName,NULL,\
                        WS_CHILD or WS_VISIBLE or WS_BORDER or ES_LEFT or\
                        ES_AUTOHSCROLL,\
                        50,35,200,25,hWnd,8,hInstance,NULL
        mov  hwndEdit,eax
        invoke SetFocus, hwndEdit
        invoke CreateWindowEx,NULL, ADDR ButtonClassName,ADDR ButtonText,\
                        WS_CHILD or WS_VISIBLE or BS_DEFPUSHBUTTON,\
                        75,70,140,25,hWnd,ButtonID,hInstance,NULL
        mov  hwndButton,eax
    .ELSEIF uMsg==WM_COMMAND
        mov eax,wParam
        .IF lParam==0
            .IF ax==IDM_HELLO
                invoke SetWindowText,hwndEdit,ADDR TestString
            .ELSEIF ax==IDM_CLEAR
                invoke SetWindowText,hwndEdit,NULL
            .ELSEIF  ax==IDM_GETTEXT
                invoke GetWindowText,hwndEdit,ADDR buffer,512
                invoke MessageBox,NULL,ADDR buffer,ADDR AppName,MB_OK
            .ELSE
                invoke DestroyWindow,hWnd
            .ENDIF
        .ELSE
            .IF ax==ButtonID
                shr eax,16
                .IF ax==BN_CLICKED
                    invoke SendMessage,hWnd,WM_COMMAND,IDM_GETTEXT,0
                .ENDIF
            .ENDIF
        .ENDIF
    .ELSE
        invoke DefWindowProc,hWnd,uMsg,wParam,lParam
        ret
    .ENDIF
     xor    eax,eax
    ret
WndProc endp
end start

</code>```

Body:
Guys I been trying to asssemble my masm32 file in visual studio but the build fails each time. there isn't an issue with my program as it runs on other machines perfectly well it's only i think a problem with dependecies or sth or me not runnning this asemmbly file on some older windows version I guess but i tried everything peraps you could point me out to what the problem is

here is the output I get when I try to build it

1>------ Build started: Project: Project1, Configuration: Debug|Win32 ------
1>  Assembling childWnd.asm...
1>C:\masm32\include\winextra.inc(9722): error A2026: constant expected
1>C:\masm32\include\winextra.inc(9723): error A2026: constant expected
1>C:\Project1\childWnd.asm(80): warning A6004: procedure argument or local not referenced : hPrevInst
1>C:\Project1\childWnd.asm(80): warning A6004: procedure argument or local not referenced : CmdLine
1>C:\Project1\childWnd.asm(80): warning A6004: procedure argument or local not referenced : CmdShow
1>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\BuildCustomizations\masm.targets(70,5): error MSB3721: The command "ml.exe /c /nologo /Zi /Fo"Debug\childWnd.obj" /W3 /errorReport:prompt  /TachildWnd.asm" exited with code 1.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

PS: i did put my project folder inside my masm32 directory and it continues to fail

here is the code for my program

.386
.model flat,stdcall
option casemap:none
WinMain proto :DWORD,:DWORD,:DWORD,:DWORD

include \masm32\include\windows.inc
include \masm32\include\user32.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\user32.lib
includelib \masm32\lib\kernel32.lib

.data
ClassName db "SimpleWinClass",0
AppName  db "Our First Window",0
MenuName db "FirstMenu",0
ButtonClassName db "button",0
ButtonText db "My First Button",0
EditClassName db "edit",0
TestString db "Wow! I'm in an edit box now",0

.data?
hInstance HINSTANCE ?
CommandLine LPSTR ?
hwndButton HWND ?
hwndEdit HWND ?
buffer db 512 dup(?)                    ; buffer to store the text retrieved from the edit box

.const
ButtonID equ 1                                ; The control ID of the button control
EditID equ 2                                    ; The control ID of the edit control
IDM_HELLO equ 1
IDM_CLEAR equ 2
IDM_GETTEXT equ 3
IDM_EXIT equ 4

.code
start:
    invoke GetModuleHandle, NULL
    mov    hInstance,eax
    invoke GetCommandLine
    mov CommandLine,eax
    invoke WinMain, hInstance,NULL,CommandLine, SW_SHOWDEFAULT
    invoke ExitProcess,eax

WinMain proc hInst:HINSTANCE,hPrevInst:HINSTANCE,CmdLine:LPSTR,CmdShow:DWORD
    LOCAL wc:WNDCLASSEX
    LOCAL msg:MSG
    LOCAL hwnd:HWND
    mov   wc.cbSize,SIZEOF WNDCLASSEX
    mov   wc.style, CS_HREDRAW or CS_VREDRAW
    mov   wc.lpfnWndProc, OFFSET WndProc
    mov   wc.cbClsExtra,NULL
    mov   wc.cbWndExtra,NULL
    push  hInst
    pop   wc.hInstance
    mov   wc.hbrBackground,COLOR_BTNFACE+1
    mov   wc.lpszMenuName,OFFSET MenuName
    mov   wc.lpszClassName,OFFSET ClassName
    invoke LoadIcon,NULL,IDI_APPLICATION
    mov   wc.hIcon,eax
    mov   wc.hIconSm,eax
    invoke LoadCursor,NULL,IDC_ARROW
    mov   wc.hCursor,eax
    invoke RegisterClassEx, addr wc
    invoke CreateWindowEx,WS_EX_CLIENTEDGE,ADDR ClassName, \
                        ADDR AppName, WS_OVERLAPPEDWINDOW,\
                        CW_USEDEFAULT, CW_USEDEFAULT,\
                        300,200,NULL,NULL, hInst,NULL
    mov   hwnd,eax
    invoke ShowWindow, hwnd,SW_SHOWNORMAL
    invoke UpdateWindow, hwnd
    .WHILE TRUE
        invoke GetMessage, ADDR msg,NULL,0,0
        .BREAK .IF (!eax)
        invoke TranslateMessage, ADDR msg
        invoke DispatchMessage, ADDR msg
    .ENDW
    mov     eax,msg.wParam
    ret
WinMain endp

WndProc proc hWnd:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM
    .IF uMsg==WM_DESTROY
        invoke PostQuitMessage,NULL
    .ELSEIF uMsg==WM_CREATE
        invoke CreateWindowEx,WS_EX_CLIENTEDGE, ADDR EditClassName,NULL,\
                        WS_CHILD or WS_VISIBLE or WS_BORDER or ES_LEFT or\
                        ES_AUTOHSCROLL,\
                        50,35,200,25,hWnd,8,hInstance,NULL
        mov  hwndEdit,eax
        invoke SetFocus, hwndEdit
        invoke CreateWindowEx,NULL, ADDR ButtonClassName,ADDR ButtonText,\
                        WS_CHILD or WS_VISIBLE or BS_DEFPUSHBUTTON,\
                        75,70,140,25,hWnd,ButtonID,hInstance,NULL
        mov  hwndButton,eax
    .ELSEIF uMsg==WM_COMMAND
        mov eax,wParam
        .IF lParam==0
            .IF ax==IDM_HELLO
                invoke SetWindowText,hwndEdit,ADDR TestString
            .ELSEIF ax==IDM_CLEAR
                invoke SetWindowText,hwndEdit,NULL
            .ELSEIF  ax==IDM_GETTEXT
                invoke GetWindowText,hwndEdit,ADDR buffer,512
                invoke MessageBox,NULL,ADDR buffer,ADDR AppName,MB_OK
            .ELSE
                invoke DestroyWindow,hWnd
            .ENDIF
        .ELSE
            .IF ax==ButtonID
                shr eax,16
                .IF ax==BN_CLICKED
                    invoke SendMessage,hWnd,WM_COMMAND,IDM_GETTEXT,0
                .ENDIF
            .ENDIF
        .ENDIF
    .ELSE
        invoke DefWindowProc,hWnd,uMsg,wParam,lParam
        ret
    .ENDIF
     xor    eax,eax
    ret
WndProc endp
end start


问:
reactjs-popup popup menu doesn't close after clicking an option
I am trying to implement a popup menu which closes after a button or a link is clicked with reactjs-popup library.

The documentation uses { close => (...content) } for modal but this approach doesn't work for popup menu.


问:
how to show data not found when ajax call codeigniter using select option
how to show data not found,
when ajax call data not found  using select option

```<code>          <div class="col-md-6 col-12">
             <div class="mb-1">
              <label class="form-label" for="country-floating"><?php echo display('city')?></label>
                 <select name="city" id="city" class="select2 form-select"  >
                    <option value="">No Selected</option>
                </select>
            </div>
        </div>
</code>```

where my  ajax call function are as

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('#state').change(function(){
             var id=$(this).val();
            $.ajax({
                url : "<?php echo base_url('suppliers/get_city');?>",
                method : "POST",
                data : {id: id},
                async : true,
                dataType : 'json',
                success: function(data){
                    var html = '';
                    var i;
                    for(i=0; i<data.length; i++){
                        html += '<option value='+data[i].id+'>'+data[i].city_name+'</option>';
                    }
                    $('#city').html(html);
                },
               error: function(jqXHR, textStatus, errorThrown){
              alert('Error: ' + textStatus + ' - ' + errorThrown);
               }
               });
            return false;
        });
                });
</script>
</code>```

I don't understand anything now , please help

my code is working properly i just want to show that when no data is found then i want to show "data not found" in select option

Body:
how to show data not found,
when ajax call data not found  using select option

              <?php echo display('city')?>
                 <select name="city" id="city" class="select2 form-select"  >
                    <option value="">No Selected</option>
                </select>

where my  ajax call function are as

I don't understand anything now , please help

my code is working properly i just want to show that when no data is found then i want to show "data not found" in select option


问:
vue 3 : ReferenceError: can't access lexical declaration
I keep getting error Uncaught (in promise) ReferenceError: can't access lexical declaration 'primaryColor' before initialization as Iam trying to migrate from vue2 to vue 3

This is my code

```<code><template>
<div class="introduce-connect-block pt-0 pb-0">
    <img v-if="parameters.WELCOME_IMAGE" class="introduce-hero-image" :src="parameters.WELCOME_IMAGE" alt="" />
    <img v-else class="introduce-hero-image" src="/images/heros.png" alt="" />
    <p class="pop-wd-heading pop-mb-80">Welcome to {{ brandName }}</p>
</div>
</template>

<script setup>

import { defineProps, computed } from "vue";

const props = defineProps({
  parameters: Object
});

const store = useStore();

const primaryColor = computed(() => store.getters["auth/color"]);
const brandName = computed(() => store.getters["auth/brandName"]);

</script>

<style lang="scss">
@media screen and (max-device-width: 480px) and (orientation: portrait) {
  .connect-button-bg {
    border: 2px solid v-bind(primaryColor);
  }
}
</style>
</code>```

The error is happening in line

border: 2px solid v-bind(primaryColor);

The value of primaryColor is in store, how can I fix this?

Body:
I keep getting error Uncaught (in promise) ReferenceError: can't access lexical declaration 'primaryColor' before initialization as Iam trying to migrate from vue2 to vue 3

This is my code

<template>

Welcome to {{ brandName }}

</template>

The error is happening in line

border: 2px solid v-bind(primaryColor);

The value of primaryColor is in store, how can I fix this?


问:
Unable to upload bundle file to update the app in playstore
my app is on the store ..I want to upload a new version ..but I generated the new bundle file with another device (I'm still using the same Jks file ).. the store console wont accept the new bundle fie because it returns (Your app bundle is expected to be signed with the certificate with fingerprint)

Do I need to generate a new jks file or can I use the original from upload?


问:
How is the output of this expression 43?
I am learning C language and now I am confused with the output of the below snippet.

```<code>#include <stdio.h>

int main(void) {
    int p = 20;
    printf("%d\n",++p + p++);
    return 0;
}

</code>```

Online Fiddle

How is the output of this 43?

As far as I have understood, it should be evaluating as below:

++p makes it 21.

p++, makes it 22 but will be 21 during addition since it is post-increment.

So the expected output should be 21 + 21 = 42. Isn't it?

Body:
I am learning C language and now I am confused with the output of the below snippet.

#include <stdio.h>

int main(void) {
    int p = 20;
    printf("%d\n",++p + p++);
    return 0;
}

Online Fiddle

How is the output of this 43?

As far as I have understood, it should be evaluating as below:

++p makes it 21.

p++, makes it 22 but will be 21 during addition since it is post-increment.

So the expected output should be 21 + 21 = 42. Isn't it?


问:
how to add a python ide using codemirror to a django app
I'm new to Django and web-dev and was looking for a good tutorial explaining how to add a codemirror IDE to a django app but haven't been to successful can anyone lead me in the right direction or just throw up some basic code ie: models.py views.py settings.py etc of a basic python ide set up.

any help would be greatly appreciated thanks in advance.


问:
Saving and applying a keras model to unseen data
I am building a model for my multiclass text classification problem which looks like this:

```<code>model = tf.keras.Sequential()
model.add(hub_layer)
for units in [128, 128, 64 , 32]: # automatically adding layers through a for loop
   model.add(tf.keras.layers.Dense(units, activation='relu'))
   model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(18, activation='softmax'))
model.summary()

# Optimiser Function
model.compile(optimizer='adam',
              loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(train_data_f,
                    epochs=20,
                    validation_data=test_data_f,
                    verbose=1,
                    class_weight=class_weights
       )
</code>```

Once the build is done, I would like to do the following:

Save the model

Load the model and apply it to an unseen text (For Example: the column on which I would want to apply this model is df['Unseen_Text]

how can I achieve this?

Body:
I am building a model for my multiclass text classification problem which looks like this:

model = tf.keras.Sequential()
model.add(hub_layer)
for units in [128, 128, 64 , 32]: # automatically adding layers through a for loop
   model.add(tf.keras.layers.Dense(units, activation='relu'))
   model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(18, activation='softmax'))
model.summary()

# Optimiser Function
model.compile(optimizer='adam',
              loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(train_data_f,
                    epochs=20,
                    validation_data=test_data_f,
                    verbose=1,
                    class_weight=class_weights
       )

Once the build is done, I would like to do the following:

Save the model

Load the model and apply it to an unseen text (For Example: the column on which I would want to apply this model is df['Unseen_Text]

how can I achieve this?


问:
Hey, I've got some problems with hiding a part of HTML DOM using JS
I wanted to hide a part of my page from not showing up, but the HTML doesn't seem to work, please help me.

document.getElementById("login").style.display = "none";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="login">
  <h1 align="center">Login</h1>
  <input type="text" id="Name2">
  <input type="password" id="Pass2">
  <button id="login">Sign Up</button>
  <button id="switch2">Not a user? Sign Up here.</button>
</div></code>```

The same JS code works when I ran it through inspect tab of my browser, that time it worked.

It also doesn't show any particular error or anything.

And, I've added the script tag after the body tag, as I had learnt from a book to do so as getElementById only works if we do so.

Please help me (ಥ _ ಥ)

Body:
I wanted to hide a part of my page from not showing up, but the HTML doesn't seem to work, please help me.

document.getElementById("login").style.display = "none";

Login

  <input type="text" id="Name2">
  <input type="password" id="Pass2">
  <button id="login">Sign Up</button>
  <button id="switch2">Not a user? Sign Up here.</button>

The same JS code works when I ran it through inspect tab of my browser, that time it worked.

It also doesn't show any particular error or anything.

And, I've added the script tag after the body tag, as I had learnt from a book to do so as getElementById only works if we do so.

Please help me (ಥ _ ಥ)


问:
Fuzzy search of users to retrieve associated data
I am building an application which identifies people mentioned in free text (order of magnitude of a million) and stores their names as keys with one or more (for handling people with the same name) associated URIs pointing to a SPARQL based knowledge graph node which then lets me retrieve additional data about them.

Currently I am storing the name and last name as keys in a Redis DB but the problem is that I need to use fuzzy search on those names using the Rapidfuzz library https://github.com/maxbachmann/RapidFuzz because Redis only provides a simple LD distance fuzzy query which is not enough.

What architecture would you recommend? Happy 2023!!!


问:
Problem with my java keyinput listener - Minecraft 1.19.3
I tried to create keyinputlistener for my specific uses but i can't find reason why my function keyInputEvent nor Overrided function invoke from org.lwjgl.glfw.GLFWKeyCallbackI class don't execute every time there is a keyboard input. And yes i initialized my class. Here is my class:

```<code>package net.shadowgrum.shadowclient;

import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFWKeyCallbackI;

import java.util.Objects;

public class KeyInputListener implements GLFWKeyCallbackI {
    public KeyInputListener() {}

    @Override
    public void invoke(long window, int key, int scancode, int action, int mods) {
        System.out.println("you pressed"+key);
        keyInputEvent(window, KeyTranslator.toKey(key, scancode), action, mods);
    }

    public void keyInputEvent(long window, InputUtil.Key key, int action, int mods){

        if (Objects.equals(key.getTranslationKey(), "key.keyboard.k") && action ==  1) {
            SomeThing.toggle();
        }
    }

}
</code>```

I tried to Override other methods that i found in minecraft source code that seems to execute every keyinput but i wasn't successful. Can you please help me? :)

Body:
I tried to create keyinputlistener for my specific uses but i can't find reason why my function keyInputEvent nor Overrided function invoke from org.lwjgl.glfw.GLFWKeyCallbackI class don't execute every time there is a keyboard input. And yes i initialized my class. Here is my class:

package net.shadowgrum.shadowclient;

import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFWKeyCallbackI;

import java.util.Objects;

public class KeyInputListener implements GLFWKeyCallbackI {
    public KeyInputListener() {}

    @Override
    public void invoke(long window, int key, int scancode, int action, int mods) {
        System.out.println("you pressed"+key);
        keyInputEvent(window, KeyTranslator.toKey(key, scancode), action, mods);
    }

    public void keyInputEvent(long window, InputUtil.Key key, int action, int mods){

        if (Objects.equals(key.getTranslationKey(), "key.keyboard.k") && action ==  1) {
            SomeThing.toggle();
        }
    }

}

I tried to Override other methods that i found in minecraft source code that seems to execute every keyinput but i wasn't successful. Can you please help me? :)


问:
Tinymce5 not show image toolbar icon
I install TinyMce5 from npm packages and configure it, but when i try to initialize image plugin and put it in toolbar image option for upload or chose missing. Can someone see code and tell me what i do wrong? Thanks

Here is my code:

```<code> <script>
        var editor_config = {
            path_absolute: "/",
            selector: 'textarea.tinymce-editor',
            relative_urls: false,
            plugins: [
                "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars code fullscreen",
                "insertdatetime media nonbreaking save table directionality",
                "emoticons template paste textpattern"
            ],
            toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
            file_picker_callback: function(callback, value, meta) {
                var x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
                var y = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;

                var cmsURL = editor_config.path_absolute + 'laravel-filemanager?editor=' + meta.fieldname;
                if (meta.filetype == 'image') {
                    cmsURL = cmsURL + "&type=Images";
                } else {
                    cmsURL = cmsURL + "&type=Files";
                }

                tinyMCE.activeEditor.windowManager.openUrl({
                    url: cmsURL,
                    title: 'Filemanager',
                    width: x * 0.8,
                    height: y * 0.8,
                    resizable: "yes",
                    close_previous: "no",
                    onMessage: (api, message) => {
                        callback(message.content);
                    }
                });
            }
        };

        tinymce.init(editor_config);
    </script>
</code>```

Title: Tinymce5 not show image toolbar icon


问:
Is there a way to fix this django stripe integration error?
We are integrating stripe for as US stripe account.

There is no connection to India but we are getting this error... Instead of the payment URL:

Request req_OuSWvylGF8wZDi: As per Indian regulations, only registered Indian businesses (i.e. sole proprietorships, limited liability partnerships and companies, but not individuals) can accept international payments.

More info here: Stripe Documentation

We tried integrating stripe, and backend Django for US based company. But we keep on getting Indian regulations errors. We don't know how. There is no relation to India.


问:
Azure.Data.Tables SDK Converting POCO objects to TableEntity and back
Trying to work out Azure.Data.Tables SDK but seem to only find 1 trillion examples using the depricated WindowsAzure SDK which no longer seem to work in the newer SDK.

Problem: I have a number of POCO entities which implement ITableEntity and have various specific properties e.g.:

```<code>public class BenefitEntity: ITableEntity
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTimeOffset? Timestamp { get; set; }
    public ETag ETag { get; set; }
    public string Name { get; set; }
    public double Value { get; set; }
}
</code>```

I have used the TableClient<TableEntity> to query and return a Pageable<TableEntity> without any trouble

```<code> var results = tableClient.Query<TableEntity>(filter: $"PartitionKey eq '{partitionKey}'");
</code>```

I can happily iterate through the TableEntities and lift off the values I need using TableEntity.GetString("Name") etc.

What I can't do is return a Pageable<BenefitEntity> using var results = tableClient.Query<BenefitEntity>(filter: $"PartitionKey eq '{partitionKey}'"); or work out a simple way to convert TableEntity to BenefitEntity (or indeed BenefitEntity to TableEntity) to use the TableClient methods.

I am sure this is not a novel use case but I am flummoxed in terms of finding any documentation on a conversion.

What I had hoped was to make a generic class where I could specify a type <T> and use that for the Type of the tableClient.Query method and thus be able to return a typed List or observable collection back to the method call. Like you can quite easily do if you use the basic HttpClient and the rest API directly to simply deserialise the response body JSON into a collection of your POCOs.

All I can find is DynamicTableEntity options to flatten POCOs to dictionaries with reflection and use the DynamicTableEntity.Properties to reform objects which seem to have disappeared as an option with Azure.Data.Tables

Any help much appreciated.

Update

Spent hours messing around and realised you can just change the TableEntity type in the tableclient.query method to BenefitEntity to get a Pageable<BenefitEntity> in return.

Given I have 30 or so object types (in a similar form as the BenefitEntity) I then tried to make a generic version of the method:

```<code>   public Pageable<T> GetItems<T>(string tableName, string partitionKey, string accountName, string storageAccountKey, string storageUri)
    {
        var tableClient = new TableClient(
        new Uri(storageUri),
        tableName,
        new TableSharedKeyCredential(accountName, storageAccountKey));

        return tableClient.Query<T>(filter: $"PartitionKey eq '{partitionKey}'");
    }
</code>```

To find that I was getting errors about using the type T on tableClient.Query<T> and needing a reference type with a public parameterless constructor.

More time with Google and finally came across Generic Type constraints...

       public Pageable<T> GetItems<T>(string tableName, string partitionKey, string accountName, string storageAccountKey, string storageUri)

becomes

      public Pageable<T> GetItems<T>(string tableName, string partitionKey, string accountName, string storageAccountKey, string storageUri) where T : class, ITableEntity, new()

and It is now working - what a waste of a day! but I learned new things.

Body:
Trying to work out Azure.Data.Tables SDK but seem to only find 1 trillion examples using the depricated WindowsAzure SDK which no longer seem to work in the newer SDK.

Problem: I have a number of POCO entities which implement ITableEntity and have various specific properties e.g.:

public class BenefitEntity: ITableEntity
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTimeOffset? Timestamp { get; set; }
    public ETag ETag { get; set; }
    public string Name { get; set; }
    public double Value { get; set; }
}

I have used the TableClient<TableEntity> to query and return a Pageable<TableEntity> without any trouble

 var results = tableClient.Query<TableEntity>(filter: $"PartitionKey eq '{partitionKey}'");

I can happily iterate through the TableEntities and lift off the values I need using TableEntity.GetString("Name") etc.

What I can't do is return a Pageable<BenefitEntity> using var results = tableClient.Query<BenefitEntity>(filter: $"PartitionKey eq '{partitionKey}'"); or work out a simple way to convert TableEntity to BenefitEntity (or indeed BenefitEntity to TableEntity) to use the TableClient methods.

I am sure this is not a novel use case but I am flummoxed in terms of finding any documentation on a conversion.

What I had hoped was to make a generic class where I could specify a type <T> and use that for the Type of the tableClient.Query method and thus be able to return a typed List or observable collection back to the method call. Like you can quite easily do if you use the basic HttpClient and the rest API directly to simply deserialise the response body JSON into a collection of your POCOs.

All I can find is DynamicTableEntity options to flatten POCOs to dictionaries with reflection and use the DynamicTableEntity.Properties to reform objects which seem to have disappeared as an option with Azure.Data.Tables

Any help much appreciated.

Update

Spent hours messing around and realised you can just change the TableEntity type in the tableclient.query method to BenefitEntity to get a Pageable<BenefitEntity> in return.

Given I have 30 or so object types (in a similar form as the BenefitEntity) I then tried to make a generic version of the method:

   public Pageable<T> GetItems<T>(string tableName, string partitionKey, string accountName, string storageAccountKey, string storageUri)
    {
        var tableClient = new TableClient(
        new Uri(storageUri),
        tableName,
        new TableSharedKeyCredential(accountName, storageAccountKey));

        return tableClient.Query<T>(filter: $"PartitionKey eq '{partitionKey}'");
    }

To find that I was getting errors about using the type T on tableClient.Query<T> and needing a reference type with a public parameterless constructor.

More time with Google and finally came across Generic Type constraints...

       public Pageable<T> GetItems<T>(string tableName, string partitionKey, string accountName, string storageAccountKey, string storageUri)

becomes

      public Pageable<T> GetItems<T>(string tableName, string partitionKey, string accountName, string storageAccountKey, string storageUri) where T : class, ITableEntity, new()

and It is now working - what a waste of a day! but I learned new things.


问:
How do you train Huggingface Maskformer for instance segmentation?
I can see an example to train for semantic segmentation but I'm unclear how to fine tune a model for instance segmentation. Specifically how to calculate the loss function assuming the data is in COCO format?</p>


问:
Cannot update a component while rendering a different component warning
this is error :

ERROR  Warning: Cannot update a component (`ForwardRef(BaseNavigationContainer)`) while rendering a different component (`LoginScreen`). To locate the bad setState() call inside `LoginScreen`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render

```<code>const LoginScreen = (props) => {
  const userSliceData = useSelector(state => state.userSlicer)
  const dispatch = useDispatch();
  const { navigation } = props; // 네비게이션

  $Util.getStoreData('token').then(function(token) {
    if (!$Util.isEmpty(token.accessToken)) {
        dispatch(userSlicer.actions.setToken({
          accessToken: token.accessToken,
          refreshToken: token.refreshToken,
      }))
    }
  })
  if (!$Util.isEmpty(userSliceData.accessToken)) {
    navigation.dispatch(
      StackActions.replace(ROUTES.INDEX)
    )
  }
}
</code>```
```<code>After judging whether you have logged in or not, you are trying to transfer to the index or login page.
It works as I want, but I keep getting the same error, but I don't know what the problem is.

plz help
</code>```

Body:
this is error :

ERROR  Warning: Cannot update a component (`ForwardRef(BaseNavigationContainer)`) while rendering a different component (`LoginScreen`). To locate the bad setState() call inside `LoginScreen`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render

const LoginScreen = (props) => {
  const userSliceData = useSelector(state => state.userSlicer)
  const dispatch = useDispatch();
  const { navigation } = props; // 네비게이션

  $Util.getStoreData('token').then(function(token) {
    if (!$Util.isEmpty(token.accessToken)) {
        dispatch(userSlicer.actions.setToken({
          accessToken: token.accessToken,
          refreshToken: token.refreshToken,
      }))
    }
  })
  if (!$Util.isEmpty(userSliceData.accessToken)) {
    navigation.dispatch(
      StackActions.replace(ROUTES.INDEX)
    )
  }
}

After judging whether you have logged in or not, you are trying to transfer to the index or login page.
It works as I want, but I keep getting the same error, but I don't know what the problem is.

plz help


问:
Warn about unsaved state changes on flutter web
i try to do a form with flutter web but i want to show a dialog if users do unsaved changes before reloading/changing pages.

I tried onwillpop but it doesnt detect page change when i press back button or change url to go other pages.

Any suggestion about this ?


问:
How to modify an npm module installed in a React application
I would need to modify an npm module (paradox.js) that is installed in node-modules in a react app created with create-react-app; Do I make the modification and that's it or should I build or compile it for the changes to take effect? I say this because when I remove all references and uses of the fs module, I still get the following error: "ERROR in ./node_modules/paradox.js/index.js 1:11-24
Module not found: Error: Can't resolve 'fs' in 'C:\Users\User\OneDrive\Desktop\pQCTMERN\pqct-client\node_modules\paradox.js'"</p>


问:
How to control brightness and contrast of screen display in android programmatically?
I want to control the display's brightness and contrast in android.

To achieve the 'night light' effect.

Some devices may have the same functionality as the other name like: 'eye comfort' or 'read mode' etc.

I searched the play store and found some apps named 'blue light filter'.

They did right. Their app is working fine.

Is there any way to achieve the effect?
Maybe it could be achieved by Android Accessibility Permission but I don't have much knowledge.

Thanks in advance.


问:
How to map extension value to claim in B2C custom policy?
I'm using Technical Profile in B2C to call Graph API to get response looks like format

```<code>{
   extension_clientId_name : "my-name",
   extension_clientId_email: "my-email"
}
</code>```

The problem is {clientId} will change dynamically based on clientId I passed as parameter to API. For example, extension_0000-00000-0000-000_name or it can look like extension_1111-1111-1111-1111_name. So in this case, how to map it to claim ? is it possible for us to control it ?

Body:
I'm using Technical Profile in B2C to call Graph API to get response looks like format

{
   extension_clientId_name : "my-name",
   extension_clientId_email: "my-email"
}

The problem is {clientId} will change dynamically based on clientId I passed as parameter to API. For example, extension_0000-00000-0000-000_name or it can look like extension_1111-1111-1111-1111_name. So in this case, how to map it to claim ? is it possible for us to control it ?


问:
How to allow via API for IPB to download a file
I developped a page displaying all the files but if I click on a button to download the specific file it does not work

example : https://localhost/forum/files/file/62-apps-example-flat/?do=download&csrfKey=51687f96ecfdd2e70a40682c06c74a40

this link works fine and I can upload the files

with the api I have this result after the loop :

```<code>$file['files'][0]['url']

`https://localhost/forum/uploads/monthly_2018_12/apps_example_flat_zip.7eb05295830880e718e49429840ef224`
</code>```

How to resolve this point allowing to download a file from the forum / Files module

Thank you

Body:
I developped a page displaying all the files but if I click on a button to download the specific file it does not work

example : https://localhost/forum/files/file/62-apps-example-flat/?do=download&csrfKey=51687f96ecfdd2e70a40682c06c74a40

this link works fine and I can upload the files

with the api I have this result after the loop :

$file['files'][0]['url']

`https://localhost/forum/uploads/monthly_2018_12/apps_example_flat_zip.7eb05295830880e718e49429840ef224`

How to resolve this point allowing to download a file from the forum / Files module

Thank you


问:
Elements positioned too far down on mobile
The website is supposed to have all elements vertically centered, but on my android tablet and mobile, they're placed below center.

This is what the site looks like on PC (tested on both Blink and Gecko browsers): website on PC

and this is what it looks like on mobile (ditto):
Website on tablet/mobile

Link to the website

The elements on the page are in containers that are 100vw wide and 100vh tall, with display:grid and place-items: center - the images on the right also have scroll-snap-align:center.

I've tried resizing my browser window to match the mobile aspect ratio and size, but I can't recreate the problem on my PC. I've also rewritten the positioning from scratch, but can't seem to figure out what the issue is.


问:
TypeError: this.pingIntervalTimer.refresh is not a function
I use the gulp for my project. When I run the task 'gulp watch', the server launches as it should, but after 500-600ms I get an error in the console "TypeError: this.pingIntervalTimer.refresh is not a function".
Gulpfile:

```<code>var gulp = require('gulp'),
watch = require('gulp-watch'),
browserSync = require('browser-sync').create();
gulp.task('serve', function() {
    browserSync.init({
        server: {
            baseDir: "src"
        },
        notify: false
    });

});

gulp.task('watch', ['serve'], function() {
    gulp.watch('./src/*.html', browserSync.reload);
});
</code>```

Console screenshot: console error

This error occurred after I updated the modules with the npm update --save command in my project folder.

Can you help me with my problem?

Body:
I use the gulp for my project. When I run the task 'gulp watch', the server launches as it should, but after 500-600ms I get an error in the console "TypeError: this.pingIntervalTimer.refresh is not a function".
Gulpfile:

var gulp = require('gulp'),
watch = require('gulp-watch'),
browserSync = require('browser-sync').create();
gulp.task('serve', function() {
    browserSync.init({
        server: {
            baseDir: "src"
        },
        notify: false
    });

});

gulp.task('watch', ['serve'], function() {
    gulp.watch('./src/*.html', browserSync.reload);
});

Console screenshot: console error

This error occurred after I updated the modules with the npm update --save command in my project folder.

Can you help me with my problem?


问:
Set a limit above 50MB on pgAdmin to upload a database backup to the server with Docker Compose
As written in the title I would like to set a limit higher than 50MB on pgAdmin to upload a backup of a database on the server with Docker Compose.

I have postgresql as database and pgadmin as program for managing that database. When I access pgadmin and I upload a file larger than 50MB the program blocks me. To solve it I have to change the default settings of pgadmin and increase the limit to 100MB, for safety and not to think about it I write 5000MB. I would like to change the pgadmin value of 50 to 5000 using docker compose and not the pgadmin control panel.

I looked at the following links but couldn't find anything:

https://hub.docker.com/r/dpage/pgadmin4

https://www.pgadmin.org/docs/pgadmin4/latest/container_deployment.html

https://www.pgadmin.org/docs/pgadmin4/development/container_deployment.html

https://www.pgadmin.org/support/list/

https://stackoverflow.com

I can do this manually but I would like to do it when I upload my project to the server with Docker.
This is my dockerfile:

```<code>FROM dpage/pgadmin4:6.18
LABEL Author="My name and my surname"
# ??? New limit ???
</code>```

This is my docker compose .yaml file:

```<code>  pgadmin:
    build: ./pgadmin
    ...
    networks:
      ...
    labels:
      ...
    volumes:
      - type: bind
        source: ./volumes/data-pgadmin/servers.json
        target: /pgadmin4/servers.json
    environment:
      PGADMIN_DEFAULT_EMAIL: ...
      PGADMIN_DEFAULT_PASSWORD: ...
      # ??? New limit ???
    depends_on:
      - postgresql-postgis
</code>```

Can you help me?
thank you

Body:
As written in the title I would like to set a limit higher than 50MB on pgAdmin to upload a backup of a database on the server with Docker Compose.

I have postgresql as database and pgadmin as program for managing that database. When I access pgadmin and I upload a file larger than 50MB the program blocks me. To solve it I have to change the default settings of pgadmin and increase the limit to 100MB, for safety and not to think about it I write 5000MB. I would like to change the pgadmin value of 50 to 5000 using docker compose and not the pgadmin control panel.

I looked at the following links but couldn't find anything:

https://hub.docker.com/r/dpage/pgadmin4

https://www.pgadmin.org/docs/pgadmin4/latest/container_deployment.html

https://www.pgadmin.org/docs/pgadmin4/development/container_deployment.html

https://www.pgadmin.org/support/list/

https://stackoverflow.com

I can do this manually but I would like to do it when I upload my project to the server with Docker.
This is my dockerfile:

FROM dpage/pgadmin4:6.18
LABEL Author="My name and my surname"
# ??? New limit ???

This is my docker compose .yaml file:

  pgadmin:
    build: ./pgadmin
    ...
    networks:
      ...
    labels:
      ...
    volumes:
      - type: bind
        source: ./volumes/data-pgadmin/servers.json
        target: /pgadmin4/servers.json
    environment:
      PGADMIN_DEFAULT_EMAIL: ...
      PGADMIN_DEFAULT_PASSWORD: ...
      # ??? New limit ???
    depends_on:
      - postgresql-postgis

Can you help me?
thank you


问:
Get heap bounds in Intel Pin
in Intel Pin (version 3.25), I would like to be able to detect where the heap is allocated at runtime. In GDB, you can run info proc mappings which will report back all mapped address spaces, including the heap. I would like to be able to do something similar in Intel Pin. The only method I know of is to trace memory allocations manually and record the addresses that are allocated, but this seems rather inefficient.

Title: Get heap bounds in Intel Pin


问:
Unexpected error every time I upload images to Create ML
I'm new to create ML and I have downloaded Xcode and then I open Create ML. I'm using my mac book pro with OS Monterey. Version of Xcode = 14.2 Version of Create ML = 4.0

I simply open a new project and choose image classification. I then save the project and then choose the set of image that I want to train. As soon as I drag and drop the image folder in Training data box I get an unexpected error message. I even restarted my macbook and restarted XCode and CreateML.

I have tried everything from people discussing online about the image size and types and even used online available set of images but I still get the same unexpected error message. Really appreciate your help. Happy new year
Regards
Lutfi

I simply open a new project and choose image classification. I then save the project and then choose the set of image that I want to train. As soon as I drag and drop the image folder in Training data box I get an unexpected error message. I even restarted my macbook and restarted XCode and CreateML.


问:
scp requires named directory to exist on target server
I'm using scp to upload a directory to a remote server. However, if the remote server does not have a "target" directory of the same name, I get a "No such file" error.

Failed directory upload example:

```<code>$ mkdir test_local
$ touch test_local/test_local.txt
$ scp -r ./test_local user@host.edu:
> scp: realpath ./test_local: No such file
> scp: upload "./test_local": path canonicalization failed
> scp: failed to upload directory ./test_local to .
</code>```

However, if I create an empty target directory on the remote machine, the command does work and successfully updates the target directory with the contents of the local directory.

It's my understanding that scp should not require an empty "target" directory of the same name to exist, so why is this the case here?

This question is not a duplicate of the question here, because the target directory (in my example, the home directory of the remote server) does exist. It simply doesn't share a name with the sent directory.

Body:
I'm using scp to upload a directory to a remote server. However, if the remote server does not have a "target" directory of the same name, I get a "No such file" error.

Failed directory upload example:

$ mkdir test_local
$ touch test_local/test_local.txt
$ scp -r ./test_local user@host.edu:
> scp: realpath ./test_local: No such file
> scp: upload "./test_local": path canonicalization failed
> scp: failed to upload directory ./test_local to .

However, if I create an empty target directory on the remote machine, the command does work and successfully updates the target directory with the contents of the local directory.

It's my understanding that scp should not require an empty "target" directory of the same name to exist, so why is this the case here?

This question is not a duplicate of the question here, because the target directory (in my example, the home directory of the remote server) does exist. It simply doesn't share a name with the sent directory.


问:
'printf' function and 'proc' directive behaving weird in ml64(masm x64)?
```<code>;this file -> test1.asm

includelib msvcrt.lib
includelib legacy_stdio_definitions.lib

extern _CRT_INIT: proc     ;custom entrypoint needs c-runtime to be initialised by the programmer.
extern printf: proc
extern ExitProcess: proc

.data
    msg db "hello world!", 13, 10, 0

.code
fun proc
    sub rsp, 32          ;for shadow space
    call _CRT_INIT       ;called _CRT_INIT because I have my own entry point named "fun"
    lea rcx,msg
    call printf
    add rsp, 32
    call ExitProcess
fun endp
end
</code>```

commandline for assembler: ml64 /nologo /c test1.asm

commandline for linker: link /entry:fun /subsystem:console test1.obj

This standalone assembly program seems to be working fine. But doing some changes(mentioned below) make the program crash.

1st change -> according to this link both libcmt.lib and msvcrt.lib statically links the native CRT startup (ie both can be used to call _CRT_INIT) into my code. The difference is msvcrt.lib is used with dll. As I don't have any dll   I considered using libcmt.lib in place of msvcrt.lib but then the program crashes. Considering there is only printf function associated, that concludes printf function breaks the program. But why?

2nd change -> Now I tried calling this fun() function from a simple .C file. For that I made the necessary changes.

```<code>;this file -> test1.asm

;not including any libraries. linking the .c file make the libraries link too because that is in my libpath environment variable

;extern _CRT_INIT: proc    ;no need of _CRT_INIT because now mainCRTStartup() will be the entrypoint and .c file will take care of initializing the c-runtime
extern printf: proc
;extern ExitProcess: proc  ;no need of exitprocess. Instead i'm using ret instruction because I'm calling fun() from .c file.

.data
    msg db "hello world!", 13, 10, 0

.code
fun proc c               ;even if I replace 'c' with something like "abed" the program works. but if I dont give anything after proc then the program crashes.
    sub rsp, 32          ;for shadow space
    lea rcx,msg
    call printf
    add rsp, 32
    ret
fun endp
end
</code>```
```<code>//this file -> test2.c
#include <stdio.h>
#include <conio.h>
void fun();    //in C no need of extern keyword. extern is needed in c++
int main()
{
   fun();
   getch();
}
</code>```

commandline for assembler: ml64 /nologo /c test1.asm

commandline for compiler: cl /nologo /c test2.c

commandline for linker: link test1.obj test2.obj

In the previous working example (ie. with msvcrt.lib) I don't have to give any suffixes after 'proc' directive. But in this case when I am calling 'fun' as a function from my C file I need to give anything like 'a'/'b'/combination('abcd') after 'proc' directive and only then the program works. If I don't give anything after 'proc' the program crashes. According to official MSDN documentation proc directive also accept language type. Even so wrong/random 'language type name' ie. any word seem to work. But how?

I tried many things like changing the libraries, using different version of printf (like vfprintf) and tried assigning more shadow space also googled much but unable to find any answer.

Body:
;this file -> test1.asm

includelib msvcrt.lib
includelib legacy_stdio_definitions.lib

extern _CRT_INIT: proc     ;custom entrypoint needs c-runtime to be initialised by the programmer.
extern printf: proc
extern ExitProcess: proc

.data
    msg db "hello world!", 13, 10, 0

.code
fun proc
    sub rsp, 32          ;for shadow space
    call _CRT_INIT       ;called _CRT_INIT because I have my own entry point named "fun"
    lea rcx,msg
    call printf
    add rsp, 32
    call ExitProcess
fun endp
end

commandline for assembler: ml64 /nologo /c test1.asm

commandline for linker: link /entry:fun /subsystem:console test1.obj

This standalone assembly program seems to be working fine. But doing some changes(mentioned below) make the program crash.

1st change -> according to this link both libcmt.lib and msvcrt.lib statically links the native CRT startup (ie both can be used to call _CRT_INIT) into my code. The difference is msvcrt.lib is used with dll. As I don't have any dll   I considered using libcmt.lib in place of msvcrt.lib but then the program crashes. Considering there is only printf function associated, that concludes printf function breaks the program. But why?

2nd change -> Now I tried calling this fun() function from a simple .C file. For that I made the necessary changes.

;this file -> test1.asm

;not including any libraries. linking the .c file make the libraries link too because that is in my libpath environment variable

;extern _CRT_INIT: proc    ;no need of _CRT_INIT because now mainCRTStartup() will be the entrypoint and .c file will take care of initializing the c-runtime
extern printf: proc
;extern ExitProcess: proc  ;no need of exitprocess. Instead i'm using ret instruction because I'm calling fun() from .c file.

.data
    msg db "hello world!", 13, 10, 0

.code
fun proc c               ;even if I replace 'c' with something like "abed" the program works. but if I dont give anything after proc then the program crashes.
    sub rsp, 32          ;for shadow space
    lea rcx,msg
    call printf
    add rsp, 32
    ret
fun endp
end

//this file -> test2.c
#include <stdio.h>
#include <conio.h>
void fun();    //in C no need of extern keyword. extern is needed in c++
int main()
{
   fun();
   getch();
}

commandline for assembler: ml64 /nologo /c test1.asm

commandline for compiler: cl /nologo /c test2.c

commandline for linker: link test1.obj test2.obj

In the previous working example (ie. with msvcrt.lib) I don't have to give any suffixes after 'proc' directive. But in this case when I am calling 'fun' as a function from my C file I need to give anything like 'a'/'b'/combination('abcd') after 'proc' directive and only then the program works. If I don't give anything after 'proc' the program crashes. According to official MSDN documentation proc directive also accept language type. Even so wrong/random 'language type name' ie. any word seem to work. But how?

I tried many things like changing the libraries, using different version of printf (like vfprintf) and tried assigning more shadow space also googled much but unable to find any answer.


问:
how to calculate PCA loadings in R
I performed a weighted PCA using {EasyCODA} r package, but apparently the output doesn't return the loadings for each component.

```<code>library(easyCODA)
data(veg)
veg.CLR <- CLR(veg)
veg.PCA <- PCA(veg.CLR$LR, weight=F)
summary(veg.PCA)
</code>```

Any idea about how to calculate it in R? Thanks

Title: how to calculate PCA loadings in R

Body:
I performed a weighted PCA using {EasyCODA} r package, but apparently the output doesn't return the loadings for each component.

library(easyCODA)
data(veg)
veg.CLR <- CLR(veg)
veg.PCA <- PCA(veg.CLR$LR, weight=F)
summary(veg.PCA)

Any idea about how to calculate it in R? Thanks


问:
failed to resolve: maybe a missing crate `image`? Rust
I'm attempting to start my first project in Rust using VScode. I added the '''image = "0.24.5"''' to the dependencies section of the Cargo.toml file, built the project with cargo build. However, whenever I try and run the file I get an error that says:

```<code>error[E0433]: failed to resolve: maybe a missing crate `image`?
 --> main.rs:1:5
  |
1 | use image::io::Reader;
  |     ^^^^^ maybe a missing crate `image`?
  |
= help: consider adding `extern crate image` to use the `image` crate
</code>```

This is the main file:

```<code>use image::io::Reader;

fn main() {
    println!("Hello, world!");
}

</code>```

Cargo.toml

```<code>[package]
name = "imaging"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
image = "0.24.5"
</code>```

Not quite sure why I'm getting this error. My guess is that it may be that VScode is unable to find the dependency.

Body:
I'm attempting to start my first project in Rust using VScode. I added the '''image = "0.24.5"''' to the dependencies section of the Cargo.toml file, built the project with cargo build. However, whenever I try and run the file I get an error that says:

error[E0433]: failed to resolve: maybe a missing crate `image`?
 --> main.rs:1:5
  |
1 | use image::io::Reader;
  |     ^^^^^ maybe a missing crate `image`?
  |
= help: consider adding `extern crate image` to use the `image` crate

This is the main file:

use image::io::Reader;

fn main() {
    println!("Hello, world!");
}

Cargo.toml

[package]
name = "imaging"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
image = "0.24.5"

Not quite sure why I'm getting this error. My guess is that it may be that VScode is unable to find the dependency.


问:
Close Select2 Dropdown after clicking on X to Clear
I'm trying to get a Select2 Dropdown to close after clicking on X to clear it because it stays open. I'm currently using the .on('select2:unselect') function to trigger it when the button is clicked to clear the selections but I either get an error or it just doesn't do anything.

Error

```<code>TypeError: Cannot read properties of null (reading 'query')
</code>```

Select2 HTML

```<code><select class="softwareReleaseItem" name="softwareReleaseItem" id="softwareReleaseItem" data-control="select2">
   <option></option>
   <?php
     asort($softwaredb);
     foreach ($softwareDB as $software) {
       echo "<option value=\"" . $software['Guid'] . "\">" . strtoupper($software['Name']) . "</option>";
     }
   ?>
</select>
<div id="sRI"></div>
</code>```

Javascript

```<code>$('.softwareReleaseItem').on('select2:select', function(e) {
            var sri_data = e.params.data;
            var sri_callType = 'softwareReleaseItem';
            //console.log(sri_data);
            $("#sRI").show();
            $.ajax({
                type: "POST",
                url: "dist/php/ajax/ajax_getItemsByName.php",
                data: {
                    sri_id: sri_data['id'],
                    sri_text: sri_data['text'],
                    sri_call: sri_callType
                },
                success: function(data) {
                    $('#sRI').html(data);
                }
            });
        }).on('select2:unselect', function(e) {
            $("#sRI").hide();
            closeSelect();
        });
</code>```

All my attempts to close it ->

```<code> function closeSelect() {
            //$('.softwareReleaseItem').trigger('select2:close');
            //$(".softwareReleaseItem").focusout();
            $(".softwareReleaseItem").select2().trigger('close');
            //$("#softwareReleaseItem").select2("select2:close");
            //$("#select2-drop-mask").click();
            //$(document.body).trigger('mousedown');
            //$('body').trigger('mousedown');
            //$('.select2-hidden-accessible').select2('select2:close');
            //$(".softwareReleaseItem").select2("select2:close");
        };
</code>```

UPDATE:
So far this is the only working solution I have come up with that works
I just simulate a mouseclick on a hidden div.

```<code>.on('select2:unselect', function(e) {
            $("#sRI").hide();
            $(".softwareReleaseItem").trigger("reset").trigger("change")
            document.getElementById('#sRI')
                .dispatchEvent(new MouseEvent('click', {
                    shiftKey: true
                }))
        });
</code>```

Body:
I'm trying to get a Select2 Dropdown to close after clicking on X to clear it because it stays open. I'm currently using the .on('select2:unselect') function to trigger it when the button is clicked to clear the selections but I either get an error or it just doesn't do anything.

Error

TypeError: Cannot read properties of null (reading 'query')

Select2 HTML

<select class="softwareReleaseItem" name="softwareReleaseItem" id="softwareReleaseItem" data-control="select2">
   <option></option>
   <?php
     asort($softwaredb);
     foreach ($softwareDB as $software) {
       echo "<option value=\"" . $software['Guid'] . "\">" . strtoupper($software['Name']) . "</option>";
     }
   ?>
</select>

Javascript

$('.softwareReleaseItem').on('select2:select', function(e) {
            var sri_data = e.params.data;
            var sri_callType = 'softwareReleaseItem';
            //console.log(sri_data);
            $("#sRI").show();
            $.ajax({
                type: "POST",
                url: "dist/php/ajax/ajax_getItemsByName.php",
                data: {
                    sri_id: sri_data['id'],
                    sri_text: sri_data['text'],
                    sri_call: sri_callType
                },
                success: function(data) {
                    $('#sRI').html(data);
                }
            });
        }).on('select2:unselect', function(e) {
            $("#sRI").hide();
            closeSelect();
        });

All my attempts to close it ->

 function closeSelect() {
            //$('.softwareReleaseItem').trigger('select2:close');
            //$(".softwareReleaseItem").focusout();
            $(".softwareReleaseItem").select2().trigger('close');
            //$("#softwareReleaseItem").select2("select2:close");
            //$("#select2-drop-mask").click();
            //$(document.body).trigger('mousedown');
            //$('body').trigger('mousedown');
            //$('.select2-hidden-accessible').select2('select2:close');
            //$(".softwareReleaseItem").select2("select2:close");
        };

UPDATE:
So far this is the only working solution I have come up with that works
I just simulate a mouseclick on a hidden div.

.on('select2:unselect', function(e) {
            $("#sRI").hide();
            $(".softwareReleaseItem").trigger("reset").trigger("change")
            document.getElementById('#sRI')
                .dispatchEvent(new MouseEvent('click', {
                    shiftKey: true
                }))
        });


问:
Layered box annotations
Is it possible to draw a box annotation on top of another one?
I need to have two bands, one higher than the other as shown below.

I was able to achieve so by using three annotations with the code below. But, it would be better if I can just have two annotations (one with yMin: 4, yMax: 14 and another with yMin: 2, yMax: 18)

<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <canvas id="myChart"></canvas>

```

Title: Layered box annotations


问:
How to add a Paging to asp.net razor page
How to create a pagging for grid that looks something like below; it has with 10 page buttons & and in end [...] button

[1][2][3][4][5][6][7][8][9][10][...]

[...] button will load next 10 pages (assuming there are next 10 pages). if there are only 2 more pages. than it will load next 2 pages. and [...] dispears. below is an example of that

[3][4][5][6][7][8][9][10][11][12]

below are some more examples

```<code>[1][2][3]

[11][12][13][14][15][16][17][18][19][20][...]
</code>```

Index.csHtml - front-end page - here I am creating a for loop to load 10 paging buttons. I am using PageIndex to pass URL variable to tell which page I am on. Here paging work fine for 10 buttons. but I am not sure how to create [...] button that will load next 10 pages

```<code> @{
                var StartPage = 1;
                var LastPage = 10;
                var IncPage = 10;

                for (int x = StartPage; x <= LastPage; x++)
                {
                    <a asp-page="./Index"
                        asp-route-pageIndex="@x"
                        class="btn btn-primary">@x</a>
                }

}

</code>```

Index.csHmtl - back-end file. here I am creating a List by using paginatedList class.

```<code>public PaginatedList<CourseTaken_Model> CourseTakenList { get; set; } = default!;

CourseTakenList = await PaginatedList<CourseTaken_Model>.CreateAsync(CourseTakenList_Temp.AsNoTracking(), pageIndex ?? 1, pageSize);
</code>```

PaginatedList class - this is basic class taken from Microsoft Website documents. Here there is PagexIndex(current page), TotalPages, HasPreviousPage & HasNextPage;

```<code> public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);

            AddRange(items);
        }

        public bool HasPreviousPage => PageIndex > 1;

        public bool HasNextPage => PageIndex < TotalPages;

        public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }
    }
</code>```

Body:
How to create a pagging for grid that looks something like below; it has with 10 page buttons & and in end [...] button

[1][2][3][4][5][6][7][8][9][10][...]

[...] button will load next 10 pages (assuming there are next 10 pages). if there are only 2 more pages. than it will load next 2 pages. and [...] dispears. below is an example of that

[3][4][5][6][7][8][9][10][11][12]

below are some more examples

[1][2][3]

[11][12][13][14][15][16][17][18][19][20][...]

Index.csHtml - front-end page - here I am creating a for loop to load 10 paging buttons. I am using PageIndex to pass URL variable to tell which page I am on. Here paging work fine for 10 buttons. but I am not sure how to create [...] button that will load next 10 pages

 @{
                var StartPage = 1;
                var LastPage = 10;
                var IncPage = 10;

                for (int x = StartPage; x <= LastPage; x++)
                {
                    @x
                }

}

Index.csHmtl - back-end file. here I am creating a List by using paginatedList class.

public PaginatedList<CourseTaken_Model> CourseTakenList { get; set; } = default!;

CourseTakenList = await PaginatedList<CourseTaken_Model>.CreateAsync(CourseTakenList_Temp.AsNoTracking(), pageIndex ?? 1, pageSize);

PaginatedList class - this is basic class taken from Microsoft Website documents. Here there is PagexIndex(current page), TotalPages, HasPreviousPage & HasNextPage;

 public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);

            AddRange(items);
        }

        public bool HasPreviousPage => PageIndex > 1;

        public bool HasNextPage => PageIndex < TotalPages;

        public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }
    }


问:
Javascript: How to get URL before listening for firebase changes?
I am trying to create a Chrome Extension but I am having som trouble.

I want to use thing function to listen to updates in my Firebase Database:

```<code>firebase
.database()
.ref(`${URLOfCurrentTab}/messages`)
.endAt()
.limitToLast(1)
.on("child_added", function (snapshot) {)}
</code>```

So I have added this function in my background.js file so i can consistently listen for updates, to do that I need the current URL of the active tab. But the problem is that the firebase "function" runs before the URL is retrieved.

This is how I retrieve the URL. I have added these functions in the background.js file just above the firebase stuff:

```<code>  let activeTabId, lastUrl, lastTitle;

  function getTabInfo(tabId) {
    console.log("first");
    chrome.tabs.get(tabId, function (tab) {
      if (lastUrl != tab.url || lastTitle != tab.title) {
        console.log((lastUrl = tab.url));

        lastUrl = tab.url;
      }
    });
  }

  // When tab is clicked on
  chrome.tabs.onActivated.addListener(function (activeInfo) {
    console.log("second");
    getTabInfo((activeTabId = activeInfo.tabId));
  });

  // When update in already clicked tab happens
  chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    console.log("third");

    if (activeTabId == tabId) {
      getTabInfo(tabId);
    }
  });
</code>```

Any ideas on what to do?

Body:
I am trying to create a Chrome Extension but I am having som trouble.

I want to use thing function to listen to updates in my Firebase Database:

firebase
.database()
.ref(`${URLOfCurrentTab}/messages`)
.endAt()
.limitToLast(1)
.on("child_added", function (snapshot) {)}

So I have added this function in my background.js file so i can consistently listen for updates, to do that I need the current URL of the active tab. But the problem is that the firebase "function" runs before the URL is retrieved.

This is how I retrieve the URL. I have added these functions in the background.js file just above the firebase stuff:

  let activeTabId, lastUrl, lastTitle;

  function getTabInfo(tabId) {
    console.log("first");
    chrome.tabs.get(tabId, function (tab) {
      if (lastUrl != tab.url || lastTitle != tab.title) {
        console.log((lastUrl = tab.url));

        lastUrl = tab.url;
      }
    });
  }

  // When tab is clicked on
  chrome.tabs.onActivated.addListener(function (activeInfo) {
    console.log("second");
    getTabInfo((activeTabId = activeInfo.tabId));
  });

  // When update in already clicked tab happens
  chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    console.log("third");

    if (activeTabId == tabId) {
      getTabInfo(tabId);
    }
  });

Any ideas on what to do?


问:
How to assign generic type of return value of api call to ref
I have a component which is supposed to handle strongly typed API calls passed as prop. After the call, its return value is then stored into ref (and passed outside through the scoped slot). The problem is I can't figure out how to make ref understand the type of returned value.

This is what I've tried

Example of API call:

```<code>const fetchStuff = async (): Promise<boolean> => {
  // fetch and return the result here
}
</code>```

The API handler component (simplified):

```<code><template>
  <slot :result="result"></slot>
</template>

<script setup lang="ts">
  import { defineProps, ref } from 'vue'

  type ApiHandlerProps = {
    call: () => Promise<unknown>
  }

  const props = defineProps<ApiHandlerProps>()

  // HOW TO TYPE THIS WITH GENERICS? -> INFERING DOES NOT WORK!
  const result = ref<???>(undefined)

  const handleApiCall = async <T>(apiCall: () => Promise<T>) => {
    try {
      const response = await apiCall()

      result.value = response
    } catch (error) {
      // ...
    }
  }

  handleApiCall(props.call)
</script>
</code>```

Usage:

```<code><template>
  <api-handler :call="fetchStuff" v-slot={ result }>
    // DO SOMETHING HERE WITH THE RESULT
  </api-handler>
</template>
</code>```

Struggled to find help with this kind of approach, so I ask here.

EDIT - 23-01-02

I tried to use composable as @leifmarcus suggested like this:

As composable / api-handler-utils.ts:

```<code>import { shallowRef } from 'vue'

export const handleApiCall = async <T>(apiCall: () => Promise<T>) => {
  const result = shallowRef<T | undefined>(undefined)

  try {
    const response = await apiCall()

    result.value = response
  } catch (error) {
    //...
  }

  return result
}
</code>```

Note! Used shallowRef instead of ref to dodge another linting error.

Ended up having another error by trying to import function from ts file. Seems like there is a new error around every corner. At this point, working with Vue seems to take more time to figure out how to solve small edge cases / errors. After all, coming from React (which I hate) background, this is supposed to be a relatively easy thing to do. So I started to read Svelte's docs :D

Body:
I have a component which is supposed to handle strongly typed API calls passed as prop. After the call, its return value is then stored into ref (and passed outside through the scoped slot). The problem is I can't figure out how to make ref understand the type of returned value.

This is what I've tried

Example of API call:

const fetchStuff = async (): Promise<boolean> => {
  // fetch and return the result here
}

The API handler component (simplified):

<template>
  <slot :result="result"></slot>
</template>

Usage:

<template>
  <api-handler :call="fetchStuff" v-slot={ result }>
    // DO SOMETHING HERE WITH THE RESULT
  </api-handler>
</template>

Struggled to find help with this kind of approach, so I ask here.

EDIT - 23-01-02

I tried to use composable as @leifmarcus suggested like this:

As composable / api-handler-utils.ts:

import { shallowRef } from 'vue'

export const handleApiCall = async <T>(apiCall: () => Promise<T>) => {
  const result = shallowRef<T | undefined>(undefined)

  try {
    const response = await apiCall()

    result.value = response
  } catch (error) {
    //...
  }

  return result
}

Note! Used shallowRef instead of ref to dodge another linting error.

Ended up having another error by trying to import function from ts file. Seems like there is a new error around every corner. At this point, working with Vue seems to take more time to figure out how to solve small edge cases / errors. After all, coming from React (which I hate) background, this is supposed to be a relatively easy thing to do. So I started to read Svelte's docs :D