Downloading file js

I have noticed when i download a bigger file it doesent download in smaller packets with a loading bar, you just have to wait a while and then it pops up at 100% is there anyother method that fixes this.

It currently looks like this.

const link = document.createElement("a");
link.href = myUrl;
link.setAttribute("download", data.name);
document.body.appendChild(link);
link.click();
link.remove();

I looked for how to use a stream, but im not sure if that is what you use. Thank you.

Grid Layout display not appearing

Here is my code for a Quiz web application I am currently trying to have the quiz container have display: none; until I press start game where the container will then change to display: grid;
This is where I encounter my issue when I try to reveal the div it will not appear.
HTML

const buttonGrid = document.querySelector('.grid');
function startGame() {
    buttonGrid.remove(); // Remove the entire grid container
    logo.forEach(logoElement => logoElement.remove()); // Remove each logo element

    const selectedFile = fileInput.files[0];

    if (selectedFile) {
        const reader = new FileReader();

        reader.onload = function (e) {
            const fileContent = e.target.result;

            try {
                const quizData = JSON.parse(fileContent);
                displayQuiz(quizData);
            } catch (error) {
                console.error("Error parsing JSON file:", error);
            }
        };

        reader.readAsText(selectedFile);
    } else {
        console.error("No file selected.");
    }
    
    const quizField = document.getElementById('quiz-container');
    quizField.classList.add('show-container');

}
.container{
    background: white;
    height: 100vh;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center; /* Center vertically */
    align-items: center; /* Center horizontally */
    #question{
    font-size: 25px;
    margin-bottom: 150px;

}
.quizField{
    display: none;
    text-align: center;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
    

}
#submit-btn{
    margin-top: 50px;
    display: inline-block;
    margin: 0 auto;
    
}
#result {
    margin-top: 20px;
}
#total-score{
    font-size: 18px;
    margin-top: 20px;
    font-weight: bold;
}
show-container{
    display: grid;
}
.button-56{
    align-items: center;
    background-color: rgb(74, 227, 36);
    border: 2px solid #111;
    border-radius: 8px;
    box-sizing: border-box;
    color: #111;
    cursor: pointer;
    display: flex;
    font-size: 16px;
    height: 48px;
    justify-content: center;
    line-height: 24px;
    max-width: 100%;
    padding: 0 25px;
    position: relative;
    text-align: center;
    text-decoration: none;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
}
.button-56:after{
    background-color: lightgrey;
    border-radius: 8px;
    content: "";
    display: block;
    height: 48px;
    left: 0;
    width: 100%;
    position: absolute;
    top: -2px;
    transform: translate(8px, 8px);
    transition: transform .2s ease-out;
    z-index: -1;
}
.button-56:hover:after{
    transform: translate(0, 0);
}
  
.button-56:active{
    background-color: #ffdeda;
    outline: 0;
}
  
.button-56:hover{
    outline: 0;
}
<body>
    <!-- Main container for the page -->
    <div class="container">
        <!-- Question and Answer Fields-->
        <div id='quiz-container' class="quizField">
        <div id="question"></div>
        <input type="text" id="answer-input" placeholder="Your Answer">
        <button class='button-56' id="submit-btn" onclick="submitAnswer()">Submit</button>
        <div id="result"></div>
        <div id="total-score"></div>
    </div>
     <div class="grid">
            <button id="start" class="button-56" role="button">Start</button>
            <label  for='fileInput' id='list' class="button-56">Open JSON File </label>
                <input type="file" id="fileInput" class="file" accept=".json" /></button>
                 
            <button id='contact' class="button-56" role="button">Contact</button>
        </div>
        

hello , so i’m working on my logging for my project using Django and the auth is with metamask but when the user tries to register the data isnt saved

when the user logs for the first time using metamask , he’s redirected to the register form to complete his account by adding email , first name , last name and password but when the user submit thr form and i check the admin dashboard i only see the username aka the eth address but the other info from the form arent saved , here’s the view :

import json
import requests
import datetime
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from .forms import RegisterForm
from django.contrib.auth.decorators import login_required


API_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJub25jZSI6IjBhM2I2MTRjLWQ2ZjQtNGRkOS04M2RmLTIzNmZiMjBjNzg1OCIsIm9yZ0lkIjoiMzY5NTYzIiwidXNlcklkIjoiMzc5ODE2IiwidHlwZUlkIjoiOTNiZDhjOWYtNTViZC00ZmFmLThiMTQtNTZhYTFhZmIyMjZhIiwidHlwZSI6IlBST0pFQ1QiLCJpYXQiOjE3MDM1MjQ5NTcsImV4cCI6NDg1OTI4NDk1N30.CrZJcIyqcCdYMtM45pbRB4tY7-fOqwxSRhEtmE_dba0'

def moralis_auth(request):
   return render(request, 'login.html', {})


def request_message(request):
   data = json.loads(request.body)
   print(data)

   REQUEST_URL = 'https://authapi.moralis.io/challenge/request/evm'
   
   # Adjusted expiration time to 5 minutes from the current time
   expiration_time = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)).isoformat() + "Z"

   request_object = {
       "domain": "defi.finance",
       "chainId": 1,
       "address": data['address'],
       "statement": "Please confirm",
       "uri": "https://defi.finance/",
       "expirationTime": expiration_time,
       "notBefore": "2020-01-01T00:00:00.000Z",
       "timeout": 15
   }
   x = requests.post(
       REQUEST_URL,
       json=request_object,
       headers={'X-API-KEY': API_KEY})

   return JsonResponse(json.loads(x.text))

def verify_message(request):
   data = json.loads(request.body)
   print(data)

   REQUEST_URL = 'https://authapi.moralis.io/challenge/verify/evm'
   x = requests.post(
       REQUEST_URL,
       json=data,
       headers={'X-API-KEY': API_KEY})
   print(json.loads(x.text))
   print(x.status_code)
   if x.status_code == 201:
       # user can authenticate
       eth_address = json.loads(x.text).get('address')
       print("eth address", eth_address)
       try:
           user = User.objects.get(username=eth_address)
       except User.DoesNotExist:
           # If user does not exist, create a new user
           user = User.objects.create_user(username=eth_address, password=None)
           user.save()
           # Set a flag in the session to indicate that the user needs to complete the registration process
           request.session['needs_registration'] = True
       if user is not None:
           if user.is_active:
               login(request, user)
           request.session['auth_info'] = data
           request.session['verified_data'] = json.loads(x.text)
           return JsonResponse({'user': user.username})
       else:
           return JsonResponse({'error': 'account disabled'})
   else:
       # If user does not exist, create a new user
       user = User.objects.create_user(username= eth_address, password=None)
       user.save()
       # Set a flag in the session to indicate that the user needs to complete the registration process
       request.session['needs_registration'] = True
       return JsonResponse(json.loads(x.text))


def register(request):
    # Assuming your verification process sets 'needs_registration' in the session
    needs_registration = request.session.get('needs_registration', False)

    # If the user doesn't need registration, redirect to the profile
    if not needs_registration:
        return redirect('my_profile')

    form = RegisterForm(request=request)

    if request.method == 'POST':
        form = RegisterForm(request.POST, request=request)
        if form.is_valid():
            eth_address = request.session.get('verified_data', {}).get('address')
            
            # Check if the user already exists
            user_exists = User.objects.filter(username=eth_address).exists()

            if user_exists:
                # User exists, proceed with login
                user = User.objects.get(username=eth_address)
            else:
                # User doesn't exist, create the user
                user = form.save()

            # Authenticate the user
            login(request, user)

            # Set 'needs_registration' to False after registration
            request.session['needs_registration'] = False

            # Redirect to the user's profile
            return redirect('my_profile')

    return render(request, 'register.html', {'form': form})


@login_required
def my_profile(request):
   eth_address = request.user.username

   if User.objects.filter(username=eth_address).exists():
       print("User already exists in the database")
       if 'needs_registration' in request.session:
           print("User needs registration")
           # Clear the 'needs_registration' flag from the session to prevent infinite redirection loop
           del request.session['needs_registration']
           return redirect('register')
       else:
           print("User does not need registration")
           return render(request, 'profile.html', {'user': request.user})
   else:
       print("User does not exist in the database")
       return redirect('register')

this is my form.py :

from django import forms
from django.contrib.auth.models import User

class RegisterForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ["username", "email", "first_name", "last_name", "password"]

    def __init__(self, *args, request=None, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        if request:
            self.fields['username'].widget = forms.HiddenInput()
            self.fields['username'].initial = request.session.get('verified_data', {}).get('address')

    def save(self, commit=True):
        # Override the save method to handle user instance updates
        user = super(RegisterForm, self).save(commit=False)

        # Update user data
        user.email = self.cleaned_data.get('email')
        user.first_name = self.cleaned_data.get('first_name')
        user.last_name = self.cleaned_data.get('last_name')
        user.set_password(self.cleaned_data.get('password'))

        if commit:
            user.save()

        return user

and this is the register form :

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Register</title>
</head>
<body>
   <h1>Register</h1>
   <form method="POST" id="registrationForm">
       {% csrf_token %}
       {{ form.as_p }}
       <button type="submit">Register</button>
       {% if form.errors %}
    <div style="color: red;">
        <strong>Error(s):</strong>
        <ul>
            {% for error in form.errors %}
                <li>{{ error }}</li>
            {% endfor %}
        </ul>
    </div>
{% endif %}
   </form>

   <script>
    document.getElementById('registrationForm').addEventListener('submit', async function(event) {
        event.preventDefault();

        // Fetch the form data
        const formData = new FormData(this);

        try {
            // Make an asynchronous POST request to the registration endpoint
            const response = await fetch('/web3_auth/register', {
                method: 'POST',
                body: formData,
            });

            // Check if the registration was successful
            if (response.ok) {
                // Redirect the user to the dynamically generated profile page URL
                const profileUrl = '{% url 'my_profile' %}';
                window.location.href = profileUrl;
            } else {
                // Handle registration errors (show an alert, update UI, etc.)
                alert('Registration failed. Please try again.');
            }
        } catch (error) {
            console.error('An error occurred during registration:', error);
            alert('An error occurred during registration. Please try again.');
        }
    });
</script>


</body>
</html>

i dont get any error it just the data doesnt get saved

Why do I get a CORS issue on only some of my API endpoints?

I am having a problem with my API endpoints. I am using flask for my backend, and for frontend just js, html/css, react.

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route('/users/login', methods=['POST'])
@cross_origin()
def user_logon():
    if request.is_json:

I looked around and i thought this was working. It worked for a similar endpoint, but the one above it doesnt work for. I tried adding headers in the front end, but that didn’t work. I am not sure why one works and the other doesnt when they are the exact same.

I keep getting the classic cors error

Access to fetch at ‘http://localhost:5000/users/login’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

I’m very confused lol

reactjs dynamic line chart

Good evening everyone,

I am creating a dynamic line chart, where I process the data received from the Api and pass it to the chart, but no lines are generated when I save the data in usestate. But if I create a const with a list of objects, and pass it to the graph it works perfectly, does anyone have any idea how to solve it?

Code Reacjs App.

ProductionTableDailyChart

import React, { useState, useEffect } from "react";
import axios from "axios";
import { Spinner, Form, Row, Col, Button } from "react-bootstrap";
import {
    LineChart,
    Line,
    XAxis,
    YAxis,
    CartesianGrid,
    Tooltip,
    Legend,
    ResponsiveContainer,
} from "recharts";
import moment from "moment";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Select from "react-select";
import ProductionTableLineChart from "./ProductionTableLineChart";

const ProductionTableDailyChart = ({ uniqueProjects }) => {
    const [chartData, setChartData] = useState([]);
    const [activities, setActivities] = useState([]);
    const [selectedProjects, setSelectedProjects] = useState(
        JSON.parse(localStorage.getItem("selectedProjects")) || [],
    );
    const [selectedActivity, setSelectedActivity] = useState(
        localStorage.getItem("selectedActivity") || "",
    );
    const [startDate, setStartDate] = useState(
        localStorage.getItem("startDate") ||
            moment().subtract(7, "days").format("YYYY-MM-DD"),
    );
    const [finishDate, setFinishDate] = useState(
        localStorage.getItem("finishDate") || moment().format("YYYY-MM-DD"),
    );
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        localStorage.setItem(
            "selectedProjects",
            JSON.stringify(selectedProjects),
        );
    }, [selectedProjects]);

    useEffect(() => {
        localStorage.setItem("selectedActivity", selectedActivity);
    }, [selectedActivity]);

    useEffect(() => {
        localStorage.setItem("startDate", startDate);
    }, [startDate]);

    useEffect(() => {
        localStorage.setItem("finishDate", finishDate);
    }, [finishDate]);

    const handleProjectChange = (selectedOptions) => {
        console.log(selectedOptions);
        setSelectedProjects(selectedOptions.map((option) => option.value)); // Extrair os valores dos objetos selecionados
    };

    const handleActivityChange = (e) => {
        setSelectedActivity(e.target.value);
    };

    const handleStartDateChange = (e) => {
        setStartDate(e.target.value);
    };

    const handleFinishDateChange = (e) => {
        setFinishDate(e.target.value);
    };

    const fetchChartData = async () => {
        setIsLoading(true);

        if (selectedProjects.length === 0) {
            toast.error("Os campo projeto é obrigatório.");
            setIsLoading(false);
            return;
        }

        if (selectedActivity === "") {
            toast.error("Os campo atividade é obrigatório.");
            setIsLoading(false);
            return;
        }

        try {
            const promises = selectedProjects.map(async (project) => {
                const endpoint = project
                    ? `/api/production/getperiodProduction/${startDate}/${finishDate}/${project.name}`
                    : `/api/production/getperiodProduction/${startDate}/${finishDate}/`;
                const response = await axios.get(endpoint);
                const processedData = processActivityData(
                    response.data,
                    project,
                );
                return processedData;
            });

            const chartData = await Promise.all(promises);

            const combinedChartData = chartData.reduce((result, data) => {
                data.forEach((entry) => {
                    if (entry.project) {
                        // Check if entry.project exists
                        const existingEntry = result.find(
                            (item) => item.date === entry.date,
                        );
                        if (existingEntry) {
                            existingEntry["P" + entry.project.id] =
                                entry.accumulatedValue;
                        } else {
                            const newEntry = {
                                date: entry.date,
                                ["P" + entry.project.id]:
                                    entry.accumulatedValue,
                                name: entry.name,
                            };
                            result.push(newEntry);
                        }
                    }
                });
                return result;
            }, []);

            setChartData(combinedChartData);
        } catch (error) {
            console.error("Error fetching chart data:", error);
        }
        setIsLoading(false);
    };

    const processActivityData = (activities, project) => {
        let selectedActivityData = activities.find(
            (item) => item.activitie === selectedActivity,
        );

        if (!selectedActivityData || !selectedActivityData.dailyProduction) {
            console.error(
                "No valid dailyProduction data found for the selected activity.",
            );
            return [];
        }

        let accumulated = 0;

        const dailyProduction = selectedActivityData.dailyProduction;
        const processedData = Object.entries(dailyProduction)
            .sort(([date1], [date2]) => new Date(date1) - new Date(date2))
            .map(([date, quantity]) => {
                quantity = Number(quantity);
                accumulated += isNaN(quantity) ? 0 : quantity;
                return {
                    date: moment(date).format("DD-MM-YYYY"),
                    ["P" + project.id]: accumulated,
                    name: project.name,
                };
            });

        return processedData;
    };

    const fetchActivities = async () => {
        try {
            const response = await axios.get("/api/markers");
            setActivities(response.data);
        } catch (error) {
            console.error("Error fetching activities:", error);
        }
    };

    const getRandomColor = () => {
        const letters = "0123456789ABCDEF";
        let color = "#";
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    };

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

    useEffect(() => {
        if (selectedActivity) {
            fetchChartData();
        }
    }, [selectedActivity, selectedProjects]);

    if (isLoading) {
        return (
            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    height: "100vh",
                }}
            >
                <Spinner animation="border" />
            </div>
        );
    }

    return (
        <>
            <Row className="mb-3 align-items-end">
                <Col md={5}>
                    <Form.Group controlId="projectDropdown">
                        <Form.Label>Selecione o Projeto:</Form.Label>
                        <Select
                            options={uniqueProjects.map((project) => ({
                                value: project,
                                label: project.name,
                            }))}
                            isMulti
                            onChange={handleProjectChange}
                            value={selectedProjects.map((project) => ({
                                value: project,
                                label: project.name,
                            }))}
                        />
                    </Form.Group>
                </Col>
                <Col md={2}>
                    <Form.Group controlId="activityDropdown">
                        <Form.Label>Selecione a Atividade:</Form.Label>
                        <Form.Control
                            as="select"
                            onChange={handleActivityChange}
                            value={selectedActivity}
                        >
                            <option value="">Todas as Atividades</option>
                            {activities.map((activity) => (
                                <option
                                    key={activity.id}
                                    value={activity.atividade}
                                >
                                    {activity.atividade}
                                </option>
                            ))}
                        </Form.Control>
                    </Form.Group>
                </Col>
                <Col md={2}>
                    <Form.Group controlId="startDate">
                        <Form.Label>Data Inicial</Form.Label>
                        <Form.Control
                            type="date"
                            required
                            value={startDate}
                            onChange={handleStartDateChange}
                        />
                    </Form.Group>
                </Col>
                <Col md={2}>
                    <Form.Group controlId="finishDate">
                        <Form.Label>Data Final</Form.Label>
                        <Form.Control
                            type="date"
                            required
                            value={finishDate}
                            onChange={handleFinishDateChange}
                        />
                    </Form.Group>
                </Col>
                <Col md={2}>
                    <Button
                        onClick={fetchChartData}
                        variant="primary"
                        style={{ marginTop: "32px" }}
                    >
                        Atualizar Gráfico
                    </Button>
                </Col>
            </Row>

            <ProductionTableLineChart
                chartData={chartData}
                selectedProjects={selectedProjects}
            />

            {/* <div style={{ width: "100%", height: 600 }}>
                {chartData && selectedProjects.length > 0 ? (
                    <ResponsiveContainer>
                        <LineChart data={chartData}>
                            <XAxis dataKey="date" style={{ fontSize: "8px" }} />
                            <YAxis />
                            <CartesianGrid
                                stroke="#eee"
                                strokeDasharray="5 5"
                            />
                            <Tooltip />
                            <Legend />
                            {selectedProjects.map((project) => (
                                <Line
                                    key={project.id}
                                    type="monotone"
                                    dataKey={`P${project.id}`}
                                    stroke={getRandomColor()}
                                    name={project.name}
                                />
                            ))}
                        </LineChart>
                    </ResponsiveContainer>
                ) : (
                    <p>Carregando dados ou nenhum projeto selecionado...</p>
                )}
            </div> */}
            <ToastContainer />
        </>
    );
};

export default ProductionTableDailyChart;


import React from "react";
import {
    LineChart,
    Line,
    XAxis,
    YAxis,
    CartesianGrid,
    Tooltip,
    Legend,
    ResponsiveContainer,
} from "recharts";

const getRandomColor = () => {
    const letters = "0123456789ABCDEF";
    let color = "#";
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
};

const data1 = [
    {
        date: "01-10-2023",
        P4: 0,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "02-10-2023",
        P4: 1,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "03-10-2023",
        P4: 2,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "04-10-2023",
        P4: 4,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "05-10-2023",
        P4: 6,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "06-10-2023",
        P4: 8,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "07-10-2023",
        P4: 8,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "08-10-2023",
        P4: 8,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "09-10-2023",
        P4: 8,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "10-10-2023",
        P4: 10,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "11-10-2023",
        P4: 11,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "12-10-2023",
        P4: 11,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "13-10-2023",
        P4: 12,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "14-10-2023",
        P4: 16,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "15-10-2023",
        P4: 16,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "16-10-2023",
        P4: 18,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "17-10-2023",
        P4: 19,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "18-10-2023",
        P4: 19,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "19-10-2023",
        P4: 23,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "20-10-2023",
        P4: 26,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "21-10-2023",
        P4: 27,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "22-10-2023",
        P4: 27,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "23-10-2023",
        P4: 27,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "24-10-2023",
        P4: 31,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "25-10-2023",
        P4: 32,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "26-10-2023",
        P4: 35,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "27-10-2023",
        P4: 37,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "28-10-2023",
        P4: 37,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "29-10-2023",
        P4: 37,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "30-10-2023",
        P4: 37,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
    {
        date: "31-10-2023",
        P4: 38,
        name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
    },
];

const ProductionTableLineChart = ({ chartData, selectedProjects }) => {
    // Gerar uma string única baseada no conteúdo de chartData.
    // Isso pode ser um timestamp ou um identificador único derivado dos dados.
    const chartKey = JSON.stringify(chartData);

    return (
        <div style={{ width: "100%", height: 600 }}>
            {chartData && selectedProjects.length > 0 ? (
                <ResponsiveContainer key={chartKey}>
                    <LineChart data={chartData}>
                        <XAxis dataKey="date" style={{ fontSize: "8px" }} />
                        <YAxis />
                        <CartesianGrid stroke="#eee" strokeDasharray="5 5" />
                        <Tooltip />
                        <Legend />
                        {selectedProjects.map((project) => (
                            <Line
                                key={project.id}
                                type="monotone"
                                dataKey={`P${project.id}`}
                                stroke={getRandomColor()}
                                name={project.name}
                            />
                        ))}
                    </LineChart>
                </ResponsiveContainer>
            ) : (
                <p>Carregando dados ou nenhum projeto selecionado...</p>
            )}
        </div>
    );
};

export default ProductionTableLineChart;

In code have Array list

const data1 = [
{
    date: "01-10-2023",
    P4: 0,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "02-10-2023",
    P4: 1,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "03-10-2023",
    P4: 2,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "04-10-2023",
    P4: 4,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "05-10-2023",
    P4: 6,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "06-10-2023",
    P4: 8,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "07-10-2023",
    P4: 8,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "08-10-2023",
    P4: 8,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "09-10-2023",
    P4: 8,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "10-10-2023",
    P4: 10,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "11-10-2023",
    P4: 11,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "12-10-2023",
    P4: 11,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "13-10-2023",
    P4: 12,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "14-10-2023",
    P4: 16,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "15-10-2023",
    P4: 16,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "16-10-2023",
    P4: 18,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "17-10-2023",
    P4: 19,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "18-10-2023",
    P4: 19,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "19-10-2023",
    P4: 23,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "20-10-2023",
    P4: 26,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "21-10-2023",
    P4: 27,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "22-10-2023",
    P4: 27,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "23-10-2023",
    P4: 27,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "24-10-2023",
    P4: 31,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "25-10-2023",
    P4: 32,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "26-10-2023",
    P4: 35,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "27-10-2023",
    P4: 37,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "28-10-2023",
    P4: 37,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "29-10-2023",
    P4: 37,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "30-10-2023",
    P4: 37,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
},
{
    date: "31-10-2023",
    P4: 38,
    name: "LT 500 kV ENG. LECHUGA - EQUADOR-T2B",
}];

i want to make a click and reveal on my 4 text pads

i am a begginer and i really want to make a click or hold cursor on the each pad separately and reveal the text inside:
thisis the code:

`
<!DOCTYPE html>
<html>
<head>
  <title>ProiectIA1</title>
  <link rel="stylesheet" href="style.css"/>
  <script src="script.js" defer></script>
</head>
<body>
  <section>
    <div class="container">
      <div class="box">
        <h2 class="heading--text">PROIECT=IA1</h2>
      </div>
    </div>
  </section>

  <div class="main-container">
    <div class="eu">
      <img src="eu.jpg" alt="eu">
    </div>



    <section class="text-pad-section">
      <div class="container">
        <div class="text-pad1">
          <p>This is text pad 1. You can replace this text with your own content.</p>
        </div>
        <div class="text-pad2">
          <p>This is text pad 2. You can replace this text with your own content.</p>
        </div>
        <div class="text-pad3">
          <p>This is text pad 3. You can replace this text with your own content.</p>
        </div>

        <div class="text-pad4">
          <p>This is text pad 4. You can replace this text with your own content.</p>
        </div>
      


</div>
    </section>
  </div>
</body>
</html>
`

CSS:
`

body{
background-image: url("fundal.jpg");
background-repeat: no-repeat;
background-size: cover;


 height: 100vh; 
  overflow: hidden;
}



html {
  height: 100%; 

section{
    display: flex;
    align-items:center;
    justify-content: left;
    min-height: 98vh;
    padding: 10px;


}
.box{
    display: inline;
    width: 80%;
}
.heading--text{
  display:inline;
  letter-spacing: 15px;
  height: 595px;
width: 37px;
  padding: 15px;
  background-color: #000000;
  color:white;

font-size: 36px;
font-family:"Copperplate";
text-orientation: upright;
writing-mode: vertical-lr;
}

.eu img{
width: 415px;
    height: auto;
    position: absolute;
    top: 51%;
    left: 7%;
    transform: translatey(-50%);
}


.main-container {
  display: flex;

}



.text-pad-section {
  display: flex;
  flex-wrap: wrap;
  margin-top: 40px; 

}

.text-pad1 {
  width: 70%;
  margin-right: 20%; 
  margin-bottom: 20px;
  padding: 115px;
  border: 5px solid #191970;
  border-radius: 20px;
  box-sizing: border-box;
  font-family: Arial, sans-serif;
  background-color: rgba(30, 144, 255, 0.4);
position: relative;
left: 600px;
bottom: 785px;

}

.text-pad2 {
  width: 70%;
  margin-right: 20%; 
  margin-bottom: 20px;
  padding: 115px;
  border: 5px solid #191970;
  border-radius: 20px;
  box-sizing: border-box;
  font-family: Arial, sans-serif;
  background-color: rgba(30, 144, 255, 0.4); 
position: relative;
left: 1120px;
bottom: 1115px;

}


.text-pad3 {
 width: 70%;
  margin-right: 20%; 
  margin-bottom: 20px;
  padding: 115px;
  border: 5px solid #191970;
  border-radius: 20px;
  box-sizing: border-box;
  font-family: Arial, sans-serif;
  background-color: rgba(30, 144, 255, 0.4); 
position: relative;
left: 600px;
bottom: 1110px;}







.text-pad4 {
  width: 70%;
  margin-right: 20%; 
  margin-bottom: 20px;
  padding: 115px;
  border: 5px solid #191970;
  border-radius: 20px;
  box-sizing: border-box;
  font-family: Arial, sans-serif;
  background-color: rgba(30, 144, 255, 0.4); 
position: relative;
left: 1120px;
bottom: 1437px;
backface-visibility: hidden;
}

I need help with this s*it bcs i had my head around for 2 days and i can’t figure it out

I need help with this s*it bcs i had my head around for 2 days and i can’t figure it out

I need help with this s*it bcs i had my head around for 2 days and i can’t figure it out

I need help with this s*it bcs i had my head around for 2 days and i can’t figure it out

I need help with this s*it bcs i had my head around for 2 days and i can’t figure it out

I need help with this s*it bcs i had my head around for 2 days and i can’t figure it out

I need help with this s*it bcs i had my head around for 2 days and i can’t figure it out

I need help with this s*it bcs i had my head around for 2 days and i can’t figure it out

Unsure of how to structure Node JS Web APP with express user auth

I’m teaching myself web dev, I made a website display inside my App.js file with the HTML inside the App.js
with some JS functionality I wrote being imported into App.js.

function App() {
const DailyrandNum = getDailyRandomInt(); //var for daily random image  - img 
const RefreshrandNum  = getRandomInt();   //var for refresh page  refereshimage - img 
const isDarkmode = true;
const seedTest = getSeed();

const [startTransition] = useTransition();

return (
<div className="App">
 <header className="App-header">
     <nav> 
       <button id="lightDarkButton"       onClick={lightDarkmode}> <img src={'/Light-Dark mode photos/sun-icon.png'} width="30" height="30"/></button>
        </nav>
    <div className="header-content">
      <h2>Habbit!</h2>  
      <img src={`${process.env.PUBLIC_URL}/frog_photos/frog_${DailyrandNum}.png`} alt="frog_emoji" width="128" height="128" />
      </div>
      <p>Daily Habit Tracker</p>
       <p>Welcome back - *name </p>
    <div className = "Date and time">
    <hr className = 'solidline'></hr>
     <DateTime></DateTime>
      </div>
     <div className="container mt-5">
      <DynamicCheckbox/>
    </div>
  </header>
  </div>
  );
}

Than I followed a tutorial to make a express login system, I created a views folder and route between login.ejs, register.ejs and index.ejs as home.

The login system tutorial redirects to index.ejs, I cant figure out where to go from here.

Should I route from index.ejs to App.js ? or try to display the functionality from app.js on index.ejs ?
and how would you recommend I structure my files for my web app.
Thanks

Displaying webapp, can only direct to index.ejs. Dont know how to display App.js content or reroute user to App.js.

JS Dispatch mousemove event for smartphones from Bing Map V8 to the website’s parent

The issue: I am using Bing Map V8, but when you are on a mobile device, the presence of the map makes it hard to scroll down the page, as touches on the map cause panning of the map and prevent further scrolling of the page.

My idea to address the issue is to disable panning on small devices and let users scroll further instead. To achieve this I’ve tried so far:

  1. Disable panning using map options disablePanning: true. The panning indeed no longer possible, but touching the map area doesn’t scroll the page either.
  2. CSS property touch-action: none; on the #map-div and #map-div *. Doesn’t work at all, the map keeps panning.
  3. Tried to preventDefault() for mousemove events on small devices. It prevents map from panning, spams with dozens of errors to the console, but doesn’t scroll the page.
  4. Tried to combine approach #1 and dispatchEvent function to catch mousemove/touchmove events and trigger them on the window instead. It doesn’t seem to work, which makes me wonder if I am doing it all wrong. Here is my code (I am using vanilla JS):
Microsoft.Maps.Events.addHandler(map, 'mousemove', function (e) {
  window.dispatchEvent(new Event('mousemove'));
});

I’ve tried different variations of the code above, like mousemove/touchmove, window.dispatchEvent/document.dispatchEvent, new Event/new MouseEvent, passing ‘e’ with the dispatchEvent etc. Nothing seems to work as expected, please help.

a simple algorithm to calculate a price but there is a problem

This is a js code very simple

let priceTl = document.getElementById("tl");
let priceSar = document.getElementById("sar");
let finalPrice = document.getElementById("price");

let convertFromTl = () => {
    let tl = priceTl.value;

  //toFixed(2) limits the decimals to 2 digits.
    priceSar.value = tl / 7.6503;

      if (priceSar.value * 0.1 <= 5) {
        finalPrice.value = priceSar.value + 5;
      }
      if (priceSar.value * 0.1 >= 15) {
        finalPrice.value = priceSar.value + 15;
      } else {
        finalPrice.value = priceSar.value * 1.1;
      }
};

priceTl.addEventListener("input", convertFromTl);
window.addEventListener("load", convertFromTl);

The code gets 3 data from the index.html – gets the priceTl, priceSar, finalPrice.
This is how my website looks like
enter image description here

It’s a very simple calculator to put a price in the first input in Turkish lira which calculate it to Saudi Arabian riyals in the second input and so far there is no problem.

But the third input should check the second input the Saudi Arabian riyals if the (price * 0.1) is less than or equal to 5 then the final price should be the price in Saudi riyals + 5, and if the price *0.1 is bigger than or equal to 15 then the final price should equal 15.
and if it’s between 5 and 15 then the final price should equal the Saudi riyals *1.1, and it should automatically update the data in the website but what happens for no reason is it calculates the final price as Saudi riyals *1.1 always even if the value is less than 5 or bigger than 15.

Playwright locator getByRole() auto-await is not working on HTML element

I have these HTML elements:

<p data-v-2fa66444="" data-v-5092a3fc="" data-cy="p-0" class="card-text">Cash</p>
...
...
...
<h1 data-v-76f2b6ec="" data-cy="h1-0" class="mb-3"><span data-v-76f2b6ec="" aria-hidden="true" data-cy="span-0" class="fa fa-check-circle text-60 text-success"></span></h1>

When I’m trying to target them using Playwright locators respectively like so:

await page.getByRole('p', { name: "Cash" }).click();
// more code in-between
await expect(page.getByRole('dialog').locator('h1 span')).toBeVisible();

It fails unless I add an arbitrary await which is discouraged.

This is my spec file code:

await page.getByRole('button', { name: 'Payment' }).click();
await page.waitForTimeout(4000); // if I dont have this wait, the test fails
await page.getByRole('p', { name: "Cash" }).click();
await page.getByRole('button', { name: 'Charge' }).click();
await page.waitForTimeout(4000); // if I dont have this wait, the test fails
await expect(page.getByRole('dialog').locator('h1 span')).toBeVisible();

How to push data from one HTML page to another

I wanna transfer some data (e.g. div with the book information in it, such as title, price, author etc.) from one html page to another html, which is my wishlist page. I don’t have much of experience with this, so does any of you guys have a solution what is the best way to do that?

I tried to use localStorage method but get unexpected behaviour.

Why does my class declaration throw an Uncaught ReferenceError in Chrome’s Console?

I am trying to learn how to work with class declarations and how to actually use them in my own code.

I have a class named Car that I have written in my project. I have given it various methods to call on later objects when I create them. But when I try to create a new object the console tells me that Car has not been defined. What am I doing wrong?

I thought that creating the Class would mean that any new object I create would then inherit those methods and properties.

The script is linked to my HTML page and I am working with the console in Chrome. When I load the page the script instantly throws the following error:

Uncaught ReferenceError: Car is not defined
at :1:20
(anonymous) @ VM2084:1

class Car {
    constructor() {
        this.make = make;
        this.model = model;
        this.year = year;
        this.color = color;          
    };
    
    admire() {
        return `I really love the looks of this ${make}.`;
    }
    
    clean() {
        return `The ${make} really needs a good cleaning. Let's give the ${model} a good wash.`
    }
    
    drive() {
        return `Take the ${model} out for a drive!`;
    }
    
    park() {
        return `Parked the ${make} in what seemed to be a good spot.`;
    }
    
    parkAtHome() {
    
        return `Pulled the ${model} into the garage.`;
    }

    crash() {
        return `Ended up crashing the ${make}.`;
    }
}

On React Component Using array.filter() and not recieving a return value, (if no matching elements it should be an empty array)

I am running the following function component with React.
I am destructuring a name parameter using useParams, and I want to use it to specify the array of dog objects being passed in and destructered as props.

Using console.log I can see that the dogs array is passing into the component with no trouble, and using array.map() can confirm it is an array. name is also destructured and being passed in via useParams and confirmed with console.log
The issue I am having is that array.filter(dogs.filter) is returning no response.
There is a matching object and property in dogs, which its contents I have included below.
So I cannot seem to see when I print out my copy variable that I have no data.
Any ideas, Im sure its something simple I just cannot seem to grasp it.

const Home = ({dogs}) => {
    //all dogs. 

    //lets destructure name from our useParams hook. 
    const {name} = useParams()
    console.log(name)
    dogs.map(m => console.log("mapping: " + m)) // it is an array
  
    let queryDog;
    if(name){
        console.log("name is truthy")
        let copy = dogs.filter(d => d.name === name)
        console.log("here is a copy: " + copy)
        queryDog = copy
    }else { queryDog = dogs
    }

  return (
    <div className="App">
      {queryDog.map(d => 
        
       <Dog name={d.name} age={d.age} src={d.src} facts={d.facts} key={uuidv4()}/>

      )}

    </div>
  )
}

Here are the dogs, an array of objects passed into the Home component.

App.defaultProps = {
  dogs: [
    {
      name: "Whiskey",
      age: 5,
      src: "whiskey.jpg",
      facts: [
        "Whiskey loves eating popcorn.",
        "Whiskey is a terrible guard dog.",
        "Whiskey wants to cuddle with you!"
      ]
    },
    {
      name: "Duke",
      age: 3,
      src: "duke.jpg",
      facts: [
        "Duke believes that ball is life.",
        "Duke likes snow.",
        "Duke enjoys pawing other dogs."
      ]
    },
    {
      name: "Perry",
      age: 4,
      src: "perry.jpg",
      facts: [
        "Perry loves all humans.",
        "Perry demolishes all snacks.",
        "Perry hates the rain."
      ]
    },
    {
      name: "Tubby",
      age: 4,
      src: "tubby.jpg",
      facts: [
        "Tubby is really stupid.",
        "Tubby does not like walks.",
        "Angelina used to hate Tubby, but claims not to anymore."
      ]
    }
  ]
}

tried to troubleshoot and understand the nature of the issue.

Extension has not been invoked for the current page (see activeTab permission). Chrome pages cannot be captured

Good day.

I’m facing a problem with implementing a Google extension. For technical reasons, I need to open the extension in a separate window (as the auto-disappearing pop-up breaks the logic). However, a nuance has arisen that it’s not possible to capture sound from a separate window, resulting in the following error:

“Error when capturing a tab. Extension has not been invoked for the current page (see activeTab permission). Chrome pages cannot be captured.”

I’ve scrolled through all the answers on similar topics but didn’t find or didnt understand a solution. Other extensions, such as Volume Recorder Online, are capable of the functionality I need, but their code is obfuscated, preventing me from understanding the differences and why it works for them but not for me.

I would appreciate any help.
I’m attaching the code below:

Manifest v3:

  {
    "update_url": "https://clients2.google.com/service/update2/crx",
    
        "name": "AnyTalk",
        "version": "1.0.1",
        "manifest_version": 3,
        "minimum_chrome_version": "114",
        "background": {
            "service_worker": "scripts/window.js"
        },
        "icons": {
            "16": "assets/icon-16.png",
            "32": "assets/icon-32.png",
            "48": "assets/icon-48.png",
            "128": "assets/icon-128.png"
        },
        "action": {
            "default_icon": "assets/icon-128.png",
            "default_title": "AnyTalk"
        },
        "permissions": [
            "tabCapture",
            "downloads",
            "storage",
            "activeTab",
            "system.display",
            "tabs"
        ],
        "host_permissions": [
            "<all_urls>"
        ]
    }

window.js (background)
Opens extension window and send current tabid in query

chrome.action.onClicked.addListener(function(tab) {
  var tabId = tab.id;
  chrome.windows.create({
      url: '../views/recorder.html?tabId=' + tabId,
      type: 'popup',
      width: 400,
      height: 500
  }); 
});

recorder.js

let recordingEnabled = false;
let socket = null;
let recorder = null;


function getQueryParam(param) {
    console.log('Executing getQueryParam function');
    var urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(param);
}
let tabId = parseInt(getQueryParam("tabId"));

document.addEventListener('DOMContentLoaded', function () {
    console.log('DOMContentLoaded event listener triggered');
    var statusCircle = document.getElementById('status-circle');
    
    statusCircle.addEventListener('click', async function() {
        console.log('statusCircle click event listener triggered');
        if (recordingEnabled) {
            console.log('Recording is enabled. Stopping recording...');
            recordingEnabled = false;
            statusCircle.style.backgroundColor = 'blue';
            stopRecording();
        } else {
            console.log('Recording is disabled. Starting recording...');
            recordingEnabled = true;
            statusCircle.style.backgroundColor = 'red';
            captureTab(tabId);
        }
    });
});
function captureTab(tabId) {
    console.log('Executing captureTab function');

    console.log(typeof(tabId))
    chrome.tabs.update(tabId, { active: true }, function(tab) {
        if (chrome.runtime.lastError) {
            console.error('Error when updating a tab', chrome.runtime.lastError.message);
            return;
        }
        console.log('Tab updated:', tab);

        var captureOptions = { audio: true, video: false };
        chrome.tabCapture.capture(captureOptions, function(stream) {
            console.log('Tab captured:', stream);
            if (chrome.runtime.lastError) {
                console.error('Error when capturing a tab ', chrome.runtime.lastError.message);
                return;
            }

log results are here

in openstreemap how to make a html code that when i move the mouse over the map it will display in real time the coordinates in a small tooltip?

I want that when i move the mouse over the map it will display like in a small tool tip balloon the coordinates in real time on the mouse cursor for example like: 35.56, 56.765

I tried this code in my wix site but it’s showing the map but the coordinate with the mouse is not working showing anything.

<html>
<head>
   <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
   <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
   <style>
      body, html, #map {
         height: 100%;
         margin: 0;
      }
   </style>
</head>
<body>
   <div id="map"></div>

   <script>
      var map = L.map('map').setView([32.921, 39.562], 10);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
         attribution: '© OpenStreetMap contributors'
      }).addTo(map);

      var marker = L.marker([32.921, 39.562]).addTo(map);
      marker.bindPopup("<b>Hello World!</b><br>This is a customizable popup.").openPopup();

      // Create a tooltip to show coordinates
      var tooltip = L.tooltip({
         permanent: true,
         direction: 'bottom',
         opacity: 0.7
      });

      // Add the tooltip to the map
      tooltip.addTo(map);

      // Event listener for mousemove
      map.on('mousemove', function (e) {
         var latlng = e.latlng;
         tooltip.setLatLng(latlng).setContent('Coordinates: ' + latlng.lat.toFixed(6) + ', ' + latlng.lng.toFixed(6));
      });
   </script>
</body>
</html>