问:
Search for specific string format, like 'KB9999999' (7 digit) where '9' is use as a wildcard
I'm learning Powershell.

I found this module so useful:
Get-WindowsUpdate

From Microsoft Powershell
https://www.powershellgallery.com/

And it's working awesome for me! I do recommend it to you, specially if you work Backstage/Remote

Now, I can update all, or manually do 1 update at a time.

My IT Manager wants me to install only those KB (Windows Update) instead the mixed list that module will give you (such as drivers, bios update, etc)

Therefore I need a Powershell command lines for:

Get the result of Get-WindowsUpdate (if you use it 'as is', it will list all pending updates) to a file.

Search the file for the string format 'KB9999999' (7 digit) where '9' or whatever symbol is a wildcard instead, so any present number (only) will do the match.

After find each of them, output it to a unique file.

Then with that unique file do ANOTHER LOOP to install those, like

```<code>--- Loop (ForEach-Object??)
Get-WindowsUpdate -KBArticleID KB9999999 -Install (where KB9999999 is taken from the output file one by one.
--- Loop
</code>```

I hope I made myself clear on the situation.
Thanks for any help ! :)

Here is how it works:

```<code># -------------------------- Install Windows Update via Powershell
# Allow script execution (disabled by default)
Set-ExecutionPolicy unrestricted
# Native Windows module
Install-Module PSWindowsUpdate
# Gallery Windows module
Install-Module -Name PendingReboot
# Find out available Update
Get-WindowsUpdate

Here you get the full list
Examples depending what you will install

# **************** REVIEW UPDATE BEFORE TO CONTINUE  ****************
# ----- Install all possible update. If need to reboot, add -AutoReboot
Get-WindowsUpdate -AcceptAll -Install
# ----- To install 1 by 1 by KD ID (example)
Get-WindowsUpdate -KBArticleID KB5022282 -Install
# ---- or do a bunch of them (example) Get-WindowsUpdate -KBArticleID KB4484527,  KB890830, KB5022546 -Install
# find out if there is any pending reboot
test-pendingreboot
# disable script execution
Set-ExecutionPolicy restricted
</code>```

Body:
I'm learning Powershell.

I found this module so useful:
Get-WindowsUpdate

From Microsoft Powershell
https://www.powershellgallery.com/

And it's working awesome for me! I do recommend it to you, specially if you work Backstage/Remote

Now, I can update all, or manually do 1 update at a time.

My IT Manager wants me to install only those KB (Windows Update) instead the mixed list that module will give you (such as drivers, bios update, etc)

Therefore I need a Powershell command lines for:

Get the result of Get-WindowsUpdate (if you use it 'as is', it will list all pending updates) to a file.

Search the file for the string format 'KB9999999' (7 digit) where '9' or whatever symbol is a wildcard instead, so any present number (only) will do the match.

After find each of them, output it to a unique file.

Then with that unique file do ANOTHER LOOP to install those, like

--- Loop (ForEach-Object??)
Get-WindowsUpdate -KBArticleID KB9999999 -Install (where KB9999999 is taken from the output file one by one.
--- Loop

I hope I made myself clear on the situation.
Thanks for any help ! :)

Here is how it works:

# -------------------------- Install Windows Update via Powershell
# Allow script execution (disabled by default)
Set-ExecutionPolicy unrestricted
# Native Windows module
Install-Module PSWindowsUpdate
# Gallery Windows module
Install-Module -Name PendingReboot
# Find out available Update
Get-WindowsUpdate

Here you get the full list
Examples depending what you will install

# **************** REVIEW UPDATE BEFORE TO CONTINUE  ****************
# ----- Install all possible update. If need to reboot, add -AutoReboot
Get-WindowsUpdate -AcceptAll -Install
# ----- To install 1 by 1 by KD ID (example)
Get-WindowsUpdate -KBArticleID KB5022282 -Install
# ---- or do a bunch of them (example) Get-WindowsUpdate -KBArticleID KB4484527,  KB890830, KB5022546 -Install
# find out if there is any pending reboot
test-pendingreboot
# disable script execution
Set-ExecutionPolicy restricted


来源: stackexchange

问:
Microsoft Access: Group By Function and list out variances
I am looking to use the Group By function in Microsoft Access. I have used it before to sum all the values that are grouped together. However, instead of grouping the data and then having a numerican operation performed on the field I choose, I want it to instead list the different results in one cell.

As an example, consider the simplified data below of people and the cars they own:

Name   Age     Job         Car Make

Will   30   Accountant      Ford

Will   30   Accountant      Honda

Will   30   Accountant      Jeep

Tim    30   Sales VP        Audi

Tim    30   Sales VP        Ford

I want a result that will group the name, the age, and the job together, and then list the different cars in a single cell:

Name   Age     Job         Car(s) Make

Will   30   Accountant      Ford, Honda, Jeep

Tim    30   Sales VP        Audi, Ford

Even a result like this below would work where it lists each car in its own column:

Name   Age     Job         Car Make 1  Car Make 2  Car Make 3

Will   30   Accountant      Ford          Honda       Jeep

Tim    30   Sales VP        Audi          Ford

Bottom line is that I want a single row per person and all the results of a field (Car Make) listed out in the single line as well.

Thanks,

Will

I haven't tried too much yet. I figured there would be a built in way to perform this but the only options are mathmatical operations such as Sum, Avg, First, Last, High, Low, etc. I tried looking on Google for solutions but no websites/articles actually addressed this. They were all simply articles or videos that intro'd how to used the group by function in general.

ContentLicense: CC BY-SA 4.0


问:
Unable to import python package in vs-code but, no issues in terminal
I'm trying to use https://github.com/uber/orbit.  I have the package installed without errors as far as I can see.

I can run everything just fine in my terminal on my mac.  However, I load up vs-code and try and run there and I receive the error below.    I can't figure out what the problem is or how to configure my vs-code to avoid this issue.

This causes the following error.  NO issues in terminal.
from orbit.utils.dataset import load_iclaims
from orbit.models import DLT
from orbit.diagnostics.plot import plot_predicted_data

My python version is 3.9.15 that I am running this in both in terminal and in vs-code.

If anyone has an idea, can you please be specific on steps on how to fix this, as I have been hunting in vscode for a while and can't figure it out why I don't have this issue in terminal, but only in VSCODE

```<code>OperationalError                          Traceback (most recent call last)
Cell In[3], line 1
----> 1 from orbit.models import DLT

File ~/opt/anaconda3/lib/python3.9/site-packages/orbit/__init__.py:3
      1 __all__ = ["satellite", "tle", "utilities"]
----> 3 from .satellite import satellite

File ~/opt/anaconda3/lib/python3.9/site-packages/orbit/satellite.py:3
      1 from math import degrees
----> 3 from . import tle, utilities
      5 class satellite:
      6     def __init__(self,catnr):

File ~/opt/anaconda3/lib/python3.9/site-packages/orbit/tle.py:10
      6 import ephem
      8 from . import utilities
---> 10 requests_cache.install_cache(expire_after=86400)
     12 def get(catnr):
     13     page = html.fromstring(requests.get('http://www.celestrak.com/cgi-bin/TLE.pl?CATNR=%s' % catnr).text)

File ~/opt/anaconda3/lib/python3.9/site-packages/requests_cache/patcher.py:48, in install_cache(cache_name, backend, expire_after, urls_expire_after, allowable_codes, allowable_methods, filter_fn, stale_if_error, session_factory, **kwargs)
     23 def install_cache(
     24     cache_name: str = 'http_cache',
...
--> 168     self._local_context.con = sqlite3.connect(self.db_path, **self.connection_kwargs)
    169     if self.fast_save:
    170         self._local_context.con.execute('PRAGMA synchronous = 0;')

OperationalError: unable to open database file
</code>```

Body:
I'm trying to use https://github.com/uber/orbit.  I have the package installed without errors as far as I can see.

I can run everything just fine in my terminal on my mac.  However, I load up vs-code and try and run there and I receive the error below.    I can't figure out what the problem is or how to configure my vs-code to avoid this issue.

This causes the following error.  NO issues in terminal.
from orbit.utils.dataset import load_iclaims
from orbit.models import DLT
from orbit.diagnostics.plot import plot_predicted_data

My python version is 3.9.15 that I am running this in both in terminal and in vs-code.

If anyone has an idea, can you please be specific on steps on how to fix this, as I have been hunting in vscode for a while and can't figure it out why I don't have this issue in terminal, but only in VSCODE

OperationalError                          Traceback (most recent call last)
Cell In[3], line 1
----> 1 from orbit.models import DLT

File ~/opt/anaconda3/lib/python3.9/site-packages/orbit/__init__.py:3
      1 __all__ = ["satellite", "tle", "utilities"]
----> 3 from .satellite import satellite

File ~/opt/anaconda3/lib/python3.9/site-packages/orbit/satellite.py:3
      1 from math import degrees
----> 3 from . import tle, utilities
      5 class satellite:
      6     def __init__(self,catnr):

File ~/opt/anaconda3/lib/python3.9/site-packages/orbit/tle.py:10
      6 import ephem
      8 from . import utilities
---> 10 requests_cache.install_cache(expire_after=86400)
     12 def get(catnr):
     13     page = html.fromstring(requests.get('http://www.celestrak.com/cgi-bin/TLE.pl?CATNR=%s' % catnr).text)

File ~/opt/anaconda3/lib/python3.9/site-packages/requests_cache/patcher.py:48, in install_cache(cache_name, backend, expire_after, urls_expire_after, allowable_codes, allowable_methods, filter_fn, stale_if_error, session_factory, **kwargs)
     23 def install_cache(
     24     cache_name: str = 'http_cache',
...
--> 168     self._local_context.con = sqlite3.connect(self.db_path, **self.connection_kwargs)
    169     if self.fast_save:
    170         self._local_context.con.execute('PRAGMA synchronous = 0;')

OperationalError: unable to open database file


问:
Using v4l2sink with DeepStream
I'm working on deepstream code to pass rtsp streams to virtual V4L2 devices (I used v4l2loopback to create the virtual devices). I have a code that works without errors, however, I can't read the V4L2 device.

Does anyone know of a working DeepStream code where v4l2sink is used? I have tried to find an example without success.

Here is my code. The writing part to v4l2sink is in the function: create_v4l2sink_branch()

```<code>import sys
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
import math
import sys
import common.utils as DS_UTILS
import pyds
from common.bus_call import bus_call
from common.FPS import PERF_DATA
from common.is_aarch_64 import is_aarch64
from gi.repository import GLib, Gst, GstRtspServer

CODEC="H264"
BITRATE=4000000
MAX_DISPLAY_LEN = 64
MUXER_OUTPUT_WIDTH = 1920
MUXER_OUTPUT_HEIGHT = 1080
MUXER_BATCH_TIMEOUT_USEC = 400000
TILED_OUTPUT_WIDTH = 1920
TILED_OUTPUT_HEIGHT = 1080
GST_CAPS_FEATURES_NVMM = "memory:NVMM"
OSD_PROCESS_MODE = 0
OSD_DISPLAY_TEXT = 1
MUX_SYNC_INPUTS = 0

ds_loop=None
perf_data = None

def terminate_pipeline(u_data):
    global ds_loop
    pass
    # if global_config.request_to_stop == True:
    #     print("Aborting pipeline by request")
    #     ds_loop.quit()
    #     return False
    return True

def create_onscreen_branch(pipeline, gst_elem, index):
    print("Creating EGLSink")
    sink = DS_UTILS.create_gst_element("nveglglessink", f"nvvideo-renderer-{index}")
    sink.set_property('sync', 0)
    sink.set_property('async', 1)
    pipeline.add(sink)

    if is_aarch64():
        transform = DS_UTILS.create_gst_element("nvegltransform", f"nvegl-transform{index}")
        pipeline.add(transform)
        gst_elem.link(transform)
        transform.link(sink)
    else:
        gst_elem.link(sink)
    sink.set_property("qos", 0)

def create_v4l2sink_branch(pipeline, gst_elem, index, output_video_device):
    # Create a caps filter
    caps = DS_UTILS.create_gst_element("capsfilter", f"filter-{index}")
    #caps.set_property("caps", Gst.Caps.from_string("video/x-raw(memory:NVMM), format=I420"))
    #caps.set_property("caps", Gst.Caps.from_string("video/x-raw(memory:NVMM), format=NV12"))

    identity = DS_UTILS.create_gst_element("identity", f"identity-{index}")
    identity.set_property("drop-allocation", 1)

    nvvidconv = DS_UTILS.create_gst_element("nvvideoconvert", f"convertor-{index}")

    sink = DS_UTILS.create_gst_element("v4l2sink", f"v4l2sink-{index}")
    sink.set_property('device', output_video_device)
    sink.set_property("sync", 0)
    sink.set_property("async", 1)

    pipeline.add(caps)
    pipeline.add(nvvidconv)
    pipeline.add(identity)
    pipeline.add(sink)

    gst_elem.link(caps)
    caps.link(nvvidconv)
    nvvidconv.link(identity)
    identity.link(sink)

def run_pipeline(rtsp_v4l2_pairs):
    # Check input arguments
    number_sources = len(rtsp_v4l2_pairs)
    perf_data = PERF_DATA(number_sources)

    # Standard GStreamer initialization
    Gst.init(None)

    # Create gstreamer elements */
    # Create Pipeline element that will form a connection of other elements
    print("Creating Pipeline")
    pipeline = Gst.Pipeline()
    is_live = False
    if not pipeline:
        sys.stderr.write(" Unable to create Pipeline \n")
        return

    # Create nvstreammux instance to form batches from one or more sources.
    streammux = DS_UTILS.create_gst_element("nvstreammux", "Stream-muxer")
    pipeline.add(streammux)
    for i in range(number_sources):
        uri_name = rtsp_v4l2_pairs[i][0]
        print("  Creating source_bin {} --> {}".format(i, uri_name))
        is_live = uri_name.find("rtsp://") == 0
        source_bin = DS_UTILS.create_source_bin(i, uri_name)

        pipeline.add(source_bin)
        padname = "sink_%u" % i
        sinkpad = streammux.get_request_pad(padname)
        if not sinkpad:
            sys.stderr.write("Unable to create sink pad bin \n")
        srcpad = source_bin.get_static_pad("src")
        if not srcpad:
            sys.stderr.write("Unable to create src pad bin \n")
        srcpad.link(sinkpad)

    # streammux setup
    if is_live:
        print("  At least one of the sources is live")
        streammux.set_property('live-source', 1)
    streammux.set_property('width', MUXER_OUTPUT_WIDTH)
    streammux.set_property('height', MUXER_OUTPUT_HEIGHT)
    streammux.set_property('batch-size', number_sources)
    streammux.set_property("batched-push-timeout", MUXER_BATCH_TIMEOUT_USEC)
    #streammux.set_property("sync-inputs", MUX_SYNC_INPUTS)

    queue = DS_UTILS.create_gst_element("queue", "queue1")
    pipeline.add(queue)
    nvstreamdemux = DS_UTILS.create_gst_element("nvstreamdemux", "nvstreamdemux")
    pipeline.add(nvstreamdemux)

    # linking
    streammux.link(queue)
    queue.link(nvstreamdemux)

    for i in range(number_sources):
        queue = DS_UTILS.create_gst_element("queue", f"queue{2+i}")
        pipeline.add(queue)

        demuxsrcpad = nvstreamdemux.get_request_pad(f"src_{i}")
        if not demuxsrcpad:
            sys.stderr.write("Unable to create demux src pad \n")

        queuesinkpad = queue.get_static_pad("sink")
        if not queuesinkpad:
            sys.stderr.write("Unable to create queue sink pad \n")
        demuxsrcpad.link(queuesinkpad)

        #create_onscreen_branch(pipeline=pipeline, gst_elem=queue, index=i)
        create_v4l2sink_branch(pipeline=pipeline, gst_elem=queue, index=i, output_video_device=rtsp_v4l2_pairs[i][1])

    # for termate the pipeline
    GLib.timeout_add_seconds(1, terminate_pipeline, 0)
    # display FPS
    GLib.timeout_add(5000, perf_data.perf_print_callback)

    # create an event loop and feed gstreamer bus mesages to it
    loop = GLib.MainLoop()
    ds_loop = loop
    bus = pipeline.get_bus()
    bus.add_signal_watch()
    bus.connect("message", bus_call, loop)

    print("Starting pipeline")
    # start play back and listed to events
    pipeline.set_state(Gst.State.PLAYING)
    try:
        loop.run()
    except:
        pass
    # cleanup
    print("Pipeline ended")
    pipeline.set_state(Gst.State.NULL)

if __name__ == '__main__':
    import json
    import sys

    pairs = [
        ("rtsp://192.168.1.88:554/22", "/dev/video6")
    ]

    run_pipeline(rtsp_v4l2_pairs=pairs)
</code>```

Title: Using v4l2sink with DeepStream

Body:
I'm working on deepstream code to pass rtsp streams to virtual V4L2 devices (I used v4l2loopback to create the virtual devices). I have a code that works without errors, however, I can't read the V4L2 device.

Does anyone know of a working DeepStream code where v4l2sink is used? I have tried to find an example without success.

Here is my code. The writing part to v4l2sink is in the function: create_v4l2sink_branch()

import sys
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
import math
import sys
import common.utils as DS_UTILS
import pyds
from common.bus_call import bus_call
from common.FPS import PERF_DATA
from common.is_aarch_64 import is_aarch64
from gi.repository import GLib, Gst, GstRtspServer

CODEC="H264"
BITRATE=4000000
MAX_DISPLAY_LEN = 64
MUXER_OUTPUT_WIDTH = 1920
MUXER_OUTPUT_HEIGHT = 1080
MUXER_BATCH_TIMEOUT_USEC = 400000
TILED_OUTPUT_WIDTH = 1920
TILED_OUTPUT_HEIGHT = 1080
GST_CAPS_FEATURES_NVMM = "memory:NVMM"
OSD_PROCESS_MODE = 0
OSD_DISPLAY_TEXT = 1
MUX_SYNC_INPUTS = 0

ds_loop=None
perf_data = None

def terminate_pipeline(u_data):
    global ds_loop
    pass
    # if global_config.request_to_stop == True:
    #     print("Aborting pipeline by request")
    #     ds_loop.quit()
    #     return False
    return True

def create_onscreen_branch(pipeline, gst_elem, index):
    print("Creating EGLSink")
    sink = DS_UTILS.create_gst_element("nveglglessink", f"nvvideo-renderer-{index}")
    sink.set_property('sync', 0)
    sink.set_property('async', 1)
    pipeline.add(sink)

    if is_aarch64():
        transform = DS_UTILS.create_gst_element("nvegltransform", f"nvegl-transform{index}")
        pipeline.add(transform)
        gst_elem.link(transform)
        transform.link(sink)
    else:
        gst_elem.link(sink)
    sink.set_property("qos", 0)

def create_v4l2sink_branch(pipeline, gst_elem, index, output_video_device):
    # Create a caps filter
    caps = DS_UTILS.create_gst_element("capsfilter", f"filter-{index}")
    #caps.set_property("caps", Gst.Caps.from_string("video/x-raw(memory:NVMM), format=I420"))
    #caps.set_property("caps", Gst.Caps.from_string("video/x-raw(memory:NVMM), format=NV12"))

    identity = DS_UTILS.create_gst_element("identity", f"identity-{index}")
    identity.set_property("drop-allocation", 1)

    nvvidconv = DS_UTILS.create_gst_element("nvvideoconvert", f"convertor-{index}")

    sink = DS_UTILS.create_gst_element("v4l2sink", f"v4l2sink-{index}")
    sink.set_property('device', output_video_device)
    sink.set_property("sync", 0)
    sink.set_property("async", 1)

    pipeline.add(caps)
    pipeline.add(nvvidconv)
    pipeline.add(identity)
    pipeline.add(sink)

    gst_elem.link(caps)
    caps.link(nvvidconv)
    nvvidconv.link(identity)
    identity.link(sink)

def run_pipeline(rtsp_v4l2_pairs):
    # Check input arguments
    number_sources = len(rtsp_v4l2_pairs)
    perf_data = PERF_DATA(number_sources)

    # Standard GStreamer initialization
    Gst.init(None)

    # Create gstreamer elements */
    # Create Pipeline element that will form a connection of other elements
    print("Creating Pipeline")
    pipeline = Gst.Pipeline()
    is_live = False
    if not pipeline:
        sys.stderr.write(" Unable to create Pipeline \n")
        return

    # Create nvstreammux instance to form batches from one or more sources.
    streammux = DS_UTILS.create_gst_element("nvstreammux", "Stream-muxer")
    pipeline.add(streammux)
    for i in range(number_sources):
        uri_name = rtsp_v4l2_pairs[i][0]
        print("  Creating source_bin {} --> {}".format(i, uri_name))
        is_live = uri_name.find("rtsp://") == 0
        source_bin = DS_UTILS.create_source_bin(i, uri_name)

        pipeline.add(source_bin)
        padname = "sink_%u" % i
        sinkpad = streammux.get_request_pad(padname)
        if not sinkpad:
            sys.stderr.write("Unable to create sink pad bin \n")
        srcpad = source_bin.get_static_pad("src")
        if not srcpad:
            sys.stderr.write("Unable to create src pad bin \n")
        srcpad.link(sinkpad)

    # streammux setup
    if is_live:
        print("  At least one of the sources is live")
        streammux.set_property('live-source', 1)
    streammux.set_property('width', MUXER_OUTPUT_WIDTH)
    streammux.set_property('height', MUXER_OUTPUT_HEIGHT)
    streammux.set_property('batch-size', number_sources)
    streammux.set_property("batched-push-timeout", MUXER_BATCH_TIMEOUT_USEC)
    #streammux.set_property("sync-inputs", MUX_SYNC_INPUTS)

    queue = DS_UTILS.create_gst_element("queue", "queue1")
    pipeline.add(queue)
    nvstreamdemux = DS_UTILS.create_gst_element("nvstreamdemux", "nvstreamdemux")
    pipeline.add(nvstreamdemux)

    # linking
    streammux.link(queue)
    queue.link(nvstreamdemux)

    for i in range(number_sources):
        queue = DS_UTILS.create_gst_element("queue", f"queue{2+i}")
        pipeline.add(queue)

        demuxsrcpad = nvstreamdemux.get_request_pad(f"src_{i}")
        if not demuxsrcpad:
            sys.stderr.write("Unable to create demux src pad \n")

        queuesinkpad = queue.get_static_pad("sink")
        if not queuesinkpad:
            sys.stderr.write("Unable to create queue sink pad \n")
        demuxsrcpad.link(queuesinkpad)

        #create_onscreen_branch(pipeline=pipeline, gst_elem=queue, index=i)
        create_v4l2sink_branch(pipeline=pipeline, gst_elem=queue, index=i, output_video_device=rtsp_v4l2_pairs[i][1])

    # for termate the pipeline
    GLib.timeout_add_seconds(1, terminate_pipeline, 0)
    # display FPS
    GLib.timeout_add(5000, perf_data.perf_print_callback)

    # create an event loop and feed gstreamer bus mesages to it
    loop = GLib.MainLoop()
    ds_loop = loop
    bus = pipeline.get_bus()
    bus.add_signal_watch()
    bus.connect("message", bus_call, loop)

    print("Starting pipeline")
    # start play back and listed to events
    pipeline.set_state(Gst.State.PLAYING)
    try:
        loop.run()
    except:
        pass
    # cleanup
    print("Pipeline ended")
    pipeline.set_state(Gst.State.NULL)

if __name__ == '__main__':
    import json
    import sys

    pairs = [
        ("rtsp://192.168.1.88:554/22", "/dev/video6")
    ]

    run_pipeline(rtsp_v4l2_pairs=pairs)


问:
Target CSS class using nested declaration but only using a partial matcher for the Classes on the elements
Trying to style a JS chart.  The Chart generates an ID value every time it loads so I have to target it using a partial match like this:

```<code>path[class^='fillSelection-upset-'] {...}
</code>```

which works great.  However I need to target the text element that comes right after that path element (siblings) and change the text to white when it is hovered over

What I have tried is

```<code>path[class^='fillSelection-upset-'] ~ text[class^='valueTextStyle-upset-']
</code>```

and

```<code>path[class^='fillSelection-upset-'] + text[class^='valueTextStyle-upset-']
</code>```

But neither of those target the element.

Body:
Trying to style a JS chart.  The Chart generates an ID value every time it loads so I have to target it using a partial match like this:

path[class^='fillSelection-upset-'] {...}

which works great.  However I need to target the text element that comes right after that path element (siblings) and change the text to white when it is hovered over

What I have tried is

path[class^='fillSelection-upset-'] ~ text[class^='valueTextStyle-upset-']

and

path[class^='fillSelection-upset-'] + text[class^='valueTextStyle-upset-']

But neither of those target the element.


问:
Power Shell Stop IIS Website and Application pool
I'm trying to update a dotnet 6 web site hosted with IIS by copying new files into the folder so my steps are as follows

Stop the IIS web site

```<code>$site = $manager.Sites["MySite"]
 if ($site.State -ne "Stopped") {
         $site.Stop()
}

</code>```

I'm waiting for the site to stop

while ($site.State -ne "Stopped") { "waiting 1 second for site to stop..." Start-Sleep -s 1 }

I'm checking if the files are locked

Here is my issue Its stays locked until I stop the Application
Pool manually

Body:
I'm trying to update a dotnet 6 web site hosted with IIS by copying new files into the folder so my steps are as follows

Stop the IIS web site

$site = $manager.Sites["MySite"]
 if ($site.State -ne "Stopped") {
         $site.Stop()
}

I'm waiting for the site to stop

while ($site.State -ne "Stopped") { "waiting 1 second for site to stop..." Start-Sleep -s 1 }

I'm checking if the files are locked

Here is my issue Its stays locked until I stop the Application
Pool manually


问:
React passing data from generated pages to other components
I am creating pages dynamically per product id and I am able to access the data via pageContext within each page. The product pages are generating correctly with the data expected, however I am struggling with the logic of passing the data to other components eg the shopping cart. How do I pass the data across?

gatsby-node.js

```<code>    const products = require('./src/helpers/product.json');

    products.forEach(product => {
      createPage({
      path: `/product/${product.productCode}/`,
      component : require.resolve('./src/templates/product.js'),
      context : {
        title: product.title,
        description: product.description,
        image: product.image,
        price: product.price,
        productCode: product.productCode,
      }
    })
    })
</code>```

The Products page has various components such as QuickView of the item, MiniCartView, add to Cart- all of which I would like to share the product data across the components.

Product.js (reduced code snippet)

```<code>const Product = ({ pageContext }) => {

const ctxAddItemNotification = useContext(AddItemNotificationContext);
const showNotification = ctxAddItemNotification.showNotification;

return (
   <Layout>
       <div className={styles.root}>
           <Container size={'large'} spacing={'min'}>
               <Breadcrumbs
                   crumbs={[
                       { link: '/', label: 'Home' },
                       { label: `${pageContext.name}` },
                   ]}
               />
               <div className={styles.content}>
                   <div className={styles.gallery}>
                       <Gallery images={pageContext.gallery} />
                   </div>
                   <div className={styles.details}>
                       <h1>{pageContext.name}</h1>

                       <div className={styles.actionContainer}>
                           <div className={styles.addToButtonContainer}>
                               <Button
                                   onClick={() => { showNotification() }}
                                   fullWidth
                                   level={'primary'}
                                   setProductID={setProductID}>
                                   Add to Bag
                               </Button>
                           </div>

                       </div>
                   </div>
}
</code>```

I am using a template and trying to add functionality but unable to work out how to pass data through to the other components. The miniCart component has hardcoded mock data but I want to pass in the data per product which was retrieved from the json file.

MiniCart.js

```<code>const MiniCart = ({props}) => {

  const sampleCartItem = {
    image: '',
    alt: '',
    name: 'name',
    price: 220,
    color: 'Anthracite Melange',
    size: 'xs',
  };

  return (
    <div className={styles.root}>
      <div className={styles.titleContainer}>
        <h4>My Bag</h4>
      </div>
    </div>
....
</code>```

The <MiniCart> reference is within another component (header.js). Levels above the Product.js, therefore I was unable to use  to pass the selected product's data across.

header.js

```<code>   <Drawer visible={showMiniCart} close={() => setShowMiniCart(false)}>
        <MiniCart />
      </Drawer>
</code>```

If anyone is able to help I would greatly appreciate :)

Body:
I am creating pages dynamically per product id and I am able to access the data via pageContext within each page. The product pages are generating correctly with the data expected, however I am struggling with the logic of passing the data to other components eg the shopping cart. How do I pass the data across?

gatsby-node.js

    const products = require('./src/helpers/product.json');

    products.forEach(product => {
      createPage({
      path: `/product/${product.productCode}/`,
      component : require.resolve('./src/templates/product.js'),
      context : {
        title: product.title,
        description: product.description,
        image: product.image,
        price: product.price,
        productCode: product.productCode,
      }
    })
    })

The Products page has various components such as QuickView of the item, MiniCartView, add to Cart- all of which I would like to share the product data across the components.

Product.js (reduced code snippet)

const Product = ({ pageContext }) => {

const ctxAddItemNotification = useContext(AddItemNotificationContext);
const showNotification = ctxAddItemNotification.showNotification;

return (
   <Layout>

           <Container size={'large'} spacing={'min'}>
               <Breadcrumbs
                   crumbs={[
                       { link: '/', label: 'Home' },
                       { label: `${pageContext.name}` },
                   ]}
               />

                       <Gallery images={pageContext.gallery} />

{pageContext.name}

                               <Button
                                   onClick={() => { showNotification() }}
                                   fullWidth
                                   level={'primary'}
                                   setProductID={setProductID}>
                                   Add to Bag
                               </Button>

}

I am using a template and trying to add functionality but unable to work out how to pass data through to the other components. The miniCart component has hardcoded mock data but I want to pass in the data per product which was retrieved from the json file.

MiniCart.js

const MiniCart = ({props}) => {

  const sampleCartItem = {
    image: '',
    alt: '',
    name: 'name',
    price: 220,
    color: 'Anthracite Melange',
    size: 'xs',
  };

  return (

My Bag

....

The <MiniCart> reference is within another component (header.js). Levels above the Product.js, therefore I was unable to use  to pass the selected product's data across.

header.js

   <Drawer visible={showMiniCart} close={() => setShowMiniCart(false)}>
        <MiniCart />
      </Drawer>

If anyone is able to help I would greatly appreciate :)


问:
Deadlock in SQL
I have multiple python scripts that run in parallel and insert/update 2 tables.

```<code>Table 1: Nmap_Scans_Hosts
Table 2: Nmap_Scans_Ports
</code>```

Both these tables have no PK, only a FK referencing a 3rd table Nmap_Scans.

When the scripts run, I get a deadlock on the tables. The scripts use pymssql and cursors for inserting/updating data.

The statements the scripts run are the following:

```<code>update lan.nmap_scans set latest = 0 where latest = 1 and target = '{target}'

INSERT INTO nvlanteam.LAN.Nmap_Scans

UPDATE nvlanteam.LAN.Nmap_Scans_Hosts SET Latest = 0 WHERE Host_Address = '{host_address}' and Tags = '{args.tags}'

INSERT INTO nvlanteam.LAN.Nmap_Scans_Hosts

UPDATE nvlanteam.LAN.Nmap_Scans_Ports SET Latest = 0 WHERE Host_Address = '{host_address}' AND Port is NULL

INSERT INTO nvlanteam.LAN.Nmap_Scans_Ports

update nvlanteam.lan.Nmap_Scans_Ports set Latest = 0 where Host_Address = '{host_address}' and Port = '{port_number}'

INSERT INTO nvlanteam.LAN.Nmap_Scans_Ports
</code>```

The first 2 statements are only run once per script, while the other 6 are run in a loop for each ip address.

I tried setting pymssql's autocommit = True option but deadlocks still occur. Snapshot isolation is also enabled at database level.

Is there anything inherently wrong with my design? Or is there an option that I could enable that would prevent these deadlocks from occuring? Also, I know SQL Server kills one of the 2 deadlocked processes, but in my case, deadlocks are not resolved by SQL Server until I kill one of the Python processes.

Edit:
Included the DDL for the tables used.

```<code>CREATE TABLE nvlanteam.LAN.Nmap_Scans (
    Target varchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Hosts_Total int NULL,
    Hosts_Up int NULL,
    Scan_ID int IDENTITY(0,1) NOT NULL,
    Scan_Server varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Scan_Command varchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Scan_Start datetime NULL,
    Scan_Finish datetime NULL,
    Elapsed int NULL,
    Latest bit NULL,
    Tags varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    CONSTRAINT Nmap_Scans_PK PRIMARY KEY (Scan_ID)
);

CREATE TABLE nvlanteam.LAN.Nmap_Scans_Hosts (
    Scan_ID int NOT NULL,
    Host_Address varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Host_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Region varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Country varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Location varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Division varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Subnet_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    CIDR varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Reason varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    RTT float NULL,
    Latest bit NULL,
    Tags varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
);

-- nvlanteam.LAN.Nmap_Scans_Hosts foreign keys

ALTER TABLE nvlanteam.LAN.Nmap_Scans_Hosts ADD CONSTRAINT Nmap_Scans_Hosts_FK FOREIGN KEY (Scan_ID) REFERENCES nvlanteam.LAN.Nmap_Scans(Scan_ID) ON DELETE CASCADE ON UPDATE CASCADE;

CREATE TABLE nvlanteam.LAN.Nmap_Scans_Ports (
    Scan_ID int NULL,
    Host_Address varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Port int NULL,
    Protocol varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    State varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Reason varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Reason_TTL int NULL,
    Service_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Service_Product varchar(500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Service_Version varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Service_Extra_Info varchar(1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Device_Type varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Latest bit NULL
);

-- nvlanteam.LAN.Nmap_Scans_Ports foreign keys

ALTER TABLE nvlanteam.LAN.Nmap_Scans_Ports ADD CONSTRAINT Nmap_Scans_Ports_FK FOREIGN KEY (Scan_ID) REFERENCES nvlanteam.LAN.Nmap_Scans(Scan_ID) ON DELETE CASCADE ON UPDATE CASCADE;
</code>```

Title: Deadlock in SQL

Body:
I have multiple python scripts that run in parallel and insert/update 2 tables.

Table 1: Nmap_Scans_Hosts
Table 2: Nmap_Scans_Ports

Both these tables have no PK, only a FK referencing a 3rd table Nmap_Scans.

When the scripts run, I get a deadlock on the tables. The scripts use pymssql and cursors for inserting/updating data.

The statements the scripts run are the following:

update lan.nmap_scans set latest = 0 where latest = 1 and target = '{target}'

INSERT INTO nvlanteam.LAN.Nmap_Scans

UPDATE nvlanteam.LAN.Nmap_Scans_Hosts SET Latest = 0 WHERE Host_Address = '{host_address}' and Tags = '{args.tags}'

INSERT INTO nvlanteam.LAN.Nmap_Scans_Hosts

UPDATE nvlanteam.LAN.Nmap_Scans_Ports SET Latest = 0 WHERE Host_Address = '{host_address}' AND Port is NULL

INSERT INTO nvlanteam.LAN.Nmap_Scans_Ports

update nvlanteam.lan.Nmap_Scans_Ports set Latest = 0 where Host_Address = '{host_address}' and Port = '{port_number}'

INSERT INTO nvlanteam.LAN.Nmap_Scans_Ports

The first 2 statements are only run once per script, while the other 6 are run in a loop for each ip address.

I tried setting pymssql's autocommit = True option but deadlocks still occur. Snapshot isolation is also enabled at database level.

Is there anything inherently wrong with my design? Or is there an option that I could enable that would prevent these deadlocks from occuring? Also, I know SQL Server kills one of the 2 deadlocked processes, but in my case, deadlocks are not resolved by SQL Server until I kill one of the Python processes.

Edit:
Included the DDL for the tables used.

CREATE TABLE nvlanteam.LAN.Nmap_Scans (
    Target varchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Hosts_Total int NULL,
    Hosts_Up int NULL,
    Scan_ID int IDENTITY(0,1) NOT NULL,
    Scan_Server varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Scan_Command varchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Scan_Start datetime NULL,
    Scan_Finish datetime NULL,
    Elapsed int NULL,
    Latest bit NULL,
    Tags varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    CONSTRAINT Nmap_Scans_PK PRIMARY KEY (Scan_ID)
);

CREATE TABLE nvlanteam.LAN.Nmap_Scans_Hosts (
    Scan_ID int NOT NULL,
    Host_Address varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Host_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Region varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Country varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Location varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Division varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Subnet_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    CIDR varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Reason varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    RTT float NULL,
    Latest bit NULL,
    Tags varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
);

-- nvlanteam.LAN.Nmap_Scans_Hosts foreign keys

ALTER TABLE nvlanteam.LAN.Nmap_Scans_Hosts ADD CONSTRAINT Nmap_Scans_Hosts_FK FOREIGN KEY (Scan_ID) REFERENCES nvlanteam.LAN.Nmap_Scans(Scan_ID) ON DELETE CASCADE ON UPDATE CASCADE;

CREATE TABLE nvlanteam.LAN.Nmap_Scans_Ports (
    Scan_ID int NULL,
    Host_Address varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Port int NULL,
    Protocol varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    State varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Reason varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Reason_TTL int NULL,
    Service_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Service_Product varchar(500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Service_Version varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Service_Extra_Info varchar(1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Device_Type varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Latest bit NULL
);

-- nvlanteam.LAN.Nmap_Scans_Ports foreign keys

ALTER TABLE nvlanteam.LAN.Nmap_Scans_Ports ADD CONSTRAINT Nmap_Scans_Ports_FK FOREIGN KEY (Scan_ID) REFERENCES nvlanteam.LAN.Nmap_Scans(Scan_ID) ON DELETE CASCADE ON UPDATE CASCADE;


问:
Rotating rectangle with collisions
So currently im making a game in raylib library in C

I was expecting to rotate the rectangle but what really did happen the rectangle was being rotated using rectanglepro function but collision werent defined on it so it failed.

im using the following code but it doesnt work

```<code>RotatedVector = Vector2Rotate(Vector2Normalize(Center),angle*DEG2RAD);
</code>```

Where as Vector2Rotate is function of raymath.h defined as:

```<code>
RMAPI Vector2 Vector2Rotate(Vector2 v, float angle)
{
    Vector2 result = { 0 };

    float cosres = cosf(angle);

    float sinres = sinf(angle);

    result.x = v.x*cosres - v.y*sinres;
    result.y = v.x*sinres + v.y*cosres;

    return result;
}

</code>```

Vector2Normalize is defined as

```<code>RMAPI Vector2 Vector2Normalize(Vector2 v)
{
    Vector2 result = { 0 };
    float length = sqrtf((v.x*v.x) + (v.y*v.y));

    if (length > 0)
    {
        float ilength = 1.0f/length;
        result.x = v.x*ilength;
        result.y = v.y*ilength;
    }

    return result;
}

</code>```

Title: Rotating rectangle with collisions

Body:
So currently im making a game in raylib library in C

I was expecting to rotate the rectangle but what really did happen the rectangle was being rotated using rectanglepro function but collision werent defined on it so it failed.

im using the following code but it doesnt work

RotatedVector = Vector2Rotate(Vector2Normalize(Center),angle*DEG2RAD);

Where as Vector2Rotate is function of raymath.h defined as:

RMAPI Vector2 Vector2Rotate(Vector2 v, float angle)
{
    Vector2 result = { 0 };

    float cosres = cosf(angle);

    float sinres = sinf(angle);

    result.x = v.x*cosres - v.y*sinres;
    result.y = v.x*sinres + v.y*cosres;

    return result;
}

Vector2Normalize is defined as

RMAPI Vector2 Vector2Normalize(Vector2 v)
{
    Vector2 result = { 0 };
    float length = sqrtf((v.x*v.x) + (v.y*v.y));

    if (length > 0)
    {
        float ilength = 1.0f/length;
        result.x = v.x*ilength;
        result.y = v.y*ilength;
    }

    return result;
}


问:
How to filter test based on tags using Junit 5?
I want to filter tests from different packages based on environment using a command line argument.

Below test case is referring the development environment

```<code>-package A
  class TestCase
  @Test1
  public void scenario(){
  }
</code>```

Below test case referring to UAT environment

```<code>-package B
 class TestCase2
  @Test1
  public void scenario1(){
  }
</code>```

I am trying to filter test cases using the environment. I am using Gradle and passing commands like the below:

```<code>./gradlew Pargs="Test1",ENV=dev
</code>```

Body:
I want to filter tests from different packages based on environment using a command line argument.

Below test case is referring the development environment

-package A
  class TestCase
  @Test1
  public void scenario(){
  }

Below test case referring to UAT environment

-package B
 class TestCase2
  @Test1
  public void scenario1(){
  }

I am trying to filter test cases using the environment. I am using Gradle and passing commands like the below:

./gradlew Pargs="Test1",ENV=dev


问:
Spring reactive connection prematurely closed BEFORE response reactor netty WebClient HttpClient
WebClient configuration (minimized reproducible use case, tested with different durations, no effect):

```<code>    public WebClient createWebClient() {
        ConnectionProvider provider = ConnectionProvider.builder("WebClientProvider")
                .maxConnections(2)
                .maxIdleTime(Duration.ofSeconds(10))
                .maxLifeTime(Duration.ofSeconds(20))
                .pendingAcquireTimeout(Duration.ofSeconds(10))
                .evictInBackground(Duration.ofSeconds(10))
                .build();

        HttpClient httpClient = HttpClient.create(provider).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);

        ReactorClientHttpConnector reactorClientHttpConnector = new ReactorClientHttpConnector(httpClient);

        return WebClient.builder()
            .clientConnector(reactorClientHttpConnector)
            .build();
    }
</code>```

Usage of the client, as a GET to a public cloud service provider:

```<code>    public Flux<SomeClass> doGetSomething() {
        return webClient.get()
                .uri(buildUri())
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(byte[].class)
                .flatMapMany(byteArray -> Flux.fromArray(byteArrayToModel(byteArray, SomeClass[].class)))
                .onErrorResume(e -> {
                    return Flux.error(new RuntimeException("Failed to call get", e));
                });
    }
</code>```

Exception:

```<code>org.springframework.web.reactive.function.client.WebClientRequestException: Connection prematurely closed BEFORE response; nested exception is reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
    at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141)
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Assembly trace from producer [reactor.core.publisher.MonoLift] :
    reactor.core.publisher.Mono.error(Mono.java:330)
    org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.wrapException(ExchangeFunctions.java:141)
Error has been observed at the following site(s):
    *__________Mono.error ⇢ at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.wrapException(ExchangeFunctions.java:141)
    *__Mono.onErrorResume ⇢ at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.exchange(ExchangeFunctions.java:106)
    |_           Mono.map ⇢ at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.exchange(ExchangeFunctions.java:107)
    *________Mono.flatMap ⇢ at org.springframework.web.reactive.function.client.ExchangeFilterFunction.lambda$ofResponseProcessor$4(ExchangeFilterFunction.java:96)
    *________Mono.flatMap ⇢ at org.springframework.web.reactive.function.client.ExchangeFilterFunction.lambda$ofRequestProcessor$3(ExchangeFilterFunction.java:85)
    |_         checkpoint ⇢ Request to GET https://***********************.com/someendpoint*********************** [DefaultWebClient]
    |_ Mono.switchIfEmpty ⇢ at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.lambda$exchange$7(DefaultWebClient.java:433)
    *__________Mono.defer ⇢ at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.exchange(DefaultWebClient.java:430)
    |_       Mono.flatMap ⇢ at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultResponseSpec.bodyToMono(DefaultWebClient.java:540)
    |_   Mono.flatMapMany ⇢ at com.mycode(SomeClass.java:57)
Original Stack Trace:
        at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141)
        at reactor.core.publisher.MonoErrorSupplied.subscribe(MonoErrorSupplied.java:55)
        at reactor.core.publisher.Mono.subscribe(Mono.java:4400)
        at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:103)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onError(FluxPeekFuseable.java:234)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onError(FluxPeekFuseable.java:234)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onError(FluxPeekFuseable.java:234)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.MonoNext$NextSubscriber.onError(MonoNext.java:93)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.MonoFlatMapMany$FlatMapManyMain.onError(MonoFlatMapMany.java:204)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.SerializedSubscriber.onError(SerializedSubscriber.java:124)
        at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.whenError(FluxRetryWhen.java:225)
        at reactor.core.publisher.FluxRetryWhen$RetryWhenOtherSubscriber.onError(FluxRetryWhen.java:274)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.innerError(FluxConcatMap.java:309)
        at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onError(FluxConcatMap.java:875)
        at reactor.core.publisher.Operators.error(Operators.java:198)
        at reactor.core.publisher.MonoError.subscribe(MonoError.java:53)
        at reactor.core.publisher.Mono.subscribe(Mono.java:4400)
        at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:451)
        at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onNext(FluxConcatMap.java:251)
        at reactor.core.publisher.EmitterProcessor.drain(EmitterProcessor.java:491)
        at reactor.core.publisher.EmitterProcessor.tryEmitNext(EmitterProcessor.java:299)
        at reactor.core.publisher.SinkManySerialized.tryEmitNext(SinkManySerialized.java:100)
        at reactor.core.publisher.InternalManySink.emitNext(InternalManySink.java:27)
        at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.onError(FluxRetryWhen.java:190)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.MonoCreate$DefaultMonoSink.error(MonoCreate.java:194)
        at reactor.netty.http.client.HttpClientConnect$HttpObserver.onUncaughtException(HttpClientConnect.java:384)
        at reactor.netty.ReactorNetty$CompositeConnectionObserver.onUncaughtException(ReactorNetty.java:670)
        at reactor.netty.resources.DefaultPooledConnectionProvider$DisposableAcquire.onUncaughtException(DefaultPooledConnectionProvider.java:202)
        at reactor.netty.resources.DefaultPooledConnectionProvider$PooledConnection.onUncaughtException(DefaultPooledConnectionProvider.java:450)
        at reactor.netty.http.client.HttpClientOperations.onInboundClose(HttpClientOperations.java:294)
        at reactor.netty.channel.ChannelOperationsHandler.channelInactive(ChannelOperationsHandler.java:73)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)
        at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelInactive(CombinedChannelDuplexHandler.java:418)
        at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:392)
        at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:357)
        at io.netty.handler.codec.http.HttpClientCodec$Decoder.channelInactive(HttpClientCodec.java:326)
        at io.netty.channel.CombinedChannelDuplexHandler.channelInactive(CombinedChannelDuplexHandler.java:221)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)
        at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:392)
        at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:357)
        at io.netty.handler.ssl.SslHandler.channelInactive(SslHandler.java:1074)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1405)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
        at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:901)
        at io.netty.channel.AbstractChannel$AbstractUnsafe$7.run(AbstractChannel.java:813)
        at io.netty.util.concurrent.AbstractEventExecutor.safeExecute$$$capture(AbstractEventExecutor.java:164)
        at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java)
        at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:469)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.base/java.lang.Thread.run(Thread.java:833)
</code>```

Test mechanism:
GET requests through insomnia to the reactive web app (clicking with the mouse on Send button continuously until it fails), requests failing intermittently, at random intervals with no obvious (for me), causes.

Any ideas how to solve this?

Versions:

```<code>org.springframework.boot:spring-boot-starter-reactor-netty:jar:2.6.6
io.projectreactor.netty:reactor-netty-http:jar:1.0.17
io.projectreactor.netty:reactor-netty-core:jar:1.0.17
io.projectreactor:reactor-core:jar:3.4.16
io.netty:netty-codec:jar:4.1.75
org.springframework:spring-webflux:jar:5.3.18
</code>```

P.S.
Debugged internal libraries workflow, and got here, in reactor netty http:

Body:
WebClient configuration (minimized reproducible use case, tested with different durations, no effect):

    public WebClient createWebClient() {
        ConnectionProvider provider = ConnectionProvider.builder("WebClientProvider")
                .maxConnections(2)
                .maxIdleTime(Duration.ofSeconds(10))
                .maxLifeTime(Duration.ofSeconds(20))
                .pendingAcquireTimeout(Duration.ofSeconds(10))
                .evictInBackground(Duration.ofSeconds(10))
                .build();

        HttpClient httpClient = HttpClient.create(provider).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);

        ReactorClientHttpConnector reactorClientHttpConnector = new ReactorClientHttpConnector(httpClient);

        return WebClient.builder()
            .clientConnector(reactorClientHttpConnector)
            .build();
    }

Usage of the client, as a GET to a public cloud service provider:

    public Flux<SomeClass> doGetSomething() {
        return webClient.get()
                .uri(buildUri())
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(byte[].class)
                .flatMapMany(byteArray -> Flux.fromArray(byteArrayToModel(byteArray, SomeClass[].class)))
                .onErrorResume(e -> {
                    return Flux.error(new RuntimeException("Failed to call get", e));
                });
    }

Exception:

org.springframework.web.reactive.function.client.WebClientRequestException: Connection prematurely closed BEFORE response; nested exception is reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
    at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141)
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Assembly trace from producer [reactor.core.publisher.MonoLift] :
    reactor.core.publisher.Mono.error(Mono.java:330)
    org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.wrapException(ExchangeFunctions.java:141)
Error has been observed at the following site(s):
    *__________Mono.error ⇢ at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.wrapException(ExchangeFunctions.java:141)
    *__Mono.onErrorResume ⇢ at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.exchange(ExchangeFunctions.java:106)
    |_           Mono.map ⇢ at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.exchange(ExchangeFunctions.java:107)
    *________Mono.flatMap ⇢ at org.springframework.web.reactive.function.client.ExchangeFilterFunction.lambda$ofResponseProcessor$4(ExchangeFilterFunction.java:96)
    *________Mono.flatMap ⇢ at org.springframework.web.reactive.function.client.ExchangeFilterFunction.lambda$ofRequestProcessor$3(ExchangeFilterFunction.java:85)
    |_         checkpoint ⇢ Request to GET https://***********************.com/someendpoint*********************** [DefaultWebClient]
    |_ Mono.switchIfEmpty ⇢ at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.lambda$exchange$7(DefaultWebClient.java:433)
    *__________Mono.defer ⇢ at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultRequestBodyUriSpec.exchange(DefaultWebClient.java:430)
    |_       Mono.flatMap ⇢ at org.springframework.web.reactive.function.client.DefaultWebClient$DefaultResponseSpec.bodyToMono(DefaultWebClient.java:540)
    |_   Mono.flatMapMany ⇢ at com.mycode(SomeClass.java:57)
Original Stack Trace:
        at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141)
        at reactor.core.publisher.MonoErrorSupplied.subscribe(MonoErrorSupplied.java:55)
        at reactor.core.publisher.Mono.subscribe(Mono.java:4400)
        at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:103)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onError(FluxPeekFuseable.java:234)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onError(FluxPeekFuseable.java:234)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onError(FluxPeekFuseable.java:234)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.MonoNext$NextSubscriber.onError(MonoNext.java:93)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.MonoFlatMapMany$FlatMapManyMain.onError(MonoFlatMapMany.java:204)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.SerializedSubscriber.onError(SerializedSubscriber.java:124)
        at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.whenError(FluxRetryWhen.java:225)
        at reactor.core.publisher.FluxRetryWhen$RetryWhenOtherSubscriber.onError(FluxRetryWhen.java:274)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.innerError(FluxConcatMap.java:309)
        at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onError(FluxConcatMap.java:875)
        at reactor.core.publisher.Operators.error(Operators.java:198)
        at reactor.core.publisher.MonoError.subscribe(MonoError.java:53)
        at reactor.core.publisher.Mono.subscribe(Mono.java:4400)
        at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:451)
        at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onNext(FluxConcatMap.java:251)
        at reactor.core.publisher.EmitterProcessor.drain(EmitterProcessor.java:491)
        at reactor.core.publisher.EmitterProcessor.tryEmitNext(EmitterProcessor.java:299)
        at reactor.core.publisher.SinkManySerialized.tryEmitNext(SinkManySerialized.java:100)
        at reactor.core.publisher.InternalManySink.emitNext(InternalManySink.java:27)
        at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.onError(FluxRetryWhen.java:190)
        at io.opentracing.contrib.reactor.TracedSubscriber.lambda$onError$4(TracedSubscriber.java:79)
        at io.opentracing.contrib.reactor.TracedSubscriber.withActiveSpan(TracedSubscriber.java:95)
        at io.opentracing.contrib.reactor.TracedSubscriber.onError(TracedSubscriber.java:79)
        at reactor.core.publisher.MonoCreate$DefaultMonoSink.error(MonoCreate.java:194)
        at reactor.netty.http.client.HttpClientConnect$HttpObserver.onUncaughtException(HttpClientConnect.java:384)
        at reactor.netty.ReactorNetty$CompositeConnectionObserver.onUncaughtException(ReactorNetty.java:670)
        at reactor.netty.resources.DefaultPooledConnectionProvider$DisposableAcquire.onUncaughtException(DefaultPooledConnectionProvider.java:202)
        at reactor.netty.resources.DefaultPooledConnectionProvider$PooledConnection.onUncaughtException(DefaultPooledConnectionProvider.java:450)
        at reactor.netty.http.client.HttpClientOperations.onInboundClose(HttpClientOperations.java:294)
        at reactor.netty.channel.ChannelOperationsHandler.channelInactive(ChannelOperationsHandler.java:73)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)
        at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelInactive(CombinedChannelDuplexHandler.java:418)
        at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:392)
        at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:357)
        at io.netty.handler.codec.http.HttpClientCodec$Decoder.channelInactive(HttpClientCodec.java:326)
        at io.netty.channel.CombinedChannelDuplexHandler.channelInactive(CombinedChannelDuplexHandler.java:221)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)
        at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:392)
        at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:357)
        at io.netty.handler.ssl.SslHandler.channelInactive(SslHandler.java:1074)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241)
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1405)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248)
        at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:901)
        at io.netty.channel.AbstractChannel$AbstractUnsafe$7.run(AbstractChannel.java:813)
        at io.netty.util.concurrent.AbstractEventExecutor.safeExecute$$$capture(AbstractEventExecutor.java:164)
        at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java)
        at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:469)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.base/java.lang.Thread.run(Thread.java:833)

Test mechanism:
GET requests through insomnia to the reactive web app (clicking with the mouse on Send button continuously until it fails), requests failing intermittently, at random intervals with no obvious (for me), causes.

Any ideas how to solve this?

Versions:

org.springframework.boot:spring-boot-starter-reactor-netty:jar:2.6.6
io.projectreactor.netty:reactor-netty-http:jar:1.0.17
io.projectreactor.netty:reactor-netty-core:jar:1.0.17
io.projectreactor:reactor-core:jar:3.4.16
io.netty:netty-codec:jar:4.1.75
org.springframework:spring-webflux:jar:5.3.18

P.S.
Debugged internal libraries workflow, and got here, in reactor netty http:


问:
While trying to use key bindings in java, the actionPerformed method isn't getting called. How can I fix this?
While working on a game, I have run into a problem with key bindings. The method actionPerformed isn't getting called when I try and use the keys. I have successfully used key bindings before, but after I moved the code to my current project and refactored, it hasn't been working.</p>
```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.EventObject;

public class PlayerMovement {
// FIELDS =======================================================================
    Player player;

    Action moveUp;
    Action moveDown;
    Action moveLeft;
    Action moveRight;

// CONSTRUCTORS =================================================================
  public PlayerMovement (Player player) {
        moveUp = new UpAction();
        moveDown = new DownAction();
        moveLeft = new LeftAction();
        moveRight = new RightAction();

        player.label.getInputMap().put(KeyStroke.getKeyStroke('w'), "UpAction");
        player.label.getActionMap().put("UpAction", moveUp);
        player.label.getInputMap().put(KeyStroke.getKeyStroke('s'), "down");
        player.label.getActionMap().put("down", moveDown);
        player.label.getInputMap().put(KeyStroke.getKeyStroke('a'), "left");
        player.label.getActionMap().put("left", moveLeft);
        player.label.getInputMap().put(KeyStroke.getKeyStroke('d'), "right");
        player.label.getActionMap().put("right", moveRight);
  }

// INSTANCE METHODS =============================================================

// NESTED CLASSES ===============================================================
  public class UpAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            player.label.setLocation(player.label.getX(), player.label.getY()-10);
      System.out.println("Up");
        }
    }
    public class DownAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            player.label.setLocation(player.label.getX(), player.label.getY()+10);
      System.out.println("Down");
        }
    }
    public class LeftAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            player.label.setLocation(player.label.getX()-10, player.label.getY());
      System.out.println("Left");
        }
    }
    public class RightAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            player.label.setLocation(player.label.getX()+10, player.label.getY());
      System.out.println("Right");
        }
    }
}
</code>```

Body:
While working on a game, I have run into a problem with key bindings. The method actionPerformed isn't getting called when I try and use the keys. I have successfully used key bindings before, but after I moved the code to my current project and refactored, it hasn't been working.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.EventObject;

public class PlayerMovement {
// FIELDS =======================================================================
    Player player;

    Action moveUp;
    Action moveDown;
    Action moveLeft;
    Action moveRight;

// CONSTRUCTORS =================================================================
  public PlayerMovement (Player player) {
        moveUp = new UpAction();
        moveDown = new DownAction();
        moveLeft = new LeftAction();
        moveRight = new RightAction();

        player.label.getInputMap().put(KeyStroke.getKeyStroke('w'), "UpAction");
        player.label.getActionMap().put("UpAction", moveUp);
        player.label.getInputMap().put(KeyStroke.getKeyStroke('s'), "down");
        player.label.getActionMap().put("down", moveDown);
        player.label.getInputMap().put(KeyStroke.getKeyStroke('a'), "left");
        player.label.getActionMap().put("left", moveLeft);
        player.label.getInputMap().put(KeyStroke.getKeyStroke('d'), "right");
        player.label.getActionMap().put("right", moveRight);
  }

// INSTANCE METHODS =============================================================

// NESTED CLASSES ===============================================================
  public class UpAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            player.label.setLocation(player.label.getX(), player.label.getY()-10);
      System.out.println("Up");
        }
    }
    public class DownAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            player.label.setLocation(player.label.getX(), player.label.getY()+10);
      System.out.println("Down");
        }
    }
    public class LeftAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            player.label.setLocation(player.label.getX()-10, player.label.getY());
      System.out.println("Left");
        }
    }
    public class RightAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            player.label.setLocation(player.label.getX()+10, player.label.getY());
      System.out.println("Right");
        }
    }
}


问:
How to do time series analysis for document published date and read date?
I want to find whether there is a particular hour when the author should publish the documents online to get maximum views/reads.

Data looks something like this -

Document ID
Published Date
Read Date

1
1/1/2022 10:00:00
1/1/2022 11:00:00

1
1/1/2022 10:00:00
1/1/2022 12:00:00

1
1/1/2022 10:00:00
1/1/2022 11:05:00

1
1/1/2022 10:00:00
1/1/2022 15:05:00

2
1/2/2022 11:00:00
1/2/2022 19:05:00

2
1/2/2022 11:00:00
1/3/2022 20:05:00

4
1/3/2022 23:04:00
1/4/2022 11:05:00

4
1/3/2022 23:04:00
1/4/2022 23:11:00

Note - The documents with same document id have the same published date.

Read date represents the active date and time of the users, and published date represents the date and time of the authors when they mostly publish the documents.

Since, both the columns are dates, How should I use the correlation and time series analysis to get to a conclusion. Should I make the data stationery first? There is a pattern in the read date as in more readers are active in the morning and afternoons as compared to night.

I was able to find patterns between document published date and read date, but I am not sure how to use time series here.


问:
Compare two RSA encrypted strings which uses different encoding
I have a string "test_string", which is encrypted using RSA algorithm using two different encodings as shown in the below C# code. I want to check if the encrypted value in both the cases are the same, since I am using the same key in both cases. But due to RSA padding, the encrypted value changes every time even if I am using the same key and the same data "test_string" and same encoding. So, is there any way I can make sure that the encrypted value is same/different by avoid the padding? Any other recommendations are welcome.

```<code>        string encryptedUTF16;
        string encryptedUTF8;

        RSA rsa = RSA.Create();
        RSAParameters rsaParams = rsa.ExportParameters(true);

        using (var rsa1 = new RSACryptoServiceProvider())
        {
            rsa1.ImportParameters(rsaParams);
            byte[] bytesEncrytedKeyUTF16 = Encoding.Unicode.GetBytes("test_string".ToCharArray());

            byte[] encrytedKeyUTF16 = rsa1.Encrypt(bytesEncrytedKeyUTF16, true);
            encryptedUTF16 = Convert.ToBase64String(encrytedKeyUTF16);
            Console.WriteLine(encryptedUTF16);
        }

        using (var rsa2 = new RSACryptoServiceProvider())
        {
            rsa2.ImportParameters(rsaParams);
            byte[] bytesEncrytedKeyUTF8 = Encoding.UTF8.GetBytes("test_string".ToCharArray());
            byte[] encrytedKeyUTF8 = rsa2.Encrypt(bytesEncrytedKeyUTF8, true);
            encryptedUTF8 = Convert.ToBase64String(encrytedKeyUTF8);
            Console.WriteLine(encryptedUTF8);
        }
</code>```

I tried using OpenSSl and BouncyCastle as well. But ran into technical issues running them.

Body:
I have a string "test_string", which is encrypted using RSA algorithm using two different encodings as shown in the below C# code. I want to check if the encrypted value in both the cases are the same, since I am using the same key in both cases. But due to RSA padding, the encrypted value changes every time even if I am using the same key and the same data "test_string" and same encoding. So, is there any way I can make sure that the encrypted value is same/different by avoid the padding? Any other recommendations are welcome.

        string encryptedUTF16;
        string encryptedUTF8;

        RSA rsa = RSA.Create();
        RSAParameters rsaParams = rsa.ExportParameters(true);

        using (var rsa1 = new RSACryptoServiceProvider())
        {
            rsa1.ImportParameters(rsaParams);
            byte[] bytesEncrytedKeyUTF16 = Encoding.Unicode.GetBytes("test_string".ToCharArray());

            byte[] encrytedKeyUTF16 = rsa1.Encrypt(bytesEncrytedKeyUTF16, true);
            encryptedUTF16 = Convert.ToBase64String(encrytedKeyUTF16);
            Console.WriteLine(encryptedUTF16);
        }

        using (var rsa2 = new RSACryptoServiceProvider())
        {
            rsa2.ImportParameters(rsaParams);
            byte[] bytesEncrytedKeyUTF8 = Encoding.UTF8.GetBytes("test_string".ToCharArray());
            byte[] encrytedKeyUTF8 = rsa2.Encrypt(bytesEncrytedKeyUTF8, true);
            encryptedUTF8 = Convert.ToBase64String(encrytedKeyUTF8);
            Console.WriteLine(encryptedUTF8);
        }

I tried using OpenSSl and BouncyCastle as well. But ran into technical issues running them.


问:
FirebaseError: Function Query.where() called with invalid data. Unsupported field value: a custom Promise object.I am getting this error
I am working on a react project using firebase. I am getting this error that query.where()  is called with invalid data while getting a user  but in the firestore i have that data. I am not able to figure out why is it happening.

below is the code for my function

```<code>

export async function getUserByUserId(userId){

  const result = await firebase.firestore().collection('users').where('userId','==',userId).get();

  const user= result.docs.map((item)=>({
       ...item.data(),
    docId:item.id

  }));
  return {user};
}
</code>```

function call

```<code>
    export default function useUser(){
        const [activeUser,setActiveUser]=useState({});
        const {user}=useContext(UserContext);

    useEffect(()=>{
        async function getUserObjByUserId(){
            const response = await getUserByUserId;
          setActiveUser(response);
        }
        if(user?.uid){
            getUserObjByUserId();
        }
    },[user]);
    return {user:activeUser};
    }

</code>```

In place for giving me the 'userId' it is showing error in console and i am not able to get the 'userId' details.

Body:
I am working on a react project using firebase. I am getting this error that query.where()  is called with invalid data while getting a user  but in the firestore i have that data. I am not able to figure out why is it happening.

below is the code for my function

export async function getUserByUserId(userId){

  const result = await firebase.firestore().collection('users').where('userId','==',userId).get();

  const user= result.docs.map((item)=>({
       ...item.data(),
    docId:item.id

  }));
  return {user};
}

function call

    export default function useUser(){
        const [activeUser,setActiveUser]=useState({});
        const {user}=useContext(UserContext);

    useEffect(()=>{
        async function getUserObjByUserId(){
            const response = await getUserByUserId;
          setActiveUser(response);
        }
        if(user?.uid){
            getUserObjByUserId();
        }
    },[user]);
    return {user:activeUser};
    }

In place for giving me the 'userId' it is showing error in console and i am not able to get the 'userId' details.


问:
Where can I find a the code related to custom block in Wordpress plugin?
I am now looking into a legacy Wordpress project with some custom plugin that are written by previous developer that no longer work in the company. I am a PHP developer but haven't touched Wordpress for some time. I have done some research on Google and it seems that to add a new block type in a plugin, it is the register_block_type() function. I found in the plugin code that there is a few register_block_type() in one of the files, but not all custom block are found. To be specific, the custom block circled in the screenshot (the one named "Cards") are all not found anywhere in the plugin code.

I am sure it is added in the plugin, as all the custom block types are gone when the plugin is disabled, but where else in the plugin / what other functions can the custom block types be added?


问:
In Vue, when switching between pages, the data of the old page remains on the new page even though the new data is received
I'm trying to make a simple app that had a list of 'employees' and when you click on an employee you're brought to the details page of this employee. I have a MySQL on localhost with the employees and a route to get the data of all the employees and a route to get just the data of one employee. I have a problem with the details page where I'm representing the data of just one employee.

When loading the page of one employee for the first time, I get the correct data of that employee represented on the page. But when I return to the total employee overview and select another employee, the represented data is that of the first selected employee. When I then return to the overview and select a third employee, I see the data of the second. So I'm always one step behind.

I can't find a way around this issue.

The component I use for getting the data

```<code>import axios from "axios";
import { ref } from "vue"

const getEmployee = (id) => {
    const employee = ref(null);
    const error = ref(null)

    const load = () => {
        axios.get(`http://localhost:8080/employees/${id}`)
            .then(response => {
                employee.value = response.data
                console.log(employee.value)
            })
            .catch(err => {
                error.value = err.message
                console.log(err.message)
            })
    }

    return { employee, error, load }
}

export default getEmployee
</code>```

The vue employee details file

```<code><template>
  <div>
    <div v-if="employee">
      <p >Hey</p>
      <p>{{ employee[0].idemployee_personal_info }}</p>
      <p>{{ employee[0].surname }}</p>
      <p>{{ employee[0].firstname }}</p>
      <p>{{ employee[0].birthdate }}</p>
      <p>{{ employee[0].sex }}</p>
      <p>{{ employee }}</p>
    </div>
    <div v-else>
      <p>Loading...</p>
    </div>
    <div>

    </div>
  </div>
</template>

<script>
import getEmployee from '@/composables/getEmployee';
import { useRoute } from 'vue-router';

export default {
  name: 'EmployeeDetails',

  setup() {
    const route = useRoute()
    let routeId = route.params.id
    const { employee, error, load } = getEmployee(routeId)

    load()

    return { employee, error }
  }

}
</script>

<style>

</style>
</code>```

The backend

```<code>const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const connection = require('./SQLdb')

const app = express();

// Middle ware
app.use(bodyParser.json());
app.use(cors())

app.get('/', (req, res) => {
    let results = 'hello'
    connection.query('SELECT * FROM hrapp.employee_personal_info', function (err, result) {
        if (err) throw err;
        results = result
    });
    res.json(results);
})

let employees = null
app.get('/employees', (req, res) => {
    connection.query('SELECT idemployee_personal_info, surname, firstname, sex, date_format(birthdate, "%d/%m/%Y") AS birthdate FROM hrapp.employee_personal_info', function (err, result) {
        if (err) throw err;
        employees = result
    });
    res.json(employees);
})

let employeeDetails = null
app.get('/employees/:id', (req, res) => {
    let employee = req.params.id
    connection.query(`SELECT * FROM employee_personal_info WHERE idemployee_personal_info=${employee}`, function (err, result) {
        if (err) throw err;
        employeeDetails = result
    });
    res.json(employeeDetails);
})

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`)
});

</code>```

I've tried all kinds of things with the lifecycle, like setting the employee back to null. But he info as previously received seems to be safed on the client-side so that doens't do anything.

Body:
I'm trying to make a simple app that had a list of 'employees' and when you click on an employee you're brought to the details page of this employee. I have a MySQL on localhost with the employees and a route to get the data of all the employees and a route to get just the data of one employee. I have a problem with the details page where I'm representing the data of just one employee.

When loading the page of one employee for the first time, I get the correct data of that employee represented on the page. But when I return to the total employee overview and select another employee, the represented data is that of the first selected employee. When I then return to the overview and select a third employee, I see the data of the second. So I'm always one step behind.

I can't find a way around this issue.

The component I use for getting the data

import axios from "axios";
import { ref } from "vue"

const getEmployee = (id) => {
    const employee = ref(null);
    const error = ref(null)

    const load = () => {
        axios.get(`http://localhost:8080/employees/${id}`)
            .then(response => {
                employee.value = response.data
                console.log(employee.value)
            })
            .catch(err => {
                error.value = err.message
                console.log(err.message)
            })
    }

    return { employee, error, load }
}

export default getEmployee

The vue employee details file

<template>

Hey

{{ employee[0].idemployee_personal_info }}

{{ employee[0].surname }}

{{ employee[0].firstname }}

{{ employee[0].birthdate }}

{{ employee[0].sex }}

{{ employee }}

Loading...

</template>

The backend

const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const connection = require('./SQLdb')

const app = express();

// Middle ware
app.use(bodyParser.json());
app.use(cors())

app.get('/', (req, res) => {
    let results = 'hello'
    connection.query('SELECT * FROM hrapp.employee_personal_info', function (err, result) {
        if (err) throw err;
        results = result
    });
    res.json(results);
})

let employees = null
app.get('/employees', (req, res) => {
    connection.query('SELECT idemployee_personal_info, surname, firstname, sex, date_format(birthdate, "%d/%m/%Y") AS birthdate FROM hrapp.employee_personal_info', function (err, result) {
        if (err) throw err;
        employees = result
    });
    res.json(employees);
})

let employeeDetails = null
app.get('/employees/:id', (req, res) => {
    let employee = req.params.id
    connection.query(`SELECT * FROM employee_personal_info WHERE idemployee_personal_info=${employee}`, function (err, result) {
        if (err) throw err;
        employeeDetails = result
    });
    res.json(employeeDetails);
})

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`)
});

I've tried all kinds of things with the lifecycle, like setting the employee back to null. But he info as previously received seems to be safed on the client-side so that doens't do anything.


问:
How can I split a long pdf page into several pages with iText7 in C# in different lengths?
I have pdf files in receipt format (e.g. 80x1000mm), one long page per document.
I want to create a new pdf and split the receipt into several printable A4 pages.
The receipt contains blocks (e.g. QR.Codes) which must not be cut in the middle.
So the new pages must be created based on given lengths (rectangles) (measured from the top edge). e.g.
Page 1: 0 - 272mm
Page 2: 272 - 513mm
Page 3: 513 - 783 mm
Page 4: 783 - to end

How can I split the pdf page into several pages with iText7 in c# by specifying rectangels?

looked at several examples (git TileClipped.java, C06E02_TheGoldenGateBridge_Tiles)

I have created a very simple example to play around with coordinates, AddXObjectAt, PdfCanvas AffineTransform, ConcatMatrix, Clip etc..
The example generates a 1000mm long pdf.
I have experimented with this pdf. For the beginning I just tried to cut 4 x 250mm.

Unfortunately without success.

```<code>using System;using iText.Commons;using iText.Kernel;using iText.Kernel.Colors;using iText.Kernel.Font;using iText.Kernel.Geom;using iText.Kernel.Pdf;using iText.Kernel.Pdf.Canvas;using iText.Kernel.Pdf.Xobject;using iText.Layout;using iText.Layout.Element;

namespace SplitPage
{
    internal class Program
    {
        public const string fileReceipt = "c:\\tmp\\receipt1000mm.pdf";
        public const string fileA4 = "c:\\tmp\\receiptA4.pdf";

        static void Main(string[] args)
        {
            new Program().CreateAndSplitPdfReceipt();
        }

        static float mmToPt(float mm) => mm * 72.0f / 25.4f;

        void CreateAndSplitPdfReceipt()
        {
            float recieptLength = 2834.6f;          // 1000mm approx 2834.6 pt
            float recieptWidth = 220f;              // approx 78mm

            // Create 1000mm long receipt (= 2834.6pt)
            {
                PdfDocument pdfDoc = new PdfDocument(new PdfWriter(fileReceipt));
                pdfDoc.SetDefaultPageSize(new PageSize(recieptWidth, recieptLength));
                Document doc = new Document(pdfDoc);

                for (int i = 1; i <= 250; i++)
                {
                    float y = recieptLength - mmToPt(i * 4f);    // 4mm per row  *  250rows = 1000mm

                    var p = new Paragraph(string.Format("Row {0}: y={1:f1}    y'={2}mm ", i, y, i*4));
                    p.SetFontSize(8);
                    p.SetFixedPosition(10, y, 220);
                    p.SetMargin(0);

                    doc.Add(p);
                }
                pdfDoc.Close();
            }

            // split receipt1000.pdf in 4 equal parts a 250mm
            {
                float chunk = recieptLength / 4f;

                PdfDocument srcDoc = new PdfDocument(new PdfReader(fileReceipt));
                PdfDocument pdfA4 = new PdfDocument(new PdfWriter(fileA4));
                pdfA4.SetDefaultPageSize(PageSize.A4);

                PdfPage srcPage = srcDoc.GetPage(1); // just one page in receipt

                PdfFormXObject copyObject = srcPage.CopyAsFormXObject(pdfA4);

                PdfPage pageA4;
                PdfCanvas canvas;

                // 1st
                pageA4 = pdfA4.AddNewPage(PageSize.A4);
                canvas = new PdfCanvas(pageA4);
                canvas.AddXObjectAt(copyObject, 0, 3 * chunk);

                // 2nd
                pageA4 = pdfA4.AddNewPage(PageSize.A4);
                canvas = new PdfCanvas(pageA4);
                canvas.AddXObjectAt(copyObject, 0, 2 * chunk);

                // 3rd
                pageA4 = pdfA4.AddNewPage(PageSize.A4);
                canvas = new PdfCanvas(pageA4);
                canvas.AddXObjectAt(copyObject, 0, 1 * chunk);

                // 4th
                pageA4 = pdfA4.AddNewPage(PageSize.A4);
                canvas = new PdfCanvas(pageA4);
                canvas.AddXObjectAt(copyObject, 0, 0);

                srcDoc.Close();
                pdfA4.Close();    }}}}

</code>```

My problem is obviously that I did not understand the basic operations.

Body:
I have pdf files in receipt format (e.g. 80x1000mm), one long page per document.
I want to create a new pdf and split the receipt into several printable A4 pages.
The receipt contains blocks (e.g. QR.Codes) which must not be cut in the middle.
So the new pages must be created based on given lengths (rectangles) (measured from the top edge). e.g.
Page 1: 0 - 272mm
Page 2: 272 - 513mm
Page 3: 513 - 783 mm
Page 4: 783 - to end

How can I split the pdf page into several pages with iText7 in c# by specifying rectangels?

looked at several examples (git TileClipped.java, C06E02_TheGoldenGateBridge_Tiles)

I have created a very simple example to play around with coordinates, AddXObjectAt, PdfCanvas AffineTransform, ConcatMatrix, Clip etc..
The example generates a 1000mm long pdf.
I have experimented with this pdf. For the beginning I just tried to cut 4 x 250mm.

Unfortunately without success.

using System;using iText.Commons;using iText.Kernel;using iText.Kernel.Colors;using iText.Kernel.Font;using iText.Kernel.Geom;using iText.Kernel.Pdf;using iText.Kernel.Pdf.Canvas;using iText.Kernel.Pdf.Xobject;using iText.Layout;using iText.Layout.Element;

namespace SplitPage
{
    internal class Program
    {
        public const string fileReceipt = "c:\\tmp\\receipt1000mm.pdf";
        public const string fileA4 = "c:\\tmp\\receiptA4.pdf";

        static void Main(string[] args)
        {
            new Program().CreateAndSplitPdfReceipt();
        }

        static float mmToPt(float mm) => mm * 72.0f / 25.4f;

        void CreateAndSplitPdfReceipt()
        {
            float recieptLength = 2834.6f;          // 1000mm approx 2834.6 pt
            float recieptWidth = 220f;              // approx 78mm

            // Create 1000mm long receipt (= 2834.6pt)
            {
                PdfDocument pdfDoc = new PdfDocument(new PdfWriter(fileReceipt));
                pdfDoc.SetDefaultPageSize(new PageSize(recieptWidth, recieptLength));
                Document doc = new Document(pdfDoc);

                for (int i = 1; i <= 250; i++)
                {
                    float y = recieptLength - mmToPt(i * 4f);    // 4mm per row  *  250rows = 1000mm

                    var p = new Paragraph(string.Format("Row {0}: y={1:f1}    y'={2}mm ", i, y, i*4));
                    p.SetFontSize(8);
                    p.SetFixedPosition(10, y, 220);
                    p.SetMargin(0);

                    doc.Add(p);
                }
                pdfDoc.Close();
            }

            // split receipt1000.pdf in 4 equal parts a 250mm
            {
                float chunk = recieptLength / 4f;

                PdfDocument srcDoc = new PdfDocument(new PdfReader(fileReceipt));
                PdfDocument pdfA4 = new PdfDocument(new PdfWriter(fileA4));
                pdfA4.SetDefaultPageSize(PageSize.A4);

                PdfPage srcPage = srcDoc.GetPage(1); // just one page in receipt

                PdfFormXObject copyObject = srcPage.CopyAsFormXObject(pdfA4);

                PdfPage pageA4;
                PdfCanvas canvas;

                // 1st
                pageA4 = pdfA4.AddNewPage(PageSize.A4);
                canvas = new PdfCanvas(pageA4);
                canvas.AddXObjectAt(copyObject, 0, 3 * chunk);

                // 2nd
                pageA4 = pdfA4.AddNewPage(PageSize.A4);
                canvas = new PdfCanvas(pageA4);
                canvas.AddXObjectAt(copyObject, 0, 2 * chunk);

                // 3rd
                pageA4 = pdfA4.AddNewPage(PageSize.A4);
                canvas = new PdfCanvas(pageA4);
                canvas.AddXObjectAt(copyObject, 0, 1 * chunk);

                // 4th
                pageA4 = pdfA4.AddNewPage(PageSize.A4);
                canvas = new PdfCanvas(pageA4);
                canvas.AddXObjectAt(copyObject, 0, 0);

                srcDoc.Close();
                pdfA4.Close();    }}}}

My problem is obviously that I did not understand the basic operations.