问:
how to increase next input range for making input range sum 100
I have created a jquery function for validate total sum of ranges value should be 100, It works like that When we increase any range,
If total sum is bigger then 100  it descrese a range of second input, Now I need to validate it when total sum is less then 100, Then the next range
should be increase automatically for making it's total 100.

HTML

```<code><div>Total : <span id="total">0</span></div>
<div>
    <input type="range" min="0" max="100" value="0" class="price" id="s1" />
    <div class="input-v" id="v1">0</div>
</div>

<div>
    <input type="range" min="0" max="100" value="0" class="price" id="s2" />
    <div class="input-v" id="v2">0</div>
</div>
<div>
    <input type="range" min="0" max="100" value="0" class="price" id="s3" />
    <div class="input-v" id="v3">0</div>
</div>
<div>
    <input type="range" min="0" max="100" value="0" class="price" id="s4" />
    <div class="input-v" id="v4">0</div>
</div>
<div>
    <input type="range" min="0" max="100" value="0" class="price" id="s5" />
    <div class="input-v" id="v5">0</div>
</div>
<div>
    <input type="range" min="0" max="100" value="0" class="price" id="s6" />
    <div class="input-v" id="v6">0</div>
</div>
</code>```

Jquery

```<code>   <script>
        $(".price").change(function () {
            var getVal = $(this).val();
            $(this).next(".input-v").text(getVal);

            var returnValue = Calculation(getVal);

            if (!returnValue) {

                var TempTotal = 0;

                $(".price").each(function () {
                    TempTotal += Number($(this).val());
                });
                var totalDifference = TempTotal - 100;// Number($("#total").text());

                var finalDifference = getVal - totalDifference;

                $(this).val(finalDifference);
                $(this).next(".input-v").text(finalDifference);
                Calculation(finalDifference);

                $(this).attr("disabled", "true");
                //alert("stop the scroll");

            }
        });
        function Calculation(getVal) {

            var GetTotal = Number($("#total").text());

            var TempTotal = 0;

            $(".price").each(function () {
                TempTotal += Number($(this).val());

            });

            if (TempTotal <= 100) {
                $("#total").text(TempTotal);

                $(".price").removeAttr("disabled");
                return true;

            }

            else {
                // Temptotal is greter
                return false;

            }

        }

    </script>
</code>```

Body:
I have created a jquery function for validate total sum of ranges value should be 100, It works like that When we increase any range,
If total sum is bigger then 100  it descrese a range of second input, Now I need to validate it when total sum is less then 100, Then the next range
should be increase automatically for making it's total 100.

HTML

Total : 0

    <input type="range" min="0" max="100" value="0" class="price" id="s1" />

0

    <input type="range" min="0" max="100" value="0" class="price" id="s2" />

0

    <input type="range" min="0" max="100" value="0" class="price" id="s3" />

0

    <input type="range" min="0" max="100" value="0" class="price" id="s4" />

0

    <input type="range" min="0" max="100" value="0" class="price" id="s5" />

0

    <input type="range" min="0" max="100" value="0" class="price" id="s6" />

0

Jquery


来源: stackexchange

问:
Is there any way to implement Google Vision Api V2 api with Arabic Translation?
I have implemented Google vision ocr from this documentation but I have to translate the detected live text to Arabic.
https://developers.google.com/ml-kit/vision/text-recognition/v2/android

This is the Quick start provided by Google.
https://github.com/googlesamples/mlkit/tree/master/android/vision-quickstart

I was able to install and detect the text in English but not able to translate in Arabic.

ContentLicense: CC BY-SA 4.0


问:
Trianglular 2D Mesh edge/vertexes finding
I have a list of 2D points/vertex with it's identifier.
And a list of Triangles in each triangle we have 3 vertex identifier which makes up the triangle.
This triangles can overlap each other as well.

This Green edge points is what I want be it internal or external
Any logic to find the same would be greatly helpful.
If there is any C# sample or library you can point me to also.


问:
How can I set a Jquery Ajax middleware that only works on 401 or 403 status code?
I am using Aspnet Core MVC, with dotnet version 6.0 .

I am trying to handle ajax results. I want to set an ajax middleware that catches 401 or 403 status code and handle on it. If I don't do it like this, I have to check the 401 status code in the success and error sections for each ajax code.

Can we set a middleware on layout or any shortcut code to handle this XHR requests?

I tried this link on my project :Global AJAX Handler, but I was not sure, if it overrode my local ajax code. It seems it did not work. This is my ajax global handler on layout view script.

`

```<code> $(document).ajaxError(function (event, jqxhr, settings, thrownError) {

            if (jqxhr.statusCode == 401) {
                log("401");
                event.preventDefault();
                window.location.reload();
            }
        });
</code>```

`
This is my example ajax usage on any view:

```<code> function ExampleMethod() {
            $.ajax({
                method: "GET",
                url: "xxxxxxx",
                beforeSend: function () {

                },
                success: function (res) {

                },
                error: function (xhr) {

                }
            });
</code>```

So I want to override ExampleMethod when it takes 401 error. My thinking may be wrong. My problem is I want to control this ajax 401 responses in one method...

Body:
I am using Aspnet Core MVC, with dotnet version 6.0 .

I am trying to handle ajax results. I want to set an ajax middleware that catches 401 or 403 status code and handle on it. If I don't do it like this, I have to check the 401 status code in the success and error sections for each ajax code.

Can we set a middleware on layout or any shortcut code to handle this XHR requests?

I tried this link on my project :Global AJAX Handler, but I was not sure, if it overrode my local ajax code. It seems it did not work. This is my ajax global handler on layout view script.

`

 $(document).ajaxError(function (event, jqxhr, settings, thrownError) {

            if (jqxhr.statusCode == 401) {
                log("401");
                event.preventDefault();
                window.location.reload();
            }
        });

`
This is my example ajax usage on any view:

 function ExampleMethod() {
            $.ajax({
                method: "GET",
                url: "xxxxxxx",
                beforeSend: function () {

                },
                success: function (res) {

                },
                error: function (xhr) {

                }
            });

So I want to override ExampleMethod when it takes 401 error. My thinking may be wrong. My problem is I want to control this ajax 401 responses in one method...


问:
Python error when trying to destroy an object in Ursina
I'm pretty new to coding in python but I have started a small little script. Its a first person shooter and right now I'm working on ammo boxes you can pick up. This is the code:

```<code>from ursina import *
from random import uniform
from ursina.shaders import lit_with_shadows_shader
from ursina.prefabs.first_person_controller import FirstPersonController

app = Ursina()
Entity.default_shader = lit_with_shadows_shader
player = FirstPersonController(model='cube', color=color.orange, origin_y=-.5, speed=8, position = (-52, 0, 57))
player.collider = BoxCollider(player, Vec3(0,1,0))
player.visible = False
ammo = 10
editor_camera = EditorCamera(enabled=False, ignore_paused=True)
ammoCounter = Text(text= ammo + ammo, position = (-0.4,-0.4), color = color.black)

def update():
    ammoCounter.text = ammo
def pause_input(key):
    if key == 'tab':    # press tab to toggle edit/play mode
        editor_camera.position = player.position
        editor_camera.rotation = (90,180,0)
        editor_camera.y = 50
        editor_camera.enabled = not editor_camera.enabled
        player.visible =True
        player.visible_self = editor_camera.enabled
        player.cursor.enabled = not editor_camera.enabled
        gun.enabled = not editor_camera.enabled
        mouse.locked = not editor_camera.enabled
        application.paused = editor_camera.enabled
pause_handler = Entity(ignore_paused=True, input=pause_input)

def input(key):
    global ammo

    ## destroy ammo crates##
    if key == 'e':
        if mouse.hovered_entity == ammo1:
            if distance(player, ammo1) <= 5:
                ammo += 10
                destroy(ammo1)
        if mouse.hovered_entity == ammo2:
            if distance(player, ammo2) <= 5:
                ammo += 10
                destroy(ammo2)
        if mouse.hovered_entity == ammo3:
            if distance(player, ammo3) <= 5:
                ammo += 10
                destroy(ammo3)
        if mouse.hovered_entity == ammo4:
            if distance(player, ammo4) <= 5:
                ammo += 10
                destroy(ammo4)

    if key == 'k':
        print (player.position)
        print (ammo)

    if key=="left mouse down" and ammo > 0:
        ammo -= 1
        if mouse.hovered_entity and hasattr(mouse.hovered_entity, 'hp'):
            mouse.hovered_entity.hp -= 10
            mouse.hovered_entity.blink(color.red)
            print (ammo)
        Audio("gunshot")
        if gun.position == (0.45,-0.2,0):
            Animation("spark", parent=camera.ui, fps=5, scale=.15, position=(0.28, -0.01), loop=False)
            print (ammo)
        if gun.position == (0,-0.15,0):
            Animation("spark", parent=camera.ui, fps=5, scale=.15, position=(-0.005,0.08,0), loop=False)
            print (ammo)

    if held_keys["q"]:
            gun.position = (0,-0.15,0)
            gun.rotation = (0,0,0)
            Cursor = False
            player.speed = 1
            if held_keys["shift"]:
                player.speed = 100

    else:
        gun.position = (0.45,-0.2,0)
        gun.rotation = (5,30,0)
        player.speed = 250 * time.dt
    if held_keys["shift"]:
        player.speed = 400 * time.dt

## ammo refill class#

class AmmoR(Entity):
    def __init__(self, **kwargs):
        super().__init__(model='cube', texture = 'ammobox', scale = 1, origin_y=-0.5, collider = "mesh", **kwargs)

## amount of amo refill boxes##

ammo1 = AmmoR()
ammo2 = AmmoR()
ammo3 = AmmoR()
ammo4 = AmmoR()
ammo1.position = (-9,2,53)
ammo2.position = (50,1,21)
ammo3.position = (-17,0,31)
ammo4.position = (15,0,8)

class Enemy(Entity):
    def __init__(self, **kwargs):
        super().__init__(model='cube', scale_y=2, origin_y=-0.5, color=color.light_gray, collider='box', **kwargs)
        self.health_bar = Entity(parent=self, y=1.2, model='cube', color=color.red, world_scale=(1.5,.1,.1))
        self.max_hp = 100
        self.hp = self.max_hp

    def update(self):
        dist = distance_xz(player.position, self.position)
        if dist > 40:
            return

        self.health_bar.alpha = max(0, self.health_bar.alpha - time.dt)

        self.look_at_2d(player.position, 'y')
        hit_info = raycast(self.world_position + Vec3(0,1,0), self.forward, 30, ignore=(self,))
        if hit_info.entity == player:
            if dist > 1:
                self.position += self.forward * time.dt * 5

    @property
    def hp(self):
        return self._hp

    @hp.setter
    def hp(self, value):
        self._hp = value
        if value <= 0:
            destroy(self)
            return

        self.health_bar.world_scale_x = self.hp / self.max_hp * 1.5
        self.health_bar.alpha = 1

## ENEMYS FIRST LEVEL
enemie1 = Enemy()
enemie2 = Enemy()
enemie3 = Enemy()
enemie4 = Enemy()
enemie5 = Enemy()
enemie6 = Enemy()
enemie7 = Enemy()
enemie8 = Enemy()
enemie9 = Enemy()
enemie10 = Enemy()
enemie11 = Enemy()

enemie1.position = (10,0,-2)
enemie2.position = (51.9096, 0, -57.6378)
enemie3.position = (53.7879, 0, -57.4827)
enemie4.position = (53.5366, 0, -39.0536)
enemie5.position = (50,0,-2)
enemie6.position = (50,0,-5)
enemie7.position = (22,0,-20)
enemie8.position = (55,0,-4)
enemie9.position = (15,0,-2)

Sky()
maze=Entity(model="maze", scale=10, texture="BK", color= color.gold,collider="mesh")

gun=Entity(model="colt", parent=camera.ui, scale=0.07, texture='tx', position=(0.45,-0.2,0), rotation=(5,30,0))

app.run()
</code>```

The AmmoR class is the class for the ammo boxes and ammo1,ammo2,ammo3,and ammo4 are the ammo boxes. When I go to pick up the ammo boxes it works fine but when I try to pick up ammo2 Ursina Crashes giving me this error:

```<code>(3 aux display modules not yet loaded.)
:prc(warning): changing default value for ConfigVariable paste-emit-keystrokes from '1' to '0'.
:pnmimage:png(warning): iCCP: known incorrect sRGB profile
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\maze.obj
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\colt.obj
info: psd-tools3 not installed
warning: missing texture: 'tx'
screen resolution: (1920, 1080)
os: Windows
development mode: True
application successfully started
info: changed aspect ratio: 1.778 -> 1.778
PS C:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game>  c:; cd 'c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game'; & 'C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\python.exe' 'c:\Users\MoerkerkeThomas\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '50586' '--' 'c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py'
package_folder: C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina
asset_folder: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game
:prc(warning): Invalid integer value for ConfigVariable win-size: 864.0
:prc(warning): Invalid integer value for ConfigVariable win-size: 1536.0
Known pipe types:
  wglGraphicsPipe
(3 aux display modules not yet loaded.)
:prc(warning): changing default value for ConfigVariable paste-emit-keystrokes from '1' to '0'.
:pnmimage:png(warning): iCCP: known incorrect sRGB profile
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\maze.obj
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\colt.obj
info: psd-tools3 not installed
warning: missing texture: 'tx'
screen resolution: (1920, 1080)
os: Windows
development mode: True
application successfully started
info: changed aspect ratio: 1.778 -> 1.778
Assertion failed: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
Traceback (most recent call last):
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 49, in eventLoopTask
    self.doEvents()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 43, in doEvents
    processFunc(dequeueFunc())
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 99, in processEvent
    messenger.send(eventName, paramList)
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 337, in send
    self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 422, in __dispatch
    result = method (*(extraArgs + sentArgs))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 176, in input
    __main__.input(key)
  File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 52, in input
    if distance(player, ammo4) <= 5:
       ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\ursinamath.py", line 24, in distance
    if hasattr(b, 'position'): b = b.position
       ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\entity.py", line 466, in position
    return Vec3(*self.getPos())
                 ^^^^^^^^^^^^^
AssertionError: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
:task(error): Exception occurred in PythonTask eventManager
Traceback (most recent call last):
  File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 197, in <module>
    app.run()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 237, in run
    super().run()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\ShowBase.py", line 3330, in run
    self.taskMgr.run()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\task\Task.py", line 553, in run
    self.step()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\task\Task.py", line 504, in step
    self.mgr.poll()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 49, in eventLoopTask
    self.doEvents()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 43, in doEvents
    processFunc(dequeueFunc())
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 99, in processEvent
    messenger.send(eventName, paramList)
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 337, in send
    self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 422, in __dispatch
    result = method (*(extraArgs + sentArgs))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 176, in input
    __main__.input(key)
  File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 52, in input
    if distance(player, ammo4) <= 5:
       ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\ursinamath.py", line 24, in distance
    if hasattr(b, 'position'): b = b.position
       ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\entity.py", line 466, in position
    return Vec3(*self.getPos())
                 ^^^^^^^^^^^^^
AssertionError: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
PS C:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game>
</code>```

I have tried changing the the if function to be structured differently but I think the statement is correct. The only thing I could think of being the issue is the distance between objects variable.

Body:
I'm pretty new to coding in python but I have started a small little script. Its a first person shooter and right now I'm working on ammo boxes you can pick up. This is the code:

from ursina import *
from random import uniform
from ursina.shaders import lit_with_shadows_shader
from ursina.prefabs.first_person_controller import FirstPersonController

app = Ursina()
Entity.default_shader = lit_with_shadows_shader
player = FirstPersonController(model='cube', color=color.orange, origin_y=-.5, speed=8, position = (-52, 0, 57))
player.collider = BoxCollider(player, Vec3(0,1,0))
player.visible = False
ammo = 10
editor_camera = EditorCamera(enabled=False, ignore_paused=True)
ammoCounter = Text(text= ammo + ammo, position = (-0.4,-0.4), color = color.black)

def update():
    ammoCounter.text = ammo
def pause_input(key):
    if key == 'tab':    # press tab to toggle edit/play mode
        editor_camera.position = player.position
        editor_camera.rotation = (90,180,0)
        editor_camera.y = 50
        editor_camera.enabled = not editor_camera.enabled
        player.visible =True
        player.visible_self = editor_camera.enabled
        player.cursor.enabled = not editor_camera.enabled
        gun.enabled = not editor_camera.enabled
        mouse.locked = not editor_camera.enabled
        application.paused = editor_camera.enabled
pause_handler = Entity(ignore_paused=True, input=pause_input)

def input(key):
    global ammo

    ## destroy ammo crates##
    if key == 'e':
        if mouse.hovered_entity == ammo1:
            if distance(player, ammo1) <= 5:
                ammo += 10
                destroy(ammo1)
        if mouse.hovered_entity == ammo2:
            if distance(player, ammo2) <= 5:
                ammo += 10
                destroy(ammo2)
        if mouse.hovered_entity == ammo3:
            if distance(player, ammo3) <= 5:
                ammo += 10
                destroy(ammo3)
        if mouse.hovered_entity == ammo4:
            if distance(player, ammo4) <= 5:
                ammo += 10
                destroy(ammo4)

    if key == 'k':
        print (player.position)
        print (ammo)

    if key=="left mouse down" and ammo > 0:
        ammo -= 1
        if mouse.hovered_entity and hasattr(mouse.hovered_entity, 'hp'):
            mouse.hovered_entity.hp -= 10
            mouse.hovered_entity.blink(color.red)
            print (ammo)
        Audio("gunshot")
        if gun.position == (0.45,-0.2,0):
            Animation("spark", parent=camera.ui, fps=5, scale=.15, position=(0.28, -0.01), loop=False)
            print (ammo)
        if gun.position == (0,-0.15,0):
            Animation("spark", parent=camera.ui, fps=5, scale=.15, position=(-0.005,0.08,0), loop=False)
            print (ammo)

    if held_keys["q"]:
            gun.position = (0,-0.15,0)
            gun.rotation = (0,0,0)
            Cursor = False
            player.speed = 1
            if held_keys["shift"]:
                player.speed = 100

    else:
        gun.position = (0.45,-0.2,0)
        gun.rotation = (5,30,0)
        player.speed = 250 * time.dt
    if held_keys["shift"]:
        player.speed = 400 * time.dt

## ammo refill class#

class AmmoR(Entity):
    def __init__(self, **kwargs):
        super().__init__(model='cube', texture = 'ammobox', scale = 1, origin_y=-0.5, collider = "mesh", **kwargs)

## amount of amo refill boxes##

ammo1 = AmmoR()
ammo2 = AmmoR()
ammo3 = AmmoR()
ammo4 = AmmoR()
ammo1.position = (-9,2,53)
ammo2.position = (50,1,21)
ammo3.position = (-17,0,31)
ammo4.position = (15,0,8)

class Enemy(Entity):
    def __init__(self, **kwargs):
        super().__init__(model='cube', scale_y=2, origin_y=-0.5, color=color.light_gray, collider='box', **kwargs)
        self.health_bar = Entity(parent=self, y=1.2, model='cube', color=color.red, world_scale=(1.5,.1,.1))
        self.max_hp = 100
        self.hp = self.max_hp

    def update(self):
        dist = distance_xz(player.position, self.position)
        if dist > 40:
            return

        self.health_bar.alpha = max(0, self.health_bar.alpha - time.dt)

        self.look_at_2d(player.position, 'y')
        hit_info = raycast(self.world_position + Vec3(0,1,0), self.forward, 30, ignore=(self,))
        if hit_info.entity == player:
            if dist > 1:
                self.position += self.forward * time.dt * 5

    @property
    def hp(self):
        return self._hp

    @hp.setter
    def hp(self, value):
        self._hp = value
        if value <= 0:
            destroy(self)
            return

        self.health_bar.world_scale_x = self.hp / self.max_hp * 1.5
        self.health_bar.alpha = 1

## ENEMYS FIRST LEVEL
enemie1 = Enemy()
enemie2 = Enemy()
enemie3 = Enemy()
enemie4 = Enemy()
enemie5 = Enemy()
enemie6 = Enemy()
enemie7 = Enemy()
enemie8 = Enemy()
enemie9 = Enemy()
enemie10 = Enemy()
enemie11 = Enemy()

enemie1.position = (10,0,-2)
enemie2.position = (51.9096, 0, -57.6378)
enemie3.position = (53.7879, 0, -57.4827)
enemie4.position = (53.5366, 0, -39.0536)
enemie5.position = (50,0,-2)
enemie6.position = (50,0,-5)
enemie7.position = (22,0,-20)
enemie8.position = (55,0,-4)
enemie9.position = (15,0,-2)

Sky()
maze=Entity(model="maze", scale=10, texture="BK", color= color.gold,collider="mesh")

gun=Entity(model="colt", parent=camera.ui, scale=0.07, texture='tx', position=(0.45,-0.2,0), rotation=(5,30,0))

app.run()

The AmmoR class is the class for the ammo boxes and ammo1,ammo2,ammo3,and ammo4 are the ammo boxes. When I go to pick up the ammo boxes it works fine but when I try to pick up ammo2 Ursina Crashes giving me this error:

(3 aux display modules not yet loaded.)
:prc(warning): changing default value for ConfigVariable paste-emit-keystrokes from '1' to '0'.
:pnmimage:png(warning): iCCP: known incorrect sRGB profile
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\maze.obj
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\colt.obj
info: psd-tools3 not installed
warning: missing texture: 'tx'
screen resolution: (1920, 1080)
os: Windows
development mode: True
application successfully started
info: changed aspect ratio: 1.778 -> 1.778
PS C:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game>  c:; cd 'c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game'; & 'C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\python.exe' 'c:\Users\MoerkerkeThomas\.vscode\extensions\ms-python.python-2022.18.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '50586' '--' 'c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py'
package_folder: C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina
asset_folder: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game
:prc(warning): Invalid integer value for ConfigVariable win-size: 864.0
:prc(warning): Invalid integer value for ConfigVariable win-size: 1536.0
Known pipe types:
  wglGraphicsPipe
(3 aux display modules not yet loaded.)
:prc(warning): changing default value for ConfigVariable paste-emit-keystrokes from '1' to '0'.
:pnmimage:png(warning): iCCP: known incorrect sRGB profile
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\maze.obj
read obj at: c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\models_compressed\colt.obj
info: psd-tools3 not installed
warning: missing texture: 'tx'
screen resolution: (1920, 1080)
os: Windows
development mode: True
application successfully started
info: changed aspect ratio: 1.778 -> 1.778
Assertion failed: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
Traceback (most recent call last):
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 49, in eventLoopTask
    self.doEvents()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 43, in doEvents
    processFunc(dequeueFunc())
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 99, in processEvent
    messenger.send(eventName, paramList)
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 337, in send
    self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 422, in __dispatch
    result = method (*(extraArgs + sentArgs))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 176, in input
    __main__.input(key)
  File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 52, in input
    if distance(player, ammo4) <= 5:
       ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\ursinamath.py", line 24, in distance
    if hasattr(b, 'position'): b = b.position
       ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\entity.py", line 466, in position
    return Vec3(*self.getPos())
                 ^^^^^^^^^^^^^
AssertionError: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
:task(error): Exception occurred in PythonTask eventManager
Traceback (most recent call last):
  File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 197, in <module>
    app.run()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 237, in run
    super().run()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\ShowBase.py", line 3330, in run
    self.taskMgr.run()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\task\Task.py", line 553, in run
    self.step()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\task\Task.py", line 504, in step
    self.mgr.poll()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 49, in eventLoopTask
    self.doEvents()
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 43, in doEvents
    processFunc(dequeueFunc())
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\EventManager.py", line 99, in processEvent
    messenger.send(eventName, paramList)
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 337, in send
    self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\direct\showbase\Messenger.py", line 422, in __dispatch
    result = method (*(extraArgs + sentArgs))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\main.py", line 176, in input
    __main__.input(key)
  File "c:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game\main game fps.py", line 52, in input
    if distance(player, ammo4) <= 5:
       ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\ursinamath.py", line 24, in distance
    if hasattr(b, 'position'): b = b.position
       ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\MoerkerkeThomas\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\entity.py", line 466, in position
    return Vec3(*self.getPos())
                 ^^^^^^^^^^^^^
AssertionError: !is_empty() at line 1045 of panda/src/pgraph/nodePath.cxx
PS C:\Users\MoerkerkeThomas\Desktop\Python stuff\RIP URSINA SHIT\fps game>

I have tried changing the the if function to be structured differently but I think the statement is correct. The only thing I could think of being the issue is the distance between objects variable.


问:
how to create the input div on clicking the reply button of a comment below that particular comment using react
I want on clicking the reply button the div to write the reply to come

I tried to create a seperate component for reply textarea but as I am a beginner in react I am not able to get an idea how to do it.

Comment.js

import Userdata from "./data.json";
import Score from "./Score";
import Person from "./person";
import Reply from "./Reply";

const Comment = () => {
    return (
{
        Userdata.comments.map((comment, index) => {
            return (

                        <Score score={comment.score} />

                            <Person user={comment.user} />
                            {comment.createdAt}
                            <Reply index={index} />

{comment.content}

                    {comment.replies.map((reply) => {
                        return (

                                    <Score score={reply.score} />

                                        <Person user={reply.user} />
                                        {reply.createdAt}
                                        <Reply />

{reply.content}

                        );
                    })}

            );
        })
    }

    );
}
export default Comment;
```
<p>Reply Component</p>
<pre class="lang-js prettyprint-override"><code>const Reply = (props) => {

const handleClick = () => {
    console.log(`reply of ${props.index}`)
}
return (
    <div onClick= {handleClick} className="btn-reply">
        <img className="reply-icon" src="images/icon-reply.svg" alt="reply" />
        <span>Reply</span>
        </div>
    );
}

export default Reply;
</code>```

Body:
I want on clicking the reply button the div to write the reply to come

I tried to create a seperate component for reply textarea but as I am a beginner in react I am not able to get an idea how to do it.

Comment.js

import Userdata from "./data.json";
import Score from "./Score";
import Person from "./person";
import Reply from "./Reply";

const Comment = () => {
    return (
{
        Userdata.comments.map((comment, index) => {
            return (

                        <Score score={comment.score} />

                            <Person user={comment.user} />
                            {comment.createdAt}
                            <Reply index={index} />

{comment.content}

                    {comment.replies.map((reply) => {
                        return (

                                    <Score score={reply.score} />

                                        <Person user={reply.user} />
                                        {reply.createdAt}
                                        <Reply />

{reply.content}

                        );
                    })}

            );
        })
    }

    );
}
export default Comment;

Reply Component

const Reply = (props) => {

const handleClick = () => {
    console.log(`reply of ${props.index}`)
}
return (

        Reply

    );
}

export default Reply;


问:
Always showed Intent to receive required on Xero Webhooks and not x-xero-signature header not matched
When a click on Intent to Receive then it always showed me same like Intent to Received required, not showed 200 OK.

Method for ensuring_security is:

```<code>def ensuring_security?
      key = 'XERO_WEBHOOK_KEY'
      payload = request.body.read
      calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest('sha256', key, payload))
      begin
        if calculated_hmac.strip() == request.headers['x-xero-signature']
          true
        else
          false
        end
      rescue JSON::ParserError => e
        false
      end

end
</code>```

The result is alweays false because the calculated_hmac.strip() is not equal to request.headers['x-xero-signature']. I think if the intent can't be 200 OK so if I will updation in Contacts or Invoices the webhook can not be received. So What should I do?

I want to show a result of 200 OK and after this will get a webhook if updation in invoices and contacts.

Body:
When a click on Intent to Receive then it always showed me same like Intent to Received required, not showed 200 OK.

Method for ensuring_security is:

def ensuring_security?
      key = 'XERO_WEBHOOK_KEY'
      payload = request.body.read
      calculated_hmac = Base64.encode64(OpenSSL::HMAC.digest('sha256', key, payload))
      begin
        if calculated_hmac.strip() == request.headers['x-xero-signature']
          true
        else
          false
        end
      rescue JSON::ParserError => e
        false
      end

end

The result is alweays false because the calculated_hmac.strip() is not equal to request.headers['x-xero-signature']. I think if the intent can't be 200 OK so if I will updation in Contacts or Invoices the webhook can not be received. So What should I do?

I want to show a result of 200 OK and after this will get a webhook if updation in invoices and contacts.


问:
Communicate with frontend without going through backend
Is there anyway that I could potentially communicate with a web server without the need to store any temporary data in the backend, due to unspeakable constraints.

Background:
I have a sensor, and every time there is a new reading, the new readings has to be updated to the frontend, however, due to unspeakable reasons, I dont want to do that through the backend.

I am not going to update this to the backend yet. I only update it to the backend after I have let's say 10 validated readings (that are deemed to be acceptable).

The problem:
there are now 4 layers instead of just having: FE, BE, DB. Now we are going to introduce the sensor as another layer. Unless we could somehow classify this sensor as a frontend component?

**Due to some constraints, the problem needs to be solved using these technologies:
**1. excel VBA (using VB script)
2. frontend is ASP.NET

Potential solutions:

I have tried exploring windows socket, but I am not exactly sure if it might solve my problem. Im not sure, but

Creating a temporary table in the backend to pass the data to the frontend, I didnt want to do this because it seems a bit messy, and wonder if there are better ways.


问:
How can I get SU permission on an android device after I whiped all data?
I followed along with a guide on installing lineageOS on my OnePlus 5. I had the phone set up, with OEM and debugger permissions. I also installed TWRP. After the initial setup I was prompted to wipe the phone system and cache to clear some errors I was having as that seemed the solution. In doing so I fixed my errors, however, I also lost the lineageOS I had on my phone previously and everything else.

I still have TWRP installed interestingly enough, however, I can't go into fastboot mode to flash a new lineageOS from my computer. I want to upload the lineageOS to the phone with the "ADB push" command however that does not work as it seems to lack privileges and the error it gives is "could not create file: No such file found" when I try to push the lineageOS .zip file onto the /sdcard.

When I try to go into "ADB shell" and change the permissions to the /sdcard, I get an error saying SU is not present or something to that degree.


问:
how to use emojis in my project in Xcode and declare them in a dictionary array?
simply I have a uiimage and want to use one of the emojis in that . how can I get some of these emojis and place into my project? this is the place I ll get them from.

https://apps.timwhitlock.info/emoji/tables/iso3166

one more question . next to my uiimage I have a uilabel for currency codes. so to use the image along with the corresponding code  do I need to use a dictionary  like :

```<code>var dict = ["EUR": "imagenameinString"]
</code>```

or

```<code>var dict = ["code" : "EUR", "image": "imagenameinString"
</code>```

i want to call the currency code and related image/emoji together. This is my code below using a string value for emoji but I get error in this way naturally. how do I edit this code to work? Thank you!

```<code>class ViewController: UIViewController {

    @IBOutlet weak var amountText: UITextField!

    @IBOutlet weak var amountText2: UITextField!

    @IBOutlet weak var fromLabel: UILabel!

    @IBOutlet weak var fromImage: UIImageView!

    @IBOutlet weak var toImage: UIImageView!

    @IBOutlet weak var toLabel: UILabel!

    let flag = "\u{1F1F8}\u{1F1EA}"
    var currencyManager = CurrencyManager()

    var from: String = "EUR"
    var to: String = "TRY"
    var amount: String = "0"

    override func viewDidLoad() {
        super.viewDidLoad()

        amountText.delegate = self
        currencyManager.delegate = self
        fromImage.image = flag

    }
</code>```

Body:
simply I have a uiimage and want to use one of the emojis in that . how can I get some of these emojis and place into my project? this is the place I ll get them from.

https://apps.timwhitlock.info/emoji/tables/iso3166

one more question . next to my uiimage I have a uilabel for currency codes. so to use the image along with the corresponding code  do I need to use a dictionary  like :

var dict = ["EUR": "imagenameinString"]

or

var dict = ["code" : "EUR", "image": "imagenameinString"

i want to call the currency code and related image/emoji together. This is my code below using a string value for emoji but I get error in this way naturally. how do I edit this code to work? Thank you!

class ViewController: UIViewController {

    @IBOutlet weak var amountText: UITextField!

    @IBOutlet weak var amountText2: UITextField!

    @IBOutlet weak var fromLabel: UILabel!

    @IBOutlet weak var fromImage: UIImageView!

    @IBOutlet weak var toImage: UIImageView!

    @IBOutlet weak var toLabel: UILabel!

    let flag = "\u{1F1F8}\u{1F1EA}"
    var currencyManager = CurrencyManager()

    var from: String = "EUR"
    var to: String = "TRY"
    var amount: String = "0"

    override func viewDidLoad() {
        super.viewDidLoad()

        amountText.delegate = self
        currencyManager.delegate = self
        fromImage.image = flag

    }


问:
PySide application losses palette settings after PC suspend
I'm using the Fusion style for my application. I define a dark theme by customizing the palette. With the dark theme active, it sometimes happens that the palette colors are partially lost when the PC goes to sleep or is suspended.

This is how the application normally looks like

And this is how it looks after suspend. Sometimes even the names list has grey background

To mitigate this I've added an event filter but it doesn't seem to do the job. The palette is re-applied in the set_theme method

```<code>class WinEventFilter(QtCore.QAbstractNativeEventFilter):
    def __init__(self):
        super().__init__()
        self.main_window = None

    def nativeEventFilter(self, event_type, message):
        if event_type == b"windows_generic_MSG":
            msg = ctypes.wintypes.MSG.from_address(message.__int__())

            if msg.message == 0x15 and self.main_window is not None:
                self.main_window.hide()
                self.main_window.set_theme(apply=True)
                self.main_window.show()

        return False, 0

win_event_filter = WinEventFilter()
app.installNativeEventFilter(win_event_filter)
</code>```

Any idea how to fix this?

Body:
I'm using the Fusion style for my application. I define a dark theme by customizing the palette. With the dark theme active, it sometimes happens that the palette colors are partially lost when the PC goes to sleep or is suspended.

This is how the application normally looks like

And this is how it looks after suspend. Sometimes even the names list has grey background

To mitigate this I've added an event filter but it doesn't seem to do the job. The palette is re-applied in the set_theme method

class WinEventFilter(QtCore.QAbstractNativeEventFilter):
    def __init__(self):
        super().__init__()
        self.main_window = None

    def nativeEventFilter(self, event_type, message):
        if event_type == b"windows_generic_MSG":
            msg = ctypes.wintypes.MSG.from_address(message.__int__())

            if msg.message == 0x15 and self.main_window is not None:
                self.main_window.hide()
                self.main_window.set_theme(apply=True)
                self.main_window.show()

        return False, 0

win_event_filter = WinEventFilter()
app.installNativeEventFilter(win_event_filter)

Any idea how to fix this?


问:
vars(count) declared outside of the function won't work, which's inside the if else inside of a function
as in title, I am making a number-guessing game. And the document.getelementbyid inside the if-else of a function returns undefined.</p>
```<code>var count = 5;
function checkans() {
        console.log(count);
        var UIC = document.getElementById("usrinput");

        console.log(UIC.value);
        console.log(c1 + count + c2);
         //main
         if (count > 0)
         {
         if (UIC.value > ranNum) {
            document.getElementById("tips").innerHTML = "The number is too large!";
            var count = count - 1;
            document.getElementById("chance").innerHTML = (c1 + count + c2);
            document.getElementById("totalChances").innerHTML = (count);

         } else if (UIC.value < ranNum) {
            document.getElementById("tips").innerHTML = "The number is too small!";
            var count = count - 1;
            document.getElementById("chance").innerHTML = (c1 + count + c2);
            document.getElementById("totalChances").innerHTML = (count);

         } else {
            document.getElementById("tips").innerHTML = "Congrats! The number is correct. "
         }
    }
}
</code>```
```<code></code>```

Body:
as in title, I am making a number-guessing game. And the document.getelementbyid inside the if-else of a function returns undefined.

var count = 5;
function checkans() {
        console.log(count);
        var UIC = document.getElementById("usrinput");

        console.log(UIC.value);
        console.log(c1 + count + c2);
         //main
         if (count > 0)
         {
         if (UIC.value > ranNum) {
            document.getElementById("tips").innerHTML = "The number is too large!";
            var count = count - 1;
            document.getElementById("chance").innerHTML = (c1 + count + c2);
            document.getElementById("totalChances").innerHTML = (count);

         } else if (UIC.value < ranNum) {
            document.getElementById("tips").innerHTML = "The number is too small!";
            var count = count - 1;
            document.getElementById("chance").innerHTML = (c1 + count + c2);
            document.getElementById("totalChances").innerHTML = (count);

         } else {
            document.getElementById("tips").innerHTML = "Congrats! The number is correct. "
         }
    }
}


问:
How can I remove error in installing caret package in R?
I get the following error when I'm trying to load caret package in R:

Loading required package: ggplot2 Loading required package: lattice
Error: package or namespace load failed for ‘caret’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
namespace ‘glue’ 1.4.2 is already loaded, but >= 1.6.2 is required

I updated 'glue' but I got this massage again.


问:
To add a loop in the VBA code to run automatically
the below mentioned code moves 1 file at a time (Oldest first) from Source to Destination, however i would like to add a loop in the code so that if there are 100 files in a source folder I do not need to press the run button 100 times. it could move the files one by one automatically. Also please if the file already exist in the destination folder it should skip that file and should not stop the process.

Function OldestFile(strFold As String) As String

    Dim FSO As Object, Folder As Object, File As Object, oldF As String
    Dim lastFile As Date: lastFile = Now

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set Folder = FSO.GetFolder(strFold)

    For Each File In Folder.files
        If File.DateCreated < lastFile Then
            lastFile = File.DateCreated: oldF = File.name
        End If
    Next
    OldestFile = oldF
End Function

Sub MoveOldestFile()
     Dim FromPath As String, ToPath As String, fileName As String

     FromPath = "E:\Source\"
     ToPath = "E:\Destination\"
     fileName = OldestFile(FromPath)

     If Dir(ToPath & fileName) = "" Then
         Name FromPath & fileName As ToPath & fileName
     Else
         MsgBox "File """ & fileName & """ already moved..."
     End If
End Sub
```

will be highly appreciated.

regards

Body:
the below mentioned code moves 1 file at a time (Oldest first) from Source to Destination, however i would like to add a loop in the code so that if there are 100 files in a source folder I do not need to press the run button 100 times. it could move the files one by one automatically. Also please if the file already exist in the destination folder it should skip that file and should not stop the process.

Function OldestFile(strFold As String) As String

    Dim FSO As Object, Folder As Object, File As Object, oldF As String
    Dim lastFile As Date: lastFile = Now

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set Folder = FSO.GetFolder(strFold)

    For Each File In Folder.files
        If File.DateCreated < lastFile Then
            lastFile = File.DateCreated: oldF = File.name
        End If
    Next
    OldestFile = oldF
End Function

Sub MoveOldestFile()
     Dim FromPath As String, ToPath As String, fileName As String

     FromPath = "E:\Source\"
     ToPath = "E:\Destination\"
     fileName = OldestFile(FromPath)

     If Dir(ToPath & fileName) = "" Then
         Name FromPath & fileName As ToPath & fileName
     Else
         MsgBox "File """ & fileName & """ already moved..."
     End If
End Sub

will be highly appreciated.

regards


问:
django.db.utils.ProgrammingError: invalid dsn: invalid connection option "charset"
while running with psycopg the django is omitting error as the up above,

  File "/Users/abhishekratnam/Library/Python/3.9/lib/python/site-packages/django/db/backends/base/base.py", line 194, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/Users/abhishekratnam/Library/Python/3.9/lib/python/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/Users/abhishekratnam/Library/Python/3.9/lib/python/site-packages/psycopg2/__init__.py", line 121, in connect
    dsn = _ext.make_dsn(dsn, **kwargs)
  File "/Users/abhishekratnam/Library/Python/3.9/lib/python/site-packages/psycopg2/extensions.py", line 167, in make_dsn
    parse_dsn(dsn)
django.db.utils.ProgrammingError: invalid dsn: invalid connection option "charset"
```

I tried changing the postgresql to

postgresql_psycopg2, that didin't worked

Body:
while running with psycopg the django is omitting error as the up above,

  File "/Users/abhishekratnam/Library/Python/3.9/lib/python/site-packages/django/db/backends/base/base.py", line 194, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/Users/abhishekratnam/Library/Python/3.9/lib/python/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/Users/abhishekratnam/Library/Python/3.9/lib/python/site-packages/psycopg2/__init__.py", line 121, in connect
    dsn = _ext.make_dsn(dsn, **kwargs)
  File "/Users/abhishekratnam/Library/Python/3.9/lib/python/site-packages/psycopg2/extensions.py", line 167, in make_dsn
    parse_dsn(dsn)
django.db.utils.ProgrammingError: invalid dsn: invalid connection option "charset"

I tried changing the postgresql to

postgresql_psycopg2, that didin't worked


问:
Adding extra path to django get_full_path() through form
I just want to add something to mypath like: bla1/bla2/bla3/something
or whatever pass in member!
how can i do this?

```<code>def to(request):

   if request.method == "POST":
    x = request.POST['username']
    member = whome(unique_user=x)
    member.save()

    links.objects.create(path=request.get_full_path())
    links().save()

    return render(request, "home.html")
</code>```

Body:
I just want to add something to mypath like: bla1/bla2/bla3/something
or whatever pass in member!
how can i do this?

def to(request):

   if request.method == "POST":
    x = request.POST['username']
    member = whome(unique_user=x)
    member.save()

    links.objects.create(path=request.get_full_path())
    links().save()

    return render(request, "home.html")


问:
Retain built image from a different configuration in Yocto
I have different configuration files all corresponding to the same hardware board. The configurations correspond to different recipes that we want to include or exclude for our customers. Each configuration file also specifies a directory where the final built images are placed (with DEPLOY_DIR_IMAGE=deploy/images/somedir_suffix).

The problem is that whenever I build an image, bitbake -r foo.conf core-image-minimal, the previously built image, in a different directory, is also deleted. How can I build an image without cleaning / deleting the contents of the other directories in deploy/images ?

Our yocto version is 2.3


问:
AAC bitstream not in ADTS format and extradata missing in MPEG-TS output
I am using ffmpeg 5.1.2 stable version, and fdk-aac v0.1.6 .
I am trying to encapsulate a LATM/LOAS in an MPEGTS DVB standard output, using this cmdline:

```<code>ffmpeg -i <source> -af volume=volume=1dB:precision=fixed -c:a libfdk_aac -latm 1 -b:a 128k -c:v libx264 -pix_fmt yuv420p -preset veryfast -x264-params "nal-hrd=cbr:keyint=50:min-keyint=50" -b:v 3200k -minrate 3200k -maxrate 3200k -bufsize 6400k -flush_packets 0 -f mpegts -mpegts_original_network_id 1 -mpegts_transport_stream_id 1 -mpegts_service_id 1 -mpegts_service_type '0x19' -mpegts_flags 'latm' -mpegts_flags 'system_b' -mpegts_flags 'nit' -muxrate 4000000 -metadata service_provider='MyRTV' -metadata service_name='My TV' -tables_version 0 'udp://238.0.0.1:6000?ttl=1&pkt_size=1316&bitrate=4000000'
</code>```

It logs and error:

```<code>[mpegts @ 0x556dc3e6a840] AAC bitstream not in ADTS format and extradata missing
</code>```

What am I missing ?
Thanks in advance and best regards

I am trying to encapsulate a LATM/LOAS in an MPEGTS DVB standard output, so expect to have a LOAS/LATM output, but I obtain an ADTS output.

Body:
I am using ffmpeg 5.1.2 stable version, and fdk-aac v0.1.6 .
I am trying to encapsulate a LATM/LOAS in an MPEGTS DVB standard output, using this cmdline:

ffmpeg -i <source> -af volume=volume=1dB:precision=fixed -c:a libfdk_aac -latm 1 -b:a 128k -c:v libx264 -pix_fmt yuv420p -preset veryfast -x264-params "nal-hrd=cbr:keyint=50:min-keyint=50" -b:v 3200k -minrate 3200k -maxrate 3200k -bufsize 6400k -flush_packets 0 -f mpegts -mpegts_original_network_id 1 -mpegts_transport_stream_id 1 -mpegts_service_id 1 -mpegts_service_type '0x19' -mpegts_flags 'latm' -mpegts_flags 'system_b' -mpegts_flags 'nit' -muxrate 4000000 -metadata service_provider='MyRTV' -metadata service_name='My TV' -tables_version 0 'udp://238.0.0.1:6000?ttl=1&pkt_size=1316&bitrate=4000000'

It logs and error:

[mpegts @ 0x556dc3e6a840] AAC bitstream not in ADTS format and extradata missing

What am I missing ?
Thanks in advance and best regards

I am trying to encapsulate a LATM/LOAS in an MPEGTS DVB standard output, so expect to have a LOAS/LATM output, but I obtain an ADTS output.


问:
C# - Using XmlRoot and XmlElement to receive Xml Node Values in Model
I have been trying to receive the Xml Node values in my model using the WCF Service.  I am posting the XML to my service, however, I am unable to receive the values as I have tried Console.WriteLine() but it did not display anything. Am I doing something wrong?

This is my XML:

```<code><query>
    <Username>test1</username>
    <Password>pass1</Password>
</query>
</code>```

This is my model:

    [XmlRoot(ElementName = "query")]
    public class XmlCls
    {
        [XmlElement(ElementName = "Username")]
        public string username { get; set; }
        [XmlElement(ElementName = "Password")]
        public string password { get; set; }
    }
```
<p>This is my Service:</p>
<pre class="lang-cs prettyprint-override"><code>public void Login(XmlCls xmlCls)
{
    Console.WriteLine("Username: " + xmlCls.username);
    Console.WriteLine("Password: " + xmlCls.password);
}
</code>```

Service Interface:

    [ServiceContract]
    [XmlSerializerFormat]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/Login", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
        void Login(XmlCls xmlCls);
    }
```

Someone please let me know if this is even possible. If not, I will just have to receive XML as string in my Service instead of using a model.

Body:
I have been trying to receive the Xml Node values in my model using the WCF Service.  I am posting the XML to my service, however, I am unable to receive the values as I have tried Console.WriteLine() but it did not display anything. Am I doing something wrong?

This is my XML:

<query>
    <Username>test1</username>
    <Password>pass1</Password>
</query>

This is my model:

    [XmlRoot(ElementName = "query")]
    public class XmlCls
    {
        [XmlElement(ElementName = "Username")]
        public string username { get; set; }
        [XmlElement(ElementName = "Password")]
        public string password { get; set; }
    }

This is my Service:

public void Login(XmlCls xmlCls)
{
    Console.WriteLine("Username: " + xmlCls.username);
    Console.WriteLine("Password: " + xmlCls.password);
}

Service Interface:

    [ServiceContract]
    [XmlSerializerFormat]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/Login", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
        void Login(XmlCls xmlCls);
    }

Someone please let me know if this is even possible. If not, I will just have to receive XML as string in my Service instead of using a model.


问:
I need to add values from user to add it in matrix
I need to input matrix from user 3x3 matrix
to calculate the linear, I take this code from another resource, but I need to get values from user

```<code>import numpy as np

def cramer(mat, constant):  # takes the matrix and the costants
    D = np.linalg.det(mat)  # calculating the determinant of the original matrix
    # substitution of the column with costant and creating new matrix
    mat1 = np.array([constant, mat[1], mat[2]])
    mat2 = np.array([mat[0], constant, mat[2]])
    mat3 = np.array([mat[0], mat[1], constant])
    # calculatin determinant of the matrix
    D1 = np.linalg.det(mat1)
    D2 = np.linalg.det(mat2)
    D3 = np.linalg.det(mat3)
    # finding the X1, X2, X3
    X1 = D1 / D
    X2 = D2 / D
    X3 = D3 / D
    print(X1, X2, X3)

matrix = []
for i in range(3):
    row = list(map(int, input().split()))
    matrix.append(row)
print(matrix)

a = np.array(matrix)
b = np.array([300, 360, 390])
cramer(a,b)

</code>```

I add this

```<code>matrix = []
for i in range(3):
    row = list(map(int, input().split()))
    matrix.append(row)
print(matrix)

to put it in a function (a = np.array(matrix))
</code>```

I get this Errors):

2 3 4
4 5 6
7 7 7
[[2, 3, 4], [4, 5, 6], [7, 7, 7]]
inf -inf inf
RuntimeWarning: divide by zero encountered in double_scalars
X1 = D1 / D
RuntimeWarning: divide by zero encountered in double_scalars
X2 = D2 / D
RuntimeWarning: divide by zero encountered in double_scalars
X3 = D3 / D

Body:
I need to input matrix from user 3x3 matrix
to calculate the linear, I take this code from another resource, but I need to get values from user

import numpy as np

def cramer(mat, constant):  # takes the matrix and the costants
    D = np.linalg.det(mat)  # calculating the determinant of the original matrix
    # substitution of the column with costant and creating new matrix
    mat1 = np.array([constant, mat[1], mat[2]])
    mat2 = np.array([mat[0], constant, mat[2]])
    mat3 = np.array([mat[0], mat[1], constant])
    # calculatin determinant of the matrix
    D1 = np.linalg.det(mat1)
    D2 = np.linalg.det(mat2)
    D3 = np.linalg.det(mat3)
    # finding the X1, X2, X3
    X1 = D1 / D
    X2 = D2 / D
    X3 = D3 / D
    print(X1, X2, X3)

matrix = []
for i in range(3):
    row = list(map(int, input().split()))
    matrix.append(row)
print(matrix)

a = np.array(matrix)
b = np.array([300, 360, 390])
cramer(a,b)

I add this

matrix = []
for i in range(3):
    row = list(map(int, input().split()))
    matrix.append(row)
print(matrix)

to put it in a function (a = np.array(matrix))

I get this Errors):

2 3 4
4 5 6
7 7 7
[[2, 3, 4], [4, 5, 6], [7, 7, 7]]
inf -inf inf
RuntimeWarning: divide by zero encountered in double_scalars
X1 = D1 / D
RuntimeWarning: divide by zero encountered in double_scalars
X2 = D2 / D
RuntimeWarning: divide by zero encountered in double_scalars
X3 = D3 / D


问:
How to get Excel encoded non english text back
I have a csv file with a column with non-English text and viewing it on excel leads to odd characters. I ended up saving the file. Now the saved file has the non english text replaced with excel encoded text. Is there a way to get the original text back?</p>


问:
Speech recognizer not working: PCM WAV, AIFF/AIFF-C, or Native FLAC error
I have the following audio file

It says the word 'down'

I am trying to turn the audio to text:

```<code>import speech_recognition

r = sr.Recognizer()
with sr.AudioFile("example.wav") as source:
    audio = r.record(source)

    audio_data = r.listen(source)
try:
    s = r.recognize_google(audio)
    print("Text: "+s)
except Exception as e:
    print("Exception: "+str(e))
</code>```

I get the error:

```<code>ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format
</code>```

I tried all the solutions here

I tried to convert the audio file using wavio and scipy.io.wavfile

Any idea how to get around this?

I am using speech_recognition 3.9.0 and python 3.9

Body:
I have the following audio file

It says the word 'down'

I am trying to turn the audio to text:

import speech_recognition

r = sr.Recognizer()
with sr.AudioFile("example.wav") as source:
    audio = r.record(source)

    audio_data = r.listen(source)
try:
    s = r.recognize_google(audio)
    print("Text: "+s)
except Exception as e:
    print("Exception: "+str(e))

I get the error:

ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format

I tried all the solutions here

I tried to convert the audio file using wavio and scipy.io.wavfile

Any idea how to get around this?

I am using speech_recognition 3.9.0 and python 3.9


问:
Redis node.js optimization to avoid the problem of the number of connected clients in Node.js
I keep having a problem that I don't know how to solve..
I've been looking for information but I can't really find how to optimize
For example:
When I add something to the cache, I have the following class

```<code>export class RedisCache {
    private readonly cache: any;
    private readonly ttl?: number;

    constructor(ttl?: number) {
        this.ttl = ttl;
        this.cache = createClient({
            socket: {
                host: process.env.REDIS_HOST,
                port: Number(process.env.REDIS_PORT)
            },
            password: process.env.REDIS_PASSWORD
        });

        this.cache.connect();
    }
}
set = async (key: string, data: object | string) => {
        let cachedData = await this.get(key);
        cachedData = JSON.parse(cachedData);

        if (cachedData && typeof(cachedData) === 'object') {
            cachedData.push(data);

            this.cache.set(
                key,
                JSON.stringify(cachedData),
                {
                    EX: this.ttl,
                    NX: false
                }
            );

            if (typeof data === "string") {
                console.log(`Data added in cache ${JSON.parse(data)}`);
            }

            return;
        }

        this.cache.set(
            key,
            typeof(data) === 'object' ? JSON.stringify([data]) : data,
            {
                EX: this.ttl,
                NX: false
            }
        );

        console.log(`Data added in cache ${data}`);
    }
</code>```

I also call this class to instantiate an event

```<code>export class SaveCacheEvent extends EventEmitter {
    private readonly ttl: number;
    private redis: any;

    constructor(ttl: number) {
        super();
        this.ttl = ttl;

        this.redis = new RedisCache(this.ttl);
    }

    set = async (key: any, data: object | string) : Promise<void> => {
        await this.redis.set(key, data);
    }
}

Which I further use to add things to the cache.
This is not the only place where I add things to the cache, I also have a queue bull
</code>```
```<code>class Queue {
    private queue;

    /**
     *
     * @param type
     */
    constructor(type: string) {
        this.queue = new Bull(type, {
            redis: {
                host: process.env.REDIS_HOST,
                password: process.env.REDIS_PASSWORD,
                port: Number(process.env.REDIS_PORT)
            },
            limiter: {
                max: parseInt(process.env.QUEUE_MAX_PROCESS!),
                duration: parseInt(process.env.QUEUE_MAX_TIME!)
            }
        });
    }
}

/**
     *
     * @param service: any
     * @param priority: number
     * @param delay: number
     * @param data: any
     * @return Promise<void>
     */
    queueProcess = async (service: any, priority: number, delay: number, data: any) : Promise<void> => {
        this.queue.add(data, {priority: priority, delay: delay});

        this.queue.process(service);
    }
</code>```

My problem is that at certain times there are full customers
My max clients is 10000
How could I optimize this?
I tried with quit() but nothing is added to the cache and queue :)

Is there a way to optimize this implementation with redis?

It's quite strange what happens and I lose a lot of data at a time because of it

```<code>ReplyError parseError(redis-parser.lib:parser)
ERR max number of clients reached
</code>```

Body:
I keep having a problem that I don't know how to solve..
I've been looking for information but I can't really find how to optimize
For example:
When I add something to the cache, I have the following class

export class RedisCache {
    private readonly cache: any;
    private readonly ttl?: number;

    constructor(ttl?: number) {
        this.ttl = ttl;
        this.cache = createClient({
            socket: {
                host: process.env.REDIS_HOST,
                port: Number(process.env.REDIS_PORT)
            },
            password: process.env.REDIS_PASSWORD
        });

        this.cache.connect();
    }
}
set = async (key: string, data: object | string) => {
        let cachedData = await this.get(key);
        cachedData = JSON.parse(cachedData);

        if (cachedData && typeof(cachedData) === 'object') {
            cachedData.push(data);

            this.cache.set(
                key,
                JSON.stringify(cachedData),
                {
                    EX: this.ttl,
                    NX: false
                }
            );

            if (typeof data === "string") {
                console.log(`Data added in cache ${JSON.parse(data)}`);
            }

            return;
        }

        this.cache.set(
            key,
            typeof(data) === 'object' ? JSON.stringify([data]) : data,
            {
                EX: this.ttl,
                NX: false
            }
        );

        console.log(`Data added in cache ${data}`);
    }

I also call this class to instantiate an event

export class SaveCacheEvent extends EventEmitter {
    private readonly ttl: number;
    private redis: any;

    constructor(ttl: number) {
        super();
        this.ttl = ttl;

        this.redis = new RedisCache(this.ttl);
    }

    set = async (key: any, data: object | string) : Promise<void> => {
        await this.redis.set(key, data);
    }
}

Which I further use to add things to the cache.
This is not the only place where I add things to the cache, I also have a queue bull

class Queue {
    private queue;

    /**
     *
     * @param type
     */
    constructor(type: string) {
        this.queue = new Bull(type, {
            redis: {
                host: process.env.REDIS_HOST,
                password: process.env.REDIS_PASSWORD,
                port: Number(process.env.REDIS_PORT)
            },
            limiter: {
                max: parseInt(process.env.QUEUE_MAX_PROCESS!),
                duration: parseInt(process.env.QUEUE_MAX_TIME!)
            }
        });
    }
}

/**
     *
     * @param service: any
     * @param priority: number
     * @param delay: number
     * @param data: any
     * @return Promise<void>
     */
    queueProcess = async (service: any, priority: number, delay: number, data: any) : Promise<void> => {
        this.queue.add(data, {priority: priority, delay: delay});

        this.queue.process(service);
    }

My problem is that at certain times there are full customers
My max clients is 10000
How could I optimize this?
I tried with quit() but nothing is added to the cache and queue :)

Is there a way to optimize this implementation with redis?

It's quite strange what happens and I lose a lot of data at a time because of it

ReplyError parseError(redis-parser.lib:parser)
ERR max number of clients reached


问:
How can I replicate this console action in VB.net with Webview2?
So in edge I F12, goto console and type in SM.Player.token and receive a value back, not sure what you call this - a javascript variable or function?

I've got a program that does various interactions with this page and whilst I can manually go into the console, retrieve this value and enter it into a text box in the app it would be nice to be able to automate this part of the process.

I tried :

```<code>Dim token As String = ""
Dim script As String = "document.getElementById('SM.Player.token')"
token = "" & WebView2.ExecuteScriptAsync(script).ToString
</code>```

But that just returns :

"System.Threading.Tasks.Task`1[System.String]"

Anyone able to point me in the right direction?

Body:
So in edge I F12, goto console and type in SM.Player.token and receive a value back, not sure what you call this - a javascript variable or function?

I've got a program that does various interactions with this page and whilst I can manually go into the console, retrieve this value and enter it into a text box in the app it would be nice to be able to automate this part of the process.

I tried :

Dim token As String = ""
Dim script As String = "document.getElementById('SM.Player.token')"
token = "" & WebView2.ExecuteScriptAsync(script).ToString

But that just returns :

"System.Threading.Tasks.Task`1[System.String]"

Anyone able to point me in the right direction?


问:
Extract Content after Match
I would like to partially automate the configuration of our Aruba switch using the daily configuration *.cfg backups.

With the following command I get the desired block of a vlan from the Configfile:

```<code>$content=Get-Content -Path $switch.fullname | Select-String 'vlan 53' -Context 0,4
</code>```

The result can then look like this, for example:

```<code>> vlan 53
 name "WIFI"
 tagged 5,8,47-52
 no ip address
 exit
</code>```

Does anyone know how I can extract only the "tagged" vlan ports from $Content?
I would then like to use these in further steps for configuration.

Maybe via magic regex commands.

But unfortunately I am too stupid for that.

Many thanks in advance

Daniel

Title: Extract Content after Match

Body:
I would like to partially automate the configuration of our Aruba switch using the daily configuration *.cfg backups.

With the following command I get the desired block of a vlan from the Configfile:

$content=Get-Content -Path $switch.fullname | Select-String 'vlan 53' -Context 0,4

The result can then look like this, for example:

> vlan 53
 name "WIFI"
 tagged 5,8,47-52
 no ip address
 exit

Does anyone know how I can extract only the "tagged" vlan ports from $Content?
I would then like to use these in further steps for configuration.

Maybe via magic regex commands.

But unfortunately I am too stupid for that.

Many thanks in advance

Daniel


问:
chrome.runtime.onInstalled event fired unexpected in Puppeteer
I have installed this extension below
https://chrome.google.com/webstore/detail/microsoft-editor-spelling/gpaiobkfhnonedkhhfjpmhdalgeoebfa
I see, the event chrome.runtime.onInstalled always fired when you run the code below.

```<code>const puppeteer = require('puppeteer-core');

(async function(){
    const browser = await puppeteer.launch({
        userDataDir:'C:\\Users\\xxxxxx\\AppData\\Local\\Google\\Chrome\\User Data',
        executablePath:'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        headless:false,
        ignoreDefaultArgs:[
    ],
        args:[
        '--disable-extensions-except=C:\\Users\\xxxxxx\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions\\gpaiobkfhnonedkhhfjpmhdalgeoebfa\\1.2211.1007_0',
    ]
    });
    const pages=await browser.pages();
    const page=pages[0];
    await page.goto("https://www.bing.com/");

    globalThis.setTimeout(async function(){
        await browser.close();
    },2 * 60 *1000);

})();
</code>```

Additional,you can make an extension by yourself and same issue here.

```<code>chrome.runtime.onInstalled.addListener((reason) => {
    const t = Date.now();
    console.log('chrome.runtime.onInstalled','reason',reason,t);
    chrome.tabs.create({ url: `https://www.google.com/?${t}` });
  }
);
</code>```

Body:
I have installed this extension below
https://chrome.google.com/webstore/detail/microsoft-editor-spelling/gpaiobkfhnonedkhhfjpmhdalgeoebfa
I see, the event chrome.runtime.onInstalled always fired when you run the code below.

const puppeteer = require('puppeteer-core');

(async function(){
    const browser = await puppeteer.launch({
        userDataDir:'C:\\Users\\xxxxxx\\AppData\\Local\\Google\\Chrome\\User Data',
        executablePath:'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        headless:false,
        ignoreDefaultArgs:[
    ],
        args:[
        '--disable-extensions-except=C:\\Users\\xxxxxx\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions\\gpaiobkfhnonedkhhfjpmhdalgeoebfa\\1.2211.1007_0',
    ]
    });
    const pages=await browser.pages();
    const page=pages[0];
    await page.goto("https://www.bing.com/");

    globalThis.setTimeout(async function(){
        await browser.close();
    },2 * 60 *1000);

})();

Additional,you can make an extension by yourself and same issue here.

chrome.runtime.onInstalled.addListener((reason) => {
    const t = Date.now();
    console.log('chrome.runtime.onInstalled','reason',reason,t);
    chrome.tabs.create({ url: `https://www.google.com/?${t}` });
  }
);


问:
Improving batch insert/update/delete in Spring Boot
I am working with a Spring boot project and Oracle Database. My task is importing data from a csv file. The file includes 10000 rows; each row is equal to a row in a table and includes three attributes which are sCode, isDeleted (isDeleted=1 -> delete, isDeleted=0 -> update or insert). I am using batch size of 1000 to insert, update or delete. Each batch, I do the following steps:

Use JPA findAllBySCodeInAndDepartmentId to file all rows that exist in the table (departmentId is the department of current user, (sCode, departmentId) is unique)

Use Map to store data from the first step's result (key is sCode)

Filter out rows in batch that have isDeleted = 1 and exist in the Map to delete (I use JPA deleteAll)

Filter out rows that isDeleted = 0 and exist in the Map to update (I use JPA saveAll)

Left rows in batch which were not updated or deleted (not in the Map) will be inserted into the table (I use JPA saveAll)

It takes around 5 minutes to finish importing 10000 rows
How can I shrink the amount of time to around 1 minute?


问:
Firefox not displaying larger image thumbnail >15MB image
Firefox not displaying larger image thumbnail >15MB image

I am expecting it needs to be done with blob not with the data:image


问:
Page is automatically vertically scrolled when using angular 13 clarity 13 version
In our project we are having a dropdown. I am using clarity dropdown. On opening clarity dropdown menu I can see page is getting automatically scrolled vertically. This is not happening in case of angular 9 and clarity 3.x. Can you suggest me any fix regarding this issue.

I have tried changing versions by trial and error. If Iam downgrading clarity to 3.x and angular to 13 I can see there we are getting compilation issues regarding types check. Please let me know whether we can use skiplibcheck true in tsconfig whether it is ideal solution or not.


问:
How to change text encoding and pass it to axios?
The API host wants me to send euc-kr encoded parameters.

But I'm not sure how to do it.

My Node.Js doesn't seem to support euc-kr.

I succeeded in getting the text written in euc-kr through a module iconv-lite.

const eucKrBuffer = incov.encode("ㅎㅎㅎ", "euc-kr");

But this is a Buffer type.

I need to convert this to String type to use it as a parameter.

I called eucKrBuffer.toString(). However,
I'm not sure what this results in.

eucKrBuffer.toString() => ???  I am not sure what result actually is

So I just send it obviously it failed.

```<code>    const result = await Axios.post(
        url,
        stringify({
            Name: eucKrBuffer.toString()
        }),
        {
            headers: {
                "Content-Type":
                    "application/x-www-form-urlencoded; charset=euc-kr",
            },
        }
    );
</code>```

Body:
The API host wants me to send euc-kr encoded parameters.

But I'm not sure how to do it.

My Node.Js doesn't seem to support euc-kr.

I succeeded in getting the text written in euc-kr through a module iconv-lite.

const eucKrBuffer = incov.encode("ㅎㅎㅎ", "euc-kr");

But this is a Buffer type.

I need to convert this to String type to use it as a parameter.

I called eucKrBuffer.toString(). However,
I'm not sure what this results in.

eucKrBuffer.toString() => ???  I am not sure what result actually is

So I just send it obviously it failed.

    const result = await Axios.post(
        url,
        stringify({
            Name: eucKrBuffer.toString()
        }),
        {
            headers: {
                "Content-Type":
                    "application/x-www-form-urlencoded; charset=euc-kr",
            },
        }
    );


问:
extraction of tabular data from pdf
I am trying to extract tabular data from the pdf using Tabula however the output is not coming in tabular format.

I am attaching the screenshot of the data.

```<code>tables = tabula.read_pdf(pdffile, pages='all', stream = 'True')
</code>```

df_table = pd.DataFrame(tables)

Please assist me with this how it is possible.

Thank you in advance.

Output :-

Title: extraction of tabular data from pdf

Body:
I am trying to extract tabular data from the pdf using Tabula however the output is not coming in tabular format.

I am attaching the screenshot of the data.

tables = tabula.read_pdf(pdffile, pages='all', stream = 'True')

df_table = pd.DataFrame(tables)

Please assist me with this how it is possible.

Thank you in advance.

Output :-


问:
Yubikey shell script, not working any more
Using expect to check/navigate to correct menu and send desired cmd input
After update of Yubikey-manager etc, pin code popup window appears... that make the script to fail

(Default pin are used in this example)

```<code>#!/usr/bin/expect -f

set prompt "gpg/card\>"
set keyprompt "\\? "

eval spawn gpg2 --card-edit
expect "Yubico Yubikey"
expect $prompt
send -- "admin\r"
expect $prompt
send -- "generate\r"
expect "Make off-card backup of encryption key"
send -- "n\r"
expect "PIN:"
send -- "123456"
# ..... and continue
</code>```

Any input how it should be solved?

How to disable pin code popup window?

Body:
Using expect to check/navigate to correct menu and send desired cmd input
After update of Yubikey-manager etc, pin code popup window appears... that make the script to fail

(Default pin are used in this example)

#!/usr/bin/expect -f

set prompt "gpg/card\>"
set keyprompt "\\? "

eval spawn gpg2 --card-edit
expect "Yubico Yubikey"
expect $prompt
send -- "admin\r"
expect $prompt
send -- "generate\r"
expect "Make off-card backup of encryption key"
send -- "n\r"
expect "PIN:"
send -- "123456"
# ..... and continue

Any input how it should be solved?

How to disable pin code popup window?


问:
SpringBoot 3 extend PostgresSQL Dialect
We have the custom postgres dialect, by extending Postgres Dialect, and registerFunctions, but looks like this is not supported in spring boot 3.

What are the alternative ways to implement this in spring boot 3.

```<code>public class GlobalPostgresDialect extends PostgreSQL10Dialect {

    public static final String STRING_AGG = "string_agg";
    public static final String STRING_AGG_ORDER_BY = "string_agg_order_by";
    public static final String STRING_AGG_DISTINCT = "string_agg_distinct";
    public static final String STRING_AGG_DISTINCT_ORDER_BY = "string_agg_distinct_order_by";
    public static final String ARRAY_AGG = "array_agg";
    public static final String ARRAY_AGG_DISTINCT = "array_agg_distinct";
    public static final String ARRAY_AGG_ORDER_BY = "array_agg_order_by";
    public static final String ARRAY_AGG_DISTINCT_ORDER_BY = "array_agg_distinct_order_by";
    public static final String COUNT_DISTINCT_5_ARGS = "count_distinct_5_args";

    public GlobalPostgresDialect() {
        super();
        registerFunction(STRING_AGG, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(?1, ?2)"));
        registerFunction(STRING_AGG_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(?1, ?2 order by ?3)"));
        registerFunction(STRING_AGG_DISTINCT, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(distinct ?1, ?2)"));
        registerFunction(STRING_AGG_DISTINCT_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(distinct ?1, ?2 order by ?3)"));
        registerFunction(ARRAY_AGG, new SQLFunctionTemplate(StandardBasicTypes.STRING, "array_agg(?1)"));
        registerFunction(ARRAY_AGG_DISTINCT, new SQLFunctionTemplate(StandardBasicTypes.STRING, "array_agg(distinct ?1)"));
        registerFunction(ARRAY_AGG_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "array_agg(?1 order by ?2)"));
        registerFunction(ARRAY_AGG_DISTINCT_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "array_agg(?1, ?2 order by ?2)"));
        registerFunction(COUNT_DISTINCT_5_ARGS, new SQLFunctionTemplate(LongType.INSTANCE, "count(distinct(?1, ?2, ?3, ?4, ?5))"));
    }
}
</code>```

Title: SpringBoot 3 extend PostgresSQL Dialect

Body:
We have the custom postgres dialect, by extending Postgres Dialect, and registerFunctions, but looks like this is not supported in spring boot 3.

What are the alternative ways to implement this in spring boot 3.

public class GlobalPostgresDialect extends PostgreSQL10Dialect {

    public static final String STRING_AGG = "string_agg";
    public static final String STRING_AGG_ORDER_BY = "string_agg_order_by";
    public static final String STRING_AGG_DISTINCT = "string_agg_distinct";
    public static final String STRING_AGG_DISTINCT_ORDER_BY = "string_agg_distinct_order_by";
    public static final String ARRAY_AGG = "array_agg";
    public static final String ARRAY_AGG_DISTINCT = "array_agg_distinct";
    public static final String ARRAY_AGG_ORDER_BY = "array_agg_order_by";
    public static final String ARRAY_AGG_DISTINCT_ORDER_BY = "array_agg_distinct_order_by";
    public static final String COUNT_DISTINCT_5_ARGS = "count_distinct_5_args";

    public GlobalPostgresDialect() {
        super();
        registerFunction(STRING_AGG, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(?1, ?2)"));
        registerFunction(STRING_AGG_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(?1, ?2 order by ?3)"));
        registerFunction(STRING_AGG_DISTINCT, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(distinct ?1, ?2)"));
        registerFunction(STRING_AGG_DISTINCT_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(distinct ?1, ?2 order by ?3)"));
        registerFunction(ARRAY_AGG, new SQLFunctionTemplate(StandardBasicTypes.STRING, "array_agg(?1)"));
        registerFunction(ARRAY_AGG_DISTINCT, new SQLFunctionTemplate(StandardBasicTypes.STRING, "array_agg(distinct ?1)"));
        registerFunction(ARRAY_AGG_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "array_agg(?1 order by ?2)"));
        registerFunction(ARRAY_AGG_DISTINCT_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "array_agg(?1, ?2 order by ?2)"));
        registerFunction(COUNT_DISTINCT_5_ARGS, new SQLFunctionTemplate(LongType.INSTANCE, "count(distinct(?1, ?2, ?3, ?4, ?5))"));
    }
}


问:
Why is my LambdaMetafactory slower than the reflection
I know from the Faster alternatives to Java's reflection, Using LambdaMetafactory with MethodHandle is closer to a direct call, but in my JMH program results, LambdaMetafactory is even slower than reflection, It's quite different from the previous questions. I don't know what went wrong

Here are my JMH test results，the BenchmarkMode is AverageTime

```<code>Benchmark                                      Mode  Cnt     Score     Error  Units
MhExceptionBenchMark.MhExceptioTest.directNew  avgt   10   248.059 ±  52.375  ns/op
MhExceptionBenchMark.MhExceptioTest.mhLamda    avgt   10  2435.962 ±  45.767  ns/op
MhExceptionBenchMark.MhExceptioTest.mhNoLamda  avgt   10  2573.739 ± 688.203  ns/op
MhExceptionBenchMark.MhExceptioTest.reflet     avgt   10  2344.597 ± 237.946  ns/op
</code>```

All I have to do is dynamically build a constructor with a String input and assign the value message to it

This class is called ValidException

```<code>public class ValidException extends AbstractException {

    private static final long serialVersionUID = 1L;

    private static final String DEFAULT_VALID_ERRCODE = "test";

    public ValidException() {
        super(DEFAULT_VALID_ERRCODE);
    }

    public ValidException(String errMessage) {
        super(DEFAULT_VALID_ERRCODE, errMessage);
    }
}
</code>```

Its parent class is AbstractException

```<code>public abstract class AbstractException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    private String errMessage;

    public AbstractException(String errMessage) {
        super(errMessage);
    }
}
</code>```

My JMH program is

```<code>@Fork(1)
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 3)
@Measurement(iterations = 10, time = 5)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Threads(10)
public class MhExceptioTest {

    @State(Scope.Benchmark)
    public static class Ex {
        ValidException validException;

        @Setup(Level.Trial)
        public void prepare() {
            validException = new ValidException();
        }
    }

    @State(Scope.Benchmark)
    public static class MhNoLambda{
        MethodHandle methodHandle;

        @Setup(Level.Trial)
        public void prepare() throws NoSuchMethodException, IllegalAccessException {
            MethodType methodType = MethodType.methodType(void.class, String.class);
            methodHandle = MethodHandles.publicLookup().findConstructor(ValidException.class, methodType);
        }
    }

    @State(Scope.Benchmark)
    public static class MhLambda{
        Function<String,AbstractException> function;

        @Setup(Level.Trial)
        public void prepare() throws Throwable {
            MethodHandles.Lookup lookup = MethodHandles.lookup();
            MethodType methodType = MethodType.methodType(void.class, String.class);
            MethodHandle methodHandle = lookup.findConstructor(ValidException.class, methodType);
            CallSite site = LambdaMetafactory.metafactory(
                    lookup,
                    "apply",
                    MethodType.methodType(Function.class),
                    methodHandle.type().generic(),
                    methodHandle,
                    methodHandle.type());
            function = (Function<String, AbstractException>)site.getTarget().invokeExact();
        }
    }

    @State(Scope.Benchmark)
    public static class Constr{
        Constructor<ValidException> constructor;

        @Setup(Level.Trial)
        public void prepare() throws NoSuchMethodException {
            constructor = ValidException.class.getConstructor(String.class);
        }
    }

    @Benchmark
    public <T extends AbstractException> AbstractException directNew(Ex ex){
        ValidException validException = ex.validException;
        validException.setErrMessage("test");
        return validException;
    }

    @Benchmark
    public <T extends AbstractException> AbstractException mhNoLamda(MhNoLambda mhNoLambda) throws Throwable {
        return (AbstractException) mhNoLambda.methodHandle.invoke("test");
    }

    @Benchmark
    public <T extends AbstractException> AbstractException reflet(Constr constr) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        ValidException validException = constr.constructor.newInstance("test");
        return validException;
    }

    @Benchmark
    public <T extends AbstractException> AbstractException mhLamda(MhLambda mhLambda){
        return mhLambda.function.apply("test");
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(MhExceptioTest.class.getSimpleName())
                .result("./result-mh-ex.json")
                .resultFormat(ResultFormatType.JSON)
                .build();
        new Runner(options).run();
    }
}
</code>```

Body:
I know from the Faster alternatives to Java's reflection, Using LambdaMetafactory with MethodHandle is closer to a direct call, but in my JMH program results, LambdaMetafactory is even slower than reflection, It's quite different from the previous questions. I don't know what went wrong

Here are my JMH test results，the BenchmarkMode is AverageTime

Benchmark                                      Mode  Cnt     Score     Error  Units
MhExceptionBenchMark.MhExceptioTest.directNew  avgt   10   248.059 ±  52.375  ns/op
MhExceptionBenchMark.MhExceptioTest.mhLamda    avgt   10  2435.962 ±  45.767  ns/op
MhExceptionBenchMark.MhExceptioTest.mhNoLamda  avgt   10  2573.739 ± 688.203  ns/op
MhExceptionBenchMark.MhExceptioTest.reflet     avgt   10  2344.597 ± 237.946  ns/op

All I have to do is dynamically build a constructor with a String input and assign the value message to it

This class is called ValidException

public class ValidException extends AbstractException {

    private static final long serialVersionUID = 1L;

    private static final String DEFAULT_VALID_ERRCODE = "test";

    public ValidException() {
        super(DEFAULT_VALID_ERRCODE);
    }

    public ValidException(String errMessage) {
        super(DEFAULT_VALID_ERRCODE, errMessage);
    }
}

Its parent class is AbstractException

public abstract class AbstractException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    private String errMessage;

    public AbstractException(String errMessage) {
        super(errMessage);
    }
}

My JMH program is

@Fork(1)
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 3)
@Measurement(iterations = 10, time = 5)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Threads(10)
public class MhExceptioTest {

    @State(Scope.Benchmark)
    public static class Ex {
        ValidException validException;

        @Setup(Level.Trial)
        public void prepare() {
            validException = new ValidException();
        }
    }

    @State(Scope.Benchmark)
    public static class MhNoLambda{
        MethodHandle methodHandle;

        @Setup(Level.Trial)
        public void prepare() throws NoSuchMethodException, IllegalAccessException {
            MethodType methodType = MethodType.methodType(void.class, String.class);
            methodHandle = MethodHandles.publicLookup().findConstructor(ValidException.class, methodType);
        }
    }

    @State(Scope.Benchmark)
    public static class MhLambda{
        Function<String,AbstractException> function;

        @Setup(Level.Trial)
        public void prepare() throws Throwable {
            MethodHandles.Lookup lookup = MethodHandles.lookup();
            MethodType methodType = MethodType.methodType(void.class, String.class);
            MethodHandle methodHandle = lookup.findConstructor(ValidException.class, methodType);
            CallSite site = LambdaMetafactory.metafactory(
                    lookup,
                    "apply",
                    MethodType.methodType(Function.class),
                    methodHandle.type().generic(),
                    methodHandle,
                    methodHandle.type());
            function = (Function<String, AbstractException>)site.getTarget().invokeExact();
        }
    }

    @State(Scope.Benchmark)
    public static class Constr{
        Constructor<ValidException> constructor;

        @Setup(Level.Trial)
        public void prepare() throws NoSuchMethodException {
            constructor = ValidException.class.getConstructor(String.class);
        }
    }

    @Benchmark
    public <T extends AbstractException> AbstractException directNew(Ex ex){
        ValidException validException = ex.validException;
        validException.setErrMessage("test");
        return validException;
    }

    @Benchmark
    public <T extends AbstractException> AbstractException mhNoLamda(MhNoLambda mhNoLambda) throws Throwable {
        return (AbstractException) mhNoLambda.methodHandle.invoke("test");
    }

    @Benchmark
    public <T extends AbstractException> AbstractException reflet(Constr constr) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        ValidException validException = constr.constructor.newInstance("test");
        return validException;
    }

    @Benchmark
    public <T extends AbstractException> AbstractException mhLamda(MhLambda mhLambda){
        return mhLambda.function.apply("test");
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(MhExceptioTest.class.getSimpleName())
                .result("./result-mh-ex.json")
                .resultFormat(ResultFormatType.JSON)
                .build();
        new Runner(options).run();
    }
}


问:
Joining two temp tables and making calculations within them to find price elasticity
I'm trying to calculate price elasticity in product level, where I have to find Δprice/Δvolume for elasticity calculations. We have a weekly aggregated sales data with start and end date of each week. I know this is not the optimal solution but I try to create temp tables and then join them week over week to find Δprice/Δvolume, from the table:

sales2022YTD
TABLE Example

with the code:

```<code>with X as
(SELECT DATE_FROM, PRODUCT_NAME, VOLUME as volume1, NET_SALES/VOLUME as netprice1
FROM sales2022YTD
WHERE DATE_FROM = '2022-01-03'),

Y as
(SELECT DATE_FROM, PRODUCT_NAME, VOLUME as volume2, NET_SALES/VOLUME as netprice2
FROM sales2022YTD
WHERE DATE_FROM = '2022-08-03')

SELECT netprice2/netprice1 as pricediff, volume2/volume1 as volumediff
FROM Y as y1
LEFT JOIN X as x1
ON y1.PRODUCT_NAME = x1.PRODUCT_NAME
WHERE x1.PRODUCT_NAME = y1.PRODUCT_NAME
</code>```

So basically I want to merge the two temp tables on the common product names and see weekly price and volume differences. With this query, I get only pricediff and volumediff columns without any value. I also would like to note that I have common product names in the two seperate weeks.

As a further step, I will extend the code to 52 weeks to calculate weekly elasticity. Any easier/less bulkier approach would be really appreciated.

Much thanks!!

Body:
I'm trying to calculate price elasticity in product level, where I have to find Δprice/Δvolume for elasticity calculations. We have a weekly aggregated sales data with start and end date of each week. I know this is not the optimal solution but I try to create temp tables and then join them week over week to find Δprice/Δvolume, from the table:

sales2022YTD
TABLE Example

with the code:

with X as
(SELECT DATE_FROM, PRODUCT_NAME, VOLUME as volume1, NET_SALES/VOLUME as netprice1
FROM sales2022YTD
WHERE DATE_FROM = '2022-01-03'),

Y as
(SELECT DATE_FROM, PRODUCT_NAME, VOLUME as volume2, NET_SALES/VOLUME as netprice2
FROM sales2022YTD
WHERE DATE_FROM = '2022-08-03')

SELECT netprice2/netprice1 as pricediff, volume2/volume1 as volumediff
FROM Y as y1
LEFT JOIN X as x1
ON y1.PRODUCT_NAME = x1.PRODUCT_NAME
WHERE x1.PRODUCT_NAME = y1.PRODUCT_NAME

So basically I want to merge the two temp tables on the common product names and see weekly price and volume differences. With this query, I get only pricediff and volumediff columns without any value. I also would like to note that I have common product names in the two seperate weeks.

As a further step, I will extend the code to 52 weeks to calculate weekly elasticity. Any easier/less bulkier approach would be really appreciated.

Much thanks!!