how to position my dropdown just under the top bar

I am making a website about trains and I want to make a version for desktop and tablet. In the tablet version I want to hide the navigation bar and make it into a dropdown menu and I have done it but I cant put it right underneath the top bar. Even if i put the position absolute and the top value to be the height of the top bar its still doesnt work and when i resize it it always changes the position of the menu. Like if i fine tune it for one pixel size screen the moment i resize to test it just isnt placed in the right spot again.

function TrainDropdown() { 
  const trainMenu = document.getElementById("trains");
  trainMenu.classList.toggle("show");
  console.log("TrainDropdown toggled:", trainMenu.classList.contains("show"));
}

  function Menu() {
    const navBar = document.getElementById("phone-nav-bar");
    navBar.classList.toggle("show-nav-bar");
}
function MobileTrainDropdown() {
  const trainElements = document.getElementById("tablet-trains");
  if (trainElements.style.display === "none") {
      trainElements.style.display = "flex";
  } else {
      trainElements.style.display = "none";
  }
}

window.addEventListener("click", function (event) {
  console.log("Window click detected on:", event.target);

  // Close train dropdown if clicked outside the dropdown button
  if (!event.target.closest('.dropdown-button')) {
    const dropdowns = document.getElementsByClassName("train-elements");
    for (let i = 0; i < dropdowns.length; i++) {
      const openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
        console.log("Closed train dropdown:", openDropdown);
      }
    }
  }

  // Close mobile nav menu if clicked outside menu button and nav bar
  const navBar = document.getElementById("phone-nav-bar");
  const menuButton = document.querySelector('.menu-button');
  if (navBar && menuButton && !menuButton.contains(event.target) && !navBar.contains(event.target)) {
    navBar.classList.remove("show-nav-bar");
    console.log("Closed mobile nav menu.");
  }
});
body {
    margin: 0;
}

/*top-bar properties*/
.top-bar {
    display: flex;
    align-items: center;
    height: 10vh;
    background-color: #A7C4FF;
}

.branding {
    display: flex;
    align-items: center;
}

.branding img {
    height: 12vh; /* Set a fixed height for the logo */
    width: auto; /* Maintain aspect ratio */
}

/*menu toggle properties*/
.menu-button {
    display: none; /* Hidden on larger screens */
}

.mobile-phone-nav-bar {
    position: absolute; /* Position below the top bar */
    top: 10vh; /* Position below the top bar */
    left: 0; /* Align to the left */
    width: 100%; /* Full width */
    display: none; /* Hidden by default */
}

.mobile-phone-branding {
    display: none; /* Hidden on larger screens */
}
/*navigation bar properties*/
.nav-bar {
    display: flex;
    flex: 1;
    align-items: center;
    margin-left: 10vw;
}

/*buttons*/
.nav-button, .dropdown-button{
    width: 100%;
    height: 8vh;
    line-height: 8vh;
    margin-right: 5px;
    font-family: Unbounded;   
    font-size: 1vw; 
    text-align: center;
    text-decoration: none;
    background-color: #A7C4FF;
    border: none;
    border-radius: 40px;
    transition: background-color 0.4s ease-in-out;
}

.nav-button:hover, .dropdown-button:hover{
    background-color: #8FA9FF;
}

/*train-dropdown and all its children properties*/
.train-dropdown{
    position: relative;
    margin-right: 5px;
    width: 100%;
}

.train-elements{
    display: none;
    width: 100%;
    position: absolute;
    top: 10vh;
    background-color: #7f9dfd;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    border-radius: 0.8vw;
    z-index: 1;
}

.train-elements a{
    padding: 1em;
    color: black;
    text-decoration: none;
}

.train-elements a:hover{
    background-color: #567dff;
}

.train-elements #first-element:hover{
    border-top-left-radius: 0.8vw;
    border-top-right-radius: 0.8vw;
}

.train-elements #last-element:hover{
    border-bottom-left-radius: 0.8vw;
    border-bottom-right-radius: 0.8vw;
}

#mobile-phone-train-button{
    display: none;
}

/*Class that JS uses to show train-elements*/
.show{
    display: flex;
    flex-direction: column;
}

@media only screen and (max-width: 1300px){
    /*hiding nav-bar to save space and make it into a dropdown*/
    .nav-bar{
        display: none;
    }

    /*a menu button that makes the nav-bar appear*/
    .menu-toggle{
        position: relative;
    }

    .menu-button{
        display: flex;
        height: 8.5vh;
        width: 8.5vh;
        justify-content: center;
        align-items: center;
        margin: 10px;
        border-radius: 20px;
        border: none;
        background-color: #A7C4FF;
    }

    .menu-button img {
        width: 5vw; /* Set a fixed width */
        height: auto; /* Maintain aspect ratio */
        max-width: none; /* Prevent scaling */
    }

    .menu-button:hover{
        background-color: #8FA9FF;
    }

    /*button properties*/
    .nav-button, .dropdown-button{
        border-radius: 0;
        background-color: #94b7ff;
    }

    .mobile-phone-nav-bar{
        position: absolute;
        box-shadow: 8px 16px 16px 0px rgba(0,0,0,0.2);
        background-color: #A7C4FF;
        width: 300px;
        top: 10vh;
    }
    
    /*train dropdown properties*/
    .tablet-train-elements{
        display: none;
        width: 100%;
        flex-direction: column;
        position: absolute;
        background-color: #7f9dfd;
    }
    
    .tablet-train-elements a{
        padding: 12px 16px;
        color: black;
        text-decoration: none;
    }

    .tablet-train-elements a:hover{
        background-color: #567dff;
    }
    
    /*hides the button i will be using for phone mode that
    substitutes the dropdown button cause there is no space*/
    #mobile-phone-train-button{
        display: none;
    }

    /*a class JS uses to display the dropdown when pressing the button*/
    .show-nav-bar{
        display: flex;
        flex-direction: column;
    }
}
<!DOCTYPE html>
<html lang="bg">
<head>
    
    <!--meta data-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!--tab view-->
    <title>Железопътна страст</title>
    <link rel="icon" href="assets/images/favicon.png">

    <!--css files-->
    <link rel="stylesheet" href="assets/css/index.css">
    <link rel="stylesheet" href="topbar/topbar.css">

    <!--google fonts-->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Unbounded:[email protected]&display=swap" rel="stylesheet">

</head>
<script src="topbar/topbar.js" defer></script>
<body>    
    <!--the top bar-->
    <div class="top-bar">
        <div class="mobile-phone-branding">

            <a href="index.html"><img id="logo" src="assets/images/logo.png" alt="Лого на влак"></a>

        </div>
        <div class="menu-toggle">

            <button class="menu-button" onclick="Menu()"><img src="assets/images/menu.png"></button>
            
            <div class="mobile-phone-nav-bar" id="phone-nav-bar">

                <a class="nav-button" href="index.html">Начало</a>

                <a class="nav-button" id="mobile-phone-train-button" href="#trains">Влакове</a>
                
                <div class="tablet-train-dropdown">
                    
                    <button onclick="MobileTrainDropdown()" class="dropdown-button">Влакове</button>
                    
                    <div id="tablet-trains" class="tablet-train-elements">
                    
                        <a href="#">Link 1</a>
                        
                        <a href="#">Link 2</a>
    
                        <a href="#">Link 3</a>
                    
                    </div>

                </div> 
                
                <a class="nav-button" href="#contacts">Контакти</a>
                <a class="nav-button" href="#aboutme">Повече за мен</a>
            
            </div>

        </div>
        
        <div class="branding">

            <a href="index.html"><img id="logo" src="assets/images/logo.png" alt="Лого на влак"></a>

        </div>
        
        <div class="nav-bar">

            <a class="nav-button" href="index.html">Начало</a>
            
            <div class="train-dropdown">
                
                <button onclick="TrainDropdown()" class="dropdown-button">Влакове</button>
                
                <div id="trains" class="train-elements">
                
                    <a id="first-element" href="#">Link 1</a>
                    
                    <a href="#">Link 2</a>

                    <a id="last-element" href="#">Link 3</a>
                
                </div>

            </div> 
            
            <a class="nav-button" href="#contacts">Контакти</a>
            <a class="nav-button" href="#aboutme">Повече за мен</a>
        
        </div>

    </div>   

   
</body>
</html>

In React Functional component why bracket notation of object is not working [closed]

at titlename.name is working but titlename[name]is not working (https://i.sstatic.net/4aVjMhXL.png)orking properly

during my learning journey of react while experimenting on functional component the parameter of functional component is a object to access the object key on using dot notation it is working properly but in square bracket notation it is not working why..?
I am expecting reason for the question

(.0) float in Javascript

I am trying to do write a code for a function that displays a boolean after checking if the value is an integer or not. see my definition of an integer in my ideal outputs below when i call the function:

So far, my code is failing because it generates true for validInteger ( 10.0 ) when i want it to be false. Javascript is struggling because 10.0 = 10

DESIRED OUTPUT

validInteger ( '10' ) // should return True
validInteger ( 10 ) // should return True 
validInteger ( '-10' ) // should return False
validInteger ( -10 ) // should return False
validInteger ( 0.0 ) // should return False
validInteger ( 10.0 ) // should return False
validInteger ( -10.0 ) // should return False

I wonder if anyone has an idea on how i can get a false result for validInteger ( 10.0 ). so far this is the code i have been able to write:

function validInteger (value) { // value can be a string or a number (integer)
  
  const numberValue = Number(value);
  return Number.isInteger(numberValue) && numberValue >= 0 && String(numberValue) ===     String(value);

}

How to write deprecated legacy JS API code in modern way(custom gulp function)

In advance, thanks for helping

In ‘gulpfile.js’ I have a function:

//Javascript Task
  function jsTask() {
    return src('app/js/script.js')
    //, { sourcemaps: true }
      .pipe(babel({ presets: ['@babel/preset-env'] }))
      .pipe(terser())
      .pipe(dest('dist', { sourcemaps: '.' }));
  }

And it’s used this way:

  // Default Gulp Task
  exports.default = series(scssTask, jsTask, browserSyncServe, watchTask);
  
  // Build Gulp Task
  exports.build = series(scssTask, jsTask);

after I run ‘gulp’ in terminal in VScode I get this message:
**[15:41:06] Starting ‘jsTask’…
Deprecation Warning: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0.

More info: https://sass-lang.com/d/legacy-js-api

[15:41:06] Finished ‘jsTask’ after 265 ms**

The project loads in my browser(locallhost) but after saving, changes to the scss files won’t take place in the web page(although the ‘browsersync:connected’ pup up is shown).

It was working just fine till yesterday!!!!!

I checked the link(legacy JS API) out but I got nothing out of it.

Changing the text of a span element with no Id

I am very new to this so please bear with me.

I’m trying to change the inner HTML of this span:

<span translate="my_team_tab" class="ng-scope">My Team</span>

on page load.

I would like to change the “My Team” text to “My Event”. I’ve been looking for hours and nothing seems to be working. Maybe it’s not possible? Like I said, I’m new and would not know otherwise.

Thank you!

I haven’t been able to try anything because almost all solutions mention using an Id and there is no Id assigned to this element. This code is hardcoded into the system I’m working in so I can’t change the HTML itself.

Integrate existing application’s UI into new Application [closed]

we have 5 existing applications which provides different kinds of services. We are essentially aiming to build an integrated system as a unified interface, where users can access all the services in one place without needing to interact with five separate applications. By reusing parts of the existing UI, we can maintain consistency and potentially save on development time, while not altering the existing applications themselves.
We thought of using Micro frontend services , but we need to make some changes to expose (module federation plugin) in existing applications. we are not allowed to make any changes. is there any way to load some part of UI dynamically.

WebSocket desde Microservicios Nest [closed]

A few days ago I’ve been thinking about a problem, I put it in context.

I have an app in NestJs which has several Microservices, and in the gateway of all of them I have a WebSocket.

Well, if I try to send information from the gateway everything is perfect, but now that I try to send information from a microservice the only thing I get are errors, circular dependencies (when there are none) and other relevant errors.

Maybe I’m doing something wrong or maybe what I raise is unfeasible.

Thank you in advance.

It is to raise a problem, any idea is good.

Navbar item selection rectangle and dropdown menu positioned with incorrect code

In this navbar when I move the mouse over one of its entries, that little green rectangle should appear exactly in the position of the photo. Also, under the little green rectangle that horizontal drop-down menu should appear exactly in the position of my photo.

enter image description here

Apparently it seems to work well, but there are problems in the css code, so I did not get this result in the best way. Previously I always got the little green rectangle that did not touch the bottom edge of the navbar and also the drop-down menu was previously detached from the navbar and there was a thin white line of empty space between the navbar and the drop-down menu. Now I have apparently solved the problem, but the code is definitely not correct.

How can I get the same result as the photo, but improving the code?

I think the wrong code is in:

.navbar-nav .nav-link:hover::after {
content: '';
display: block;
width: 100%;
height: 4px;
background-color: #459439;
 position: absolute;
 top: 100%;
 left: 0;
 z-index: 1000 } /* Orange rectangle at the bottom edge of the navbar */ .navbar-nav .nav-link { color: #ffffff;
 margin-right: 15px;
 position: relative;
 line-height: 21px;

} @media (min-width: 768px) { .navbar-expand-md .navbar-nav .nav-link { padding-right: .5rem;
 padding-left: .5rem;
 padding-top: 31px;
 padding-bottom: 31px;
 } } .navbar { z-index: 1000;
} .dropdown-menu-horizontal { z-index: 9999;
}

index.html:

<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
</head>
<body>


<!-- Navbar con logo e link -->
<nav class="navbar navbar-expand-md navbar-dark mb-0">
    <div class="container">
        <a class="navbar-brand d-flex align-items-center" href="#">
            <img src="img/.png" alt="Logo" class="logo">
            <div class="brand-text">
                <span class="aaaaaaa">AAAAAAA</span>
                <span class="xxxx">XXXX</span>
            </div>
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item dropdown">
                    <a class="nav-link" href="#" id="fondazioneDropdown">COMPANY</a>
                    <div class="dropdown-menu dropdown-menu-horizontal" aria-labelledby="fondazioneDropdown">
                        <a class="dropdown-item-horizontal" href="#"><img src="..." alt="Logo 1"> Example 1</a>
                        <a class="dropdown-item-horizontal" href="#"><img src="..." alt="Logo 2"> Example 2</a>
                        <a class="dropdown-item-horizontal" href="#"><img src="..." alt="Logo 3"> Example 3</a>
                    </div>
                </li>
                <li class="nav-item"><a class="nav-link" href="#">Item 2</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Item 3</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Item 4</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Item 5</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Item 6</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Item 7</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Item 8</a></li>
            </ul>
        </div>
    </div>
</nav>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</body>
</html>

styles.css:

* {
    box-sizing: border-box;
}



/* Navbar */
.navbar {
    background-color: #000033;
    padding: 0px;
    position: relative;
    z-index: 1000;
    margin: 0;  /* Elimina eventuali margini */
    
}

/* Stile logo e testo del brand */
.logo {
    height: 80px;
    margin-right: 10px;
}

.brand-text {
    color: #ffffff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: left;
    line-height: 1;
}

.aaaaaaa {
    font-size: 0.80em;
    font-weight: normal;
    letter-spacing: 0.28em;
}

.xxxx {
    font-size: 2.4rem;
    font-weight: bold;
    letter-spacing: 0.05em;
}

/* Rettangolino arancione sul bordo inferiore della navbar */
.navbar-nav .nav-link {
    color: #ffffff;
    margin-right: 15px;
    position: relative;
    line-height: 21px; /* Aumenta leggermente l'altezza della riga per migliorare l'allineamento */


}



.navbar-nav .nav-link:hover::after {
    content: '';
    display: block;
    width: 100%;
    height: 4px; /* Riduci leggermente l'altezza del rettangolo */
    background-color: #459439;
    position: absolute;
    top: 100%; /* Posiziona il rettangolo esattamente sotto la voce di menu */
    left: 0;
    z-index: 1000
}

/* Rimozione della freccia dropdown */
.nav-link.dropdown-toggle::after {
    display: none;
}

.navbar-dark .navbar-nav .nav-link {
    color: white;
}

/* Dropdown orizzontale */
.dropdown-menu-horizontal {
    display: none;
    background-color: #000033;
    padding: 20px;
    min-width: 100%;
    border-radius: 0; /* Rimosso il bordo arrotondato */
    position: absolute;
    left: 0;
    top: 100%; /* Cambia il valore top per allinearlo perfettamente sotto la navbar */
    z-index: 9999; /* Assicura che venga mostrato sopra tutto il resto */


}



.dropdown-item-horizontal {
    color: #ffffff;
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    margin-right: 30px; /* Distanza tra gli elementi */
    white-space: nowrap;
}

.dropdown-item-horizontal img {
    width: 50px; /* Dimensioni delle icone */
    height: 50px;
    margin-right: 15px;
}

.dropdown-item-horizontal:hover {
    color: #d4d4ff;
    text-decoration: none;
}

/* Mostra il menu a tendina al passaggio del mouse */
.nav-item:hover .dropdown-menu-horizontal {
    display: flex;
    justify-content: space-around;
}


@media (min-width: 768px) {
    .navbar-expand-md .navbar-nav .nav-link {
        padding-right: .5rem;
        padding-left: .5rem;
        padding-top: 31px;
        padding-bottom: 31px;
    }
}

script.js:

document.addEventListener("DOMContentLoaded", function () {
    const dropdowns = document.querySelectorAll(".nav-item.dropdown");

    dropdowns.forEach(dropdown => {
        dropdown.addEventListener("mouseenter", function () {
            const menu = this.querySelector(".dropdown-menu-horizontal");
            if (menu) menu.style.display = "flex";
        });

        dropdown.addEventListener("mouseleave", function () {
            const menu = this.querySelector(".dropdown-menu-horizontal");
            if (menu) menu.style.display = "none";
        });
    });
});

find() method not finding the correct item

I’m doing a uni project on an online course website like Udemy using VueJs. When I remove a course from the checkout page, the course.spaces are not being updated on the main page. I’m encountering an error where my find() and findIndex() functions are returning undefined when I console.log the variables they’re stored in. Any help would be appreciated!

main.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="styles/reset.css">
    <link rel="stylesheet" href="styles/header.css">
    <link rel="stylesheet" href="styles/afk_academy.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

    <title></title>
</head>
<body>
    <!-- Header -->
    <div id="app">
        <header id="header">
            <div id="logo-container" v-on:click="goToHome">
                <img id="logo" src="images/afk-academy-high-resolution-logo-transparent.png">
            </div>
            <div id="searchbar-container">
                <input id="search-bar" type="text" placeholder="Search...">
                <i class="search-icon fa-solid fa-magnifying-glass"></i>
            </div>
            <div id="cart-icon-container">
                <a 
                    v-if="cartItemCount > 0"
                    id="cart-link" 
                    v-on:click="toggle_page"
                >
                    <p id="cart-count"> {{ calculateCartQuantity }}</p>
                    <i class="cart-icon fa-solid fa-cart-shopping"></i>
                </a>

                <a v-else id="cart-link-disabled" href="javascript:void(0);">
                    <i class="cart-icon fa-solid fa-cart-shopping"></i>
                </a>
            </div>
        </header>
    
        <main id="main-container">

            <!-- Main Page -->

            <div v-if="!checkoutPage" id="index">
                <h1 id="courses-title">Online courses:</h1>
        
                <section id="courses-section">
                    <div id="course-container" v-for="(course, index) in coursesCopy" :key="course.id">
                        <div id="course-thumbnail-container">
                            <img id="course-thumbnail" v-bind:src="course.thumbnail" alt="Algorithms course image"></img>
                        </div>
                        <div id="course-description">
                            <p id="course-subject" v-text="course.subject"></p>
                            <p id="course-location" v-text="course.location"></p>
                            <p id="course-price" v-text="course.price"></p>
                            <p id="available-spaces" v-text="course.spaces"></p>
                            <button 
                                id="add-button"
                                v-on:click="addToCart(course.id)"
                                :disabled="!canAddToCart(course)"
                            >
                                +
                            </button>
                        </div>
                    </div>
                </section>
            </div>

            <!-- Checkout Page -->

            <div v-else id="checkout">
                <section id="courses-added">
                    <div v-for="(course, index) in cart" :key="course.id" class="course-container">
                        <figure>
                            <img v-bind:src="course.thumbnail" class="course-thumbnail">
                        </figure>
    
                        <div class="course-description">
                            <p class="course-subject" v-text="course.subject"></p>
                            <p class="course-price" v-text="course.price"></p>
                            <p class="course-quantity" v-text="course.quantity"></p>
                        </div>
    
                        <button v-on:click="removeFromCart(course.id)">Remove</button>
                    </div>
                </section>
            </div>
        </main>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script src="scripts/courses.js"></script>
    <script src="scripts/afk_academy.js" type="text/javascript"></script>
</body>
</html>

checkout.js:

let webstore = new Vue({
    el: "#app",
    data: {
        checkoutPage: false,
        cart: JSON.parse(localStorage.getItem('cart')) || [],
        courses: courses,
        coursesCopy: JSON.parse(localStorage.getItem('coursesCopy')) || [...courses],
    },
    methods: {
        addToCart: function(courseId) {
            let course = this.findCourse(courseId, this.coursesCopy);

            if (course && course.spaces > 0) {
                let matchingItem = this.findCourse(courseId, this.cart);

                if (matchingItem) {
                    matchingItem.quantity++;
                } else {
                    this.cart.push({course, quantity: 1 });
                }

                course.spaces--;
                console.log(this.coursesCopy);
                this.saveToStorage();
            }
        },
        removeFromCart(courseId) {
            const index = this.findCourseId(courseId, this.cart);

            if (index !== -1) {
                const quantity = this.cart[index].quantity;
                const originalCourse = this.findCourse(courseId, this.coursesCopy);

                this.cart.splice(index, 1);

                if (originalCourse) {
                    originalCourse.spaces += quantity;
                }
            }
            console.log(index);
            console.log(this.coursesCopy);
            this.saveToStorage();
        },
        findCourse(courseId, array) {
            const course = array.find(item => item.id === courseId);

            return course;
        },
        findCourseId(courseId, array) {
            const index = array.findIndex(item => item.id === courseId);
            
            return index;
        },
        saveToStorage() {
            try {
                localStorage.setItem('cart', JSON.stringify(this.cart));
                localStorage.setItem('coursesCopy', JSON.stringify(this.coursesCopy));
            } catch (error) {
                console.error("Error saving to localStorage:", error);
            }
        },
        goToCheckout: function() {
            this.checkoutPage = true;
        },
        goToHome: function() {
            this.checkoutPage = false;
        },
        toggle_page: function() {
            if (!this.checkoutPage) {
                this.goToCheckout();
                return;
            }
            if (this.checkoutPage) {
                this.goToHome();
                return;
            }
        }
    },
    computed: {
        cartItemCount: function() {
            return this.cart.length;
        },
        calculateCartQuantity: function() {
            let cartQuantity = 0;
    
            this.cart.forEach((cartItem) => {
                cartQuantity += cartItem.quantity;
            });
    
            return cartQuantity;
        },
        canAddToCart: function() {
            return (course) => course.spaces > 0;
        },
        checkCart: function() {
            return !(this.cartItemCount > 0);
        }
    }
});

courses.js:

const courses = [
    {
        id: 1,
        subject: "Algorithms",
        location: "London",
        price: 20,
        spaces: 5,
        thumbnail: "images/algorithms.png"
    },
    {
        id: 2,
        subject: "Maths",
        location: "Toronto",
        price: 25,
        spaces: 5,
        thumbnail: "images/algorithms.png"
    },
    {
        id: 3,
        subject: "Python",
        location: "Riyadh",
        price: 200,
        spaces: 5,
        thumbnail: "images/algorithms.png"
    },
    {
        id: 4,
        subject: "Java",
        location: "Dubai",
        price: 20,
        spaces: 5,
        thumbnail: "images/algorithms.png"
    },
    {
        id: 5,
        subject: "Chemistry",
        location: "Dublin",
        price: 350,
        spaces: 5,
        thumbnail: "images/algorithms.png"
    },
    {
        id: 6,
        subject: "Physics",
        location: "Tokyo",
        price: 230,
        spaces: 5,
        thumbnail: "images/algorithms.png"
    },
];

How to prevent the client from using Chrome Extension the Interceptor websocket of my web page

I have a website websocket. Someone used Chrome Extension to steal my websocket data. The data itself does not have sensitive information,The backend is also verified so there is no threat

I know that I can monitor any changes in the DOM or enable devtool, but Chrome Extension can still steal my websocket content.

Is there any way to stop it?

Chrome Extension code like this

chrome.debugger.attach({ tabId: tabId }, "1.2", function () {
        chrome.debugger.sendCommand({ tabId: tabId }, "Network.enable");
        chrome.debugger.onEvent.addListener(onTabDebuggerEvent);
    }); 
function onTabDebuggerEvent(debuggeeId, message, params) {
    var debugeeTabId = debuggeeId.tabId;

    chrome.tabs.get(debugeeTabId, function (targetTab) {
        var tabUrl = targetTab.url;

        if (message == "Network.webSocketFrameSent") {

        }
        else if (message == "Network.webSocketFrameReceived") {
            var payloadData = params.response.payloadData;

            var request = {
                source: tabUrl,
                payload: params.response.payloadData
            };

            websocket.send(JSON.stringify(request));
        }
    });
}  

Why is Javascript fetch and return not defined? [closed]

I have a problem with my Javascript code. It causes an error when using it.

async function request() { 
let res = await fetch('https://jsonplaceholder.typicode.com/posts/1')   .then(data => data.json());
return data;
} 

The return function is causing a “not defined” error.

main.js:4 data is not defined

I am trying to get a response from an API to use in my project but I am unable to get the response.

I expected the function to return the data so I can process the data in my project.

Creating graphs in slope intercept form

I want to create a worksheet generator that can export to pdf. I want the graphs to be created in slope intercept form with at least two visible coordinates on the graph that align with x and y axis values that are labeled and a y-intercept that goes through a visibly labeled whole number. The intervals should change for each graph. currently there are 20 gridlines on each axis, i want to be able to create smaller graphs with 10 as well. The user should be able to select 10 or 20. I attached an example image.

enter image description here

import React, { useState } from "react";
import { VictoryChart, VictoryLine, VictoryAxis } from "victory";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";

function WorksheetGenerator() {
  const [numQuestions, setNumQuestions] = useState(5);
  const [displayMode, setDisplayMode] = useState("both");
  const [worksheetOutput, setWorksheetOutput] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);

  const generateWorksheet = () => {
    const output = [];

    for (let i = 0; i < numQuestions; i++) {
      const slope = randomSlope(); // Allows negative slope
      const intervalX = randomInterval(); // Interval for x-axis
      const intervalY = randomInterval(); // Interval for y-axis
      const intercept = randomVisibleIntercept(intervalY);

      if (
        displayMode === "tables" ||
        displayMode === "both" ||
        displayMode === "matching"
      ) {
        const table = generateTable(slope, intercept, intervalX);
        output.push(
          <div key={`table-${i}`} id={`table-${i}`}>
            {table}
            <label>
              <input
                type="checkbox"
                onChange={(e) => handleCheckboxChange(e, `table-${i}`)}
              />{" "}
              Include this table in worksheet
            </label>
          </div>
        );
      }

      if (
        displayMode === "graphs" ||
        displayMode === "both" ||
        displayMode === "matching"
      ) {
        const graph = generateGraph(slope, intercept, intervalX, intervalY);
        output.push(
          <div key={`graph-${i}`} id={`graph-${i}`}>
            {graph}
            <label>
              <input
                type="checkbox"
                onChange={(e) => handleCheckboxChange(e, `graph-${i}`)}
              />{" "}
              Include this graph in worksheet
            </label>
          </div>
        );
      }
    }

    setWorksheetOutput(output);
  };

  const handleCheckboxChange = (event, id) => {
    if (event.target.checked) {
      setSelectedItems((prevItems) => [...prevItems, id]);
    } else {
      setSelectedItems((prevItems) => prevItems.filter((item) => item !== id));
    }
  };

  // Updated function to allow for negative slopes
  const randomSlope = () => {
    return Math.random() > 0.5
      ? Math.floor(Math.random() * 5) + 1 // positive slope
      : -1 * (Math.floor(Math.random() * 5) + 1); // negative slope
  };

  // Function to select an intercept that aligns with the tick marks on the y-axis
  const randomVisibleIntercept = (intervalY) => {
    const visibleIntercepts = [];
    const range = 10 * intervalY;
    for (let i = -range; i <= range; i += intervalY) {
      visibleIntercepts.push(i);
    }

    const randomIndex = Math.floor(Math.random() * visibleIntercepts.length);
    return visibleIntercepts[randomIndex]; // Return a visible intercept
  };

  const randomInterval = () => {
    const intervals = [1, 2, 3, 4, 5, 10];
    return intervals[Math.floor(Math.random() * intervals.length)];
  };

  const generateTable = (slope, intercept, intervalX) => {
    const rows = [];
    const usedXValues = new Set();

    while (usedXValues.size < 5) {
      const x = Math.floor(Math.random() * 10) - 5;
      if (!usedXValues.has(x) && x !== 0) {
        usedXValues.add(x);
      }
    }

    [...usedXValues].forEach((x) => {
      const y =
        typeof slope === "string"
          ? eval(slope) * x + intercept
          : slope * x + intercept;
      rows.push(
        <tr key={x}>
          <td style={{ border: "1px solid black", padding: "5px" }}>{x}</td>
          <td style={{ border: "1px solid black", padding: "5px" }}>{y}</td>
        </tr>
      );
    });

    return (
      <table style={{ width: "100%", borderCollapse: "collapse" }}>
        <thead>
          <tr>
            <th style={{ border: "1px solid black", padding: "5px" }}>x</th>
            <th style={{ border: "1px solid black", padding: "5px" }}>y</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  };

  const generateGraph = (slope, intercept, intervalX, intervalY) => {
    const xValues = [];
    const yValues = [];

    for (let x = -100; x <= 100; x += intervalX) {
      xValues.push(x);
      yValues.push(
        typeof slope === "string"
          ? eval(slope) * x + intercept
          : slope * x + intercept
      );
    }

    // Calculate additional points based on the slope and intercept
    const additionalPoints = [];
    for (let i = 1; i <= 2; i++) {
      const newX = i * intervalX;
      const newY = slope * newX + intercept;
      if (Math.abs(newY) <= 10 * intervalY) {
        // Ensure it falls within the domain
        additionalPoints.push({ x: newX, y: newY });
      }
    }

    const data = xValues
      .map((x, index) => ({
        x: x,
        y: yValues[index],
      }))
      .concat(additionalPoints);

    const xDomain = { x: [-10 * intervalX, 10 * intervalX] };
    const yDomain = { y: [-10 * intervalY, 10 * intervalY] };

    const xTicks = getTicks(xDomain.x, 20, intervalX);
    const yTicks = getTicks(yDomain.y, 20, intervalY);

    return (
      <VictoryChart
        domain={{ x: xDomain.x, y: yDomain.y }}
        height={300}
        width={300}
      >
        <VictoryLine
          data={data}
          style={{
            data: { stroke: "black", strokeWidth: 1.25 },
          }}
        />
        <VictoryAxis
          tickValues={xTicks}
          style={{
            tickLabels: { fontSize: 5, padding: 5 },
            grid: { stroke: "lightgray" },
            axis: { stroke: "black", strokeWidth: 1 },
          }}
        />
        <VictoryAxis
          dependentAxis
          tickValues={yTicks}
          style={{
            tickLabels: { fontSize: 5, padding: 5 },
            grid: { stroke: "lightgray" },
            axis: { stroke: "black", strokeWidth: 1 },
          }}
        />
      </VictoryChart>
    );
  };

  const getTicks = (domain, numTicks, interval) => {
    const ticks = [];
    for (let i = -10; i <= 10; i++) {
      ticks.push(i * interval);
    }
    return ticks;
  };

  const generatePDF = async () => {
    const doc = new jsPDF();
    let yOffset = 10;
    let xOffset = 10;
    const columnWidth = 90;
    const rowHeight = 100;
    const itemsPerRow = 2;

    for (const [index, elementId] of selectedItems.entries()) {
      const element = document.getElementById(elementId);
      if (element) {
        const canvas = await html2canvas(element, { useCORS: true });
        const imgData = canvas.toDataURL("image/png");

        doc.addImage(imgData, "PNG", xOffset, yOffset, columnWidth, rowHeight);

        if ((index + 1) % itemsPerRow === 0) {
          yOffset += rowHeight;
          xOffset = 10;
        } else {
          xOffset += columnWidth + 10;
        }
      }
    }

    doc.save("worksheet.pdf");
  };

  return (
    <div>
      <form>
        <label>
          Number of questions:
          <input
            type="number"
            min="1"
            value={numQuestions}
            onChange={(e) => setNumQuestions(parseInt(e.target.value))}
          />
        </label>
        <br />

        <label>
          Display:
          <select
            value={displayMode}
            onChange={(e) => setDisplayMode(e.target.value)}
          >
            <option value="both">Both Tables and Graphs</option>
            <option value="tables">Tables Only</option>
            <option value="graphs">Graphs Only</option>
            <option value="matching">Matching Tables and Graphs</option>
          </select>
        </label>
        <br />
        <button type="button" onClick={generateWorksheet}>
          Generate Worksheet
        </button>
        <button type="button" onClick={generatePDF}>
          Download PDF
        </button>
      </form>
      <div>{worksheetOutput}</div>
    </div>
  );
}

export default WorksheetGenerator;```    
   

server Side Rendering in react Project

I want server side render in my react project show that google bot can read the content of react project and my site can easily rank

I want code and method how can I do that Server Side Rendering please help me regarding this project
I tried Hydrate Root which is not working in my project