useState isn’t working when parent useState function is applied

I have a ticket child class that sets the total amount after no of tickets has been been changed the problem i am facing here is setNumber doesn’t seem to work unless setTotal is commented out, i don’t understand this and could use some help regarding this issue

const Booking = () => {

    let [total, setTotal] = useState(0)

    const Ticket = ({ ticket, index }: any) => {

        let [number, setNumber] = useState(0);

        const handleChange = (e: any) => {

            const order = {
                eventid: eventid,
                amt: ticket.price * e.target.value,
                type: ticket.type,
                tickets: e.target.value,
                email: userdata!.email,
                ticketid: ticket.ticketid,
            }

            orders[index] = order

            //setNumber doesn't seem to work unless setTotal is commented out
            setNumber(Number(e.target.value))
            console.log(number)

            let sum = orders.reduce((accumulator: number, object: any) => {
                return accumulator + object.amt;
            }, 0)
            setTotal(sum)

        }

I’ve tried changing adding the setTotal function as a parameter to the child component but it doesn’t seem to work

Products filter widget shows out of stock products

I am using the product filter widget and the problem is that the filter also shows out of stock products. For example: Pants with 3 variations: S – Out of Stock, M – In Stock, L – In Stock.
If I filter to display only size S on the shop page, it display also those pants, although size S is Out of Stock.
I know this problem is known for years now but I still couldn’t find any solution out there, hope that there is one.

Appreciate any help,
Thanks

I’m going to use class Card and class Deck to create a Black Jack game, but how do I get them to work together?

I have parameters for to make a class Card and a class Deck to then create a Black Jack game, but I keep getting stuck on what to do next. Here are the parameters:

Write a BlackJack program that plays a game of BlackJack.
The program must draw a card randomly from a standard deck of 52 cards.
Your program must not print the same card twice until the deck runs out.
Your program must shuffle the deck when if runs out of cards.
All cards should be added back to the deck when shuffle() is called.
Your program should produce different output every time it runs (Based on randomly selecting cards).
For simplicity, you can consider the BlackJack value of an Ace to be 11.

Design an object card
Design an object Deck
Design a BlackJack program

//Here's what I have right now, I can work on the BlackJack program later.
//@author newToLife
public class Card{
//Use these class diagrams to create your objects.
private int value;
private String suit;
private String Color;
private String face;

    public Card(){
    }
    
    public Card(int value, String suit){
        this.value = value;
        this.suit = suit;
    }
    
    @Override
    public String toString(){
        return face +" "+ suit;
    }
    
    public String getColor(){
        return Color;
    }

    public String getFace(){
        return face;
    }
    
    public int getValue(){
        return value;
    } 
    public int getBjValue(){
        int BJValue;
        
        return BJValue;
    } 
    
    public String getSuit(){
        return suit;
    }

}

The Deck class.

import java.util.ArrayList;
//@author newToLife
public class Deck {

private ArrayList <Card> cards = new ArrayList<>();
private int deckSize = 52;
        
public Deck(){

}
    
private void loadCards(){
    for (int i = 1; i <= deckSize; i++){
        Card card = new Card();
        cards.add(card);
    }
} 
    
public Card drawCard(){
    if (deckSize == 0)
        return null;
    deckSize--;
    return card;
} 

public int getDeckSize(){
    return deckSize;
} 

public void shuffle(){
    java.util.Collections.shuffle(cards);
}

}

And app class.

import java.util.*;
import java.util.ArrayList;

public class BlackJack{
public static void main(String[] args) 
    {
        int bets;
        int bank = 500;

        Scanner input = new Scanner(System.in);
    }
}

Race condition SSE Redux Saga with additional REST request

function* firstSubscribeSSESaga() {
  try {
    // here deleted unnecessary information

    while (true) {
      const event = yield take(channel)
      const sseEventData: {
        someProperty1: string | null
        someProperty2: string | null
      } = event.data && JSON.parse(String(event.data))

      if (sseEventData.someProperty2) {
        yield call(secondSubscribeSSESaga, sseEventData.someProperty2)
      }

      yield put(firstProviderActions.setUpdateProperty(sseEventData))
    }
  } catch (error) {
    console.log('error', error)
  }
}

Perhaps someone knows how to solve this problem, please tell me.

Inforamation:

SSE Event has two keys in the object {someProperty1: string | null, someProperty2: string | null}

if (someProperty1) comes, then nothing specific happens, I just call the action (firstProviderActions.setUpdateProperty) and update data.

when (someProperty2) arrives, I need to additionally call another Saga (secondSubscribeSSESaga) and there make an additional GET request to Backend,
when this additional request is completed and updated the data in second Redux Store, after that I return to the current Saga and execute (firstProviderActions.setUpdateProperty)

My problem:

The first SSE Event arrives and it sent (someProperty2) and I go to call an additional GET request and wait for it. While I am waiting for this GET request to be executed, I receive a second SSE Event and it only contains (someProperty1).
Since for (someProperty1) I do not need to make an additional GET request, I go to immediately update the data (firstProviderActions.setUpdateProperty), but the problem is that I should not update the data from the second SSE event until I have updated the data from the first request.

The idea is that I should save data from SSE in parallel, in what order they come in and save it, but since in certain cases I have to make an additional GET request and wait for it, I cannot fulfill this condition.

Is there a CSS / JS querySelector for “upto”?

I have the following example:

https://jsfiddle.net/p5bweLnc/10/

<div class="foo">
  <div id="a1" class="bar">
  
  </div>
</div>
<div class="foo">
  <div id="a2" class="bar">
  
  </div>
</div>
<div class="foo">
  <div id="a3" class="bar">
  
  </div>
</div>
<div class="foo">
  <div id="a4" class="bar">
  
  </div>
</div>
<div class="foo">
  <div id="a5" class="bar">
  
  </div>
</div>
<div class="foo">
  <div id="a6" class="bar">
  
  </div>
</div>

CSS:

.foo {
  width: 100px;
  height: 100px;
  padding: 10px;
  background: yellow;
}

.bar {
  width: 100%;
  height: 100%;
  background: green;
}

JS:

let fourth = document.querySelector(`#a4`);

Let’s say I have selected the fourth one using the above JS. Is there a querySelector which lets me grab all the bar class divs which are BEFORE this fourth one? So a1, a2, a3? Or, is there a way to grab the previous one – a3?

Something like an “upto” selector and from a different parent?

how can i upload an image via post in node.js v14?

The problem is simple, but it has eaten my mind

I want to be able to import zip files to the server, but I can’t find a way to do it, I already tried to read the documentation, but I didn’t understand, I don’t understand what I’m doing wrong, is there any superhero who can help me?

index.js

const express = require('express');
const app = express();
const multer = require('multer');
const fs = require('fs');


const storage = multer({
    dest: "/upload"
  });


  app.post('/upload', storage.single('archivo'), (req, res) => {
   console.log("archivo resivido")
  });


app.use(express.static('public', {
    setHeaders: (res, path) => {
        console.log(res)
        if (path.endsWith('.css')) {
            res.setHeader('Content-Type', 'text/css');
        }if (path.endsWith('.js')) {
            res.setHeader('Content-Type', 'text/javascript');
        }
        if (path.endsWith('.json')) {
            res.setHeader('Content-Type', 'application/json');
        }
    }
    
}));

app.listen(80, () => {
    console.log('Servidor escuchando en http://localhost:80');
});

/public/index.html

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Flash Back Songs</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="./css/bootstrap.min.css">
</head>

<body>
  <nav class="navbar navbar-expand-lg bg-body-tertiary">
    <div class="container-fluid">
      <a class="navbar-brand"><img width="64" src="./mods/Flash Back.png" alt=""></a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        </ul>
        <form class="d-flex" role="search">
          <button type="button" class="btn btn-primary"><img width="64" src="./mods/play.png" alt=""></button>
          <button type="button" class="btn btn-secondary"><img width="64" src="./mods/pause.png" alt=""></button>
          <button type="button" class="btn btn-success">Success</button>
          <form action="http://localhost:80/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="archivo" required>
            <button type="submit" class="btn btn-success">Subir Archivo</button>
          </form>
        </form>
      </div>
    </div>
  </nav>

</body>

</html>
<script src="./renderer.js"></script>
<script src="./js/bootstrap.min.js"></script>

a detailed explanation and implementation of my index.js, please

How do I use the Canvas to draw a smaller, but same shape inside another whilst maintaining a constant border thickness?

enter image description here

I want to to take any shape, create a smaller version of it, and then use a negative mask to create a new shape that is like an outline of the first object, but with a constant thickness border. To my understanding, this is generally not possible without distorting the smaller image slightly (e.g. changing it’s aspect ratio). So I’m ok if the solution creates some distortion of the smaller image.

I also know how to create a negative mask:

ctx.globalCompositeOperation = 'source-out'

Whether it’s a some kind of mathematical solution, algorithm or a pointer to a library that I can use I’m all ears!

Thanks in advance.

Variable is null, but im never even creating it

Im currently getting this error repeatedly even after removing all mentions of the left variable from the code
Picture of the website
This happened after i tried to add a background to one of my div elements, i removed the code for the background but the error persisted, i then tried removing all code expect the html and the error still persisted, i did check to see if the files were saved

Also, the animation works as intended, and it wouldn’t work if left was actually null

Full code (App.js is the same):
Header.js

import React, { useEffect, useState } from 'react';

const Header = () => {
    const left = document.getElementById("left-side");
    const right = document.getElementById("right-side");

    let isLeftVisible = true;

    const switchSides = () => {
        isLeftVisible = !isLeftVisible;

        if (isLeftVisible) {
            left.style.width = "0%";
        } else {
            left.style.width = "100%";
        }
    }

    // Set the initial timer
    let timer = setInterval(switchSides, 3000);

    document.addEventListener("mousemove", () => {
        clearInterval(timer);
        timer = setInterval(switchSides, 3000);
    });

    document.addEventListener("touchstart", () => {
        clearInterval(timer);
        timer = setInterval(switchSides, 3000);
    });

    // Apply smooth transition using CSS transitions
    left.style.transition = "width 1.5s";
    right.style.transition = "width 1.5s";

    return (
        <>
            <div id="left-side" class="side">
                <h2 class="title">
                    Sometimes a simple header is 
                    <span class="fancy">better</span>      
                </h2>
            </div>
            <div id="right-side" class="side">
                <h2 class="title">
                    Sometimes a simple header is  
                    <span class="fancy">worse</span>     
                </h2>
            </div>

            <a id="source-link" class="meta-link" href="https://superlist.com" target="_blank">
                <i class="fa-solid fa-link"></i>
                <span class="roboto-mono">Source</span>
            </a>
        </>
    );
};

export default Header;

Code with only html:

App.js

import React, { useEffect, useState } from 'react';
import Header from './components/Header';

const App = () => {

  return (
    <>
      <Header />
    </>
  );
};

export default App;

Header.js

import React, { useEffect, useState } from 'react';

const Header = () => {

    return (
        <>
            <div id="left-side" class="side">
                <h2 class="title">
                    Sometimes a simple header is 
                    <span class="fancy">better</span>      
                </h2>
                </div>
                <div id="right-side" class="side">
                <h2 class="title">
                    Sometimes a simple header is  
                    <span class="fancy">worse</span>     
                </h2>
            </div>
        </>
    );
};

export default Header;

Javascript email regex avoid sonar hotspot warning

I used below regex pattern to validate the general email in Javascript, and got sonar hotspot warning like below, how can i improve the regex to avoid getting this warning?

regex

/^.+@.+.[a-zA-Z]{2,3}$/

warning

Make sure the regex used here, which is vulnerable to super-linear
runtime due to backtracking, cannot lead to denial of service.

how to access buttons inside Mutiple div classes

I have a set of buttons inside multiple div classes. When any button in a particular div class is pressed I want wrong to pop up. I’m confused on how to access. I tried using document.getElementsbyClassName() but this does not work is there another way. heres what I currently have inside the body.

<div class='container'>
        <div class='sections'>

            <div class='firstRow'>
                <button id="sect">cat1</button>
                <button id="sect">cat2</button>
                <button id="sect">cat3</button>
            </div>

            <div id="myPopup">
                <div id="myPopupHeader">
                    <span id="myPopupClose">x</span>
                    <h2>popup header</h2>
                </div>
                <div id="myPopupContent">
                    <textarea id="myPopupTextbox" placeholder="Write something..."></textarea>
                </div>
            </div>
            <script>
                var btn = document.getElementsByClassName("firstRow");
                btnContainer[0].addEventListener("click", function () { console.log("Hello"); }); 
            </script>
        </div>
    </div>

Why I cannot make increment on the power in Javascript? [duplicate]

I am trying to learn about Javascript. The problem I am facing currently is that I wish to increase the power to the base of 5 eventually until the answer capped at 200.

This is the output I expect:

5 
25 
125

However, the output I gotten is only:

5
25

I cant seem to get 125 even-though the cap is at 200.

Here is the code I had written:

let y = 5;
let z = "";

for (let x = 1; z <= 200; z = (y **= (x++))) {
  console.log(z);
}

TRYIGN TO CREATE A DEMO PREDICTING TOOL FOR 2 VARIABLES

I am trying to create a demo predicting tool which whould predict when the difference between 2 changing variables will be within the value of 2, and ChatGPT NEVER does the whole thing for some reason. For some reason it always either fails to add a cruical part or gets half of the stuff completely wrong. I do not understand why. Below is my latest prompt to ChatGPT but it seems for now that it is always in vain whatever i tell it to do. I humbly ask you for your help either in concrete code or in a a suggestion for a better prompt for ChatGPT.

“Hello Chat GPT. I hope you are good. Today, I would like you to code for me the following code in JavaScript, HTML and CSS languages please: What we were talking about before, i have condensed into the following further instruction, or rather plea, if you will. This time we should focus on the consistency of coding BUT ALSO on a clear DISPLAY OF EVERYTHING: Find a connection between THE two VARIABLES which repeats in the same OR VERY SIMILAR ratio of time and scale. (WITHIN THE TOTAL VALUE OF 2.). Please display and stack the values for display as they were in the time of connection (difference within 2) and by their side display a checkmark and keep all of that displayed ( stacked). The variables which change shopuld change every 2000 miliseconds and should be displayed in real time as they change on top everything. Based on how many times the variables change within the difference of 2, please learn from that and try to predict when (Slovenia time) they will again change withing the value of 2 and please write out and stack your predictions on when the change in value of 2 will repeat. For that, add the clock – live Slovenian time, and when the prediction is accurate mark it with a checkmark and keep the satisfied predictions along with the checkmarks AND ALONG WITH THE ACCURATE TIME OF SATISFIED PREDICTION displayed and stacked. Same goes for failed predictions, so display them aswell and keep them displayed, but along side those, display and keep a slash sign, ALONG WITH THE EXACT READING OF TIME FROM THE LIVE CLOCK (SLOVENIAN TIME).”

I TRIED TO CODE MY SELF, BUT AM STRUGGLING BECAUSE IM NOT A PROGRAMMER. I TRIED FOR 40 PAGES OF CHAT GPT PROMPTS ALREADY AND IT WILL NOT WRITE OUT A WORKING CODE.