问:
Tensorflow Object Detection model doesnt detect the images in a video
I developed a TensorFlow model with one class (it had a loss of 0.03 and was trained on 680 labelled images.) I am trying to use this model to detect the object on every video frame. However, whenever I run my code, it detects something in the top left of the screen in the black border surrounding the video. I tried changing the model from one trained with mobile net to one with efficientdet D3, and the same issue persisted. I then tried changing my code to require a minisize and a higher score. I have also tried letting it make multiple detections and use the one with the highest score. However, with all of these conditions, it didn't detect anything that fulfilled the requirements. my code is as follows:

```<code>import os
import time
import tensorflow as tf
import cv2
import scipy
import math
import pandas as pd
import numpy as np
from PIL import Image
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
from base64 import b64encode

#os.chdir("C:\\Users\\Ibrahim\\desktop")
PATH_TO_SAVED_MODEL = "C:/Users/Ibrahim/Desktop/fine_tuned_model/content/fine_tuned_model/saved_model"
# Load label map and obtain class names and ids
#label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
category_index=label_map_util.create_category_index_from_labelmap("C:\\Users\\Ibrahim\\Desktop\\customTF2-20221225T123609Z-001\\customTF2\\data\\label_map.pbtxt",use_display_name=True)

file = "CL_1_S0003.mp4"
video = cv2.VideoCapture(file)
ret,frame=video.read()

#getting the walls bbox
wall_bbox = cv2.selectROI(frame)
(x_wall,y_wall,x2_wall,y2_wall) = wall_bbox
print(wall_bbox)
num_cont_frames=0

#video = cv.VideoCapture(path)
ball_size = 0.22 #diameter of a regulation ball in meters
fps_cam = 10000 # Change this to the required fps of the video
fps_vid =video.get(cv2.CAP_PROP_FPS)
fps_time= fps_vid / fps_cam
#print(fps_time)

model = tf.saved_model.load(PATH_TO_SAVED_MODEL)
signature = list(model.signatures.values())[0]

# Initialize variable to track state of ball (in contact with wall or not)
in_contact = False

# Initialize variable to track whether in_contact has ever been True
in_contact_ever = False

# Initialize lists for inbound and outbound velocities
inbound_velocities = []
outbound_velocities = []

# Calculate time interval between frames in seconds
time_interval = 1 / fps_cam

scale  = []
x_list = []
y_list = []
x_def=[]
inbound_x = []
inbound_y = []
outbound_x = []
outbound_y = []
w1=[]
score_thresh = 0.8   # Minimum threshold for object detection
max_detections = 20

while True:
# Read frame from video
    ret, frame = video.read()
    if not ret:
        break

    # Add a batch dimension to the frame tensor
    frame_tensor = tf.expand_dims(frame, axis=0)

    # Get detections for image
    detections = signature(frame_tensor)  # Replace this with a call to your TensorFlow model's predict method
    scores = detections['detection_scores'][0, :max_detections].numpy()
    bboxes = detections['detection_boxes'][0, :max_detections].numpy()
    labels = detections['detection_classes'][0, :max_detections].numpy().astype(np.int64)
    labels = [category_index[n]['name'] for n in labels]

    # Initialize variables to keep track of the maximum score and corresponding bounding box
    max_score = 0
    selected_bbox = None

    # Loop through all bounding boxes
    for bbox, score in zip(bboxes, scores):
        # Check if the score is greater than the current maximum score
        if score > max_score:
            # Update the maximum score and corresponding bounding box
            max_score = score
            selected_bbox = bbox

    # Check if a bounding box was selected
    if selected_bbox is not None:
        # Extract bounding box coordinates
        (x, y, w, h) = selected_bbox

        # Filter out bounding boxes that are too small (smaller than a minimum size)
        if w >= 10 and h >= 10:
            # Draw bounding box on frame
            cv2.rectangle(frame, (int(x), int(y)), (int(x+w), int(y+h)), (0,255,0), 20, 1)
            cv2.imshow('Frame', frame)
            cv2.waitKey(1)
            x2=x+w
            y2=y+h

            # Calculate center point of bounding box
            x_center = (x + x2) / 2
            y_center = (y + y2) / 2

            # Append x and y center points to lists
            x_list.append(x_center)
            y_list.append(y_center)
            w1.append(w)

            # Calculate other variables and metrics using bbox
            scale.append(ball_size/h)  #meters per pixel.diameter in pixels or coordinate value / real diameter in m to give pixel per m for a scale factor
            #x_list.append(x2) #list of x positions of right edge
            #y_list.append(y2)

            if (x_center - w) < max(x2_wall, x_wall): #sometimes the bbox is the wrong way around
                # Set in_contact to True
                in_contact = True
                # Set in_contact_ever to True
                in_contact_ever = True
                # Increment counter
                num_cont_frames = num_cont_frames + 1
                x_defe = x2-x2_wall
                x_def.append(x_defe)
            else:
                in_contact = False

            if in_contact == False and in_contact_ever==False:
                inbound_x.append(x_center) #list of x positions at center of ball
                inbound_y.append(y_center) #list of y positions at center of ball

            if in_contact == False and in_contact_ever==True:
                outbound_x.append(x_center) #list of x positions of right edge
                outbound_y.append(x_center)
                print(outbound_x)
        else:
            cv2.putText(frame,'Error',(100,0),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),2)
        cv2.imshow('Tracking',frame)
        if cv2.waitKey(1) & 0XFF==27:
            break

cv2.destroyAllWindows()

scale_ave=scipy.stats.trim_mean(scale, 0.2) #trim_mean 20% either way to remove some extrainious results

x_diff=[]
y_diff=[]
x_len=len(x_list)-1 #minus 1 as python starts with 0 so we dont overflow

for i in range(x_len):
    x_diff.append(x_list[i]-x_list[i+1]) #find x distance per frame

for i in range(x_len):
    y_diff.append(y_list[i]-y_list[i+1])  #find y distance per frame

pyth_dist=[]
pyth_sub=[]
x2_len=len(x_diff)-1
x_speed=[]
y_speed=[]

for i in range(x2_len):
    x_speeds=x_diff[i]*scale_ave*fps_cam
    x_speed.append(x_speeds)
    y_speeds=y_diff[i]*scale_ave*fps_cam
    y_speed.append(y_speeds)
    pyth_sub=math.hypot(x_diff[i] , y_diff[i])
    pyth_dist.append(pyth_sub) #do pythagoras to find pixel distance per frame

realdist=[]
speed=[]
for i in range(x2_len):
    realdistcalc=(pyth_dist[i]*scale_ave)
    realdist.append(realdistcalc) # change from pixels to meters

for item in realdist:
    if item > 1:
        realdist.remove(item)

distlen=len(realdist)-1

for i in range(distlen):
    speedcalc=realdist[i]*fps_cam
    speed.append(speedcalc)

contact_time=num_cont_frames/fps_cam
print(contact_time)

if x_def:
    realxdef = min(x_def)*scale_ave
else:
    realxdef = 0

print(realxdef)

# Calculate inbound velocities
inbound_x_diff = []
inbound_y_diff = []
# Calculate inbound x- and y-velocities
inbound_x_velocities = []
inbound_y_velocities = []
inbound_len = len(inbound_x) - 1

# Calculate differences between consecutive x and y coordinates
for i in range(inbound_len):
    inbound_x_diff.append(inbound_x[i] - inbound_x[i + 1])
    inbound_y_diff.append(inbound_y[i] - inbound_y[i + 1])

# Calculate inbound velocities in meters per second
inbound_velocities = []
for i in range(inbound_len):
    inbound_x_velocity = inbound_x_diff[i] * scale_ave * fps_cam
    inbound_x_velocities.append(inbound_x_velocity)
    inbound_y_velocity = inbound_y_diff[i] * scale_ave * fps_cam
    inbound_y_velocities.append(inbound_y_velocity)
    inbound_velocity = math.hypot(inbound_x_diff[i], inbound_y_diff[i]) * scale_ave * fps_cam
    inbound_velocities.append(inbound_velocity)

# Calculate outbound velocities
outbound_x_diff = []
outbound_y_diff = []

outbound_len = len(outbound_x) - 1

# Calculate differences between consecutive x and y coordinates
for i in range(outbound_len):
    outbound_x_diff.append(outbound_x[i] - outbound_x[i + 1])
    outbound_y_diff.append(outbound_y[i] - outbound_y[i + 1])

# Calculate outbound velocities in meters per second
outbound_velocities = []
outbound_x_velocities = []
outbound_y_velocities = []

for i in range(outbound_len):
    outbound_x_velocity = outbound_x_diff[i] * scale_ave * fps_cam
    outbound_x_velocities.append(outbound_x_velocity)
    outbound_y_velocity = outbound_y_diff[i] * scale_ave * fps_cam
    outbound_y_velocities.append(outbound_y_velocity)
    outbound_velocity = math.hypot(outbound_x_diff[i], outbound_y_diff[i]) * scale_ave * fps_cam
    outbound_velocities.append(outbound_velocity)e
</code>```

I expected a bounding box around the ball. I tried changing the model, increasing the number of maximum detections, adding a minimum size to the detections, and increasing the required score for detection.

Body:
I developed a TensorFlow model with one class (it had a loss of 0.03 and was trained on 680 labelled images.) I am trying to use this model to detect the object on every video frame. However, whenever I run my code, it detects something in the top left of the screen in the black border surrounding the video. I tried changing the model from one trained with mobile net to one with efficientdet D3, and the same issue persisted. I then tried changing my code to require a minisize and a higher score. I have also tried letting it make multiple detections and use the one with the highest score. However, with all of these conditions, it didn't detect anything that fulfilled the requirements. my code is as follows:

import os
import time
import tensorflow as tf
import cv2
import scipy
import math
import pandas as pd
import numpy as np
from PIL import Image
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
from base64 import b64encode

#os.chdir("C:\\Users\\Ibrahim\\desktop")
PATH_TO_SAVED_MODEL = "C:/Users/Ibrahim/Desktop/fine_tuned_model/content/fine_tuned_model/saved_model"
# Load label map and obtain class names and ids
#label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
category_index=label_map_util.create_category_index_from_labelmap("C:\\Users\\Ibrahim\\Desktop\\customTF2-20221225T123609Z-001\\customTF2\\data\\label_map.pbtxt",use_display_name=True)

file = "CL_1_S0003.mp4"
video = cv2.VideoCapture(file)
ret,frame=video.read()

#getting the walls bbox
wall_bbox = cv2.selectROI(frame)
(x_wall,y_wall,x2_wall,y2_wall) = wall_bbox
print(wall_bbox)
num_cont_frames=0

#video = cv.VideoCapture(path)
ball_size = 0.22 #diameter of a regulation ball in meters
fps_cam = 10000 # Change this to the required fps of the video
fps_vid =video.get(cv2.CAP_PROP_FPS)
fps_time= fps_vid / fps_cam
#print(fps_time)

model = tf.saved_model.load(PATH_TO_SAVED_MODEL)
signature = list(model.signatures.values())[0]

# Initialize variable to track state of ball (in contact with wall or not)
in_contact = False

# Initialize variable to track whether in_contact has ever been True
in_contact_ever = False

# Initialize lists for inbound and outbound velocities
inbound_velocities = []
outbound_velocities = []

# Calculate time interval between frames in seconds
time_interval = 1 / fps_cam

scale  = []
x_list = []
y_list = []
x_def=[]
inbound_x = []
inbound_y = []
outbound_x = []
outbound_y = []
w1=[]
score_thresh = 0.8   # Minimum threshold for object detection
max_detections = 20

while True:
# Read frame from video
    ret, frame = video.read()
    if not ret:
        break

    # Add a batch dimension to the frame tensor
    frame_tensor = tf.expand_dims(frame, axis=0)

    # Get detections for image
    detections = signature(frame_tensor)  # Replace this with a call to your TensorFlow model's predict method
    scores = detections['detection_scores'][0, :max_detections].numpy()
    bboxes = detections['detection_boxes'][0, :max_detections].numpy()
    labels = detections['detection_classes'][0, :max_detections].numpy().astype(np.int64)
    labels = [category_index[n]['name'] for n in labels]

    # Initialize variables to keep track of the maximum score and corresponding bounding box
    max_score = 0
    selected_bbox = None

    # Loop through all bounding boxes
    for bbox, score in zip(bboxes, scores):
        # Check if the score is greater than the current maximum score
        if score > max_score:
            # Update the maximum score and corresponding bounding box
            max_score = score
            selected_bbox = bbox

    # Check if a bounding box was selected
    if selected_bbox is not None:
        # Extract bounding box coordinates
        (x, y, w, h) = selected_bbox

        # Filter out bounding boxes that are too small (smaller than a minimum size)
        if w >= 10 and h >= 10:
            # Draw bounding box on frame
            cv2.rectangle(frame, (int(x), int(y)), (int(x+w), int(y+h)), (0,255,0), 20, 1)
            cv2.imshow('Frame', frame)
            cv2.waitKey(1)
            x2=x+w
            y2=y+h

            # Calculate center point of bounding box
            x_center = (x + x2) / 2
            y_center = (y + y2) / 2

            # Append x and y center points to lists
            x_list.append(x_center)
            y_list.append(y_center)
            w1.append(w)

            # Calculate other variables and metrics using bbox
            scale.append(ball_size/h)  #meters per pixel.diameter in pixels or coordinate value / real diameter in m to give pixel per m for a scale factor
            #x_list.append(x2) #list of x positions of right edge
            #y_list.append(y2)

            if (x_center - w) < max(x2_wall, x_wall): #sometimes the bbox is the wrong way around
                # Set in_contact to True
                in_contact = True
                # Set in_contact_ever to True
                in_contact_ever = True
                # Increment counter
                num_cont_frames = num_cont_frames + 1
                x_defe = x2-x2_wall
                x_def.append(x_defe)
            else:
                in_contact = False

            if in_contact == False and in_contact_ever==False:
                inbound_x.append(x_center) #list of x positions at center of ball
                inbound_y.append(y_center) #list of y positions at center of ball

            if in_contact == False and in_contact_ever==True:
                outbound_x.append(x_center) #list of x positions of right edge
                outbound_y.append(x_center)
                print(outbound_x)
        else:
            cv2.putText(frame,'Error',(100,0),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),2)
        cv2.imshow('Tracking',frame)
        if cv2.waitKey(1) & 0XFF==27:
            break

cv2.destroyAllWindows()

scale_ave=scipy.stats.trim_mean(scale, 0.2) #trim_mean 20% either way to remove some extrainious results

x_diff=[]
y_diff=[]
x_len=len(x_list)-1 #minus 1 as python starts with 0 so we dont overflow

for i in range(x_len):
    x_diff.append(x_list[i]-x_list[i+1]) #find x distance per frame

for i in range(x_len):
    y_diff.append(y_list[i]-y_list[i+1])  #find y distance per frame

pyth_dist=[]
pyth_sub=[]
x2_len=len(x_diff)-1
x_speed=[]
y_speed=[]

for i in range(x2_len):
    x_speeds=x_diff[i]*scale_ave*fps_cam
    x_speed.append(x_speeds)
    y_speeds=y_diff[i]*scale_ave*fps_cam
    y_speed.append(y_speeds)
    pyth_sub=math.hypot(x_diff[i] , y_diff[i])
    pyth_dist.append(pyth_sub) #do pythagoras to find pixel distance per frame

realdist=[]
speed=[]
for i in range(x2_len):
    realdistcalc=(pyth_dist[i]*scale_ave)
    realdist.append(realdistcalc) # change from pixels to meters

for item in realdist:
    if item > 1:
        realdist.remove(item)

distlen=len(realdist)-1

for i in range(distlen):
    speedcalc=realdist[i]*fps_cam
    speed.append(speedcalc)

contact_time=num_cont_frames/fps_cam
print(contact_time)

if x_def:
    realxdef = min(x_def)*scale_ave
else:
    realxdef = 0

print(realxdef)

# Calculate inbound velocities
inbound_x_diff = []
inbound_y_diff = []
# Calculate inbound x- and y-velocities
inbound_x_velocities = []
inbound_y_velocities = []
inbound_len = len(inbound_x) - 1

# Calculate differences between consecutive x and y coordinates
for i in range(inbound_len):
    inbound_x_diff.append(inbound_x[i] - inbound_x[i + 1])
    inbound_y_diff.append(inbound_y[i] - inbound_y[i + 1])

# Calculate inbound velocities in meters per second
inbound_velocities = []
for i in range(inbound_len):
    inbound_x_velocity = inbound_x_diff[i] * scale_ave * fps_cam
    inbound_x_velocities.append(inbound_x_velocity)
    inbound_y_velocity = inbound_y_diff[i] * scale_ave * fps_cam
    inbound_y_velocities.append(inbound_y_velocity)
    inbound_velocity = math.hypot(inbound_x_diff[i], inbound_y_diff[i]) * scale_ave * fps_cam
    inbound_velocities.append(inbound_velocity)

# Calculate outbound velocities
outbound_x_diff = []
outbound_y_diff = []

outbound_len = len(outbound_x) - 1

# Calculate differences between consecutive x and y coordinates
for i in range(outbound_len):
    outbound_x_diff.append(outbound_x[i] - outbound_x[i + 1])
    outbound_y_diff.append(outbound_y[i] - outbound_y[i + 1])

# Calculate outbound velocities in meters per second
outbound_velocities = []
outbound_x_velocities = []
outbound_y_velocities = []

for i in range(outbound_len):
    outbound_x_velocity = outbound_x_diff[i] * scale_ave * fps_cam
    outbound_x_velocities.append(outbound_x_velocity)
    outbound_y_velocity = outbound_y_diff[i] * scale_ave * fps_cam
    outbound_y_velocities.append(outbound_y_velocity)
    outbound_velocity = math.hypot(outbound_x_diff[i], outbound_y_diff[i]) * scale_ave * fps_cam
    outbound_velocities.append(outbound_velocity)e

I expected a bounding box around the ball. I tried changing the model, increasing the number of maximum detections, adding a minimum size to the detections, and increasing the required score for detection.


来源: stackexchange

问:
How to make sure all inserted instruction compiled?
I'm working on RISC-v ISA editing and there should be a compiler for my modified ISA.
The modification is to insert authentication code into return address and authenticate it. Thus, the new instruction should appear in pair when the program call and return from functions.
But when I'm using GNU toolchain for RISC-v, some authentication instructions disappeared in the binary, and that lead to fetch segfault because unauthenticated RA is out of range.

Here are the added parts of compiler: (pac and aut are instructions I added)

```<code>void
riscv_expand_prologue (int style)
{

...
//veriable defination and initialization

if (cfun-\>machine-\>naked_p)
{
gcc_assert (style == NORMAL_RETURN);

      emit_jump_insn (gen_return ());

      return;
    }

+ //load key
+ insn = emit(gen_lui(gen_rtx_REG(Pmode,T3_REGNUM),
+ GEN_INT(32)));
+ insn = emit(gen_slli(gen_rtx_REG(Pmode,T3_REGNUM),
+ gen_rtx_REG(Pmode,T3_REGNUM),
+ GEN_INT(32)));
+ //inserting pac into ra
+ insn = emit(gen_pac(gen_rtx_REG(Pmode,RETURN_ADDR_REGNUM),
+                      gen_rtx_REG(Pmode,RETURN_ADDR_REGNUM),
+                      gen_rtx_REG(Pmode,T3_REGNUM)));
+ add_reg_note (insn, REG_CFA_TOGGLE_RA_MANGLE, const0_rtx);
+ RTX_FRAME_RELATED_P (insn) = 1;

...

}

void
riscv_expand_epilogue (int style)
{

...
//veriable defination and initialization

if (cfun-\>machine-\>naked_p)
{
gcc_assert (style == NORMAL_RETURN);

      emit_jump_insn (gen_return ());

      return;

}

+ /\* pac \*/
+ //load key
+ insn = emit(gen_lui(gen_rtx_REG(Pmode,T3_REGNUM),
+ GEN_INT(32)));
+ insn = emit(gen_slli(gen_rtx_REG(Pmode,T3_REGNUM),
+ gen_rtx_REG(Pmode,T3_REGNUM),
+ GEN_INT(32)));
+ //authenticate ra and strip pac from ra
+ insn = emit(gen_aut(gen_rtx_REG(Pmode,RETURN_ADDR_REGNUM),
+                      gen_rtx_REG(Pmode,RETURN_ADDR_REGNUM),
+                      gen_rtx_REG(Pmode,T3_REGNUM)));
+ add_reg_note (insn, REG_CFA_TOGGLE_RA_MANGLE, const0_rtx);
+ RTX_FRAME_RELATED_P (insn) = 1;

...

}
</code>```

when I compiling helloworld c program, I found the number of aut instruction is only half of pac's. But I searched the source code of RISC-v gcc and found the riscv_expand_prologue function and riscv_expand_epilogue function are called in pair.

What should I do to make these two instructions properly appeared in pair in the prologue and epilogue?

ContentLicense: CC BY-SA 4.0

Body:
I'm working on RISC-v ISA editing and there should be a compiler for my modified ISA.
The modification is to insert authentication code into return address and authenticate it. Thus, the new instruction should appear in pair when the program call and return from functions.
But when I'm using GNU toolchain for RISC-v, some authentication instructions disappeared in the binary, and that lead to fetch segfault because unauthenticated RA is out of range.

Here are the added parts of compiler: (pac and aut are instructions I added)

void
riscv_expand_prologue (int style)
{

...
//veriable defination and initialization

if (cfun-\>machine-\>naked_p)
{
gcc_assert (style == NORMAL_RETURN);

      emit_jump_insn (gen_return ());

      return;
    }

+ //load key
+ insn = emit(gen_lui(gen_rtx_REG(Pmode,T3_REGNUM),
+ GEN_INT(32)));
+ insn = emit(gen_slli(gen_rtx_REG(Pmode,T3_REGNUM),
+ gen_rtx_REG(Pmode,T3_REGNUM),
+ GEN_INT(32)));
+ //inserting pac into ra
+ insn = emit(gen_pac(gen_rtx_REG(Pmode,RETURN_ADDR_REGNUM),
+                      gen_rtx_REG(Pmode,RETURN_ADDR_REGNUM),
+                      gen_rtx_REG(Pmode,T3_REGNUM)));
+ add_reg_note (insn, REG_CFA_TOGGLE_RA_MANGLE, const0_rtx);
+ RTX_FRAME_RELATED_P (insn) = 1;

...

}

void
riscv_expand_epilogue (int style)
{

...
//veriable defination and initialization

if (cfun-\>machine-\>naked_p)
{
gcc_assert (style == NORMAL_RETURN);

      emit_jump_insn (gen_return ());

      return;

}

+ /\* pac \*/
+ //load key
+ insn = emit(gen_lui(gen_rtx_REG(Pmode,T3_REGNUM),
+ GEN_INT(32)));
+ insn = emit(gen_slli(gen_rtx_REG(Pmode,T3_REGNUM),
+ gen_rtx_REG(Pmode,T3_REGNUM),
+ GEN_INT(32)));
+ //authenticate ra and strip pac from ra
+ insn = emit(gen_aut(gen_rtx_REG(Pmode,RETURN_ADDR_REGNUM),
+                      gen_rtx_REG(Pmode,RETURN_ADDR_REGNUM),
+                      gen_rtx_REG(Pmode,T3_REGNUM)));
+ add_reg_note (insn, REG_CFA_TOGGLE_RA_MANGLE, const0_rtx);
+ RTX_FRAME_RELATED_P (insn) = 1;

...

}

when I compiling helloworld c program, I found the number of aut instruction is only half of pac's. But I searched the source code of RISC-v gcc and found the riscv_expand_prologue function and riscv_expand_epilogue function are called in pair.

What should I do to make these two instructions properly appeared in pair in the prologue and epilogue?


问:
Multiple loop functions parallel running in Python
I've 3 loops i want to be executed in parallel until the exit of program.
Actually I used this solution but i think is not optimal:

```<code>class Window(tk.Tk):
    def __init__(self, loop,app):
        self.loop = loop
        self.app = app
        self.root = tk.Tk()

    async def show(self):
        while True:
            self.root.update()
            await asyncio.sleep(0.1)

class App:
    async def exec(self):
        self.window = Window(asyncio.get_event_loop(),self)
        await asyncio.gather(self.window.show(), self.connectWS(),self.readSerial())

    async def readSerial(self):
        self.serial = serial.serial_for_url('/dev/cu.usbserial-1430', baudrate=9600, timeout=5)
        self.serial.isOpen()
        self.serial.flushInput() #flush input buffer, discarding all its contents
        self.serial.flushOutput()
        while True:
            response = self.serial.read(1)
            await asyncio.sleep(0.1)

    async def connectWS(self):
        try:
            async with websockets.connect(
                "ws://mysocket.com") as ws:
                self.ws = WebSocketHandler(str(uuid.getnode()), ws,self)
                await asyncio.gather(self.ws.start(), self.ws.send_boot_payload())
        except websockets.exceptions.ConnectionClosedError:
            print("DISCONNECTED")
            call_later(10,self.connectWS) #reconnect

asyncio.run(App().exec())
</code>```

Can someone suggest me the best practice to execute 3 (or more) loops (actually are a WebSocket, a serial reader and a Tkinter loop that update UI basing on serial and websocket)?

Body:
I've 3 loops i want to be executed in parallel until the exit of program.
Actually I used this solution but i think is not optimal:

class Window(tk.Tk):
    def __init__(self, loop,app):
        self.loop = loop
        self.app = app
        self.root = tk.Tk()

    async def show(self):
        while True:
            self.root.update()
            await asyncio.sleep(0.1)

class App:
    async def exec(self):
        self.window = Window(asyncio.get_event_loop(),self)
        await asyncio.gather(self.window.show(), self.connectWS(),self.readSerial())

    async def readSerial(self):
        self.serial = serial.serial_for_url('/dev/cu.usbserial-1430', baudrate=9600, timeout=5)
        self.serial.isOpen()
        self.serial.flushInput() #flush input buffer, discarding all its contents
        self.serial.flushOutput()
        while True:
            response = self.serial.read(1)
            await asyncio.sleep(0.1)

    async def connectWS(self):
        try:
            async with websockets.connect(
                "ws://mysocket.com") as ws:
                self.ws = WebSocketHandler(str(uuid.getnode()), ws,self)
                await asyncio.gather(self.ws.start(), self.ws.send_boot_payload())
        except websockets.exceptions.ConnectionClosedError:
            print("DISCONNECTED")
            call_later(10,self.connectWS) #reconnect

asyncio.run(App().exec())

Can someone suggest me the best practice to execute 3 (or more) loops (actually are a WebSocket, a serial reader and a Tkinter loop that update UI basing on serial and websocket)?


问:
SSH connection with VS Code by passing scripts
I have some scripts in a linux server, in the folder /etc/profile.d/ these are supposed to run whenever a new ssh connection is made. However they are not running when the ssh connection is made with VSCode windows.

The scripts in /etc/profile.d/ are working perfectly for connections with terminals, Putty and even VSCode linux.


问:
Fetched data shows undefined in first render
UPDATE:
The data is coming properly, and there is no any undefined in the component base. But inside the function, the data doesn't update itself. It's always undefined. I also tried to send the data as argument, it didn't work.
I tried useCallback again, didn't work as well.

I have a page includes some components. When I click a button, a Modal shows up. Whenever I open the Modal, I am getting data from server by using SWR. The problem I am facing is whenever I click a button inside the Modal, the data fetches again and again which is not good. I just want to fetch data only when I open the Modal.

Because of this problem, one function in the Modal doesn't work. When I click a button, it runs the function with undefined instead of normal fetched data - array of objects -

I tried to use useCallback with dependencies, and it didn't work.

I also tried to create a new state and set the data in it like below, but it didn't work again;

```<code>useEffect(() => {
if(folders){
   setData(folders)
}
},[folders])
</code>```

The codes I use for fetching data are;

import useSWR from 'swr';

```<code>export default function useFoldersAndDocuments() {
  const fetcher = (url: string) => fetch(url).then((r) => r.json());

  const { data: folders, error: foldersError } = useSWR(
    '/api/folders',
    fetcher
  );
  const { data: documents, error: documentsError } = useSWR(
    '/api/documents',
    fetcher
  );

  return { documents, folders };
}
</code>```

and the function is;

```<code>function expandGroupedListItem(id: string) {
    console.log(selectedItemIds, 'bfdbfd');

    const currentFolder = folders?.filter((a) => a.id === id);

    if (!selectedItemIds.includes(id)) {
      setSelectedItemIds((prev) => [...prev, id]);
    }

    if (currentFolder && currentFolder[0]?.parentFolder !== null) {
      expandGroupedListItem(currentFolder[0]?.parentFolder);
    }
  }
</code>```

currentFolder is always undefined.

Is there any solution for this problem?

Here is the console.log. This is folders firstly shows undefined then shows the data.

I also render the component like this, but still doesn't work.

```<code>if (!folders) {
    return null;
  }
</code>```

Body:
UPDATE:
The data is coming properly, and there is no any undefined in the component base. But inside the function, the data doesn't update itself. It's always undefined. I also tried to send the data as argument, it didn't work.
I tried useCallback again, didn't work as well.

I have a page includes some components. When I click a button, a Modal shows up. Whenever I open the Modal, I am getting data from server by using SWR. The problem I am facing is whenever I click a button inside the Modal, the data fetches again and again which is not good. I just want to fetch data only when I open the Modal.

Because of this problem, one function in the Modal doesn't work. When I click a button, it runs the function with undefined instead of normal fetched data - array of objects -

I tried to use useCallback with dependencies, and it didn't work.

I also tried to create a new state and set the data in it like below, but it didn't work again;

useEffect(() => {
if(folders){
   setData(folders)
}
},[folders])

The codes I use for fetching data are;

import useSWR from 'swr';

export default function useFoldersAndDocuments() {
  const fetcher = (url: string) => fetch(url).then((r) => r.json());

  const { data: folders, error: foldersError } = useSWR(
    '/api/folders',
    fetcher
  );
  const { data: documents, error: documentsError } = useSWR(
    '/api/documents',
    fetcher
  );

  return { documents, folders };
}

and the function is;

function expandGroupedListItem(id: string) {
    console.log(selectedItemIds, 'bfdbfd');

    const currentFolder = folders?.filter((a) => a.id === id);

    if (!selectedItemIds.includes(id)) {
      setSelectedItemIds((prev) => [...prev, id]);
    }

    if (currentFolder && currentFolder[0]?.parentFolder !== null) {
      expandGroupedListItem(currentFolder[0]?.parentFolder);
    }
  }

currentFolder is always undefined.

Is there any solution for this problem?

Here is the console.log. This is folders firstly shows undefined then shows the data.

I also render the component like this, but still doesn't work.

if (!folders) {
    return null;
  }


问:
Flutter How to remove certaint documents from a stream in Firestore
I want to stream documents from my collection orders.
Here I stream all documents in my collection orders where the parameter progress is equal to pool.

This is how I do it:

```<code>Stream<List<Order>> streamOrderPool() {
    final FirebaseAuth auth = FirebaseAuth.instance;
    final User? user = auth.currentUser;
    final uid = user!.uid;

    var ref = _db.collection('orders').where('progress', isEqualTo: 'pool');

    return ref.snapshots().map(
        (list) => list.docs.map((doc) => Order.fromJson(doc.data())).toList());

  }
</code>```

What I want to do is to remove all documents where the parameter dismissedIds contains uid.

This is how I solved it in a futurebuilder:

```<code> Future<List<Order>> getOrdersPool() async {

    final FirebaseAuth auth = FirebaseAuth.instance;
    final User? user = auth.currentUser;
    final uid = user!.uid;

    var ref = _db.collection('orders').where('progress', isEqualTo: 'pool');

    var snapshot = await ref.get();
    var data = snapshot.docs.map((s) => s.data());

    var orders = data.map((d) => Order.fromJson(d));

    var orderslist = orders.toList();
    orderslist.removeWhere((order) => order.dismissedIds.contains(uid));
    orderslist.sort((b, a) => a.startDate.compareTo(b.startDate));

    return orderslist;
  }
</code>```

How do I get the same result in a streambuilder, is it possible to use removeWhere somehow? How do I remove all documents from stream where dissmissedIds contains uid?

Body:
I want to stream documents from my collection orders.
Here I stream all documents in my collection orders where the parameter progress is equal to pool.

This is how I do it:

Stream<List<Order>> streamOrderPool() {
    final FirebaseAuth auth = FirebaseAuth.instance;
    final User? user = auth.currentUser;
    final uid = user!.uid;

    var ref = _db.collection('orders').where('progress', isEqualTo: 'pool');

    return ref.snapshots().map(
        (list) => list.docs.map((doc) => Order.fromJson(doc.data())).toList());

  }

What I want to do is to remove all documents where the parameter dismissedIds contains uid.

This is how I solved it in a futurebuilder:

 Future<List<Order>> getOrdersPool() async {

    final FirebaseAuth auth = FirebaseAuth.instance;
    final User? user = auth.currentUser;
    final uid = user!.uid;

    var ref = _db.collection('orders').where('progress', isEqualTo: 'pool');

    var snapshot = await ref.get();
    var data = snapshot.docs.map((s) => s.data());

    var orders = data.map((d) => Order.fromJson(d));

    var orderslist = orders.toList();
    orderslist.removeWhere((order) => order.dismissedIds.contains(uid));
    orderslist.sort((b, a) => a.startDate.compareTo(b.startDate));

    return orderslist;
  }

How do I get the same result in a streambuilder, is it possible to use removeWhere somehow? How do I remove all documents from stream where dissmissedIds contains uid?


问:
How can I allocate the memory space for an object but wait until a later point to initialize it using a constructor
I guess this is kinda far-fetched, but basically, I'm trying to create an instance of a class that I need to work on as if it were globally declared but initialize it once I have obtained some data from memory (previously stored data in the microcontroller). It's a project with an ESP8266 MCU that allows you to configure an led display via wifi, and for that my teammates wanted to make use of an already existing library, the problem is that in order for the user to be able to change the number of devices that they're going to use I would need to (from what I can gather, I started learning about classes a few days ago, I'm still in diapers) use the constructor again since that's when you're supposed to provide the number of devices (after that I'm not sure where I could change that variable again, I don't even know exactly what the constructor does because it's only declared in the .h file but then I wasn't able to find where is it that they define the function. There is a variable in the class that seems to have something to do with that but it's private).
Originally I thought of simply passing the value to the void loop() and the other functions I use in the code, but that proved to be ineffective given that I also use another library called ESPAsyncwebserver that returns (I think that's how it works) to the void setup() (to all the places where I used 'objectoftheclass.on()' because it makes a callback) function whenever there's an HTTP request so it throws an error saying that the object was not declared in that scope (which is where I'd be creating it in). The other solution I thought of was to copy one object into an already existing global one once I had the data I needed from memory but that also throws an error.

Is there a way to allocate the memory required for a class outside of main (like a global variable) and then make an instance of that class later on but in that space? Or like, maybe a way of not using a constructor for that object until a later point in time (without really using the object at all before I use the constructor)?

I didn't wanna post the code here because it is both messy and unnecessarily lengthy for a post but tell me if it would help because I'm not quite sure if the idea of what I need here is all that clear, thanks.


问:
can't remove word by word from a file until he became empty
i want to delete a matching word between two files , and put the rest in third file , until the third file contains nothing .

but i see that the code remove only first word .

```<code>FILE *f,*temp,*temp2;
char word[25],original_word[25];
</code>```

f = original file /  word = word from temp2 / original_word = word from f

```<code>f = fopen("test.txt","r"); //original
temp2 = fopen("temp2.txt","r"); //temp 2 equal the original file
temp = fopen("temp.txt","w"); // temp is the third file that i want to erase all his elements

while(!feof(f)){

    fscanf(f,"%s",original_word);
    rewind(temp2);

    while(!feof(temp2)){
        fscanf(temp2,"%s",word);

        if( strcmp(word,original_word) != 0 ){
            // if the two words not equals , put word in the temp
            fprintf(temp,"%s ",word);

        }
        // a condition from the original file and temp2 that every phrase ends with "."
        if (strcmp(word,".") == 0)
            fputs("\n",temp);

    }

}
</code>```

in the end closing files

```<code>        fclose(f);
        fclose(temp);
        fclose(temp2);
</code>```

Body:
i want to delete a matching word between two files , and put the rest in third file , until the third file contains nothing .

but i see that the code remove only first word .

FILE *f,*temp,*temp2;
char word[25],original_word[25];

f = original file /  word = word from temp2 / original_word = word from f

f = fopen("test.txt","r"); //original
temp2 = fopen("temp2.txt","r"); //temp 2 equal the original file
temp = fopen("temp.txt","w"); // temp is the third file that i want to erase all his elements

while(!feof(f)){

    fscanf(f,"%s",original_word);
    rewind(temp2);

    while(!feof(temp2)){
        fscanf(temp2,"%s",word);

        if( strcmp(word,original_word) != 0 ){
            // if the two words not equals , put word in the temp
            fprintf(temp,"%s ",word);

        }
        // a condition from the original file and temp2 that every phrase ends with "."
        if (strcmp(word,".") == 0)
            fputs("\n",temp);

    }

}

in the end closing files

        fclose(f);
        fclose(temp);
        fclose(temp2);


问:
DBT - how can i add model configuration (using a macro on {{this}}) in dbt_project.yml
I want to add node_color to all of my dbt models based on my filename prefix to make it easier to navigate through my dbt documentation :

fact_ => red

base__ => black.

To do so i have a macro that works well :

```<code>{% macro get_model_color(model) %}

    {% set default_color = 'blue' %}
    {% set ns = namespace(model_color=default_color) %}

    {% set dict_patterns = {"base__[a-z0-9_]+" : "black", "ref_[a-z0-9_]+" : "yellow", "fact_[a-z0-9_]+" : "red"} %}

    {% set re = modules.re %}

    {% for pattern, color in dict_patterns.items() %}

        {% set is_match = re.match(pattern, model.identifier, re.IGNORECASE) %}
        {% if is_match %}
            {% set ns.model_color = color %}
        {% endif %}

    {% endfor %}

    {{ return({'node_color': ns.model_color}) }}
{% endmacro %}
</code>```

And i call it in my model .sql :

```<code>{{config(
    materialized = 'table',
    tags=['daily'],
    docs=get_model_color(this),
)}}
</code>```

This works well but force me to add this line of code in all my models (and in all the new ones).

Is there a way i can define it in my dbt_project.yml to make it available to all my models automatically?

I have tried many things like the config jinja function or this kind of code in dbt_project.yml

```<code>    +docs:
        node_color: "{{ get_model_color(this) }}"
</code>```

returning Could not render {{ get_model_color(this) }}: 'get_model_color' is undefined

But nothing seems to work

Any idea? Thanks

Body:
I want to add node_color to all of my dbt models based on my filename prefix to make it easier to navigate through my dbt documentation :

fact_ => red

base__ => black.

To do so i have a macro that works well :

{% macro get_model_color(model) %}

    {% set default_color = 'blue' %}
    {% set ns = namespace(model_color=default_color) %}

    {% set dict_patterns = {"base__[a-z0-9_]+" : "black", "ref_[a-z0-9_]+" : "yellow", "fact_[a-z0-9_]+" : "red"} %}

    {% set re = modules.re %}

    {% for pattern, color in dict_patterns.items() %}

        {% set is_match = re.match(pattern, model.identifier, re.IGNORECASE) %}
        {% if is_match %}
            {% set ns.model_color = color %}
        {% endif %}

    {% endfor %}

    {{ return({'node_color': ns.model_color}) }}
{% endmacro %}

And i call it in my model .sql :

{{config(
    materialized = 'table',
    tags=['daily'],
    docs=get_model_color(this),
)}}

This works well but force me to add this line of code in all my models (and in all the new ones).

Is there a way i can define it in my dbt_project.yml to make it available to all my models automatically?

I have tried many things like the config jinja function or this kind of code in dbt_project.yml

    +docs:
        node_color: "{{ get_model_color(this) }}"

returning Could not render {{ get_model_color(this) }}: 'get_model_color' is undefined

But nothing seems to work

Any idea? Thanks


问:
After returning value from Async function, it takes 10-15 seconds to close the event loop
Here I am using async function for connecting the websocket,

```<code>async def getData(list):
     async with websockets.connect(endpoint) as websocket:
          result = await getConnection(websocket)
          if result:
               await websocket.send(str(strMessage))
               response = await websocket.recv()
               print('Returning from async function.....')
               return response
          return False

</code>```

Function call :

```<code>def callingFunction():
     result = asyncio.run(getData(list))
     print(result)
</code>```

here even if the print('Returning from async function.....') line executes, it takes 10-15 seconds to get back to the callingFunction() and print the result.

Thank You !!!

Body:
Here I am using async function for connecting the websocket,

async def getData(list):
     async with websockets.connect(endpoint) as websocket:
          result = await getConnection(websocket)
          if result:
               await websocket.send(str(strMessage))
               response = await websocket.recv()
               print('Returning from async function.....')
               return response
          return False

Function call :

def callingFunction():
     result = asyncio.run(getData(list))
     print(result)

here even if the print('Returning from async function.....') line executes, it takes 10-15 seconds to get back to the callingFunction() and print the result.

Thank You !!!


问:
Bot does not execute commands with queries in MySql after a few hours
After starting everything works fine, the commands that require connection to the database are executed. After 5-6 hours, the commands will no longer be executed, local commands work normally. Connection to base is made through a pool. At the end of each command, the connection is returned to the pool. What is the problem to look for? And sorry for the google translate

Connecting to the base:

```<code>import mysql.connector
from bestconfig import Config
from mysql.connector import pooling
from mysql.connector import Error

config = Config() #config['version']

def getConnection():
    try:
        connection_pool = pooling.MySQLConnectionPool(pool_name="discord_pool",
                                                    pool_size=2,
                                                    pool_reset_session=True,
                                                    host=config['host'],
                                                    database=config['database'],
                                                    user=config['user'],
                                                    password=config['password'])

        # Get connection object from a pool
        connection_object = connection_pool.get_connection()

        if connection_object.is_connected():
            db_Info = connection_object.get_server_info()
            print("Connected to MySQL database using connection pool ... MySQL Server version on ", db_Info)

            cursor = connection_object.cursor()
            cursor.execute("select database();")
            record = cursor.fetchone()
            print("Your connected to - ", record)
        else:
            connection_object.reconnect(attempts=1, delay=0)

    except Error as e:
        print("Error while connecting to MySQL using Connection pool ", e)
    return connection_object
</code>```

Python logs:

```<code>2022-12-25 05:52:00,155 INFO Shard ID None has successfully RESUMED session 5a6cfa0f2871c73636a54087ddb35c3a.
2022-12-25 07:09:37,816 ERROR Attempting a reconnect in 1.11s
Traceback (most recent call last):
  File "/usr/lib/python3.11/asyncio/tasks.py", line 490, in wait_for
    return fut.result()
           ^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/discord/gateway.py", line 372, in from_client
    socket = await client.http.ws_connect(str(url))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/discord/http.py", line 536, in ws_connect
    return await self.__session.ws_connect(url, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/client.py", line 779, in _ws_connect
    resp = await self.request(
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/client.py", line 536, in _request
    conn = await self._connector.connect(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/connector.py", line 540, in connect
    proto = await self._create_connection(req, traces, timeout)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/connector.py", line 901, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/connector.py", line 1175, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/connector.py", line 980, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/asyncio/base_events.py", line 1063, in create_connection
    sock = await self._connect_sock(
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/asyncio/base_events.py", line 967, in _connect_sock
    await self.sock_connect(sock, address)
  File "/usr/lib/python3.11/asyncio/selector_events.py", line 634, in sock_connect
    return await fut
           ^^^^^^^^^
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.11/dist-packages/discord/client.py", line 624, in connect
    self.ws = await asyncio.wait_for(coro, timeout=60.0)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/asyncio/tasks.py", line 492, in wait_for
    raise exceptions.TimeoutError() from exc
TimeoutError
2022-12-25 07:09:39,518 INFO Shard ID None has successfully RESUMED session 5a6cfa0f2871c73636a54087ddb35c3a.
2022-12-25 07:27:23,366 INFO Shard ID None has successfully RESUMED session 5a6cfa0f2871c73636a54087ddb35c3a.
2022-12-25 07:44:19,708 INFO Shard ID None has successfully RESUMED session 5a6cfa0f2871c73636a54087ddb35c3a.
</code>```

MySQL logs:

```<code>2022-12-24T23:31:25.904328Z 718 [Warning] [MY-010055] [Server] IP address '2.57.122.23' could not be resolved: Name or service not known
2022-12-25T00:43:30.330033Z 719 [Warning] [MY-010058] [Server] Hostname 'zg-1220a-127.stretchoid.com' does not resolve to '192.241.224.10'.
2022-12-25T03:47:37.608995Z 723 [Warning] [MY-010055] [Server] IP address '46.216.30.14' could not be resolved: Name or service not known
2022-12-25T03:47:37.609192Z 722 [Warning] [MY-010055] [Server] IP address '46.216.30.14' could not be resolved: Name or service not known
2022-12-25T05:31:12.652320Z 772 [Warning] [MY-010055] [Server] IP address '206.189.208.4' could not be resolved: Name or service not known
2022-12-25T06:19:41.620580Z 773 [Warning] [MY-010055] [Server] IP address '92.255.85.233' could not be resolved: Name or service not known
2022-12-25T07:45:01.564618Z 774 [Warning] [MY-010056] [Server] Host name 'pool-5-206-44-143.is74.ru' could not be resolved: Name or service not known
2022-12-25T07:45:01.565053Z 775 [Warning] [MY-010056] [Server] Host name 'pool-5-206-44-143.is74.ru' could not be resolved: Name or service not known
2022-12-25T07:48:46.702665Z 824 [Warning] [MY-010058] [Server] Hostname 'zg-1220a-17.stretchoid.com' does not resolve to '192.241.230.5'.
2022-12-25T08:52:12.885725Z 825 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:12.971229Z 826 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.079504Z 827 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.249122Z 828 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.418399Z 829 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.591984Z 830 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.763566Z 831 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.934613Z 832 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.112660Z 833 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.287298Z 834 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.461324Z 835 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.634360Z 836 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.809811Z 837 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
</code>```

Usual connection has been replaced with a pool

Body:
After starting everything works fine, the commands that require connection to the database are executed. After 5-6 hours, the commands will no longer be executed, local commands work normally. Connection to base is made through a pool. At the end of each command, the connection is returned to the pool. What is the problem to look for? And sorry for the google translate

Connecting to the base:

import mysql.connector
from bestconfig import Config
from mysql.connector import pooling
from mysql.connector import Error

config = Config() #config['version']

def getConnection():
    try:
        connection_pool = pooling.MySQLConnectionPool(pool_name="discord_pool",
                                                    pool_size=2,
                                                    pool_reset_session=True,
                                                    host=config['host'],
                                                    database=config['database'],
                                                    user=config['user'],
                                                    password=config['password'])

        # Get connection object from a pool
        connection_object = connection_pool.get_connection()

        if connection_object.is_connected():
            db_Info = connection_object.get_server_info()
            print("Connected to MySQL database using connection pool ... MySQL Server version on ", db_Info)

            cursor = connection_object.cursor()
            cursor.execute("select database();")
            record = cursor.fetchone()
            print("Your connected to - ", record)
        else:
            connection_object.reconnect(attempts=1, delay=0)

    except Error as e:
        print("Error while connecting to MySQL using Connection pool ", e)
    return connection_object

Python logs:

2022-12-25 05:52:00,155 INFO Shard ID None has successfully RESUMED session 5a6cfa0f2871c73636a54087ddb35c3a.
2022-12-25 07:09:37,816 ERROR Attempting a reconnect in 1.11s
Traceback (most recent call last):
  File "/usr/lib/python3.11/asyncio/tasks.py", line 490, in wait_for
    return fut.result()
           ^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/discord/gateway.py", line 372, in from_client
    socket = await client.http.ws_connect(str(url))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/discord/http.py", line 536, in ws_connect
    return await self.__session.ws_connect(url, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/client.py", line 779, in _ws_connect
    resp = await self.request(
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/client.py", line 536, in _request
    conn = await self._connector.connect(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/connector.py", line 540, in connect
    proto = await self._create_connection(req, traces, timeout)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/connector.py", line 901, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/connector.py", line 1175, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/aiohttp/connector.py", line 980, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/asyncio/base_events.py", line 1063, in create_connection
    sock = await self._connect_sock(
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/asyncio/base_events.py", line 967, in _connect_sock
    await self.sock_connect(sock, address)
  File "/usr/lib/python3.11/asyncio/selector_events.py", line 634, in sock_connect
    return await fut
           ^^^^^^^^^
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.11/dist-packages/discord/client.py", line 624, in connect
    self.ws = await asyncio.wait_for(coro, timeout=60.0)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/asyncio/tasks.py", line 492, in wait_for
    raise exceptions.TimeoutError() from exc
TimeoutError
2022-12-25 07:09:39,518 INFO Shard ID None has successfully RESUMED session 5a6cfa0f2871c73636a54087ddb35c3a.
2022-12-25 07:27:23,366 INFO Shard ID None has successfully RESUMED session 5a6cfa0f2871c73636a54087ddb35c3a.
2022-12-25 07:44:19,708 INFO Shard ID None has successfully RESUMED session 5a6cfa0f2871c73636a54087ddb35c3a.

MySQL logs:

2022-12-24T23:31:25.904328Z 718 [Warning] [MY-010055] [Server] IP address '2.57.122.23' could not be resolved: Name or service not known
2022-12-25T00:43:30.330033Z 719 [Warning] [MY-010058] [Server] Hostname 'zg-1220a-127.stretchoid.com' does not resolve to '192.241.224.10'.
2022-12-25T03:47:37.608995Z 723 [Warning] [MY-010055] [Server] IP address '46.216.30.14' could not be resolved: Name or service not known
2022-12-25T03:47:37.609192Z 722 [Warning] [MY-010055] [Server] IP address '46.216.30.14' could not be resolved: Name or service not known
2022-12-25T05:31:12.652320Z 772 [Warning] [MY-010055] [Server] IP address '206.189.208.4' could not be resolved: Name or service not known
2022-12-25T06:19:41.620580Z 773 [Warning] [MY-010055] [Server] IP address '92.255.85.233' could not be resolved: Name or service not known
2022-12-25T07:45:01.564618Z 774 [Warning] [MY-010056] [Server] Host name 'pool-5-206-44-143.is74.ru' could not be resolved: Name or service not known
2022-12-25T07:45:01.565053Z 775 [Warning] [MY-010056] [Server] Host name 'pool-5-206-44-143.is74.ru' could not be resolved: Name or service not known
2022-12-25T07:48:46.702665Z 824 [Warning] [MY-010058] [Server] Hostname 'zg-1220a-17.stretchoid.com' does not resolve to '192.241.230.5'.
2022-12-25T08:52:12.885725Z 825 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:12.971229Z 826 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.079504Z 827 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.249122Z 828 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.418399Z 829 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.591984Z 830 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.763566Z 831 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:13.934613Z 832 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.112660Z 833 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.287298Z 834 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.461324Z 835 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.634360Z 836 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.
2022-12-25T08:52:14.809811Z 837 [Warning] [MY-010057] [Server] IP address '35.216.148.48' has been resolved to the host name '48.148.216.35.bc.googleusercontent.com', which resembles IPv4-address itself.

Usual connection has been replaced with a pool


问:
How to remove the EXIF of the file before uploading the file into AWS S3?
I am uploading an image in AWS S3. I want to upload the image file without the EXIF data in AWS s3.

How can I remove the files' metadata (EXIF data) before uploading on AWS s3?

FYI: I am using the NodeJs and React Native platforms.


问:
Unity VR Check if a GameObject passes completely through another one
I have a Blade and it goes through an Box.

Currently it triggers when I "touch" the box. However, I would like to find out when my blade has reached the other side of my box so that I can then call my cut Method.
I tried with 4 colliders per side, but the solution was not optimal.


问:
how to use two grafana notification policy with multiple labels
I have grafana setup, and want to set a policy to get all the alerts generated for the namespace "myapp", However, I want to exclude alerts which are generated from the cluster "test-cluster".

below is my label setup
case-1

```<code>namespace=~myapp
cluster=test-cluster
</code>```

this will not help, it still sends alerts from the cluster "test-cluster"

Case-2

```<code>namespace=~myapp
  |
  |  nested policy with below condition
   --> cluster=test-cluster
</code>```

this also wont help, it give same result as case-1

Body:
I have grafana setup, and want to set a policy to get all the alerts generated for the namespace "myapp", However, I want to exclude alerts which are generated from the cluster "test-cluster".

below is my label setup
case-1

namespace=~myapp
cluster=test-cluster

this will not help, it still sends alerts from the cluster "test-cluster"

Case-2

namespace=~myapp
  |
  |  nested policy with below condition
   --> cluster=test-cluster

this also wont help, it give same result as case-1


问:
Represent a maze as binary matrix

I'm trying to apply Hillclimbing and Iterative deepening A* to solve this maze problem but i'm unable to represent this maze as binary matrix. How to represent this maze as binary matrix?

I'm trying to apply Hillclimbing and Iterative deepening A* to solve this maze problem but i'm unable to represent this maze as binary matrix. How to represent this maze as binary matrix?

Title: Represent a maze as binary matrix


问:
Are hardware locks resistant to port snooping?
When I searched on the internet, I saw that there are ways to crack the hardware locks, which method is to listen to the connected ports and copy the information that is exchanged, and design a simulator that runs the program. turns

Is there a method or a specific protocol in these modern hardware locks that locks data between the sdk and the hardware lock and is resistant to this type of attack?

I saw that most of the companies provide the lock and software to the crackers to crack the lock. Is there a special software lock in the market that makes this connection safe?

I checked most of the products and did not see anything or explanation in their writings about whether there is a secure connection in these products that is resistant to the lock being copied.

For example, the following hardware lock production companies have been able to copy the lock by individuals or teams and have taken a copy of the lock:

Safenet Sentinel SuperPro UltraPro Rainbow, DESKey DK2 DK3, Eleckey
Eutron SmartKey, Feitian Rockey 2/4ND, GV-Series, Guardant, INROKey
KEYLOK 2, Marx CryptoBox, McAMOS SmartLock, MegaLock, Microcosm
Dinkey, Matrix, SENSELOCK Dongle, SG-Lock Dongle, SecuTech UNIKEY
SecureMetric SecureDongle X, Softlok, Wibu Codemeter CmStick Box Key


问:
Xamarin scanner for small Barcodes / QRCodes
I am working on a Xamarin QRCode scanner prototype and the aim is to make the App being able to scan QR codes as small as 1.8/1.8 mm. I have tried the GoogleVision and also the ZXing. The GoogleVision is able to scan them but it is not convenient at all since it hardly depends on the Camera quality, position, illumination, and stability. Also tried Camera / Image Scannig to take a picture while the user is able to zoom on the QR code, still so hard to do that for a user (it cannot detect the QR code 9 out of 10).
TBH, I have searched a lot and manipulated these libraries and couldn't get it to work. On the other hand, there are Apps on the market that they can simply scan these small QR codes. (which I believe they are not based on Xamarin) I have noticed some of them are using ZXing but I couldn't find any useful information on how they are managing these small QR Codes! So my question is:

Is it possible to use Xamarin and ZXing or GoogleVision for this matter? If yes, any further information would be hugely appreciated.

Is there any library that can handle these small QR codes (Commercial or non-commercial)?

Thank you in advance.

Cheers


问:
Video concatenation using ffmpeg. Output video length is longer than inputs length
I have a problem with video mp4 concatenation using ffmpeg. I have two the same videos and I want to concatenate them. I created file inputs.txt and then used command:

ffmpeg  -f concat -i inputs.txt -c copy mergedVideo.mp4

Output:

```<code>ffmpeg  -f concat -i inputs.txt -c copy mergedVideo.mp4
ffmpeg version 5.0.1 Copyright (c) 2000-2022 the FFmpeg developers
  built with clang version 12.0.1
  configuration: --prefix=/Users/runner/miniforge3/conda-bld/ffmpeg_1649114094397/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_pl --cc=arm64-apple-darwin20.0.0-clang --disable-doc --disable-openssl --enable-demuxer=dash --enable-gnutls --enable-gpl --enable-hardcoded-tables --enable-libfreetype --enable-libopenh264 --enable-neon --enable-libx264 --enable-libx265 --enable-libaom --enable-libsvtav1 --enable-libxml2 --enable-libvpx --enable-pic --enable-pthreads --enable-shared --disable-static --enable-version3 --enable-zlib --enable-libmp3lame --pkg-config=/Users/runner/miniforge3/conda-bld/ffmpeg_1649114094397/_build_env/bin/pkg-config --enable-cross-compile --arch=arm64 --target-os=darwin --cross-prefix=arm64-apple-darwin20.0.0- --host-cc=/Users/runner/miniforge3/conda-bld/ffmpeg_1649114094397/_build_env/bin/x86_64-apple-darwin13.4.0-clang
  libavutil      57. 17.100 / 57. 17.100
  libavcodec     59. 18.100 / 59. 18.100
  libavformat    59. 16.100 / 59. 16.100
  libavdevice    59.  4.100 / 59.  4.100
  libavfilter     8. 24.100 /  8. 24.100
  libswscale      6.  4.100 /  6.  4.100
  libswresample   4.  3.100 /  4.  3.100
  libpostproc    56.  3.100 / 56.  3.100
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x1561044a0] Auto-inserting h264_mp4toannexb bitstream filter
Input #0, concat, from 'inputs.txt':
  Duration: N/A, start: -0.064000, bitrate: 1424 kb/s
  Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 1355 kb/s, 50 fps, 50 tbr, 12800 tbn
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
  Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 16000 Hz, mono, fltp, 68 kb/s
    Metadata:
      handler_name    : SoundHandler
      vendor_id       : [0][0][0][0]
File 'mergedVideo.mp4' already exists. Overwrite? [y/N] y
Output #0, mp4, to 'mergedVideo.mp4':
  Metadata:
    encoder         : Lavf59.16.100
  Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], q=2-31, 1355 kb/s, 50 fps, 50 tbr, 12800 tbn
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
  Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 16000 Hz, mono, fltp, 68 kb/s
    Metadata:
      handler_name    : SoundHandler
      vendor_id       : [0][0][0][0]
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (copy)
Press [q] to stop, [?] for help
frame=    0 fps=0.0 q=-1.0 size=       0kB time=00:00:00.06 bitrate=   6.0k[mov,mp4,m4a,3gp,3g2,mj2 @ 0x154f28b20] Auto-inserting h264_mp4toannexb bitstream filter
frame=  166 fps=0.0 q=-1.0 Lsize=     583kB time=00:00:03.39 bitrate=1407.4kbits/s speed= 179x
video:550kB audio:29kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.737394%
</code>```

Unfortunately the result is different then I expected:

movies comparison

The output is longer than the length of two inputs. Any thoughts?

Also I tried using different commands:

```<code>ffmpeg  -f concat -i inputs.txt -c copy mergedVideo.mp4
</code>```

or set the framerate:

```<code>ffmpeg -r 50 -f concat -i inputs.txt -c copy mergedVideo.mp4
</code>```

What is also weird that I have the same problem when using moviepy library.

```<code>from moviepy.editor import VideoFileClip, concatenate_videoclips
videos = [VideoFileClip("0.mp4"), VideoFileClip("0.mp4")]
concatenate_videoclips(videos).write_videofile('mergedVideo.mp4')
</code>```

Update
ffprobe command for output file

```<code>ffprobe -v error -select_streams v -show_entries stream=codec_name,time_base,start_pts,start_time,duration -of default=noprint_wrappers=1 mergedVideo.mp4
codec_name=h264
time_base=1/12800
start_pts=0
start_time=0.000000
duration=3.380000
</code>```

For input:

```<code>ffprobe -v error -select_streams v -show_entries stream=codec_name,time_base,start_pts,start_time,duration -of default=noprint_wrappers=1 0.mp4
codec_name=h264
time_base=1/12800
start_pts=0
start_time=0.000000
duration=1.660000
</code>```

The duration supposed to be 2*1.66 = 3.32 and but it's 3.38.

Content of the inputs.txt

```<code>file '0.mp4'
file '0.mp4'
</code>```

Body:
I have a problem with video mp4 concatenation using ffmpeg. I have two the same videos and I want to concatenate them. I created file inputs.txt and then used command:

ffmpeg  -f concat -i inputs.txt -c copy mergedVideo.mp4

Output:

ffmpeg  -f concat -i inputs.txt -c copy mergedVideo.mp4
ffmpeg version 5.0.1 Copyright (c) 2000-2022 the FFmpeg developers
  built with clang version 12.0.1
  configuration: --prefix=/Users/runner/miniforge3/conda-bld/ffmpeg_1649114094397/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_pl --cc=arm64-apple-darwin20.0.0-clang --disable-doc --disable-openssl --enable-demuxer=dash --enable-gnutls --enable-gpl --enable-hardcoded-tables --enable-libfreetype --enable-libopenh264 --enable-neon --enable-libx264 --enable-libx265 --enable-libaom --enable-libsvtav1 --enable-libxml2 --enable-libvpx --enable-pic --enable-pthreads --enable-shared --disable-static --enable-version3 --enable-zlib --enable-libmp3lame --pkg-config=/Users/runner/miniforge3/conda-bld/ffmpeg_1649114094397/_build_env/bin/pkg-config --enable-cross-compile --arch=arm64 --target-os=darwin --cross-prefix=arm64-apple-darwin20.0.0- --host-cc=/Users/runner/miniforge3/conda-bld/ffmpeg_1649114094397/_build_env/bin/x86_64-apple-darwin13.4.0-clang
  libavutil      57. 17.100 / 57. 17.100
  libavcodec     59. 18.100 / 59. 18.100
  libavformat    59. 16.100 / 59. 16.100
  libavdevice    59.  4.100 / 59.  4.100
  libavfilter     8. 24.100 /  8. 24.100
  libswscale      6.  4.100 /  6.  4.100
  libswresample   4.  3.100 /  4.  3.100
  libpostproc    56.  3.100 / 56.  3.100
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x1561044a0] Auto-inserting h264_mp4toannexb bitstream filter
Input #0, concat, from 'inputs.txt':
  Duration: N/A, start: -0.064000, bitrate: 1424 kb/s
  Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 1355 kb/s, 50 fps, 50 tbr, 12800 tbn
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
  Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 16000 Hz, mono, fltp, 68 kb/s
    Metadata:
      handler_name    : SoundHandler
      vendor_id       : [0][0][0][0]
File 'mergedVideo.mp4' already exists. Overwrite? [y/N] y
Output #0, mp4, to 'mergedVideo.mp4':
  Metadata:
    encoder         : Lavf59.16.100
  Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], q=2-31, 1355 kb/s, 50 fps, 50 tbr, 12800 tbn
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
  Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 16000 Hz, mono, fltp, 68 kb/s
    Metadata:
      handler_name    : SoundHandler
      vendor_id       : [0][0][0][0]
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (copy)
Press [q] to stop, [?] for help
frame=    0 fps=0.0 q=-1.0 size=       0kB time=00:00:00.06 bitrate=   6.0k[mov,mp4,m4a,3gp,3g2,mj2 @ 0x154f28b20] Auto-inserting h264_mp4toannexb bitstream filter
frame=  166 fps=0.0 q=-1.0 Lsize=     583kB time=00:00:03.39 bitrate=1407.4kbits/s speed= 179x
video:550kB audio:29kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.737394%

Unfortunately the result is different then I expected:

movies comparison

The output is longer than the length of two inputs. Any thoughts?

Also I tried using different commands:

ffmpeg  -f concat -i inputs.txt -c copy mergedVideo.mp4

or set the framerate:

ffmpeg -r 50 -f concat -i inputs.txt -c copy mergedVideo.mp4

What is also weird that I have the same problem when using moviepy library.

from moviepy.editor import VideoFileClip, concatenate_videoclips
videos = [VideoFileClip("0.mp4"), VideoFileClip("0.mp4")]
concatenate_videoclips(videos).write_videofile('mergedVideo.mp4')

Update
ffprobe command for output file

ffprobe -v error -select_streams v -show_entries stream=codec_name,time_base,start_pts,start_time,duration -of default=noprint_wrappers=1 mergedVideo.mp4
codec_name=h264
time_base=1/12800
start_pts=0
start_time=0.000000
duration=3.380000

For input:

ffprobe -v error -select_streams v -show_entries stream=codec_name,time_base,start_pts,start_time,duration -of default=noprint_wrappers=1 0.mp4
codec_name=h264
time_base=1/12800
start_pts=0
start_time=0.000000
duration=1.660000

The duration supposed to be 2*1.66 = 3.32 and but it's 3.38.

Content of the inputs.txt

file '0.mp4'
file '0.mp4'


问:
Dropdown depending on other drodown value in portal template
I have to place two fields in vendor portal template as Company and Branch. Branch depends on company selection.

if user select the first company, then branch should be changed following the selected company. Model used for this is res.company and res.branch.

Please guide.


问:
Unable to import pyspark ml library
when I tried to import pyspark ml library to run regression, I got the below error:

from pyspark.ml.feature import VectorAssembler
```
<pre class="lang-none prettyprint-override"><code>traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jpour/spark/spark-3.3.1-bin-hadoop3/python/pyspark/ml/__init__.py", line 22, in <module>
    from pyspark.ml.base import (
  File "/home/jpour/spark/spark-3.3.1-bin-hadoop3/python/pyspark/ml/base.py", line 40, in <module>
    from pyspark.ml.param import P
  File "/home/jpour/spark/spark-3.3.1-bin-hadoop3/python/pyspark/ml/param/__init__.py", line 32, in <module>
    import numpy as np
ModuleNotFoundError: No module named 'numpy'
</code>```

I'm unable to understand the issue with the import.

Title: Unable to import pyspark ml library

Body:
when I tried to import pyspark ml library to run regression, I got the below error:

from pyspark.ml.feature import VectorAssembler

traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jpour/spark/spark-3.3.1-bin-hadoop3/python/pyspark/ml/__init__.py", line 22, in <module>
    from pyspark.ml.base import (
  File "/home/jpour/spark/spark-3.3.1-bin-hadoop3/python/pyspark/ml/base.py", line 40, in <module>
    from pyspark.ml.param import P
  File "/home/jpour/spark/spark-3.3.1-bin-hadoop3/python/pyspark/ml/param/__init__.py", line 32, in <module>
    import numpy as np
ModuleNotFoundError: No module named 'numpy'

I'm unable to understand the issue with the import.


问:
Retranslate requests to another server cause 500 error
I need to retrsnlate all requests from
domain1.com/rtr/[all path] to another domain domain2.com/[all path] without url change

I create .htaccess in root directory of domain1 and write:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^rtr/(.*)$ https://domain2.com$1 [P]
</code>```

Try to locate https://domain1.com/rtr/jfu/server/api/status.php?uid=1
and get 500 Internal Server Error
Apache/2.4.51 (Unix)

What's wrong?

Body:
I need to retrsnlate all requests from
domain1.com/rtr/[all path] to another domain domain2.com/[all path] without url change

I create .htaccess in root directory of domain1 and write:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^rtr/(.*)$ https://domain2.com$1 [P]

Try to locate https://domain1.com/rtr/jfu/server/api/status.php?uid=1
and get 500 Internal Server Error
Apache/2.4.51 (Unix)

What's wrong?


问:
Solr indexed file not but zero result while querying
While trying to index the pdf, Solr returns this...

```<code>D:\Solr\solr-8.11.2\bin>java -DDauto -Dc=profiles_Index -Drecursive -jar D:/Solr/solr-8.11.2/example/exampledocs/post.jar "D:\LCMS\portalDocs\RESUME\Naukri\Automobile-ElectricVehicle(EV)\Research&Development\0\Naukri_LokeshSampath[10y_0m].pdf
SimplePostTool version 5.0.0
Posting files to [base] url http://localhost:8983/solr/profiles_Index/update using content-type application/xml...
Entering recursive mode, max depth=999, delay=0s
POSTing file Naukri_LokeshSampath[10y_0m].pdf to [base]
SimplePostTool: WARNING: Solr returned an error #400 (Bad Request) for url: http://localhost:8983/solr/profiles_Index/update
SimplePostTool: WARNING: Response: <?xml version="1.0" encoding="UTF-8"?>
<response>

<lst name="responseHeader">
  <int name="status">400</int>
  <int name="QTime">2</int>
</lst>
<lst name="error">
  <lst name="metadata">
    <str name="error-class">org.apache.solr.common.SolrException</str>
    <str name="root-error-class">java.io.CharConversionException</str>
  </lst>

  <str name="msg">Invalid UTF-8 start byte 0xb5 (at char #12, byte #-1)</str>
  <int name="code">400</int>
</lst>
</response>
SimplePostTool: WARNING: IOException while reading response: java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8983/solr/profiles_Index/update
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/profiles_Index/update...
Time spent: 0:00:00.066
</code>```

I am trying to index a pdf file can any one help me I am new to indexing
.Thanks in advance

Body:
While trying to index the pdf, Solr returns this...

D:\Solr\solr-8.11.2\bin>java -DDauto -Dc=profiles_Index -Drecursive -jar D:/Solr/solr-8.11.2/example/exampledocs/post.jar "D:\LCMS\portalDocs\RESUME\Naukri\Automobile-ElectricVehicle(EV)\Research&Development\0\Naukri_LokeshSampath[10y_0m].pdf
SimplePostTool version 5.0.0
Posting files to [base] url http://localhost:8983/solr/profiles_Index/update using content-type application/xml...
Entering recursive mode, max depth=999, delay=0s
POSTing file Naukri_LokeshSampath[10y_0m].pdf to [base]
SimplePostTool: WARNING: Solr returned an error #400 (Bad Request) for url: http://localhost:8983/solr/profiles_Index/update
SimplePostTool: WARNING: Response: <?xml version="1.0" encoding="UTF-8"?>
<response>

<lst name="responseHeader">
  <int name="status">400</int>
  <int name="QTime">2</int>
</lst>
<lst name="error">
  <lst name="metadata">
    <str name="error-class">org.apache.solr.common.SolrException</str>
    <str name="root-error-class">java.io.CharConversionException</str>
  </lst>

  <str name="msg">Invalid UTF-8 start byte 0xb5 (at char #12, byte #-1)</str>
  <int name="code">400</int>
</lst>
</response>
SimplePostTool: WARNING: IOException while reading response: java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8983/solr/profiles_Index/update
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/profiles_Index/update...
Time spent: 0:00:00.066

I am trying to index a pdf file can any one help me I am new to indexing
.Thanks in advance


问:
Optimize too many azure face api calls while enrolling and verification of data
I have a face dataset on which I am using Azure Face Service for identification of people.
The first step is to detect faces using face.detect in data then enroll if face is present using face lists.
The second step is to train the enrolled set.
The third step is getting inference by detecting faces on the same dataset using face.detect and then finding out what faces are there in the database that matches with it using find similar method.(Eg : Images 1,2,3 are enrolled; 1,2 is a match;1,3 is a match;2,1 is a match;3,1 is a match so on...).

Now, the problem is for large number of images the api calls would become way more expensive and we can see that the first and third step both uses face detect api call and returns a face id with its other properties that expires in 24 hours. Is there any way to minimize the api calls in this scenerio (Enrolling entire dataset and then verifying from the enrolled dataset itself).


问:
Sorting a html list by multiple attributes (with subheadings)
I have a list of publications (html) that I want to have sorted by clicking a button. I want the publications to be sorted either by year, topic, or type of publication (journal article, book chapter, etc.). In addition, the sorted list should also have subheadings. That is, for example, if I sort the publications by year, I want to have 2022, 2021, etc. as subheadings under which all publications of the years 2022, 2021, etc. will be sorted.

In the following, I provide a minimal example. This minimal example works when I click on one of the three buttons. However, when I then click on another button to change the sort order, the list of publications disappears. Can anyone fix this problem?

```<code><!DOCTYPE html>
<html lang="en">

<body>

<!-- The HTML for the list of publications -->
<ul id="publications">
    <li data-year="2022" data-topic="topic1" data-type="journal article">Publication 1</li>
    <li data-year="2021" data-topic="topic2" data-type="book chapter">Publication 2</li>
    <li data-year="2022" data-topic="topic1" data-type="journal article">Publication 3</li>
    <li data-year="2020" data-topic="topic3" data-type="conference paper">Publication 4</li>
    <li data-year="2021" data-topic="topic2" data-type="book chapter">Publication 5</li>
  </ul>

  <!-- The HTML for the buttons to sort the list -->
  <button id="sort-year">Sort by Year</button>
  <button id="sort-topic">Sort by Topic</button>
  <button id="sort-type">Sort by Type</button>

  <!-- The JavaScript to sort the list and add subheadings -->
  <script>
    // Get a reference to the list and the buttons
    var publications = document.querySelector('#publications');
    var sortYearButton = document.querySelector('#sort-year');
    var sortTopicButton = document.querySelector('#sort-topic');
    var sortTypeButton = document.querySelector('#sort-type');

    // Add click event listeners to the buttons
    sortYearButton.addEventListener('click', function() {
      sortList('data-year');
    });
    sortTopicButton.addEventListener('click', function() {
      sortList('data-topic');
    });
    sortTypeButton.addEventListener('click', function() {
      sortList('data-type');
    });

    function sortList(dataAttribute) {
  // Get all the list items and subheadings
  var items = publications.querySelectorAll('li');
  var subheadings = publications.querySelectorAll('.subheading');

  // Convert the list items and subheadings to arrays so we can use array methods on them
  items = Array.prototype.slice.call(items);
  subheadings = Array.prototype.slice.call(subheadings);

  // Remove all the existing list items and subheadings from the list
  items.forEach(function(item) {
    publications.removeChild(item);
  });
  subheadings.forEach(function(subheading) {
    publications.removeChild(subheading);
  });

  // Create a new array of list items sorted by the given data attribute
  var sortedItems = items.sort(function(a, b) {
    if (a.getAttribute(dataAttribute) < b.getAttribute(dataAttribute)) {
      return -1;
    }
    if (a.getAttribute(dataAttribute) > b.getAttribute(dataAttribute)) {
      return 1;
    }
    return 0;
  });

  // Loop through the sorted array of list items and add them to the list,
  // inserting a subheading whenever the data attribute changes
  var currentValue = null;
  sortedItems.forEach(function(item) {
    if (item.getAttribute(dataAttribute) !== currentValue) {
      var subheading = document.createElement('li');
      subheading.innerHTML = item.getAttribute(dataAttribute);
      subheading.classList.add('subheading');
      publications.appendChild(subheading);
      currentValue = item.getAttribute(dataAttribute);
    }
    publications.appendChild(item);
  });
}

  </script>

<!-- Optional CSS to style the list and subheadings -->
<style>
  #publications {
    list-style: none;
    padding: 0;
  }

  #publications li {
    margin: 10px 0;
  }

  #publications .subheading {
    font-weight: bold;
  }
</style>

</body>

</html>

</code>```

I have tried another sortList function but this only adds additional subheadings:

```<code>    function sortList(dataAttribute) {
      // Get all the list items
      var items = publications.querySelectorAll('li');

      // Convert the list items to an array so we can use array methods on them
      items = Array.prototype.slice.call(items);

      // Sort the array of list items by the given data attribute
      items.sort(function(a, b) {
        if (a.getAttribute(dataAttribute) < b.getAttribute(dataAttribute)) {
          return -1;
        }
        if (a.getAttribute(dataAttribute) > b.getAttribute(dataAttribute)) {
          return 1;
        }
        return 0;
      });

      // Loop through the sorted array of list items and add them to the list,
      // inserting a subheading whenever the data attribute changes
      var currentValue = null;
      items.forEach(function(item) {
        if (item.getAttribute(dataAttribute) !== currentValue) {
          var subheading = document.createElement('li');
          subheading.innerHTML = item.getAttribute(dataAttribute);
          subheading.classList.add('subheading');
          publications.appendChild(subheading);
          currentValue = item.getAttribute(dataAttribute);
        }
        publications.appendChild(item);
      });
    }

</code>```

Body:
I have a list of publications (html) that I want to have sorted by clicking a button. I want the publications to be sorted either by year, topic, or type of publication (journal article, book chapter, etc.). In addition, the sorted list should also have subheadings. That is, for example, if I sort the publications by year, I want to have 2022, 2021, etc. as subheadings under which all publications of the years 2022, 2021, etc. will be sorted.

In the following, I provide a minimal example. This minimal example works when I click on one of the three buttons. However, when I then click on another button to change the sort order, the list of publications disappears. Can anyone fix this problem?

<!DOCTYPE html>

Publication 1

Publication 2

Publication 3

Publication 4

Publication 5

  <button id="sort-year">Sort by Year</button>
  <button id="sort-topic">Sort by Topic</button>
  <button id="sort-type">Sort by Type</button>

I have tried another sortList function but this only adds additional subheadings:

    function sortList(dataAttribute) {
      // Get all the list items
      var items = publications.querySelectorAll('li');

      // Convert the list items to an array so we can use array methods on them
      items = Array.prototype.slice.call(items);

      // Sort the array of list items by the given data attribute
      items.sort(function(a, b) {
        if (a.getAttribute(dataAttribute)  b.getAttribute(dataAttribute)) {
          return 1;
        }
        return 0;
      });

      // Loop through the sorted array of list items and add them to the list,
      // inserting a subheading whenever the data attribute changes
      var currentValue = null;
      items.forEach(function(item) {
        if (item.getAttribute(dataAttribute) !== currentValue) {
          var subheading = document.createElement('li');
          subheading.innerHTML = item.getAttribute(dataAttribute);
          subheading.classList.add('subheading');
          publications.appendChild(subheading);
          currentValue = item.getAttribute(dataAttribute);
        }
        publications.appendChild(item);
      });
    }


问:
How do I reference the hashed image (in the html page in the dist folder) after it has been created with copy-webpack-plugin?
I have in my index.ejs file (you can consider this the .html file) a classic tag  that I'm copying in the dist folder with copy-webpack-plugin

My problem is that in 'production' mode I add an hash to my image instead in the index.ejs file the attribute src of the  still will point to the image without the hash. Thus my index.html in the dist folder doesn't display the image.

Thi is my project :

https://github.com/cuccagna/Webpack28

For convenience I put here the package.json , the webpack.production.config.js and the index.ejs files:

webpack.production.config.js

const pathM = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
/* const { CleanWebpackPlugin } = require('clean-webpack-plugin');
 */
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
   entry: './src/js/index.js',
   output: {
      filename: 'js/bundle.[contenthash].js',
      path: pathM.resolve(__dirname, './dist'),
      assetModuleFilename: '[path][name].[contenthash][ext]',
      publicPath: './',
      clean: true /* {
         dry: false,
         keep:/\.css$/
      } */   //Serve per cancellare la cartella dist dalla precedente esecuzione
   },
   mode: 'production',
   module: {
      rules:[
         {
            test: /\.(png|jpe?g|webp|avif|gif|svg)$/,
            type: 'asset',
            parser: {
               dataUrlCondition: {
                  maxSize: 3 * 1024 //3 Kilobytes QUI CAMBIA LA SOGLIA A 3 KByte

               }
            }
         },

         {
            test: /\.css$/,
            use: [MiniCssExtractPlugin.loader,'css-loader']
         },
         {
            test: /\.scss$/,
            use: [MiniCssExtractPlugin.loader,'css-loader','sass-loader']
         },
         {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
               loader: 'babel-loader',
               options: {
                  presets: [['@babel/env', {
                      targets: "> 0.1%, not dead",
                     debug:true,
                     useBuiltIns: 'usage',
                     //Puoi mettere anche solo version:3
                     //La versione la puoi prelevare da package.json
                     corejs:{version:3.26 , proposals:true}
                  }]],
                  //plugins: ['@babel/plugin-proposal-class-properties']
               }
            }
         }
      ]
   },
   plugins: [
       new CopyWebpackPlugin({
         patterns: [
             { from: './assets/img', to: './assets/img/[name].[contenthash][ext]' },

          ],
          options: {
        concurrency: 100,
      }
      }),
      new MiniCssExtractPlugin({
      filename:"css/main.[contenthash].css"
      }),
      new HtmlWebpackPlugin({

         inject: false,
         template: "./index.ejs", //Puoi mettere anche un file html
         minify:true
      })

   ]

}```
</div>
</div>
</p>
<p>package.json</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "project5",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --progress --profile --config webpack.production.config.js",
    "dev":"webpack --progress --profile --config webpack.dev.config.js",
    "watch": "webpack --progress --profile --watch"
  },
  "watch": {
    "build": "./src"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "babel-loader": "^9.1.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.3",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.7.2",
    "npm-watch": "^0.11.0",
    "sass": "^1.56.2",
    "sass-loader": "^13.2.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1"
  },
  "dependencies": {
    "core-js": "^3.26.1"
  }
}</code>```

index.ejs

<!DOCTYPE html>

      <title>Custom insertion example</title>

      <% if (process.env.NODE_ENV === 'production'){%>
       <%  for(var i=0; i < htmlWebpackPlugin.files.css.length; i++) {%>
      <link
         type="text/css"
         rel="stylesheet"
         href="<%= htmlWebpackPlugin.files.css[i] %>"
      />
      <% } }%>

      <button class="hello-world-button">Ciao</button>

      <% for(var i=0; i < htmlWebpackPlugin.files.js.length; i++) {%>

      <% } %>

```

A similar problem is described here:

https://github.com/webpack-contrib/copy-webpack-plugin/issues/279

I tried to fix the problem from myself but I can't figure how to proceed.

Body:
I have in my index.ejs file (you can consider this the .html file) a classic tag  that I'm copying in the dist folder with copy-webpack-plugin

My problem is that in 'production' mode I add an hash to my image instead in the index.ejs file the attribute src of the  still will point to the image without the hash. Thus my index.html in the dist folder doesn't display the image.

Thi is my project :

https://github.com/cuccagna/Webpack28

For convenience I put here the package.json , the webpack.production.config.js and the index.ejs files:

webpack.production.config.js

const pathM = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
/* const { CleanWebpackPlugin } = require('clean-webpack-plugin');
 */
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
   entry: './src/js/index.js',
   output: {
      filename: 'js/bundle.[contenthash].js',
      path: pathM.resolve(__dirname, './dist'),
      assetModuleFilename: '[path][name].[contenthash][ext]',
      publicPath: './',
      clean: true /* {
         dry: false,
         keep:/\.css$/
      } */   //Serve per cancellare la cartella dist dalla precedente esecuzione
   },
   mode: 'production',
   module: {
      rules:[
         {
            test: /\.(png|jpe?g|webp|avif|gif|svg)$/,
            type: 'asset',
            parser: {
               dataUrlCondition: {
                  maxSize: 3 * 1024 //3 Kilobytes QUI CAMBIA LA SOGLIA A 3 KByte

               }
            }
         },

         {
            test: /\.css$/,
            use: [MiniCssExtractPlugin.loader,'css-loader']
         },
         {
            test: /\.scss$/,
            use: [MiniCssExtractPlugin.loader,'css-loader','sass-loader']
         },
         {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
               loader: 'babel-loader',
               options: {
                  presets: [['@babel/env', {
                      targets: "> 0.1%, not dead",
                     debug:true,
                     useBuiltIns: 'usage',
                     //Puoi mettere anche solo version:3
                     //La versione la puoi prelevare da package.json
                     corejs:{version:3.26 , proposals:true}
                  }]],
                  //plugins: ['@babel/plugin-proposal-class-properties']
               }
            }
         }
      ]
   },
   plugins: [
       new CopyWebpackPlugin({
         patterns: [
             { from: './assets/img', to: './assets/img/[name].[contenthash][ext]' },

          ],
          options: {
        concurrency: 100,
      }
      }),
      new MiniCssExtractPlugin({
      filename:"css/main.[contenthash].css"
      }),
      new HtmlWebpackPlugin({

         inject: false,
         template: "./index.ejs", //Puoi mettere anche un file html
         minify:true
      })

   ]

}

package.json

{
  "name": "project5",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --progress --profile --config webpack.production.config.js",
    "dev":"webpack --progress --profile --config webpack.dev.config.js",
    "watch": "webpack --progress --profile --watch"
  },
  "watch": {
    "build": "./src"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "babel-loader": "^9.1.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.3",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.7.2",
    "npm-watch": "^0.11.0",
    "sass": "^1.56.2",
    "sass-loader": "^13.2.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1"
  },
  "dependencies": {
    "core-js": "^3.26.1"
  }
}

index.ejs

<!DOCTYPE html>

      <title>Custom insertion example</title>

      <% if (process.env.NODE_ENV === 'production'){%>
       <%  for(var i=0; i < htmlWebpackPlugin.files.css.length; i++) {%>
      <link
         type="text/css"
         rel="stylesheet"
         href="<%= htmlWebpackPlugin.files.css[i] %>"
      />
      <% } }%>

      <button class="hello-world-button">Ciao</button>

      <% for(var i=0; i < htmlWebpackPlugin.files.js.length; i++) {%>

      <% } %>

A similar problem is described here:

https://github.com/webpack-contrib/copy-webpack-plugin/issues/279

I tried to fix the problem from myself but I can't figure how to proceed.