How do I submit a form with ajax

Trying to submit a form using ajax, but it’s just not working

$('#Submit').on('click',function(){
    $.ajax({
        type: 'get',
        url: 'ItemProcessor.php',
        data: $('#input_form').serialize(),
        success: function(response){
            alert(response)
        },
        error: function(){
            alert('error')
        }
    })
event.preventDefault()
})
<form id="input_form">
    <input type="image" src="AddToCart.png" id="Submit"/>
    <input type="number" id = "stupid" name = "Amount" min="1">
    <input type="text" name = "ID" value="Ice Cream" readonly style="display: none;">
    <input type="text" name = "Cost" value="2" readonly style="display: none;">
    <input type="text" name = "Kom" value="1" readonly style="display: none;">
    <input type="text" name = "EAN" value="4551212511" readonly style="display: none;">
    <input type="text" name = "Type" value="Food/Sweets" readonly style="display: none;">
</form>

I want the javascript code to send the form to ItemProcessor.php, but when I click the form, the form just acts like normal and the function doesn’t get called. neither success nor error get called, so I’m assuming the function isn’t activating but I have no idea why. This is the only form on the page

Not being able to see the animations being rendered because the function is inside the game loop

I am quite new to game development. In fact, this is the first ever game I am creating. My game is a simple balloon popping game. The problem is I have a pump asset which inflates the balloon on click. Usually, it takes around 5 clicks to inflate the balloon. But I am caught in a weird logic wherein I have to call the blowBalloon() function [for inflating the balloon] inside the game loop. This causes the function to be rendered 24 times on a single click, resulting in the animations being skipped completely. Please help. Thanks in advance. Please refer to blowBalloon() function.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Alphabet Balloons</title>

    <style>
      body,
      html {
        margin: 0;
        padding: 0;
        overflow: hidden;
        height: 100%;
        width: 100%;
        box-sizing: border-box;
        border: 5px;
        border-radius: 5px;
        border-style: solid;
        cursor: pointer;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  <body>
    <canvas id="gameCanvas"></canvas>
      <div class="animation-container">
        <img
          src="Assets/BurstAnimation.gif"
          alt="Burst Animation"
          class="burst-animation"
          style="display: none"
        />
      </div>
    </div>
    <script>
      const canvas = document.getElementById("gameCanvas");
      const ctx = canvas.getContext("2d");

      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;

      window.addEventListener("resize", () => {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        drawBackground();
      });

      const backgroundImage = new Image();
      backgroundImage.src = "Assets/Background/backgroundImage.png";

      function drawBackground() {
        ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
      }

      const alphabetArray = [...Array(26).keys()].map((i) => ({
        src: `Assets/GeneralAssets/Alphabets/Alpha${String.fromCharCode(
          65 + i
        )}.png`,
      }));

      const alphabetImages = alphabetArray.map((alphabet) => {
        const img = new Image();
        img.src = alphabet.src;
        return img;
      });

      const balloonArray = [
        "Assets/GeneralAssets/Balloons/BalloonBlue1.png",
        "Assets/GeneralAssets/Balloons/BalloonBlue2.png",
        "Assets/GeneralAssets/Balloons/BalloonGreen1.png",
        "Assets/GeneralAssets/Balloons/BalloonGreen2.png",
        "Assets/GeneralAssets/Balloons/BalloonOrange.png",
        "Assets/GeneralAssets/Balloons/BalloonPink.png",
        "Assets/GeneralAssets/Balloons/BalloonPink2.png",
        "Assets/GeneralAssets/Balloons/BalloonPurple.png",
        "Assets/GeneralAssets/Balloons/BalloonRed.png",
        "Assets/GeneralAssets/Balloons/BalloonYellow.png",
      ].map((src) => {
        const img = new Image();
        img.src = src;
        return img;
      });

      // Importing balloon string
      const balloonString = new Image();
      balloonString.src = "Assets/GeneralAssets/Balloons/BalloonString.png";

      const pump = { x: window.innerWidth - 407, y: window.innerHeight - 407 };
      const pumpParts = [
        { src: "Assets/GeneralAssets/Pump/PumpConnector.png", x: 50, y: 170 },
        { src: "Assets/GeneralAssets/Pump/PumpHandle.png", x: 190, y: 30 },
        { src: "Assets/GeneralAssets/Pump/PumpSymbol.png", x: 190, y: 190 },
      ];

      const pumpImages = pumpParts.map((part) => {
        const img = new Image();
        img.src = part.src;
        return { img, x: part.x, y: part.y };
      });

      let shakeOffsetX = 0;
      let shakeOffsetY = 0;
      let symbolShakeX = 0;
      let symbolShakeY = 0;
      let rotationAngle = 0;
      let scale = 1;
      let handleY = 0;
      let handleMoving = false;
      let handleDirection = 1;
      let connectorShaking = false;
      let symbolShaking = false;

      function applyPumpAnimations() {
        if (connectorShaking) {
          shakeOffsetX = Math.random() * 1 - 0.5;
          shakeOffsetY = Math.random() * 1 - 0.5;
        }
        if (symbolShaking) {
          symbolShakeX = Math.random() * 3 - 1.5;
          symbolShakeY = Math.random() * 3 - 1.5;
        }
        if (handleMoving) {
          handleY += handleDirection * 50;
          if (handleY >= 200) {
            handleDirection = -1;
          } else if (handleY <= 0) {
            handleDirection = 1;
            handleMoving = false;
          }
        }
      }

      function assemblePump() {
        pumpImages.forEach((part, index) => {
          let x = pump.x + part.x,
            y = pump.y + part.y;
          ctx.save();
          if (index === 0 && connectorShaking) {
            // Pump Connector shake
            x += shakeOffsetX;
            y += shakeOffsetY;
          } else if (index === 1 && handleMoving) {
            // Pump Handle up-and-down movement
            y += handleY;
          } else if (index === 2 && symbolShaking) {
            // Pump Symbol vibration
            x += symbolShakeX;
            y += symbolShakeY;
          }
          ctx.drawImage(part.img, x, y, 250, 250);
          ctx.restore();
        });
      }

      // An empty array to keep track of multiple balloons
      const balloons = [];

      // alphabet index keeps track of the alphabet rendered.
      let alphabetIndex = 0;

      function drawBalloons() {
        balloons.forEach((balloon) => {
            ctx.drawImage(
            balloon.balloonImage,
            balloon.x,
            balloon.y,
            balloon.width,
            balloon.height
        );
        const alphabetX = balloon.x + balloon.width / 4,
        alphabetY = balloon.y + balloon.height / 4;
        ctx.drawImage(
            balloon.alphabetImg,
            alphabetX,
            alphabetY,
            balloon.width / 2,
            balloon.height / 2
        );

        // Drawing the string
        const stringX = (balloon.x + balloon.width / 2) - (balloon.balloonString.width / 2) +185;
        const stringY = balloon.y + balloon.height -50;
        ctx.drawImage(
            balloon.balloonString,
            stringX,
            stringY,
            balloon.width,
            balloon.height,
        );
  });
}

      function updateBalloonPositions() {
        balloons.forEach((balloon) => {
          if (!balloon.isGrowing) {
            balloon.x += balloon.speedX;
            balloon.y += balloon.speedY;
            if (balloon.x < 0 || balloon.x + balloon.width > canvas.width)
              balloon.speedX *= -1;
            if (balloon.y < 0 || balloon.y + balloon.height > canvas.height)
              balloon.speedY *= -1;
          }
        });
      }

      function blowBalloon(balloon) {
        if (balloon.isBlowing) return; // Prevent re-triggering
  
        balloon.isBlowing = true; // Set this only once per click
        if (balloon.width < 150 && balloon.height < 150) {
          balloon.width += 5;
          balloon.height += 5;
          balloon.x -= 12;
          balloon.y -= 20;
          console.log("blowBalloon executed");
        } else {
          balloon.isGrowing = false;
          balloon.isBlowing = false;
          console.log("Balloon grown");
        }
      }

      
      let loadedImages = 0,
        totalImages =
          alphabetImages.length + balloonArray.length + pumpImages.length + 2;
      function checkAllImagesLoaded() {
        loadedImages++;
        if (loadedImages === totalImages) gameLoop();
      }

      backgroundImage.onload = checkAllImagesLoaded;
      alphabetImages.forEach((img) => (img.onload = checkAllImagesLoaded));
      pumpImages.forEach((part) => (part.img.onload = checkAllImagesLoaded));
      balloonArray.forEach((img) => (img.onload = checkAllImagesLoaded));
      balloonString.onload = checkAllImagesLoaded;

      function gameLoop() {
        drawBackground();
        assemblePump();

        drawBalloons();
        balloons.forEach((balloon) => {
            balloon.isBlowing = false;
          if (balloon.isGrowing) {
            blowBalloon(balloon);
            applyPumpAnimations();
            console.log("PumpAnimation Executed");
          }
        });
        updateBalloonPositions();
        requestAnimationFrame(gameLoop);
      }

      canvas.addEventListener("click", function (event) {
        const rect = canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        // check if a balloon has been clicked
        for (let i = balloons.length - 1; i >= 0; i--) {
          const balloon = balloons[i];

          if (
            x >= balloon.x &&
            x <= balloon.x + balloon.width &&
            y >= balloon.y &&
            y <= balloon.y + balloon.height
          ) {
            // Playing the burst animation
            const burstAnimation = document.querySelector(".burst-animation");
            burstAnimation.style.display = "block";
            burstAnimation.style.left = `${balloon.x}px`; // Position the GIF
            burstAnimation.style.top = `${balloon.y}px`; // Position the GIF
            console.log("Burst animation played");

            // Remove the balloon from the array
            balloons.splice(i, 1);

            return;
          }
        }

        const pumpX = pump.x;
        const pumpY = pump.y;

        if (x >= pumpX && x <= pumpX + 400 && y >= pumpY && y <= pumpY + 400) {
          // If we've reached the end of the alphabet, stop creating new balloons
          if (alphabetIndex >= alphabetImages.length) {
            return; // No more balloons
          }

          // Apply pump animations
          connectorShaking = true;
          symbolShaking = true;
          handleMoving = true;

          setTimeout(() => {
            connectorShaking = false;
            symbolShaking = false;
          }, 5000); // Stop shaking after 5 second

          const newBalloon = {
            x: pump.x + 100,
            y: pump.y + 200,
            speedX: Math.random() * 4 + 0.3,
            speedY: Math.random() * 1 + 0.3,
            width: 30,
            height: 30,
            isGrowing: true,
            isBlowing: false,
            alphabetImg: alphabetImages[alphabetIndex],
            balloonImage:
              balloonArray[Math.floor(Math.random() * balloonArray.length)],
            balloonString: balloonString,
          };

          balloons.push(newBalloon);
          alphabetIndex++;
        }
      });
    </script>
  </body>
</html>

I tried moving out the function from the game loop and executing it independently outside the game loop expecting that this will solve the issue, but that ended up in the rendering of many balloons all at once.

Getting crypto not found error in React Native Expo

I keep getting this error below

ERROR  ReferenceError: Property 'crypto' doesn't exist, js engine: hermes 
    at ContextNavigator (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&app=com.testlio.deviceverificationapp.Clip&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=true:145632:24)
    at ExpoRoot (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&app=com.testlio.deviceverificationapp.Clip&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=true:145588:28)
    at App
    at ErrorToastContainer (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&app=com.testlio.deviceverificationapp.Clip&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=true:242934:24)
    at ErrorOverlay
    at withDevTools(ErrorOverlay) (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&app=com.testlio.deviceverificationapp.Clip&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=true:242437:27)
    at RCTView
    at View (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&app=com.testlio.deviceverificationapp.Clip&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=true:41517:43)
    at RCTView
    at View (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&app=com.testlio.deviceverificationapp.Clip&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=true:41517:43)

whenever I try to run my React Native Expo application in Xcode.
I don’t seem to know why. It however works when I run npm run ios on my vscode

I have tried regenerating the pod file, removing hermes from the pod file definition but still does not work on Xcode.

Here is my React Native Expo Component


import * as crypto from 'crypto';
import React, { useEffect, useState } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import * as Device from 'expo-device';
import { useVerifyDeviceMutation } from './verifyDeviceQuery.generated';

type DeviceVerificationPayload = {
    deviceVariantIdentifier: string;
    deviceOsVersion: string;
};

const encrypt = (payload: DeviceVerificationPayload) => {
    const algorithm = ‘aes-256-cbc’;
    const encryptionAlgoKey = ‘Key’;
    const encryptionKey = base64ToUtf8(encryptionAlgoKey);
    const key = CryptoJS.SHA256(encryptionKey);
    const iv = CryptoJS.lib.WordArray.create(key.words.slice(0, 4));
    const stringifiedPayload = JSON.stringify(payload);
    const cipher = crypto.createCipheriv(algorithm, key, iv); 
    let encrypted = cipher.update(stringifiedPayload, 'utf8', 'hex'); 
    encrypted += cipher.final('hex'); return encrypted;
    return encrypted;
};

export default function HomeScreen() {
    const deviceVerificationGuid = 'deviceVerificationGuid';
    const [isVerifying, setIsVerifying] = useState<boolean>(true);
    const [deviceVerificationFailure, setDeviceVerificationFailure] = useState<boolean>(false);

    const [verifyDevice, { loading }] = useVerifyDeviceMutation({
        onCompleted: () => {
            setIsVerifying(false);
        },
        onError: (data) => {
            setIsVerifying(false);
            setDeviceVerificationFailure(true);
        }
    });

    useEffect(() => {
            const deviceVariantIdentifier = Device.modelName || '';
            const deviceOsVersion = Device.osVersion || '';
            const signature = encrypt({
                deviceVariantIdentifier,
                deviceOsVersion
            });

            verifyDevice({
                variables: {
                    input: {
                        deviceVariantIdentifier,
                        deviceOsVersion,
                        signature,
                        deviceVerificationGuid
                    }
                }
            });
    }, [deviceVerificationGuid, verifyDevice]);

    if (!deviceVerificationGuid) {
        return (
            <View style={styles.container}>
                <Image source={require('./assets/loadicon.gif')} style={styles.image} />
            </View>
        );
    }

    return (
        <View style={styles.container}>
          User Interface Logic
        </View>
    );
}

The above works whenever I run npm run ios but specifically fails when I run it on Xcode.
Not really sure why this is happening

How to fix a horizontal scroll section with scrollTrigger

I’m trying to have a section that scrolls horizontally while you scroll down. I was looking at videos on how to do this, and although it seems simple enough, i cant get it to work. Can somebody help me understand what I’m doing wrong?
(it looks ugly on code pen because it doesn’t have my local files and the rest of the CSS. Just what’s necessary)

Here is my code on CodePen

This is an example of what I wanted

I tried variations of two ways i saw:

gsap.registerPlugin(ScrollTrigger)

let sections = gsap.utils.toArray('.card-scroller div')

gsap.to(sections, {
    xPercent: -100 * (sections.length - 1),
    scrollTrigger: {
        trigger: (".card-scroller"),
        pin: true,
        scrub: 1,
        end: "+=3000"
    }
})

From this YT Video

and

From this YT Video

document.addEventListener("DOMContentLoaded", (event) => {
    gsap.registerPlugin(ScrollTrigger)
});

const container = document.querySelector('.card-scroller')
const sections = gsap.utils.toArray('.card-scroller div')


let scrollTween = gsap.to(sections, {
    xPercent: -100 * (sections.length - 1),
    ease: "none",
    scrollTrigger: {
        trigger: (".card-scroller"),
        pin: true,
        scrub: 1,
        end: "+=3000"
    }
})                         

Why is my authenticated state not updating properly?

I’m trying to redirect users to /feed after they log in, but even though console.log("Login successful") prints, the page doesn’t navigate to /feed. It seems like checkAuth() isn’t updating the authenticated state in time for Login.jsx to recognize it as true. Am I using async/await incorrectly, or is there an issue with my useEffect dependency on authenticated?

Here’s the relevant code:

Context API methods:

const checkAuth = async () => {
    try {
      const response = await axiosInstance.get("/authenticate-user");

      if (response.data.isAuthenticated) {
        setAuthenticated(true);
        setUser(response.data.user);
        setProfileUrl(`/profile/${response.data.user.id}`);
      } else {
        setAuthenticated(false);
        setUser(null);
      }
    } catch (error) {
      console.error("Error during authentication check:", error.response);
      setAuthenticated(false);
      setUser(null);
    }
  };

  useEffect(() => {
    checkAuth();
  }, []);

  const handleLogin = async (email, password) => {
    try {
      await axiosInstance.post("/login", { email, password });

      // Check if login was successful
      await checkAuth();
      console.log("Login successful");
    } catch (error) {
      console.error("Error during login:", error.response);
      toast.error("Invalid Credentials");
    }
  };

Login.jsx

export default function Login() {
  const { authenticated, handleLogin, setAuthenticated } = useContext(AppContext);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (authenticated) {
      navigate("/feed");
    }
  }, [authenticated, navigate]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    const { email, password } = formData;

    await handleLogin(email, password);
    
    setFormData({
      email: "",
      password: "",
    });
    setLoading(false);
  };
// rest of the code
}

Why isn’t checkAuth() updating authenticated in time, and how can I ensure authenticated is correctly checked before Login.jsx attempts to navigate?

How do I make my gameOver function in Javascript jQuery work?

I’m new to JS and I’mm doing a project but I keep having trouble with the feature that resets the game when you fail. When you press the wrong button in a memorizing game, it will reset but then the game breaks.

HTML & CSS

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Simon</title>
  <link rel="stylesheet" href="styles.css">
  <link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>

<body>
  <h1 id="level-title">Press Any Key to Start</h1>
  <div class="container">
    <div lass="row">

      <div type="button" id="green" class="btn green">

      </div>

      <div type="button" id="red" class="btn red">

      </div>
    </div>

    <div class="row">

      <div type="button" id="yellow" class="btn yellow">

      </div>
      <div type="button" id="blue" class="btn blue">

      </div>

    </div>

  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script src="./game.js"></script>
</body>

</html>

body {
  text-align: center;
  background-color: #011F3F;
}

#level-title {
  font-family: 'Press Start 2P', cursive;
  font-size: 3rem;
  margin:  5%;
  color: #FEF2BF;
}

.container {
  display: block;
  width: 50%;
  margin: auto;

}

.btn {
  margin: 25px;
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 10px solid black;
  border-radius: 20%;
}

.game-over {
  background-color: red;
  opacity: 0.8;
}

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.yellow {
  background-color: yellow;
}

.pressed {
  box-shadow: 0 0 20px white;
  background-color: grey;
}

JS

//varibles
const buttonColors = ['red', 'blue', 'green', 'yellow'];
let gamePattern = [];

let userClickedPattern = [];
let userChosenColor;

let level = 0;
let started = false;

function playSound(name) {
  let sound = new Audio('./sounds/'+name+'.mp3');
  sound.play();
}

function gameOver() {
  playSound('wrong');
  setTimeout(function () {
    $('body').removeClass('game-over');
  }, 500);
  $('#level-title').text('Game Over, Press Any Key to Restart');
  $('body').addClass('game-over');
  
  started = false;
  level = 0;
  gamePattern = [];
}

//get a sequence
function nextSequence() {
  userClickedPattern = [];
  level++;
  $('#level-title').text('Level '+level);

  let randomNumber = Math.floor(Math.random() * 4);
  let randomColor = buttonColors[randomNumber];
  gamePattern.push(randomColor);

  for (let i = 0; i < gamePattern.length; i++) {
    setTimeout(function () {
      $('#'+gamePattern[i]).animate({opacity: 0.25}, 100);
      setTimeout(function () {
        $('#'+gamePattern[i]).animate({opacity: 1}, 100);
      }, 25);
          
      playSound(gamePattern[i]);
    }, (500*(i+1)));
  }
}

//get the user sequence stuff
function animatePress(currentColor) {
  setTimeout(function () {
    $('#'+currentColor).removeClass('pressed');
  }, 100);
  $('#'+currentColor).addClass('pressed');
}

function userSequence() {
  $('.btn').click(function () {
    userChosenColor = $(this).attr('id');
    userClickedPattern.push(userChosenColor);
  
    animatePress(userChosenColor);
    playSound(userChosenColor);
    
    checkAnswer(userClickedPattern.length);
  });
}

//check if answer is right or wrong
function checkAnswer(currentLevel) {
  // let rightCounter = 0;
  // if (gamePattern.length == currentLevel) {
  //   for (let i = 0; i < gamePattern.length; i++) {
  //     if (gamePattern[i] == userClickedPattern[i]) {
  //       rightCounter++;
  //     } else {gameOver();}
  //   }
  //   if (rightCounter == gamePattern.length) {
  //     setTimeout(function () {
  //       userClickedPattern = [];
  //       nextSequence();
  //     }, 500);
  //   } else {gameOver();}
  // }
  if (gamePattern[currentLevel-1] == userClickedPattern[currentLevel-1]) {
    if (gamePattern.length == currentLevel) {
      setTimeout(function () {
        nextSequence();
      }, 500);
    }
  }
  else {
    gameOver();
  }
}

//start game
function startGame() {
  nextSequence();
  userSequence();
}

//start game
$('body').keydown(function () {
  if (started == false) {startGame(); started = true;}
});

I’ve asked chatGPT but it always gave me advanced stuff that I didn’t know what it did and I’d like to understand my code so if I ever come across a similar problem, I can solve it. When you press the wrong button (div element), it goes into game over, but in a glitched version. Anytime you click something, it will always be wrong even if it’s the right one. I’d like it to act normally.

Persona U are U 4500 Web API POST https://127.0.0.1:54589/connect net::ERR_TIMED_OUT

When I am saving fingerprints and I have stored more than 5, the connection to the web socket drops, I have no idea why, I already created a function to renoect when clicking but it keeps failing, it only works when I restart the page but it should not work correctly

Console Error:
POST https://127.0.0.1:54589/connect net::ERR_TIMED_OUT
(anónimo) @ websdk.client.bundle.min.js:8

import {
    useCallback,
    useEffect,
    useState
} from "react";

declare global {
    interface Window {
        Fingerprint: any;
    }
}

interface Props {
    fingerPrint: string;
    handleFinger: (image: string) => void;
}

const useFingerPrintReader = ({
    fingerPrint,
    handleFinger
}: Props) => {
    const [sdk, setSdk] = useState < any > (null);
    const [imageSrc, setImageSrc] = useState(fingerPrint || "");
    const [isCapturing, setIsCapturing] = useState(false);

    const setFingerPrint = useCallback((fingerprint: string) => handleFinger(fingerprint), [handleFinger]);

    useEffect(() => {
        if (typeof window !== "undefined") {
            const sdkInstance = new window.Fingerprint.WebApi();

            sdkInstance.onSamplesAcquired = (s: any) => {
                const samples = JSON.parse(s.samples);
                const base64 = `data:image/png;base64,${window.Fingerprint.b64UrlTo64(samples[0])}`;
                setImageSrc(base64);
                setFingerPrint(base64);
                stopCapture(sdkInstance);
            };

            setSdk(sdkInstance);

            return () => {
                sdkInstance.stopAcquisition().catch(() => {
                    console.warn("Error al detener la captura de huella en cleanup");
                });
            };
        } else {
            console.warn("Fingerprint SDK no está disponible en el objeto `window`.");
        }
    }, [setFingerPrint]);

    const startCapture = async () => {
        if (sdk) {
            await sdk.startAcquisition(window.Fingerprint.SampleFormat.PngImage).then(
                () => console.log("Capturando huella"),
                () => console.error("Error al comenzar la captura de huella")
            );
            setIsCapturing(true);
        } else {
            console.warn("El SDK de huellas no está inicializado.");
        }
    };

    const stopCapture = async (sdkInstance: any) => {
        if (sdkInstance) {
            await sdkInstance.stopAcquisition().then(
                () => console.log("Captura de huella detenida"),
                () => console.error("Error al detener la captura de huella")
            );
            setIsCapturing(false);
        }
    };

    return {
        startCapture,
        isCapturing,
        imageSrc,
    };
};

export default useFingerPrintReader;

When checking the connection url everything is correct:
enter image description here

After it disconnects the program tries to reconnect but continues to fail only until I refresh the screen, is there any way to fix this?
enter image description here

The sdk files are also loaded correctly:
enter image description here

I hope the websocket doesn’t disconnect to continue fingerprinting, I am currently using nextjs 14
enter image description here

React : Component with a clock re-rendering each second

I made this component representing a HH:MM clock.
It’s re-rendering every second. I would like to be re-rendered every minute.
A tooltip is attached to it. The tooltip cannot be shown because of the re-render.
How can I handle this situation ?

import TooltipComp from '@components/Shared/TooltipComp'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'

const Clock = () => {
    const [Time, setTime] = useState(new Date())
    const { t } = useTranslation();

    useEffect(() => {
        let now = new Date()
        while (now.getSeconds() !== 0) {
            const interval = window.setInterval(() => {now = new Date()}, 1000)
            return () => window.clearInterval(interval);
        }
        setTime(now);
    }, [])
    
    const formatTime = (time) => {
        return time < 10 ? `0${time}` : time
    }

    const date = Time.toLocaleDateString(t('locale'), {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    })

    return (
    <>
        <TooltipComp text={date}>
            <div style={{fontSize: "9px", fontFamily: "PX", cursor: "default"}}>
                {formatTime(Time.getHours())}
                &thinsp;:&thinsp;
                {formatTime(Time.getMinutes())}
            </div>
        </TooltipComp>
    </>
  )

  
}

export default Clock

I already tried using useMemo hooks, and multiple variations of the useEffect one.

Vuejs + Electron – Cannot find module background.js

I am trying to build a win app for manipulating files and folders using electron and vuejs by running npm run electron:build
It creates an app but when i run it gives me following error. im sorry for all these snippets but it was expedient that i provide them since i dont know what exactly is the problem. thanks in advance

Error
A JavaScript error occurred in the main process
Uncaught Exception:
Error: Cannot find module 'C:UsersHPDesktopNewFolderprojectathlete-file-managerdist_electronwin-u..background.js'
at Module._resolveFilename (node:internal/modules/cjs/loader:1232:15)
at s_resolveFilename (node:electron/js2c/browser_init:2:123740)
at node:electron/js2c/browser_init:2:129347
at node:electron/js2c/browser_init:2:129596
at node:electron/js2c/browser_init:2:129600
at BuiltInModule.compileForInternalLoader (node:internal/bootstrap/realm:398:7)
at BuiltInModule.compileForPublicLoader (node:internal/bootstrap/realm:337:10)
at loadBuiltinModule (node:internal/modules/helpers:104:7)
at Module._load (node:internal/modules/cjs/loader:1083:17)
at c_load (node:electron/js2c/node_init:2:16955)

i have my background.js

const { app, BrowserWindow, Menu, globalShortcut } = require('electron');
//const fs = require('fs');
const path = require('path');
const isDev = process.env.NODE_ENV === 'development';


function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        }
    });

    // Add error handler
    mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
        console.error('Failed to load:', errorCode, errorDescription);
    });

    mainWindow.webContents.on('console-message', (event, level, message) => {
        console.log('Renderer Console:', message);
    });


    if (isDev) {
        setTimeout(() => {
            mainWindow.loadURL('https://localhost:3000')
                .catch((err) => {
                    console.error('Failed to load URL:', err);
                    mainWindow.loadURL('http://localhost:3000')
                        .catch((err) => console.error('Failed to load HTTP fallback:', err));
                });
        }, 2000);
    } else {
        // Fix for production build path
        const indexPath = path.join(__dirname, '../index.html');
        console.log('Loading index from:', indexPath); // For debugging
        mainWindow.loadFile(indexPath)
            .catch((err) => {
                console.error('Failed to load file:', err);
                // Fallback attempt
                const fallbackPath = path.join(process.resourcesPath, 'app.asar/dist/index.html');
                console.log('Attempting fallback path:', fallbackPath);
                mainWindow.loadFile(fallbackPath)
                    .catch((err) => console.error('Fallback also failed:', err));
            });
    }

    // Optional: Enable DevTools in development
    if (isDev) {
        mainWindow.webContents.openDevTools();
    }

    // Create the application menu
    const template = [
        {
            label: 'File',
            submenu: [
                { role: 'quit' }
            ]
        },
        {
            label: 'View',
            submenu: [
                {
                    label: 'Analytics',
                    click: () => mainWindow.webContents.send('show-analytics')
                },
                {
                    label: 'Scan History',
                    click: () => mainWindow.webContents.send('show-history')
                },
                { role: 'toggleDevTools' }
            ]
        },
        {
            label: 'Settings',
            submenu: [
                {
                    label: 'Keyboard Shortcuts',
                    click: () => mainWindow.webContents.send('show-shortcuts')
                }
            ]
        }
    ];

    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);

    // Register global shortcuts
    globalShortcut.register('Right', () => {
        mainWindow.webContents.send('shortcut', 'same-athlete');
    });

    globalShortcut.register('Down', () => {
        mainWindow.webContents.send('shortcut', 'new-athlete');
    });

    globalShortcut.register('CommandOrControl+R', () => {
        mainWindow.webContents.send('shortcut', 'reset');
    });
}

// Add before app.whenReady()
app.commandLine.appendSwitch('ignore-certificate-errors');

app.whenReady().then(createWindow);


app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

// Clean up shortcuts when quitting
app.on('will-quit', () => {
    globalShortcut.unregisterAll();
});

package.json

{
  "name": "athlete-file-manager",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "dev": "npm run serve",
    "electron:serve": "vue-cli-service electron:serve",
    "generate-certs": "node ssl/create-certificates.js",
    "server": "node athlete-file-manager-backend/server.js",
    "start": "npm run generate-certs && concurrently "npm run server" "vue-cli-service serve" "wait-on https://localhost:3000 && cross-env NODE_ENV=development electron ."",
    "setup": "npm install && npm run generate-certs",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "electron:build": "vue-cli-service electron:build",
    "electron:dev": "electron .",
    "postinstall": "electron-builder install-app-deps",
    "postuninstall": "electron-builder install-app-deps",
    "rebuild": "electron-rebuild -f -w yourmodulename",
    "clean": "rimraf dist_electron",
    "build:clean": "npm run clean && npm run electron:build"
  },
  "main": "src/background.js",
  "dependencies": {
    "@vueuse/core": "^11.1.0",
    "axios": "^1.7.7",
    "core-js": "^3.8.3",
    "file-saver": "^2.0.5",
    "html5-qrcode": "^2.3.8",
    "pinia": "^2.2.4",
    "selfsigned": "^2.4.1",
    "socket.io-client": "^4.8.0",
    "vue": "^3.5.12",
    "vue-router": "^4.4.5",
    "webpack": "^5.95.0",
    "xlsx": "^0.18.5"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@electron-forge/cli": "^7.5.0",
    "@types/electron": "^1.6.12",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-typescript": "^5.0.8",
    "@vue/cli-service": "~5.0.0",
    "assert": "^2.1.0",
    "buffer": "^6.0.3",
    "concurrently": "^9.0.1",
    "cross-env": "^7.0.3",
    "crypto-browserify": "^3.12.0",
    "electron": "^33.0.2",
    "electron-builder": "^25.1.8",
    "electron-devtools-installer": "^3.1.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.7.1",
    "events": "^3.3.0",
    "path-browserify": "^1.0.1",
    "process": "^0.11.10",
    "stream-browserify": "^3.0.0",
    "util": "^0.12.5",
    "vue-cli-plugin-electron-builder": "~2.1.1",
    "wait-on": "^8.0.1",
    "webpack-dev-middleware": "^6.1.3",
    "webpack-dev-server": "^4.15.1"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "not ie 11"
  ]
}

vue.config.js

const { defineConfig } = require('@vue/cli-service');
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

module.exports = defineConfig({
  transpileDependencies: true,
  pages: {
    index: {
      entry: 'src/background.js'
    }
  },
  configureWebpack: {
    plugins: [
      new webpack.ProvidePlugin({
        process: 'process/browser',
        Buffer: ['buffer', 'Buffer'],
      }),
    ],
    resolve: {
      fallback: {
        path: require.resolve("path-browserify"),
        fs: false,
        stream: require.resolve("stream-browserify"),
        buffer: require.resolve("buffer/"),
        events: require.resolve("events/"),
        util: require.resolve("util/"),
        assert: require.resolve("assert/"),
        crypto: require.resolve("crypto-browserify"),
      },
      alias: {
        process: "process/browser"
      }
    }
  },

  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
      preload: 'src/electron/preload.js',
      mainProcessFile: 'src/background.js',
      builderOptions: {
        productName: 'Athlete File Manager',
        appId: 'com.athlete.filemanager',
        directories: {
          output: 'dist_electron',
          buildResources: 'build'
        },
        files: [
          "dist/**/*",
          "src/electron/**/*"
        ],
        win: {
          target: ['nsis'],
          icon: 'public/favicon.ico' // Make sure this path is correct
        },
        mac: {
          target: ['dmg']
        }
      }
    }
  },

  devServer: {
    https: {
      key: fs.readFileSync(path.resolve(__dirname, 'ssl/key.pem')),
      cert: fs.readFileSync(path.resolve(__dirname, 'ssl/cert.pem')),
      //ca: fs.readFileSync(path.resolve(__dirname, 'ssl/cert.pem'))
    },
    host: 'localhost',
    port: 3000,
    proxy: {
      '/api': {
        target: 'https://localhost:5000',
        secure: false, // Allow self-signed certificates
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      '/socket.io': {
        target: 'https://localhost:5000',
        ws: true,
        changeOrigin: true,
        secure: false, // Allow self-signed certificates
      }
    },
    client: {
      webSocketURL: {
        hostname: 'localhost',
        pathname: '/ws',
        password: '',
        port: 3000,
        protocol: 'ws',
      },
      overlay: {
        errors: true,
        warnings: false
      }
    },
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
      'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization'
    },
    static: {
      directory: path.join(__dirname, 'public')
    },
    compress: true,
    hot: true,
    historyApiFallback: true
  }
});

here is my project structure

athlete-file-manager/
├── athlete-file-manager-backend/
│   ├── node_modules/
│   ├── package.json
│   ├── package-lock.json
│   └── server.js
├── dist_electron/
├── node_modules/
├── public/
│   ├── favicon.ico
│   └── index.html
├── src/
│   ├── assets/
│   │   ├── logo.png
│   │   └── main.css
│   ├── components/
│   │   ├── BulkEntryDialog.vue
│   │   ├── DataEntry.vue
│   │   ├── ExportDialog.vue
│   │   ├── FileRename.vue
│   │   ├── ScanAnalytics.vue
│   │   ├── ScanHistory.vue
│   │   ├── SearchDialog.vue
│   │   └── SecurityWarning.vue
│   ├── composables/
│   │   └── useCameraIntegration.js
│   ├── electron/
│   │   └── preload.js
│   ├── router/
│   │   └── index.js
│   ├── services/
│   │   ├── apiService.js
│   │   ├── exportService.js
│   │   ├── fileRenameService.js
│   │   ├── fileService.js
│   │   └── websocket.js
│   ├── stores/
│   │   ├── athleteStore.js
│   │   └── fileRenameStore.js
│   ├── views/
│   │   ├── Home.vue
│   │   App.vue
│   ├── axios.js
│   ├── main.js
│   └── polyfills.js
│   └── background.js
├── ssl/
│   ├── cert.pem
│   ├── create-certificates.js
│   └── key.pem
├── .env
├── .eslintrc.js
├── .gitignore
├── babel.config.js
├── jsconfig.json
├── package.json
├── package-lock.json
├── README.md
└── vue.config.js

How would I resize the stty size of a web terminal with xterm.js?

I’ve created a simple web ssh client with xterm.js, but it doesn’t resize the stty columns and rows.
It does resize the terminal, with the fit addon, but that doesn’t change the stty size.
vim example
The terminal is clearly larger, and clearly has enough space for a bigger vim.
When I execute stty size, this is what I see:
stty size

I’ve tried changing the stty size with the amount of rows and columns on the terminal automatically, but I can’t execute it in the background, as that doesn’t do anything. When I try to execute it in the foreground, it does work, but it shows the command, which I don’t want.

I have tried to find a fix for this, but I can’t.

Tracking Button Presses in a Custom CKEditor5 Plugin With Angular

I can’t figure out in Angular which plugin is pressed from ckeditor5

I’m using the change output event, but it doesn’t seem to be providing the name of the pressed button.
Additionally, while I can see the list of commands for regular buttons, my plugin’s command is missing. It appears that this functionality might not be supported in CKEditor 5. Is there an alternative approach I can take? I need to know which plugin pressed.
`

const button = new ButtonView();
      
const image='svg...' 

      button.set({
        icon: image,
        role: 'mybutton',
      });`

“How to use JavaScript to detect which page is open so it can assign a class to the correct element?

I am creating side menu, and I am trying to create javascript, that detect on what page I am on, and to add class active to the right element.

I have this html:

<div>
  <ul>
    <li> <a href="link1.html" className="menuLink"> Page 1 </a></li>
    <li> <a href="link2.html" className="menuLink"> Page 2 </a></li>
    <li> <a href="link3.html" className="menuLink"> Page 3 </a></li>
  </ul>
</div>

And ChatGpt sugestet this code for javascipt:

const currentPath = window.location.pathname;

document.querySelectorAll('.menuLink').forEach((link) => {
    
    if (link.getAttribute('href') === currentPath) {
        link.classList.add('active'); 
    }
});

Sadly it is not working. Any sugestions? Thank you.

Luck Boost for a item drop system in js

I have an item dropping system but i want to be able to give the player more luck

const blocks = [
    {
        name: "Iron",
        ratio: 1 / 2,
    },
    {
        name: "Gold nugget",
        ratio: 1 / 4,
    },
    {
        name: "Green Amulet",

        ratio: 1 / 10,
    },
    {
        name: "Red Gem",
        ratio: 1 / 20,
    },
    {
        name: "Diamond",

        ratio: 1 / 100,
    }
]


const totalRatio = blocks.reduce((sum, item) => sum + item.ratio, 0);

function rollItem(luckIncreasePercentage = 0) {


    const luckboost = (1000 * Math.random());


    let roll = Math.random();


    let cumulativeChance = 0;
    for (let i = 0; i < blocks.length; i++) {
        cumulativeChance += blocks[i].ratio / totalRatio;
        if (roll <= cumulativeChance) {
            return blocks[i];
        }
    }
}

I want to be able to add a luckboost percent for example 10% more lucky of some sort
i already did something that would do more Math.randoms and take the highest one but i am not satisfied with the solution because if you have a crazy amount of luck it starts to lag out