问:
CoreAudio in vb.net 6.0 Windows 11 : Is there a way to do a ControlChangeNotify callback?
I am writing a volume control app in vb.net 6.0, using a reference to CoreAudioApi.dll.
I can:

Change the volume of the default render and capture devices.

Mute the default devices.

Alter the balance on the render device

List the full names, guid string and status of all the devices

However, despite a lot of research, I can not setup a callback for ControlChangeNotify.
It appears to be simple in C, however I am writing in VB. Can any one suggest a solution?

Update 18/12/2022 @Jimi supplied some very useful definitions and I have edited the post to show the current code attempts. I can get the master default volume using masterVol = GetMasterVolumeObject() as an IAudioEndpointVolume.

Update 22/12/2022 Following a re-read of many postings it became apparent that it was important to create a persistent reference to mastervol and the class reference (MyCallBack) to the class module implementing IAudioEndpointVolumeCallback.

Update 24/12/2022 The AudioCallback class is now firing when volume/mute are changed internally and externally. Transferring the callback data to the main form is problematic. I now have a working system which involves:

Declaring public events in the call back class for each type of control I want to change in the main form.

Initiating a BackgroundWorker to Process the data 10mS after being called by the callback class.

Calculating new audio values from the pNotifyData pointer.

RaiseEvent for each slider/checkbox and label in the main form that needs updating.

AddHandler in the main form to process the callback events.

Create handler routines with delegates for each control type.

From my point of view this topic is solved.

My thanks to @Jimi for his contribution.

Latest Updates:

```<code>Option Explicit On
Imports System.ComponentModel
Imports System.Runtime.InteropServices

Public Class AudioCallback

    Implements IAudioEndpointVolumeCallback

    Public Event LabelReady(sender As AudioCallback, ByVal T As String)
    Public Event SliderReady(sender As AudioCallback, EP As String, ByVal T As Integer)
    Public Event CheckReady(sender As AudioCallback, EP As String, ByVal T As Boolean)

    Public Function OnNotify(pNotifyData As IntPtr) As Integer Implements IAudioEndpointVolumeCallback.OnNotify
        ' Move to global structure
        Gstructure = Marshal.PtrToStructure(pNotifyData, GetType(AUDIO_VOLUME_NOTIFICATION_DATA))

        BackGround()                                            ' Asynchronous call and delagate controls
        Return 0
    End Function

    Private Sub BackGround()

        Dim bgw = New BackgroundWorker()
        AddHandler bgw.DoWork,
            Sub()
                System.Threading.Thread.Sleep(10)
            End Sub

        AddHandler bgw.RunWorkerCompleted,
            Sub()
                Update()
            End Sub

        bgw.RunWorkerAsync()
    End Sub

    Private Sub Update()

        Dim svolL As Integer
        Dim svolR As Integer
        Dim balance As Integer

        'ChkMaster.Checked = Gstructure.bMuted
        RaiseEvent CheckReady(Me, "R", Gstructure.bMuted)

        svolL = 0.5 + 100 * Gstructure.Left
        svolR = 0.5 + 100 * Gstructure.Right
        If svolL = svolR Then
            balance = 0
        Else
            If svolR > svolL Then
                balance = 100 - svolL * 100.0 / svolR
            Else
                balance = -(100 - svolR * 100.0 / svolL)
            End If
        End If

        RaiseEvent SliderReady(Me, "RV", 0.5 + 100 * Gstructure.fMasterVolume)  ' HMaster.Value = 0.5 + 100 * Gstructure.fMasterVolume
        RaiseEvent SliderReady(Me, "RB", balance)                               ' HBalance.Value = balance

        'LGuid.Text = Gstructure.guidEventContext.ToString
        RaiseEvent LabelReady(Me, Gstructure.guidEventContext.ToString)
    End Sub

End Class

' Main form Extracts ============================================

Imports CoreAudioApi

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Show()

        ' events for handling AudioCallback events
        AddHandler MyCallBack.LabelReady, AddressOf LReady
        AddHandler MyCallBack.SliderReady, AddressOf HReady
        AddHandler MyCallBack.CheckReady, AddressOf CReady

End Sub

' Label Guid displays Callback GUID
' CheckBox ChkMaster displays Mute status
' Horizontal scrollbar HMaster displays default render volume
' Horizontal scrollbar HBalance displays default render balance
' The global variable IsSettingMaster prevents code associated
' with altering the value of the sliders from re-setting
' the volume / balance.

Private Sub LReady(sender As AudioCallback, Data As String)                                                 ' Set GUID label for Render
        UpdateLabel(LGuid, Data)
    End Sub

    Private Delegate Sub UpdateLabelDelegate(TB As Label, param As String)
    Private Sub UpdateLabel(TB As Label, param As String)
        If TB.InvokeRequired Then
            TB.Invoke(New UpdateLabelDelegate(AddressOf UpdateLabel), New Object() {TB, param})
        Else
            TB.Text = param
        End If
    End Sub

    Private Sub CReady(sender As AudioCallback, EP As String, Data As Boolean)                                  ' Set Master (Render) Mute checkbox
        If EP = "R" Then UpdateChkbox(ChkMaster, Data)
    End Sub

    Private Delegate Sub UpdateChkboxDelegate(TB As CheckBox, param As Boolean)
    Private Sub UpdateChkbox(TB As CheckBox, param As Boolean)
        If TB.InvokeRequired Then
            TB.Invoke(New UpdateChkboxDelegate(AddressOf UpdateChkbox), New Object() {TB, param})
        Else
            TB.Checked = param
        End If
    End Sub

    Private Sub HReady(sender As AudioCallback, EP As String, Data As Integer)                                  ' Set Master (Render) Volume / Master Balance slide
        IsSettingMaster = True
        If EP = "RV" Then UpdateHslide(HMaster, Data)
        If EP = "RB" Then UpdateHslide(HBalance, Data)
        IsSettingMaster = False
    End Sub

    Private Delegate Sub UpdateHslideDelegate(TB As HScrollBar, param As Integer)
    Private Sub UpdateHslide(TB As HScrollBar, param As Integer)
        If TB.InvokeRequired Then
            TB.Invoke(New UpdateHslideDelegate(AddressOf UpdateHslide), New Object() {TB, param})
        Else
            TB.Value = param
        End If
    End Sub

</code>```

History:

```<code>
' ===============================
' Public Class containing Callback:

Option Explicit On
Imports System.Runtime.InteropServices

Public Class AudioCallback

    Implements IAudioEndpointVolumeCallback
    Public Function OnNotify(pNotifyData As IntPtr) As Integer Implements IAudioEndpointVolumeCallback.OnNotify
        ' Move to global structure
        Gstructure = Marshal.PtrToStructure(pNotifyData, GetType(AUDIO_VOLUME_NOTIFICATION_DATA))

        ' Need mechanism to process new data in main form
        ' Must be asynchronous
        ' Raise event did not work
        ' Enabling Timer did not work

        HaveChange = True                                       ' Flag global variable

        Return 0
    End Function

End Class

' ===============================
' Public Class to Setup Callback:

Option Explicit On

Imports System.Runtime.InteropServices

' Implements IMMDevice, IMMDeviceEnumerator, IAudioEndpointVolume
' developed from https://exchangetuts.com/how-to-check-if-the-system-audio-is-muted-1641156904496320

Public Class CoreAudio

    ' Public definition in ModCoreaudioAlt  https://stackoverflow.com/questions/52001368/how-to-check-if-the-system-audio-is-muted/52013031#52013031
    '   Public Interface IAudioEndpointVolumeCallback
    '   Public Structure AUDIO_VOLUME_NOTIFICATION_DATA
    '   Public Interface IMMDevice
    '   Public Interface IMMDeviceEnumerator
    ' End Public definition  in ModCoreaudioAlt ==============================

    Dim CLSID_MMDeviceEnumerator As Guid = New Guid("{BCDE0395-E52F-467C-8E3D-C4579291692E}")
    Dim MMDeviceEnumeratorType As Type = Type.GetTypeFromCLSID(CLSID_MMDeviceEnumerator, True)

    Private hr As Integer

    Friend Enum EDataFlow
        eRender
        eCapture
        eAll
        EDataFlow_enum_count
    End Enum
    Friend Enum ERole
        eConsole
        eMultimedia
        eCommunications
        ERole_enum_count
    End Enum

    <Flags>
    Friend Enum CLSCTX As UInteger
        CLSCTX_INPROC_SERVER = &H1                              ' In CLSCTX_ALL
        CLSCTX_INPROC_HANDLER = &H2                             ' In CLSCTX_ALL
        CLSCTX_LOCAL_SERVER = &H4                               ' In CLSCTX_ALL
        CLSCTX_INPROC_SERVER16 = &H8
        CLSCTX_REMOTE_SERVER = &H10                             ' In CLSCTX_ALL
        CLSCTX_INPROC_HANDLER16 = &H20
        CLSCTX_RESERVED1 = &H40
        CLSCTX_RESERVED2 = &H80
        CLSCTX_RESERVED3 = &H100
        CLSCTX_RESERVED4 = &H200
        CLSCTX_NO_CODE_DOWNLOAD = &H400
        CLSCTX_RESERVED5 = &H800
        CLSCTX_NO_CUSTOM_MARSHAL = &H1000
        CLSCTX_ENABLE_CODE_DOWNLOAD = &H2000
        CLSCTX_NO_FAILURE_LOG = &H4000
        CLSCTX_DISABLE_AAA = &H8000
        CLSCTX_ENABLE_AAA = &H10000
        CLSCTX_FROM_DEFAULT_CONTEXT = &H20000
        CLSCTX_ACTIVATE_32_BIT_SERVER = &H40000
        CLSCTX_ACTIVATE_64_BIT_SERVER = &H80000
        CLSCTX_INPROC = CLSCTX_INPROC_SERVER Or CLSCTX_INPROC_HANDLER

        CLSCTX_SERVER = CLSCTX_INPROC_SERVER Or CLSCTX_LOCAL_SERVER Or CLSCTX_REMOTE_SERVER ' In CLSCTX_ALL
        CLSCTX_ALL = CLSCTX_SERVER Or CLSCTX_INPROC_HANDLER
    End Enum

    Friend Function GetMasterVolumeObject() As IAudioEndpointVolume
        ' Get the default IAudioEndpintVolume as "ppEndpoint" for eRender & eMultimedia

        Dim deviceEnumerator As IMMDeviceEnumerator = Nothing
        Dim MediaDevice As IMMDevice = Nothing
        Dim ppEndpoint As IAudioEndpointVolume = Nothing
        Dim EndPointVolID As Guid = GetType(IAudioEndpointVolume).GUID

        Try
            Dim MMDeviceEnumerator As Object = Activator.CreateInstance(MMDeviceEnumeratorType)
            deviceEnumerator = CType(MMDeviceEnumerator, IMMDeviceEnumerator)
            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, MediaDevice)
            MediaDevice.Activate(EndPointVolID, CLSCTX.CLSCTX_ALL, IntPtr.Zero, ppEndpoint)
        Catch ex As Exception
            Form1.Showme("Error in GetMasterVolumeObject: " & ex.Message, Color.Red)
            ppEndpoint = Nothing
        Finally
            If Not IsNothing(deviceEnumerator) Then Marshal.ReleaseComObject(deviceEnumerator)
            If Not IsNothing(MediaDevice) Then Marshal.ReleaseComObject(MediaDevice)
        End Try

        Return ppEndpoint
    End Function

Public Sub Callback()

        Try
            masterVol = GetMasterVolumeObject()

            ' MyCallBack defined in Module ModCoreAudioAlt : Public MyCallBack As New AudioCallback

            If IsNothing(MyCallBack) Then
                Form1.Showme("Failed to set MyCallBack", Color.Red)
            Else

                hr = masterVol.RegisterControlChangeNotify(MyCallBack)

                If hr <> 0 Then
                    Form1.Showme("Callback register failed", Color.Red)
                    If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
                Else
                    Form1.Showme("Callback register OK", Color.Blue)
                    CallBackOn = True
                End If
            End If

        Catch ex As Exception
            Form1.Showme("CallBack error " & ex.Message, Color.Red)
            If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
        End Try

    End Sub

    Public Sub Cancelcallback()
        If CallBackOn = False Then Exit Sub

        hr = masterVol.UnregisterControlChangeNotify(MyCallBack)
        If hr <> 0 Then
            MsgBox("Callback Failed to UnRegister", vbOK, "Core Audio Callback")
        Else
            If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
            Form1.Showme("Callback Un-register OK", Color.Blue)
            CallBackOn = False
        End If

    End Sub

End Class

' ==============
' Public Module:

Imports System.Runtime.InteropServices
Imports CoreAudioApi

Module ModCoreAudioAlt

    ' https://stackoverflow.com/questions/74833398/coreaudio-in-vb-net-6-0-windows-11-Is-there-a-way-to-do-a-controlchangenotify

    Public CallBackOn As Boolean = False                    ' Callback is on Flag

    Public masterVol As IAudioEndpointVolume = Nothing
    Public MyCallBack As New AudioCallback

    Public Gstructure As New AUDIO_VOLUME_NOTIFICATION_DATA ' Callback data
    Public HaveChange As Boolean = False                    ' Callback has fired

    <ComImport>
    <Guid("657804FA-D6AD-4496-8A60-352752AF4F89")>
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IAudioEndpointVolumeCallback
        <PreserveSig()>
        Function OnNotify(pNotifyData As IntPtr) As Integer

    End Interface

    <StructLayout(LayoutKind.Sequential)>
    Public Structure AUDIO_VOLUME_NOTIFICATION_DATA
        Public guidEventContext As Guid
        Public bMuted As Boolean
        Public fMasterVolume As Single
        Public nChannels As UInteger
        Public Left As Single                                   ' .net will not allow pre-dimensioned array (aVolumes(1) as single)
        Public Right As Single
    End Structure

    ' https://gist.github.com/sverrirs/d099b34b7f72bb4fb386
    <ComImport>
    <Guid("5CDF2C82-841E-4546-9722-0CF74078229A")>
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IAudioEndpointVolume
        Function RegisterControlChangeNotify(<MarshalAs(UnmanagedType.Interface)> pNotify As IAudioEndpointVolumeCallback) As Integer
        Function UnregisterControlChangeNotify(<MarshalAs(UnmanagedType.Interface)> pNotify As IAudioEndpointVolumeCallback) As Integer

        Function GetChannelCount(ByRef channelCount As Integer) As HRESULT
        Function SetMasterVolumeLevel() As HRESULT
        Function SetMasterVolumeLevelScalar(level As Single, eventContext As Guid) As HRESULT
        Function GetMasterVolumeLevel(<Out> ByRef level As Single) As HRESULT
        Function GetMasterVolumeLevelScalar(<Out> ByRef level As Single) As HRESULT
        Function SetChannelVolumeLevel(channelNumber As Integer, level As Single, eventContext As Guid) As HRESULT
        Function SetChannelVolumeLevelScalar(channelNumber As Integer, level As Single, eventContext As Guid) As HRESULT
        Function GetChannelVolumeLevel(channelNumber As Integer, <Out> ByRef level As Single) As HRESULT
        Function GetChannelVolumeLevelScalar(channelNumber As Integer, <Out> ByRef level As Single) As HRESULT
        Function SetMute(<MarshalAs(UnmanagedType.Bool)> isMuted As Boolean, eventContext As Guid) As HRESULT
        Function GetMute(<Out> ByRef isMuted As Boolean) As HRESULT
        Function GetVolumeStepInfo(<Out> ByRef pnStep As Integer, ByRef pnStepCount As Integer) As HRESULT
        Function VolumeStepUp(eventContext As Guid) As HRESULT
        Function VolumeStepDown(eventContext As Guid) As HRESULT
        Function QueryHardwareSupport(<Out> ByRef hardwareSupportMask As Integer) As HRESULT
        Function GetVolumeRange(<Out> ByRef volumeMin As Single, <Out> ByRef volumeMax As Single, <Out> ByRef volumeStep As Single) As HRESULT
    End Interface

    <ComImport>
    <Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")>
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IMMDeviceEnumerator
        Function EnumAudioEndpoints(ByVal dataFlow As EDataFlow, ByVal dwStateMask As Integer, <Out> ByRef ppDevices As IMMDeviceCollection) As HRESULT
        ' for 0x80070490 : Element not found
        <PreserveSig>
        Function GetDefaultAudioEndpoint(ByVal dataFlow As EDataFlow, ByVal role As ERole, <Out> ByRef ppEndpoint As IMMDevice) As HRESULT
        Function GetDevice(ByVal pwstrId As String, <Out> ByRef ppDevice As IMMDevice) As HRESULT
        Function NotImpl1() As Integer

    End Interface

    <ComImport>
    <Guid("D666063F-1587-4E43-81F1-B948E807363F")>
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IMMDevice
        Function Activate(ByRef iid As Guid, ByVal dwClsCtx As CLSCTX, ByVal pActivationParams As IntPtr, <Out> ByRef ppInterface As IAudioEndpointVolume) As HRESULT
        Function OpenPropertyStore(ByVal stgmAccess As Integer, <Out> ByRef ppProperties As IPropertyStore) As HRESULT
        Function GetId(<Out> ByRef ppstrId As IntPtr) As HRESULT
        Function GetState(<Out> ByRef pdwState As Integer) As HRESULT
    End Interface

End Module

' ==========
' Main Form:

Public Class Form1

' Contains:
' HMaster horizonal scroll 0-105 for Volume
' HBalance horizontal scroll -100 to 105 for Balance
' ChkMaster CheckBox for Mute
' LGuid label for Callback GUID

' Uses timer1 with 1 second interval to poll for Callback flag

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        If HaveChange = False Then Exit Sub

        HaveChange = False

        ChkMaster.Checked = Gstructure.bMuted

        Dim svolL As Integer = 100 * Gstructure.Left
        Dim svolR As Integer = 100 * Gstructure.Right
        Dim balance As Integer
        If svolL = svolR Then
            balance = 0
        Else
            If svolR > svolL Then
                balance = 100 - svolL * 100.0 / svolR
            Else
                balance = -(100 - svolR * 100.0 / svolL)
            End If
        End If

        HMaster.Value = 100 * Gstructure.fMasterVolume
        HBalance.Value = balance

        LGuid.Text = (Gstructure.guidEventContext.ToString)
    End Sub

   Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If CallBackOn Then ClassCoreAudio.Cancelcallback()
    End Sub

end class

</code>```

Body:
I am writing a volume control app in vb.net 6.0, using a reference to CoreAudioApi.dll.
I can:

Change the volume of the default render and capture devices.

Mute the default devices.

Alter the balance on the render device

List the full names, guid string and status of all the devices

However, despite a lot of research, I can not setup a callback for ControlChangeNotify.
It appears to be simple in C, however I am writing in VB. Can any one suggest a solution?

Update 18/12/2022 @Jimi supplied some very useful definitions and I have edited the post to show the current code attempts. I can get the master default volume using masterVol = GetMasterVolumeObject() as an IAudioEndpointVolume.

Update 22/12/2022 Following a re-read of many postings it became apparent that it was important to create a persistent reference to mastervol and the class reference (MyCallBack) to the class module implementing IAudioEndpointVolumeCallback.

Update 24/12/2022 The AudioCallback class is now firing when volume/mute are changed internally and externally. Transferring the callback data to the main form is problematic. I now have a working system which involves:

Declaring public events in the call back class for each type of control I want to change in the main form.

Initiating a BackgroundWorker to Process the data 10mS after being called by the callback class.

Calculating new audio values from the pNotifyData pointer.

RaiseEvent for each slider/checkbox and label in the main form that needs updating.

AddHandler in the main form to process the callback events.

Create handler routines with delegates for each control type.

From my point of view this topic is solved.

My thanks to @Jimi for his contribution.

Latest Updates:

Option Explicit On
Imports System.ComponentModel
Imports System.Runtime.InteropServices

Public Class AudioCallback

    Implements IAudioEndpointVolumeCallback

    Public Event LabelReady(sender As AudioCallback, ByVal T As String)
    Public Event SliderReady(sender As AudioCallback, EP As String, ByVal T As Integer)
    Public Event CheckReady(sender As AudioCallback, EP As String, ByVal T As Boolean)

    Public Function OnNotify(pNotifyData As IntPtr) As Integer Implements IAudioEndpointVolumeCallback.OnNotify
        ' Move to global structure
        Gstructure = Marshal.PtrToStructure(pNotifyData, GetType(AUDIO_VOLUME_NOTIFICATION_DATA))

        BackGround()                                            ' Asynchronous call and delagate controls
        Return 0
    End Function

    Private Sub BackGround()

        Dim bgw = New BackgroundWorker()
        AddHandler bgw.DoWork,
            Sub()
                System.Threading.Thread.Sleep(10)
            End Sub

        AddHandler bgw.RunWorkerCompleted,
            Sub()
                Update()
            End Sub

        bgw.RunWorkerAsync()
    End Sub

    Private Sub Update()

        Dim svolL As Integer
        Dim svolR As Integer
        Dim balance As Integer

        'ChkMaster.Checked = Gstructure.bMuted
        RaiseEvent CheckReady(Me, "R", Gstructure.bMuted)

        svolL = 0.5 + 100 * Gstructure.Left
        svolR = 0.5 + 100 * Gstructure.Right
        If svolL = svolR Then
            balance = 0
        Else
            If svolR > svolL Then
                balance = 100 - svolL * 100.0 / svolR
            Else
                balance = -(100 - svolR * 100.0 / svolL)
            End If
        End If

        RaiseEvent SliderReady(Me, "RV", 0.5 + 100 * Gstructure.fMasterVolume)  ' HMaster.Value = 0.5 + 100 * Gstructure.fMasterVolume
        RaiseEvent SliderReady(Me, "RB", balance)                               ' HBalance.Value = balance

        'LGuid.Text = Gstructure.guidEventContext.ToString
        RaiseEvent LabelReady(Me, Gstructure.guidEventContext.ToString)
    End Sub

End Class

' Main form Extracts ============================================

Imports CoreAudioApi

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Show()

        ' events for handling AudioCallback events
        AddHandler MyCallBack.LabelReady, AddressOf LReady
        AddHandler MyCallBack.SliderReady, AddressOf HReady
        AddHandler MyCallBack.CheckReady, AddressOf CReady

End Sub

' Label Guid displays Callback GUID
' CheckBox ChkMaster displays Mute status
' Horizontal scrollbar HMaster displays default render volume
' Horizontal scrollbar HBalance displays default render balance
' The global variable IsSettingMaster prevents code associated
' with altering the value of the sliders from re-setting
' the volume / balance.

Private Sub LReady(sender As AudioCallback, Data As String)                                                 ' Set GUID label for Render
        UpdateLabel(LGuid, Data)
    End Sub

    Private Delegate Sub UpdateLabelDelegate(TB As Label, param As String)
    Private Sub UpdateLabel(TB As Label, param As String)
        If TB.InvokeRequired Then
            TB.Invoke(New UpdateLabelDelegate(AddressOf UpdateLabel), New Object() {TB, param})
        Else
            TB.Text = param
        End If
    End Sub

    Private Sub CReady(sender As AudioCallback, EP As String, Data As Boolean)                                  ' Set Master (Render) Mute checkbox
        If EP = "R" Then UpdateChkbox(ChkMaster, Data)
    End Sub

    Private Delegate Sub UpdateChkboxDelegate(TB As CheckBox, param As Boolean)
    Private Sub UpdateChkbox(TB As CheckBox, param As Boolean)
        If TB.InvokeRequired Then
            TB.Invoke(New UpdateChkboxDelegate(AddressOf UpdateChkbox), New Object() {TB, param})
        Else
            TB.Checked = param
        End If
    End Sub

    Private Sub HReady(sender As AudioCallback, EP As String, Data As Integer)                                  ' Set Master (Render) Volume / Master Balance slide
        IsSettingMaster = True
        If EP = "RV" Then UpdateHslide(HMaster, Data)
        If EP = "RB" Then UpdateHslide(HBalance, Data)
        IsSettingMaster = False
    End Sub

    Private Delegate Sub UpdateHslideDelegate(TB As HScrollBar, param As Integer)
    Private Sub UpdateHslide(TB As HScrollBar, param As Integer)
        If TB.InvokeRequired Then
            TB.Invoke(New UpdateHslideDelegate(AddressOf UpdateHslide), New Object() {TB, param})
        Else
            TB.Value = param
        End If
    End Sub

History:

' ===============================
' Public Class containing Callback:

Option Explicit On
Imports System.Runtime.InteropServices

Public Class AudioCallback

    Implements IAudioEndpointVolumeCallback
    Public Function OnNotify(pNotifyData As IntPtr) As Integer Implements IAudioEndpointVolumeCallback.OnNotify
        ' Move to global structure
        Gstructure = Marshal.PtrToStructure(pNotifyData, GetType(AUDIO_VOLUME_NOTIFICATION_DATA))

        ' Need mechanism to process new data in main form
        ' Must be asynchronous
        ' Raise event did not work
        ' Enabling Timer did not work

        HaveChange = True                                       ' Flag global variable

        Return 0
    End Function

End Class

' ===============================
' Public Class to Setup Callback:

Option Explicit On

Imports System.Runtime.InteropServices

' Implements IMMDevice, IMMDeviceEnumerator, IAudioEndpointVolume
' developed from https://exchangetuts.com/how-to-check-if-the-system-audio-is-muted-1641156904496320

Public Class CoreAudio

    ' Public definition in ModCoreaudioAlt  https://stackoverflow.com/questions/52001368/how-to-check-if-the-system-audio-is-muted/52013031#52013031
    '   Public Interface IAudioEndpointVolumeCallback
    '   Public Structure AUDIO_VOLUME_NOTIFICATION_DATA
    '   Public Interface IMMDevice
    '   Public Interface IMMDeviceEnumerator
    ' End Public definition  in ModCoreaudioAlt ==============================

    Dim CLSID_MMDeviceEnumerator As Guid = New Guid("{BCDE0395-E52F-467C-8E3D-C4579291692E}")
    Dim MMDeviceEnumeratorType As Type = Type.GetTypeFromCLSID(CLSID_MMDeviceEnumerator, True)

    Private hr As Integer

    Friend Enum EDataFlow
        eRender
        eCapture
        eAll
        EDataFlow_enum_count
    End Enum
    Friend Enum ERole
        eConsole
        eMultimedia
        eCommunications
        ERole_enum_count
    End Enum

    <Flags>
    Friend Enum CLSCTX As UInteger
        CLSCTX_INPROC_SERVER = &H1                              ' In CLSCTX_ALL
        CLSCTX_INPROC_HANDLER = &H2                             ' In CLSCTX_ALL
        CLSCTX_LOCAL_SERVER = &H4                               ' In CLSCTX_ALL
        CLSCTX_INPROC_SERVER16 = &H8
        CLSCTX_REMOTE_SERVER = &H10                             ' In CLSCTX_ALL
        CLSCTX_INPROC_HANDLER16 = &H20
        CLSCTX_RESERVED1 = &H40
        CLSCTX_RESERVED2 = &H80
        CLSCTX_RESERVED3 = &H100
        CLSCTX_RESERVED4 = &H200
        CLSCTX_NO_CODE_DOWNLOAD = &H400
        CLSCTX_RESERVED5 = &H800
        CLSCTX_NO_CUSTOM_MARSHAL = &H1000
        CLSCTX_ENABLE_CODE_DOWNLOAD = &H2000
        CLSCTX_NO_FAILURE_LOG = &H4000
        CLSCTX_DISABLE_AAA = &H8000
        CLSCTX_ENABLE_AAA = &H10000
        CLSCTX_FROM_DEFAULT_CONTEXT = &H20000
        CLSCTX_ACTIVATE_32_BIT_SERVER = &H40000
        CLSCTX_ACTIVATE_64_BIT_SERVER = &H80000
        CLSCTX_INPROC = CLSCTX_INPROC_SERVER Or CLSCTX_INPROC_HANDLER

        CLSCTX_SERVER = CLSCTX_INPROC_SERVER Or CLSCTX_LOCAL_SERVER Or CLSCTX_REMOTE_SERVER ' In CLSCTX_ALL
        CLSCTX_ALL = CLSCTX_SERVER Or CLSCTX_INPROC_HANDLER
    End Enum

    Friend Function GetMasterVolumeObject() As IAudioEndpointVolume
        ' Get the default IAudioEndpintVolume as "ppEndpoint" for eRender & eMultimedia

        Dim deviceEnumerator As IMMDeviceEnumerator = Nothing
        Dim MediaDevice As IMMDevice = Nothing
        Dim ppEndpoint As IAudioEndpointVolume = Nothing
        Dim EndPointVolID As Guid = GetType(IAudioEndpointVolume).GUID

        Try
            Dim MMDeviceEnumerator As Object = Activator.CreateInstance(MMDeviceEnumeratorType)
            deviceEnumerator = CType(MMDeviceEnumerator, IMMDeviceEnumerator)
            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, MediaDevice)
            MediaDevice.Activate(EndPointVolID, CLSCTX.CLSCTX_ALL, IntPtr.Zero, ppEndpoint)
        Catch ex As Exception
            Form1.Showme("Error in GetMasterVolumeObject: " & ex.Message, Color.Red)
            ppEndpoint = Nothing
        Finally
            If Not IsNothing(deviceEnumerator) Then Marshal.ReleaseComObject(deviceEnumerator)
            If Not IsNothing(MediaDevice) Then Marshal.ReleaseComObject(MediaDevice)
        End Try

        Return ppEndpoint
    End Function

Public Sub Callback()

        Try
            masterVol = GetMasterVolumeObject()

            ' MyCallBack defined in Module ModCoreAudioAlt : Public MyCallBack As New AudioCallback

            If IsNothing(MyCallBack) Then
                Form1.Showme("Failed to set MyCallBack", Color.Red)
            Else

                hr = masterVol.RegisterControlChangeNotify(MyCallBack)

                If hr <> 0 Then
                    Form1.Showme("Callback register failed", Color.Red)
                    If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
                Else
                    Form1.Showme("Callback register OK", Color.Blue)
                    CallBackOn = True
                End If
            End If

        Catch ex As Exception
            Form1.Showme("CallBack error " & ex.Message, Color.Red)
            If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
        End Try

    End Sub

    Public Sub Cancelcallback()
        If CallBackOn = False Then Exit Sub

        hr = masterVol.UnregisterControlChangeNotify(MyCallBack)
        If hr <> 0 Then
            MsgBox("Callback Failed to UnRegister", vbOK, "Core Audio Callback")
        Else
            If Not IsNothing(masterVol) Then Marshal.ReleaseComObject(masterVol)
            Form1.Showme("Callback Un-register OK", Color.Blue)
            CallBackOn = False
        End If

    End Sub

End Class

' ==============
' Public Module:

Imports System.Runtime.InteropServices
Imports CoreAudioApi

Module ModCoreAudioAlt

    ' https://stackoverflow.com/questions/74833398/coreaudio-in-vb-net-6-0-windows-11-Is-there-a-way-to-do-a-controlchangenotify

    Public CallBackOn As Boolean = False                    ' Callback is on Flag

    Public masterVol As IAudioEndpointVolume = Nothing
    Public MyCallBack As New AudioCallback

    Public Gstructure As New AUDIO_VOLUME_NOTIFICATION_DATA ' Callback data
    Public HaveChange As Boolean = False                    ' Callback has fired

    <ComImport>
    <Guid("657804FA-D6AD-4496-8A60-352752AF4F89")>
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IAudioEndpointVolumeCallback
        <PreserveSig()>
        Function OnNotify(pNotifyData As IntPtr) As Integer

    End Interface

    <StructLayout(LayoutKind.Sequential)>
    Public Structure AUDIO_VOLUME_NOTIFICATION_DATA
        Public guidEventContext As Guid
        Public bMuted As Boolean
        Public fMasterVolume As Single
        Public nChannels As UInteger
        Public Left As Single                                   ' .net will not allow pre-dimensioned array (aVolumes(1) as single)
        Public Right As Single
    End Structure

    ' https://gist.github.com/sverrirs/d099b34b7f72bb4fb386
    <ComImport>
    <Guid("5CDF2C82-841E-4546-9722-0CF74078229A")>
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IAudioEndpointVolume
        Function RegisterControlChangeNotify(<MarshalAs(UnmanagedType.Interface)> pNotify As IAudioEndpointVolumeCallback) As Integer
        Function UnregisterControlChangeNotify(<MarshalAs(UnmanagedType.Interface)> pNotify As IAudioEndpointVolumeCallback) As Integer

        Function GetChannelCount(ByRef channelCount As Integer) As HRESULT
        Function SetMasterVolumeLevel() As HRESULT
        Function SetMasterVolumeLevelScalar(level As Single, eventContext As Guid) As HRESULT
        Function GetMasterVolumeLevel(<Out> ByRef level As Single) As HRESULT
        Function GetMasterVolumeLevelScalar(<Out> ByRef level As Single) As HRESULT
        Function SetChannelVolumeLevel(channelNumber As Integer, level As Single, eventContext As Guid) As HRESULT
        Function SetChannelVolumeLevelScalar(channelNumber As Integer, level As Single, eventContext As Guid) As HRESULT
        Function GetChannelVolumeLevel(channelNumber As Integer, <Out> ByRef level As Single) As HRESULT
        Function GetChannelVolumeLevelScalar(channelNumber As Integer, <Out> ByRef level As Single) As HRESULT
        Function SetMute(<MarshalAs(UnmanagedType.Bool)> isMuted As Boolean, eventContext As Guid) As HRESULT
        Function GetMute(<Out> ByRef isMuted As Boolean) As HRESULT
        Function GetVolumeStepInfo(<Out> ByRef pnStep As Integer, ByRef pnStepCount As Integer) As HRESULT
        Function VolumeStepUp(eventContext As Guid) As HRESULT
        Function VolumeStepDown(eventContext As Guid) As HRESULT
        Function QueryHardwareSupport(<Out> ByRef hardwareSupportMask As Integer) As HRESULT
        Function GetVolumeRange(<Out> ByRef volumeMin As Single, <Out> ByRef volumeMax As Single, <Out> ByRef volumeStep As Single) As HRESULT
    End Interface

    <ComImport>
    <Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")>
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IMMDeviceEnumerator
        Function EnumAudioEndpoints(ByVal dataFlow As EDataFlow, ByVal dwStateMask As Integer, <Out> ByRef ppDevices As IMMDeviceCollection) As HRESULT
        ' for 0x80070490 : Element not found
        <PreserveSig>
        Function GetDefaultAudioEndpoint(ByVal dataFlow As EDataFlow, ByVal role As ERole, <Out> ByRef ppEndpoint As IMMDevice) As HRESULT
        Function GetDevice(ByVal pwstrId As String, <Out> ByRef ppDevice As IMMDevice) As HRESULT
        Function NotImpl1() As Integer

    End Interface

    <ComImport>
    <Guid("D666063F-1587-4E43-81F1-B948E807363F")>
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IMMDevice
        Function Activate(ByRef iid As Guid, ByVal dwClsCtx As CLSCTX, ByVal pActivationParams As IntPtr, <Out> ByRef ppInterface As IAudioEndpointVolume) As HRESULT
        Function OpenPropertyStore(ByVal stgmAccess As Integer, <Out> ByRef ppProperties As IPropertyStore) As HRESULT
        Function GetId(<Out> ByRef ppstrId As IntPtr) As HRESULT
        Function GetState(<Out> ByRef pdwState As Integer) As HRESULT
    End Interface

End Module

' ==========
' Main Form:

Public Class Form1

' Contains:
' HMaster horizonal scroll 0-105 for Volume
' HBalance horizontal scroll -100 to 105 for Balance
' ChkMaster CheckBox for Mute
' LGuid label for Callback GUID

' Uses timer1 with 1 second interval to poll for Callback flag

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        If HaveChange = False Then Exit Sub

        HaveChange = False

        ChkMaster.Checked = Gstructure.bMuted

        Dim svolL As Integer = 100 * Gstructure.Left
        Dim svolR As Integer = 100 * Gstructure.Right
        Dim balance As Integer
        If svolL = svolR Then
            balance = 0
        Else
            If svolR > svolL Then
                balance = 100 - svolL * 100.0 / svolR
            Else
                balance = -(100 - svolR * 100.0 / svolL)
            End If
        End If

        HMaster.Value = 100 * Gstructure.fMasterVolume
        HBalance.Value = balance

        LGuid.Text = (Gstructure.guidEventContext.ToString)
    End Sub

   Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If CallBackOn Then ClassCoreAudio.Cancelcallback()
    End Sub

end class


来源: stackexchange

问:
Simple OpenMP program for detecting GPU and other devices does not work
I'm trying to write a very simple example with OpenMP using GCC 12 as compiler and the target clause in order to detect all my devices, but it does not work. First of all, I have a Lenovo W540 running Debian Sid with an integrated Inted HD Graphics 4600 (which is the GPU the GUI -plasma- is using). Also, there is a NVIDIA GK106GLM [Quadro K2100M]. I have installed the xserver-xorg-video-nvidia-legacy-390xx, nvidia-legacy-390xx-driver, and nvidia-legacy-390xx-kernel-dkms packages, as they are the corresponding drivers for my GPU. Running the lspci -k | grep -A 2 -i "VGA" command I obtain

```<code>00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)
        Subsystem: Lenovo 4th Gen Core Processor Integrated Graphics Controller
        Kernel driver in use: i915
--
01:00.0 VGA compatible controller: NVIDIA Corporation GK106GLM [Quadro K2100M] (rev a1)
        Subsystem: Lenovo GK106GLM [Quadro K2100M]
        Kernel modules: nvidia
</code>```

so I suppose that the NVDIA GPU is well configured and detected. Am I right?

Then, I borrowed this simply code from https://enccs.github.io/openmp-gpu/target/

```<code>/* Copyright (c) 2019 CSC Training */
/* Copyright (c) 2021 ENCCS */
#include <stdio.h>

#ifdef _OPENMP
#include <omp.h>
#endif

int main()
{
  int num_devices = omp_get_num_devices();
  printf("Number of available devices %d\n", num_devices);

  #pragma omp target
  {
      if (omp_is_initial_device()) {
        printf("Running on host\n");
      } else {
        int nteams= omp_get_num_teams();
        int nthreads= omp_get_num_threads();
        printf("Running on device with %d teams in total and %d threads in each team\n",nteams,nthreads);
      }
  }

}
</code>```

Compilation with GCC as gcc -Wall -fopenmp example.c -o example works fine and does not produce warnings nor errors, but at execution time I obtain simply

```<code>Number of available devices 0
Running on host
</code>```

so not Inter nor NVIDIA GPUs were detected. Inspecting the Debian repositories I've seen and installed the packages gcc-offload-nvptx, gcc-12-offload-nvptx, libgomp-plugin-nvptx1, and nvptx-tools. Now, when I compile again as gcc -Wall -fopenmp example.c -o example I obtain a warning:

```<code>/usr/bin/ld: /tmp/ccrWP8gn.crtoffloadtable.o: warning: relocation against `__offload_vars_end' in read-only section `.rodata'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
</code>```

When I execute the code I obtain again

```<code>Number of available devices 0
Running on host
</code>```

but in this case the execution is terrubly slow (various seconds of time).
Searching the web I've seen that I must add the option -foffload=nvptx-none to the compilation order, but I obtain the same results as previously (this option only is recognized if gcc-offload-nvptx et al. are installed.

Running gcc -v I can see that GCC 12 in Debian is configured for offloading:

```<code>OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
</code>```

I don't know which number is my NVIDIA card, but I've tried export OFFLOAD_TARGET_DEFAULT=0 and export OFFLOAD_TARGET_DEFAULT=2 with the same wrong result of

```<code>Number of available devices 0
Running on host
</code>```

So, how can I run my OpenMP code in the GPU?

Thanks

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a very simple example with OpenMP using GCC 12 as compiler and the target clause in order to detect all my devices, but it does not work. First of all, I have a Lenovo W540 running Debian Sid with an integrated Inted HD Graphics 4600 (which is the GPU the GUI -plasma- is using). Also, there is a NVIDIA GK106GLM [Quadro K2100M]. I have installed the xserver-xorg-video-nvidia-legacy-390xx, nvidia-legacy-390xx-driver, and nvidia-legacy-390xx-kernel-dkms packages, as they are the corresponding drivers for my GPU. Running the lspci -k | grep -A 2 -i "VGA" command I obtain

00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)
        Subsystem: Lenovo 4th Gen Core Processor Integrated Graphics Controller
        Kernel driver in use: i915
--
01:00.0 VGA compatible controller: NVIDIA Corporation GK106GLM [Quadro K2100M] (rev a1)
        Subsystem: Lenovo GK106GLM [Quadro K2100M]
        Kernel modules: nvidia

so I suppose that the NVDIA GPU is well configured and detected. Am I right?

Then, I borrowed this simply code from https://enccs.github.io/openmp-gpu/target/

/* Copyright (c) 2019 CSC Training */
/* Copyright (c) 2021 ENCCS */
#include <stdio.h>

#ifdef _OPENMP
#include <omp.h>
#endif

int main()
{
  int num_devices = omp_get_num_devices();
  printf("Number of available devices %d\n", num_devices);

  #pragma omp target
  {
      if (omp_is_initial_device()) {
        printf("Running on host\n");
      } else {
        int nteams= omp_get_num_teams();
        int nthreads= omp_get_num_threads();
        printf("Running on device with %d teams in total and %d threads in each team\n",nteams,nthreads);
      }
  }

}

Compilation with GCC as gcc -Wall -fopenmp example.c -o example works fine and does not produce warnings nor errors, but at execution time I obtain simply

Number of available devices 0
Running on host

so not Inter nor NVIDIA GPUs were detected. Inspecting the Debian repositories I've seen and installed the packages gcc-offload-nvptx, gcc-12-offload-nvptx, libgomp-plugin-nvptx1, and nvptx-tools. Now, when I compile again as gcc -Wall -fopenmp example.c -o example I obtain a warning:

/usr/bin/ld: /tmp/ccrWP8gn.crtoffloadtable.o: warning: relocation against `__offload_vars_end' in read-only section `.rodata'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE

When I execute the code I obtain again

Number of available devices 0
Running on host

but in this case the execution is terrubly slow (various seconds of time).
Searching the web I've seen that I must add the option -foffload=nvptx-none to the compilation order, but I obtain the same results as previously (this option only is recognized if gcc-offload-nvptx et al. are installed.

Running gcc -v I can see that GCC 12 in Debian is configured for offloading:

OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu

I don't know which number is my NVIDIA card, but I've tried export OFFLOAD_TARGET_DEFAULT=0 and export OFFLOAD_TARGET_DEFAULT=2 with the same wrong result of

Number of available devices 0
Running on host

So, how can I run my OpenMP code in the GPU?

Thanks


问:
Rust Async Graphql Json InputObject Type
I'm trying to use Async Graphql, I want to use sqlx json type in model. In normal api operations the code is running. But when I want to use the async graphql InputObject macro, I get an error. The codes I used are as follows, I couldn't find a solution for the problem.

```<code>#[derive(Serialize, Deserialize, Debug, Clone, sqlx::Type)]
#[sqlx(transparent)]
pub struct Meta(Map<String, Value>);

scalar!(Meta);

#[derive(Debug, Serialize, Deserialize, Clone, FromRow, SimpleObject)]
pub struct User {
    #[serde(skip_serializing)]
    #[graphql(skip)]
    pub id: Uuid,
    pub name: String,
    pub email: String,
    #[serde(skip_serializing)]
    #[graphql(skip)]
    pub password: String,
    #[serde(skip_serializing)]
    #[graphql(skip)]
    pub meta: Json<Meta>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}
</code>```

No problem so far. But the code below gives an error.

```<code>#[derive(Debug, Deserialize, Validate, InputObject)]
pub struct RegisterInput {
    #[validate(length(min = 4, max = 10))]
    pub name: String,
    #[validate(email)]
    pub email: String,
    #[validate(length(min = 6))]
    pub password: String,
    pub meta: Json<Meta>,
}
</code>```

InputObject error.

```<code>error[E0277]: the trait bound `sqlx::types::Json<Meta>: InputType` is not satisfied
  --> src/dto.rs:13:40
   |
13 | #[derive(Debug, Deserialize, Validate, InputObject)]
   |                                        ^^^^^^^^^^^ the trait `InputType` is not implemented for `sqlx::types::Json<Meta>`
   |
   = help: the following other types implement trait `InputType`:
             Arc<T>
             Arc<[T]>
             Arc<str>
             BTreeMap<K, V>
             BTreeSet<T>
             Box<T>
             Box<[T]>
             Box<str>
           and 49 others
   = note: this error originates in the derive macro `InputObject` (in Nightly builds, run with -Z macro-backtrace for more info)
</code>```

Can you help on the subject?

Body:
I'm trying to use Async Graphql, I want to use sqlx json type in model. In normal api operations the code is running. But when I want to use the async graphql InputObject macro, I get an error. The codes I used are as follows, I couldn't find a solution for the problem.

#[derive(Serialize, Deserialize, Debug, Clone, sqlx::Type)]
#[sqlx(transparent)]
pub struct Meta(Map<String, Value>);

scalar!(Meta);

#[derive(Debug, Serialize, Deserialize, Clone, FromRow, SimpleObject)]
pub struct User {
    #[serde(skip_serializing)]
    #[graphql(skip)]
    pub id: Uuid,
    pub name: String,
    pub email: String,
    #[serde(skip_serializing)]
    #[graphql(skip)]
    pub password: String,
    #[serde(skip_serializing)]
    #[graphql(skip)]
    pub meta: Json<Meta>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

No problem so far. But the code below gives an error.

#[derive(Debug, Deserialize, Validate, InputObject)]
pub struct RegisterInput {
    #[validate(length(min = 4, max = 10))]
    pub name: String,
    #[validate(email)]
    pub email: String,
    #[validate(length(min = 6))]
    pub password: String,
    pub meta: Json<Meta>,
}

InputObject error.

error[E0277]: the trait bound `sqlx::types::Json<Meta>: InputType` is not satisfied
  --> src/dto.rs:13:40
   |
13 | #[derive(Debug, Deserialize, Validate, InputObject)]
   |                                        ^^^^^^^^^^^ the trait `InputType` is not implemented for `sqlx::types::Json<Meta>`
   |
   = help: the following other types implement trait `InputType`:
             Arc<T>
             Arc<[T]>
             Arc<str>
             BTreeMap<K, V>
             BTreeSet<T>
             Box<T>
             Box<[T]>
             Box<str>
           and 49 others
   = note: this error originates in the derive macro `InputObject` (in Nightly builds, run with -Z macro-backtrace for more info)

Can you help on the subject?


问:
Discord.js cooldown not working, what should I do?
I want to create a cooldown for my team, but when using the command multiple times, the cooldown doesn't appear.

My code:

const fs = require('fs');
const UnbelievaBoat = require('unb-api');
const unb = new UnbelievaBoat.Client('token');

const Discord = require('discord.js');
const { Client, GatewayIntentBits, Collection} = require('discord.js');
const Timeout = new Discord.Collection();
const client = new Client({
    intents: [
        GatewayIntentBits['Guilds'],
        GatewayIntentBits['GuildMessages'],
        GatewayIntentBits['MessageContent']
    ]
});

const { prefix, token } = require('./config.json');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once('ready', () => {
    console.log('Ready!');
});
client.on('messageCreate', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (!client.commands.has(command)) return;

    if (command) {
        if(command.timeout) {
            if(Timeout.has(`${command.name}${message.author.id}`)) return message.channel.send(`Осталось ждать \`${ms(Timeout.get(`${command.name}${message.author.id}`) - Date.now(), {long : true})}\`секунд!`)
            command.run(client, message, args)
            Timeout.set(`${command.name}${message.author.id}`, Date.now() + command.timeout)
            setTimeout(() => {
                Timeout.delete(`${command.name}${message.author.id}`)
            }, command.timeout)
        }
    }

    try {
        client.commands.get(command).execute(client, message, args);
    } catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
    }
});
client.login(token);
```
<p>And this is the command</p>
<pre class="lang-js prettyprint-override"><code>const UnbelievaBoat = require('unb-api');
const unb = new UnbelievaBoat.Client('token');
const { EmbedBuilder} = require('discord.js');

module.exports = {
    name: 'ферма1',
    timeout: 15,

    execute(client, message, args) {
        ...
</code>```

I searched on this topic but I've still not found a way to make the cooldown work

Body:
I want to create a cooldown for my team, but when using the command multiple times, the cooldown doesn't appear.

My code:

const fs = require('fs');
const UnbelievaBoat = require('unb-api');
const unb = new UnbelievaBoat.Client('token');

const Discord = require('discord.js');
const { Client, GatewayIntentBits, Collection} = require('discord.js');
const Timeout = new Discord.Collection();
const client = new Client({
    intents: [
        GatewayIntentBits['Guilds'],
        GatewayIntentBits['GuildMessages'],
        GatewayIntentBits['MessageContent']
    ]
});

const { prefix, token } = require('./config.json');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once('ready', () => {
    console.log('Ready!');
});
client.on('messageCreate', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (!client.commands.has(command)) return;

    if (command) {
        if(command.timeout) {
            if(Timeout.has(`${command.name}${message.author.id}`)) return message.channel.send(`Осталось ждать \`${ms(Timeout.get(`${command.name}${message.author.id}`) - Date.now(), {long : true})}\`секунд!`)
            command.run(client, message, args)
            Timeout.set(`${command.name}${message.author.id}`, Date.now() + command.timeout)
            setTimeout(() => {
                Timeout.delete(`${command.name}${message.author.id}`)
            }, command.timeout)
        }
    }

    try {
        client.commands.get(command).execute(client, message, args);
    } catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
    }
});
client.login(token);

And this is the command

const UnbelievaBoat = require('unb-api');
const unb = new UnbelievaBoat.Client('token');
const { EmbedBuilder} = require('discord.js');

module.exports = {
    name: 'ферма1',
    timeout: 15,

    execute(client, message, args) {
        ...

I searched on this topic but I've still not found a way to make the cooldown work


问:
Performance degradation due to loading a shared library with thread local storage
I write a python wrapper around a large Fortran program with pybind11 as a python module. The Fortran program is a large simulation tool, that uses OpenMP for multithreading. My initial work was to reproduce the Fortran executable from a python function. That yielded (as expected) exactly the same results and the same performance. But when I started to add more functions, I observed a large performance degradation (about 50% to 100% longer runtimes).

Tracking the cause in pybind11

I could track it down to a call of the pybind11 macro PYBIND11_NUMPY_DTYPE, which loads in its internals the numpy library numpy.core._multiarray_umath. I could reproduce the performance degradation with the following code:

```<code>import ctypes
import time

# This is the fortran code, compiled to a shared library and a subroutine modulemain, that resembles the main program.
fcode = ctypes.CDLL("./libfcode.so")

# Only loading the library results in a worse performance of the Fortran code.
import numpy.core._multiarray_umath

t = time.time()
fcode.modulemain()
print("runtime: ", time.time()-t)
</code>```

Tracking the cause in numpy

After finding, that the reason of my bad performance lies just in including the numpy.core._multiarray_umath library, I further digged into it. Ultimately I could track it down to two lines in that library, where two variables with thread local storage a defined.

```<code>// from numpy 1.21.5, numpy/core/src/multiarray/multiarraymodule.c:4011
static NPY_TLS int sigint_buf_init = 0;
static NPY_TLS NPY_SIGJMP_BUF _NPY_SIGINT_BUF;
</code>```

where NPY_TLSis defined as

```<code>#define NPY_TLS __thread
</code>```

So the inclusion of a shared object with __thread TLS is the root cause for my performance degradation. This leads me to my two questions:

Why?

Is there any way to prevent it? Not using PYBIND11_NUMPY_DTYPE is no option, as the loading of the numpy library after my module will trigger the bug as well!

Minimal working example

My error is about a large and heavy Fortran code, that I wanted to export to python via pybind11. But in the end it resulted in a problem of using OpenMP thread local storage and then loading a library that exports a variable with __thread thread local storage in the python interpreter. I could create a minimal working example, that reproduced the behavior.

The worker program work.f90

```<code>module data
  integer, parameter :: N = 10000
  real :: X(1:N)
  !$omp threadprivate(X)
end module

subroutine work() bind(C, name="worker")
  use data, only: X,N

  !$omp parallel
  X(1) = 0.131
  do i=2,N
    do j=1,i-1
      X(i) = X(i) + 0.431*sin(X(i-1))
    end do
  end do
  !$omp end parallel

</code>```

The bad library tl.c

```<code>__thread int badVariable = 3;
</code>```

a python script that shows the effect run.py

```<code>import ctypes
import time

work = ctypes.CDLL("./libwork.so")

# first worker run without loaded libtl.so. Good performance!
t = time.time()
work.worker()
print("TIME: ", time.time()-t)

# load the bad library
bad = ctypes.CDLL("./libtl.so")

# second worker with degraded performance
t = time.time()
work.worker()
print("TIME: ", time.time()-t)
</code>```

The Makefile

```<code>FLAGS = -fPIC  -shared

all: libwork.so libtl.so

libwork.so: work.f90
        gfortran-11 $(FLAGS) work.f90 -fopenmp -o $@

libtl.so: tl.c
        gcc-11 $(FLAGS) tl.c -o $@

</code>```

The worker is so simple, that enabling optimization will hide the effect. I guess is could be a call to access the thread local storage area, that could be easily optimized out here. But in a real program, the effect is there with optimization.

Setup

I have the problem on a ubuntu 22.04 LTS computer with a x86 CPU (Xeon 8280M). gcc is Ubuntu 11.3.0-1ubuntu1~22.04 (I tried others down to  7.5.0 with the same effect). Python is version 3.10.6.
The problem is not Fortran specific, I can easily write a worker in plain C with the same effect. And I also tried this on a Raspberry Pi with the same effect! (ARM, GCC 8.3.0, Python 2.7.16)

Body:
I write a python wrapper around a large Fortran program with pybind11 as a python module. The Fortran program is a large simulation tool, that uses OpenMP for multithreading. My initial work was to reproduce the Fortran executable from a python function. That yielded (as expected) exactly the same results and the same performance. But when I started to add more functions, I observed a large performance degradation (about 50% to 100% longer runtimes).

Tracking the cause in pybind11

I could track it down to a call of the pybind11 macro PYBIND11_NUMPY_DTYPE, which loads in its internals the numpy library numpy.core._multiarray_umath. I could reproduce the performance degradation with the following code:

import ctypes
import time

# This is the fortran code, compiled to a shared library and a subroutine modulemain, that resembles the main program.
fcode = ctypes.CDLL("./libfcode.so")

# Only loading the library results in a worse performance of the Fortran code.
import numpy.core._multiarray_umath

t = time.time()
fcode.modulemain()
print("runtime: ", time.time()-t)

Tracking the cause in numpy

After finding, that the reason of my bad performance lies just in including the numpy.core._multiarray_umath library, I further digged into it. Ultimately I could track it down to two lines in that library, where two variables with thread local storage a defined.

// from numpy 1.21.5, numpy/core/src/multiarray/multiarraymodule.c:4011
static NPY_TLS int sigint_buf_init = 0;
static NPY_TLS NPY_SIGJMP_BUF _NPY_SIGINT_BUF;

where NPY_TLSis defined as

#define NPY_TLS __thread

So the inclusion of a shared object with __thread TLS is the root cause for my performance degradation. This leads me to my two questions:

Why?

Is there any way to prevent it? Not using PYBIND11_NUMPY_DTYPE is no option, as the loading of the numpy library after my module will trigger the bug as well!

Minimal working example

My error is about a large and heavy Fortran code, that I wanted to export to python via pybind11. But in the end it resulted in a problem of using OpenMP thread local storage and then loading a library that exports a variable with __thread thread local storage in the python interpreter. I could create a minimal working example, that reproduced the behavior.

The worker program work.f90

module data
  integer, parameter :: N = 10000
  real :: X(1:N)
  !$omp threadprivate(X)
end module

subroutine work() bind(C, name="worker")
  use data, only: X,N

  !$omp parallel
  X(1) = 0.131
  do i=2,N
    do j=1,i-1
      X(i) = X(i) + 0.431*sin(X(i-1))
    end do
  end do
  !$omp end parallel

The bad library tl.c

__thread int badVariable = 3;

a python script that shows the effect run.py

import ctypes
import time

work = ctypes.CDLL("./libwork.so")

# first worker run without loaded libtl.so. Good performance!
t = time.time()
work.worker()
print("TIME: ", time.time()-t)

# load the bad library
bad = ctypes.CDLL("./libtl.so")

# second worker with degraded performance
t = time.time()
work.worker()
print("TIME: ", time.time()-t)

The Makefile

FLAGS = -fPIC  -shared

all: libwork.so libtl.so

libwork.so: work.f90
        gfortran-11 $(FLAGS) work.f90 -fopenmp -o $@

libtl.so: tl.c
        gcc-11 $(FLAGS) tl.c -o $@

The worker is so simple, that enabling optimization will hide the effect. I guess is could be a call to access the thread local storage area, that could be easily optimized out here. But in a real program, the effect is there with optimization.

Setup

I have the problem on a ubuntu 22.04 LTS computer with a x86 CPU (Xeon 8280M). gcc is Ubuntu 11.3.0-1ubuntu1~22.04 (I tried others down to  7.5.0 with the same effect). Python is version 3.10.6.
The problem is not Fortran specific, I can easily write a worker in plain C with the same effect. And I also tried this on a Raspberry Pi with the same effect! (ARM, GCC 8.3.0, Python 2.7.16)


问:
Interpolation via Fast Discrete Fourier Transform with Chebyshev extreme points
I'm trying to interpolate a function at arbitrary points and I have the function values at Chebyshev extreme points. I use the real values from Fast Fourier Transform to compute the Chebyshev coefficients. Then I scale them with 2/N and then I use the polynomial library to evaluate the series of chebyshev polynomials at a set of points. This produces the wrong function approximation. Where am I going wrong?</p>
```<code>import numpy as np
import matplotlib.pyplot as plt

# Define the number of
# Chebyshev extreme points
N = 10

# Define the function to be
# approximated
def f(x):
   return x**2

# Evaluate the function at the
# Chebyshev extreme points
x = np.cos(np.arange(N) * np.pi / N)
y = f(x)

# Compute the discrete Fourier
# transform (DFT) of the function
# values using the FFT algorithm
DFT = np.fft.fft(y).real

# Compute the correct scaling
# factor
scaling_factor = 2/N

# Scale the DFT coefficients by
# the correct scaling factor
chebyshev_coefficients = scaling_factor * DFT

# Use Chebval to
# evaluate the approximated
# polynomial at a set of points
x_eval = np.linspace(-1, 1, 100)
y_approx =  np.polynomial.chebyshev.chebval(x_eval, chebyshev_coefficients[::-1])

# Plot the original function
# and the approximated function
plt.plot(x, y, 'o',
label='Original function')
plt.plot(x_eval, y_approx, '-',
label='Approximated function')
plt.legend()
plt.show()
</code>```

Body:
I'm trying to interpolate a function at arbitrary points and I have the function values at Chebyshev extreme points. I use the real values from Fast Fourier Transform to compute the Chebyshev coefficients. Then I scale them with 2/N and then I use the polynomial library to evaluate the series of chebyshev polynomials at a set of points. This produces the wrong function approximation. Where am I going wrong?

import numpy as np
import matplotlib.pyplot as plt

# Define the number of
# Chebyshev extreme points
N = 10

# Define the function to be
# approximated
def f(x):
   return x**2

# Evaluate the function at the
# Chebyshev extreme points
x = np.cos(np.arange(N) * np.pi / N)
y = f(x)

# Compute the discrete Fourier
# transform (DFT) of the function
# values using the FFT algorithm
DFT = np.fft.fft(y).real

# Compute the correct scaling
# factor
scaling_factor = 2/N

# Scale the DFT coefficients by
# the correct scaling factor
chebyshev_coefficients = scaling_factor * DFT

# Use Chebval to
# evaluate the approximated
# polynomial at a set of points
x_eval = np.linspace(-1, 1, 100)
y_approx =  np.polynomial.chebyshev.chebval(x_eval, chebyshev_coefficients[::-1])

# Plot the original function
# and the approximated function
plt.plot(x, y, 'o',
label='Original function')
plt.plot(x_eval, y_approx, '-',
label='Approximated function')
plt.legend()
plt.show()


问:
Weird line 1px appearing on 3d spin transition cube CSS
I'm having an issue in chrome with a css3 transform rotate transition. The transition is working fine but just after it finishes the letters P and the letter F show a weird rendering, if you pay attention you will see a strange blurry line.

The bug isn't still there if you remove the transition as well.

You can see it happening here:

svg {
  width: 400px;
  height: 400px;
}
* {
  margin: 0;
  padding: 0;
  background: black;
  box-sizing: border-box;
}
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.container .cube-container {
  perspective: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.container .cube-container .cube {
  transition: transform 2s ease-in;
  transform-style: preserve-3d;
  -webkit-transform: translateZ(0);
  backface-visibility: hidden;
  width: 400px;
  height: 400px;
  margin: 50px 0;
}
.container .cube-container .cube.cube1 {
  animation: horizontal-spin 5s ease-in-out;
}
.container .cube-container .cube.cube2 {
  animation: vertical-spin 5s infinite linear;
}
.container .cube-container .cube .box {
  width: 100%;
  height: 100%;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
}
.container .cube-container .cube .box.front {
  background: #ff66cc;
  transform: translateZ(200px);
}
.container .cube-container .cube .box.box2.front {
  background: #ff66cc;
}
.container .cube-container .cube .box.back {
  background: #ff66cc;
  transform: translateZ(-200px) rotateY(180deg);
}
.container .cube-container .cube .box.box2.back {
  background: #ff66cc;
  transform: translateZ(-200px) rotateX(-180deg);
}
.container .cube-container .cube .box.top {
  background: #ff66cc;
  transform: rotateX(-90deg) translateY(-200px);
  transform-origin: top center;
}
.container .cube-container .cube .box.box2.top {
  background: #ff66cc;
  transform: rotateX(90deg) translateY(-200px);
}
.container .cube-container .cube .box.bottom {
  background: #ff66cc;
  transform: rotateX(90deg) translateY(200px);
  transform-origin: bottom center;
}
.container .cube-container .cube .box.box2.bottom {
  background: #ff66cc;
  transform: rotateX(-90deg) translateY(200px);
}
.container .cube-container .cube .box.left {
  background: #ff66cc;
  transform: rotateY(270deg) translateX(-200px);
  transform-origin: center left;
}
.container .cube-container .cube .box.box2.left {
  background: black;
}
.container .cube-container .cube .box.right {
  background: black;
  transform: rotateY(-270deg) translateX(200px);
  transform-origin: top right;
}
.container .cube-container .cube .box.box2.right {
  background: #c976e0;
}
@keyframes horizontal-spin {
  from {
    transform: rotateY(0);
  }
  to {
    transform: rotateY(360deg);
  }
}
@keyframes vertical-spin {
  from {
    transform: rotateX(0);
  }
  to {
    transform: rotateX(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="cube-container">
    <div class="cube cube1">
      <div class="box box1 front"> <div class="span2"><svg >
    <image xlink:href="https://www.matteogiordano.info/formy-prj.svg"  width="100%" height="100%" />
</svg></div>

</div>
      <div class="box box1 right">

         <div class="span2"><svg >
    <image xlink:href="https://www.matteogiordano.info/formy-f5.svg"  width="100%" height="100%" />
</svg></div>

      </div>

      <div class="box box1 left">

        <div class="span2">
        <?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300">
  <defs>
    <style>
      .cls-1 {
        fill: #ff7dbe;
      }
    </style>
  </defs>
  <rect width="300" height="300"/>
  <path class="cls-1" d="M250.88,106.87c-44.05,0-88.1,0-134.32,0,0,54.83,0,108.97,0,164.45-26.76,0-51.38,0-77.6,0,0-80.21,0-160.06,0-242.46,11.48,0,22.81,0,34.13,0,37.23,.03,74.47-.58,111.67,.28,41.05,.95,72.8,32.95,76.05,75.01,3.04,39.45-25.25,76.79-64.47,83.48-13.14,2.24-26.92,2.76-40.21,1.69-21.03-1.69-35.4-18.51-35.31-38.73,.09-21.35,15.08-37.82,37.21-38.7,24.35-.97,48.77-.32,73.16-.37,6.82-.01,13.21,0,20.03,0-.26-1.55-.08-3.11-.33-4.66Z"/>
</svg>

</div>

      </div>
      <div class="box box1 back">

        <div class="span2"><svg >
    <image xlink:href="https://www.matteogiordano.info/formy-d.svg"  width="100%" height="100%" />
</svg></div>

      </div>

    </div>
    <!--div class="cube cube2">
      <div class="box box2 front">Front</div>
      <div class="box box2 back">Back</div>
      <div class="box box2 top">Top</div>
      <div class="box box2 bottom">Bottom</div>
      <div class="box box2 left">Left</div>
      <div class="box box2 right">Right</div>
    </div>
  </div>
</div></code>```

Body:
I'm having an issue in chrome with a css3 transform rotate transition. The transition is working fine but just after it finishes the letters P and the letter F show a weird rendering, if you pay attention you will see a strange blurry line.

The bug isn't still there if you remove the transition as well.

You can see it happening here:

svg {
  width: 400px;
  height: 400px;
}
* {
  margin: 0;
  padding: 0;
  background: black;
  box-sizing: border-box;
}
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.container .cube-container {
  perspective: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.container .cube-container .cube {
  transition: transform 2s ease-in;
  transform-style: preserve-3d;
  -webkit-transform: translateZ(0);
  backface-visibility: hidden;
  width: 400px;
  height: 400px;
  margin: 50px 0;
}
.container .cube-container .cube.cube1 {
  animation: horizontal-spin 5s ease-in-out;
}
.container .cube-container .cube.cube2 {
  animation: vertical-spin 5s infinite linear;
}
.container .cube-container .cube .box {
  width: 100%;
  height: 100%;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
}
.container .cube-container .cube .box.front {
  background: #ff66cc;
  transform: translateZ(200px);
}
.container .cube-container .cube .box.box2.front {
  background: #ff66cc;
}
.container .cube-container .cube .box.back {
  background: #ff66cc;
  transform: translateZ(-200px) rotateY(180deg);
}
.container .cube-container .cube .box.box2.back {
  background: #ff66cc;
  transform: translateZ(-200px) rotateX(-180deg);
}
.container .cube-container .cube .box.top {
  background: #ff66cc;
  transform: rotateX(-90deg) translateY(-200px);
  transform-origin: top center;
}
.container .cube-container .cube .box.box2.top {
  background: #ff66cc;
  transform: rotateX(90deg) translateY(-200px);
}
.container .cube-container .cube .box.bottom {
  background: #ff66cc;
  transform: rotateX(90deg) translateY(200px);
  transform-origin: bottom center;
}
.container .cube-container .cube .box.box2.bottom {
  background: #ff66cc;
  transform: rotateX(-90deg) translateY(200px);
}
.container .cube-container .cube .box.left {
  background: #ff66cc;
  transform: rotateY(270deg) translateX(-200px);
  transform-origin: center left;
}
.container .cube-container .cube .box.box2.left {
  background: black;
}
.container .cube-container .cube .box.right {
  background: black;
  transform: rotateY(-270deg) translateX(200px);
  transform-origin: top right;
}
.container .cube-container .cube .box.box2.right {
  background: #c976e0;
}
@keyframes horizontal-spin {
  from {
    transform: rotateY(0);
  }
  to {
    transform: rotateY(360deg);
  }
}
@keyframes vertical-spin {
  from {
    transform: rotateX(0);
  }
  to {
    transform: rotateX(360deg);
  }
}

<svg >
    <image xlink:href="https://www.matteogiordano.info/formy-prj.svg"  width="100%" height="100%" />
</svg>

<svg >
    <image xlink:href="https://www.matteogiordano.info/formy-f5.svg"  width="100%" height="100%" />
</svg>

        <?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300">
  <defs>

  </defs>
  <rect width="300" height="300"/>
  <path class="cls-1" d="M250.88,106.87c-44.05,0-88.1,0-134.32,0,0,54.83,0,108.97,0,164.45-26.76,0-51.38,0-77.6,0,0-80.21,0-160.06,0-242.46,11.48,0,22.81,0,34.13,0,37.23,.03,74.47-.58,111.67,.28,41.05,.95,72.8,32.95,76.05,75.01,3.04,39.45-25.25,76.79-64.47,83.48-13.14,2.24-26.92,2.76-40.21,1.69-21.03-1.69-35.4-18.51-35.31-38.73,.09-21.35,15.08-37.82,37.21-38.7,24.35-.97,48.77-.32,73.16-.37,6.82-.01,13.21,0,20.03,0-.26-1.55-.08-3.11-.33-4.66Z"/>
</svg>

<svg >
    <image xlink:href="https://www.matteogiordano.info/formy-d.svg"  width="100%" height="100%" />
</svg>


问:
The http status code of BadRequestKeyError
I recently used postman to test a website and it returns BadRequestKeyError with http status code 500
but its return webpage's title shows

```<code><title>werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this
        server could not understand.
        KeyError: 'user'
        // Werkzeug Debugger</title>
</code>```

so what is its http status code 500 or 400 ?

The http status code of BadRequestKeyError

Body:
I recently used postman to test a website and it returns BadRequestKeyError with http status code 500
but its return webpage's title shows

<title>werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this
        server could not understand.
        KeyError: 'user'
        // Werkzeug Debugger</title>

so what is its http status code 500 or 400 ?

The http status code of BadRequestKeyError


问:
How do I include nested objects from a C# Mongo FindSync statement and exclude certain fields?
The Entities

```<code>using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace HelloWorldApi.Entities;

public class Deck
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = ObjectId.GenerateNewId().ToString();

    public string Name { get; set; } = "";

    public List<string> Cards { get; set; } = new();
}

public class Credentials
{
    public string Username { get; set; } = "";
    public string Password { get; set; } = "";
}

[BsonIgnoreExtraElements]
public class Account {
    public string Status = "";
    public string Type = "";
    public Credentials Credentials = new();
}

[BsonIgnoreExtraElements]
public class Player
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = "";

    public Account Account = new ();

    public List<string> Roles { get; set; } = new ();

    public List<Deck> Decks { get; set; } = new ();

    public List<string> Cards { get; set; } = new ();
}
</code>```

The service:

```<code>public List<Player> GetUsers()
{
  return _players.FindSync<Player>(FilterDefinition<Player>.Empty).ToList();
}
</code>```

Specifically, I want to include the Account.Credentials.Username, but not the password.

Body:
The Entities

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace HelloWorldApi.Entities;

public class Deck
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = ObjectId.GenerateNewId().ToString();

    public string Name { get; set; } = "";

    public List<string> Cards { get; set; } = new();
}

public class Credentials
{
    public string Username { get; set; } = "";
    public string Password { get; set; } = "";
}

[BsonIgnoreExtraElements]
public class Account {
    public string Status = "";
    public string Type = "";
    public Credentials Credentials = new();
}

[BsonIgnoreExtraElements]
public class Player
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = "";

    public Account Account = new ();

    public List<string> Roles { get; set; } = new ();

    public List<Deck> Decks { get; set; } = new ();

    public List<string> Cards { get; set; } = new ();
}

The service:

public List<Player> GetUsers()
{
  return _players.FindSync<Player>(FilterDefinition<Player>.Empty).ToList();
}

Specifically, I want to include the Account.Credentials.Username, but not the password.


问:
How to use Transcribe() in Python Collab to convert runtime audio to text?
I have implemented speech recognition to record runtime audio from a microphone using JAVASCRIPT code in Collab because Pyaudio is causing issues. Now I have to transcribe audio to text in runtime (i.e without saving it into the file). I didn't find any appropriate function for this except Transcribe(). But I do not know How to use this function, passing audio and returning text.

How to use Transcribe function? or is there any other method to transcribe runtime audio to text?


问:
ReactJS hooks How to change calendar language on react-dates?

I need to change the calendar language of the react-dates lib to pt-br. But I didn't find anything about it.

`

```<code>    <S.Container>
      <DateRangePicker
        startDatePlaceholderText="Ida"
        endDatePlaceholderText="Volta"
        showDefaultInputIcon
        orientation={orientation}
        withFullScreenPortal={withFullScreenPortal}
        startDate={startDate}
        startDateId="date-start-date"
        endDate={endDate}
        endDateId="date-end-date"
        onDatesChange={handleDatesChange}
        focusedInput={focusedInput}
        onFocusChange={(focusedInput) => setFocusedInput(focusedInput)}
        numberOfMonths={numberOfMonths}
        displayFormat="DD/MM/YYYY"
        dayAriaLabelFormat="DD/MM/YYYY"
        disabled={!isTwoWays && "endDate"}
        autoFocus={false}
      />
    </S.Container>
</code>```

`

Doc react-dates.github.io

Body:
I need to change the calendar language of the react-dates lib to pt-br. But I didn't find anything about it.

`

    <S.Container>
      <DateRangePicker
        startDatePlaceholderText="Ida"
        endDatePlaceholderText="Volta"
        showDefaultInputIcon
        orientation={orientation}
        withFullScreenPortal={withFullScreenPortal}
        startDate={startDate}
        startDateId="date-start-date"
        endDate={endDate}
        endDateId="date-end-date"
        onDatesChange={handleDatesChange}
        focusedInput={focusedInput}
        onFocusChange={(focusedInput) => setFocusedInput(focusedInput)}
        numberOfMonths={numberOfMonths}
        displayFormat="DD/MM/YYYY"
        dayAriaLabelFormat="DD/MM/YYYY"
        disabled={!isTwoWays && "endDate"}
        autoFocus={false}
      />
    </S.Container>

`

Doc react-dates.github.io


问:
Sending an email to a Gmail account in vue 3 using email-js version 3.2.0
I am trying to send  an email to my Gmail account using email-js latest version in vue 3 composition API but whenever I try to do so I get an error in the console stating that net:err timed out although I configured everything correctly and I am having an internet connection . Below is the code I am using :

```<code>
      <q-dialog class="gt-sm"  v-model="dialog">
        <div align="center">
        <q-card  class="my-card" align="center">
            <q-card style="padding-top:20px;" align="center">
            <p>Place Reservation Order</p>
        <q-form method="post" @submit.prevent="Submit" style="max-width:280px;" align="center">
            <q-input label="Name" id="name" v-model="name">
                <template v-slot:prepend>
                    <q-icon name="person"/>
                </template>
            </q-input>

               <q-input label="Phone number" id="phone" v-model="phone">
                <template v-slot:prepend>
                    <q-icon name="call"/>
                </template>
            </q-input>

               <q-input label="Table number" id="table" v-model="table">
                <template v-slot:prepend>
                    <q-icon name="table"/>
                </template>
            </q-input>

               <q-input label="Food" id="food" v-model="food">
                <template v-slot:prepend>
                    <q-icon name="money"/>
                </template>
            </q-input>

            <q-btn flat color="blue" type="submit" label="Send"></q-btn>

        </q-form>
            </q-card>
        </q-card>
        </div>
      </q-dialog>

  </div>
</template>

<script>
import {ref} from 'vue'
import TastyHeader from '../components/TastyHeader.vue'
import emailjs from 'emailjs-com'
export default {
    components:{
        TastyHeader
    },
    setup(){
        const name =ref('')
        const food = ref('')
        const table =ref('')
        const phone = ref('')

        const Submit=()=>{
              var param = {
                table: table.value,
        phone: phone.value,
        food: food.value,
        name: name.value
              }
        emailjs
        .send('service_disx46e', 'template_3y41wc8',param,'user_1Y8lbGgVXBoY0P8yd')
        .then(
                    (result) => {
                        console.log('SUCCESS!', result.status, result.text)
                    },
                    (error) => {
                        console.log('FAILED...', error)
                    }
                )
      const newTodo = {
        // id:uuidv4(),
        table: table.value,
        phone: phone.value,
        food: food.value,
        name: name.value
      }
       console.log('newTodo:', newTodo)
        }
return{
            Submit,
            table,
            phone,
            food,
           name,
           dialog:ref(false)
        }
    }

</code>```

Sending an email to Gmail account but I am not able to

Body:
I am trying to send  an email to my Gmail account using email-js latest version in vue 3 composition API but whenever I try to do so I get an error in the console stating that net:err timed out although I configured everything correctly and I am having an internet connection . Below is the code I am using :

      <q-dialog class="gt-sm"  v-model="dialog">

        <q-card  class="my-card" align="center">
            <q-card style="padding-top:20px;" align="center">

Place Reservation Order

        <q-form method="post" @submit.prevent="Submit" style="max-width:280px;" align="center">
            <q-input label="Name" id="name" v-model="name">
                <template v-slot:prepend>
                    <q-icon name="person"/>
                </template>
            </q-input>

               <q-input label="Phone number" id="phone" v-model="phone">
                <template v-slot:prepend>
                    <q-icon name="call"/>
                </template>
            </q-input>

               <q-input label="Table number" id="table" v-model="table">
                <template v-slot:prepend>
                    <q-icon name="table"/>
                </template>
            </q-input>

               <q-input label="Food" id="food" v-model="food">
                <template v-slot:prepend>
                    <q-icon name="money"/>
                </template>
            </q-input>

            <q-btn flat color="blue" type="submit" label="Send"></q-btn>

        </q-form>
            </q-card>
        </q-card>

      </q-dialog>

</template>


问:
Multiprocessing default serialisation very slow
I want to build one DataFrame from several CSVs as efficiently as possible. The CSVs are quite big. Most are in excess of 1 million rows. There are 9 files in total. The combined total rows is >8 million.

Here's the code:

```<code>from pandas import read_csv, concat
from concurrent.futures import ProcessPoolExecutor
from glob import glob
from time import perf_counter

PATH = '/Users/fred/Downloads/*.csv'

def process(filename):
    try:
        return read_csv(filename, low_memory=False)
    except Exception as e:
        print(e)

def main():
    start = perf_counter()
    with ProcessPoolExecutor() as ppe:
        concat(rv for rv in ppe.map(process, glob(PATH)) if rv is not None)
    print(f'Duration={perf_counter()-start}s')

if __name__ == '__main__':
    main()
</code>```

This takes ~2 minutes to run and produces the desired result.

However, whilst monitoring the runtime behaviour in terms of CPU and memory usage, I noticed that after a while the spawned processes appear to be idle for an inordinate amount of time.

So I decided to pickle the DataFrames myself to see if performance might be improved. Obviously the code is more complex but I think it's important to show it:

```<code>from pandas import read_csv, concat
from concurrent.futures import ProcessPoolExecutor
from glob import glob
from tempfile import NamedTemporaryFile
from pickle import dump, load
from os import remove
from time import perf_counter

PATH = '/Users/fred/Downloads/*.csv'

def process(filename):
    try:
        df = read_csv(filename, low_memory=False)
        with NamedTemporaryFile(delete=False) as ntf:
            dump(df, ntf)
            return ntf.name
    except Exception as e:
        print(e)

def unpickle(filename):
    if filename is not None:
        try:
            with open(filename, 'rb') as upf:
                return load(upf)
        except Exception as e:
            print(e)
        finally:
            try:
                remove(filename)
            except Exception as e:
                print(e)

def main():
    start = perf_counter()
    with ProcessPoolExecutor() as ppe:
        concat(unpickle(rv) for rv in ppe.map(process, glob(PATH)) if rv is not None)
    print(f'Duration={perf_counter()-start}s')

if __name__ == '__main__':
    main()
</code>```

It seems to me that this more complex code (where I'm taking over the serialisation that Python should be doing for me by default) shouldn't be necessary.

BUT this "manual" approach to serialisation runs in literally half the time.

Can anyone help me understand why the "default" behaviour runs significantly slower than the "manual" approach to serialisation.

In case it's relevant:

```<code>macOS 13.0.1
Python 3.11.1
32GB RAM
3 GHz 10-Core Intel Xeon W
</code>```

Body:
I want to build one DataFrame from several CSVs as efficiently as possible. The CSVs are quite big. Most are in excess of 1 million rows. There are 9 files in total. The combined total rows is >8 million.

Here's the code:

from pandas import read_csv, concat
from concurrent.futures import ProcessPoolExecutor
from glob import glob
from time import perf_counter

PATH = '/Users/fred/Downloads/*.csv'

def process(filename):
    try:
        return read_csv(filename, low_memory=False)
    except Exception as e:
        print(e)

def main():
    start = perf_counter()
    with ProcessPoolExecutor() as ppe:
        concat(rv for rv in ppe.map(process, glob(PATH)) if rv is not None)
    print(f'Duration={perf_counter()-start}s')

if __name__ == '__main__':
    main()

This takes ~2 minutes to run and produces the desired result.

However, whilst monitoring the runtime behaviour in terms of CPU and memory usage, I noticed that after a while the spawned processes appear to be idle for an inordinate amount of time.

So I decided to pickle the DataFrames myself to see if performance might be improved. Obviously the code is more complex but I think it's important to show it:

from pandas import read_csv, concat
from concurrent.futures import ProcessPoolExecutor
from glob import glob
from tempfile import NamedTemporaryFile
from pickle import dump, load
from os import remove
from time import perf_counter

PATH = '/Users/fred/Downloads/*.csv'

def process(filename):
    try:
        df = read_csv(filename, low_memory=False)
        with NamedTemporaryFile(delete=False) as ntf:
            dump(df, ntf)
            return ntf.name
    except Exception as e:
        print(e)

def unpickle(filename):
    if filename is not None:
        try:
            with open(filename, 'rb') as upf:
                return load(upf)
        except Exception as e:
            print(e)
        finally:
            try:
                remove(filename)
            except Exception as e:
                print(e)

def main():
    start = perf_counter()
    with ProcessPoolExecutor() as ppe:
        concat(unpickle(rv) for rv in ppe.map(process, glob(PATH)) if rv is not None)
    print(f'Duration={perf_counter()-start}s')

if __name__ == '__main__':
    main()

It seems to me that this more complex code (where I'm taking over the serialisation that Python should be doing for me by default) shouldn't be necessary.

BUT this "manual" approach to serialisation runs in literally half the time.

Can anyone help me understand why the "default" behaviour runs significantly slower than the "manual" approach to serialisation.

In case it's relevant:

macOS 13.0.1
Python 3.11.1
32GB RAM
3 GHz 10-Core Intel Xeon W


问:
MissingPluginException(No implementation found for method DocumentReference#set on channel plugins.flutter.io/firebase_firestore)
I want to set data to firebase firestore and this error occured.</p>
```<code>  Future _signUp(UserModel user) async {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: MySnackBar(msg: 'Please wait...')));
    late final UserModel f_user;

    try{
      f_user = UserModel(MyEncrypter().encrypt(user.firstName), MyEncrypter().encrypt(user.lastName),
       MyEncrypter().encrypt(user.email), MyEncrypter().encrypt(user.username), MyEncrypter().encrypt(user.password));
      // await FirebaseAuth.instance.createUserWithEmailAndPassword(email: user.email, password: user.password);
      await FirebaseFirestore.instance.collection('Users').doc(f_user.username).set(f_user.toJson());
      Navigator.pushReplacement(context, MaterialPageRoute(builder: ((context) => HomeScreen())));
    }catch(e){
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: MySnackBar(msg: 'Something went wrong! Please try again : ${e}')));
      print(e);
    }

  }
</code>```

Body:
I want to set data to firebase firestore and this error occured.

  Future _signUp(UserModel user) async {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: MySnackBar(msg: 'Please wait...')));
    late final UserModel f_user;

    try{
      f_user = UserModel(MyEncrypter().encrypt(user.firstName), MyEncrypter().encrypt(user.lastName),
       MyEncrypter().encrypt(user.email), MyEncrypter().encrypt(user.username), MyEncrypter().encrypt(user.password));
      // await FirebaseAuth.instance.createUserWithEmailAndPassword(email: user.email, password: user.password);
      await FirebaseFirestore.instance.collection('Users').doc(f_user.username).set(f_user.toJson());
      Navigator.pushReplacement(context, MaterialPageRoute(builder: ((context) => HomeScreen())));
    }catch(e){
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: MySnackBar(msg: 'Something went wrong! Please try again : ${e}')));
      print(e);
    }

  }