What should be the result and why?

I’m confused as why one, two and three are printed even after encountering an error.

Here’s the code:

setTimeout(() => {
  console.log("one");
}, 1000);
setTimeout(() => {
  console.log("two");
}, 2000);
setTimeout(() => {
  console.log("three");
}, 3000);

console.log(neha);

I was expecting just an error without printing set timeout values as per my knowledge js engine runs console.log first and then set timeout after their particular timeframe. Correct me if I am wrong and I am new to Stackoverflow too. It’s my first question.

here is the output of my code

Laravel Password reset link not generated in forget_password_submit method

I’m encountering an issue with generating a password reset link in my Laravel application within the forget_password_submit method. Despite attempting to construct the link using Laravel’s URL::to() helper function, the link doesn’t seem to be generated correctly. here i used mailtrap for testing mail.

Here’s my forget_password_submit method:

public function forget_password_submit(Request $request)
{
    $request->validate([
        'email' => 'required|email'
    ]);

    $admin_data = Admin::where('email', $request->email)->first();
    if (!$admin_data) {
        return redirect()->back()->with('error', 'Email address not found!');
    }

    $token = hash('sha256', time());

    $admin_data->token = $token;
    $admin_data->update();

    $reset_link = URL::to('admin/reset-password/' . $token . '/' . $request->email);
    $subject = 'Reset Password';
    $message = 'Please click on the following link: <br>';
    $message .= '<a href="' . $reset_link . '">Click here</a>';

    Mail::to($request->email)->send(new Websitemail($subject, $message));

    return redirect()->route('admin_login')->with('success', 'Please check your email and follow the steps there');
}

Despite constructing the link using URL::to(), the link is not being generated as expected. I’ve ensured that the APP_URL variable in the .env file is correctly set, and my routes are properly defined.

GrapesJS builds on macOS but not on Windows 10+

I am hitting a wall on this one. I am building GrapesJS, a web page editor (https://github.com/GrapesJS/grapesjs). It builds fine on macOS but not on Windows 10+. Same version of node, latest release of VS Code, same updates and dependancies.

WARNING in ./src/common/index.ts 35:2-16
export 'default' (imported as 'Backbone') was not found in 'backbone' (module has no exports)
 @ ./src/editor/view/EditorView.ts 16:0-39 45:21-22 68:2-6
 @ ./src/editor/index.ts 60:0-43 866:30-40
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/common/index.ts 43:2-21
export 'default' (imported as 'Backbone') was not found in 'backbone' (module has no exports)
 @ ./src/editor/view/EditorView.ts 16:0-39 45:21-22 68:2-6
 @ ./src/editor/index.ts 60:0-43 866:30-40
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/common/index.ts 51:2-15
export 'default' (imported as 'Backbone') was not found in 'backbone' (module has no exports)
 @ ./src/editor/view/EditorView.ts 16:0-39 45:21-22 68:2-6
 @ ./src/editor/index.ts 60:0-43 866:30-40
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/dom_components/model/Component.ts 1597:18-45
export 'Model' (imported as 'Model') was not found in 'backbone' (module has no exports)
 @ ./src/dom_components/index.ts 97:0-74 262:23-32 267:26-35 588:30-39 588:41-56
 @ ./src/editor/model/Editor.ts 91:0-52 138:4-20
 @ ./src/editor/index.ts 59:0-41 79:22-33
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/dom_components/model/Component.ts 1625:25-53
export 'Model' (imported as 'Model') was not found in 'backbone' (module has no exports)
 @ ./src/dom_components/index.ts 97:0-74 262:23-32 267:26-35 588:30-39 588:41-56
 @ ./src/editor/model/Editor.ts 91:0-52 138:4-20
 @ ./src/editor/index.ts 59:0-41 79:22-33
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/editor/model/Editor.ts 113:0-10
export 'default' (imported as 'Backbone') was not found in 'backbone' (module has no exports)
 @ ./src/editor/index.ts 59:0-41 79:22-33
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/undo_manager/index.ts 76:23-34
export 'default' (imported as 'UndoManager') was not found in 'backbone-undo' (module has no exports)
 @ ./src/editor/model/Editor.ts 108:0-51 118:4-21
 @ ./src/editor/index.ts 59:0-41 79:22-33
 @ ./src/index.ts 13:0-30 61:25-31

All of the config files are the same between the instances. I can browse to the backbone node_module. I have tried various path configs. I have tried both imports * as Backbone from 'backbone' and imports { backbone } from 'backbone' to no avail. Along with various modifications to the webpack.config.js and tsconfig.json. All the usual stuff. Two days of head banging and no love yet.

How to Prevent User from Restarting a Game Until the Day Ends After Completion or Game Over in JavaScript?

I’m working on a game application where users need to complete certain tasks within a day. Once the game is completed or if it’s game over, I want to prevent the user from restarting the game until the day ends, even if they refresh the page. However, currently, even after completion or game over, users can refresh the page and start the game again.

  • I’m using local storage to store game state data and check if the game is completed or if it’s game over.
  • I have implemented logic to update the game state in local storage when the game is completed or if it’s game over.
  • When the user refreshes the page, the game allows them to play again, regardless of whether the game was completed or game over.
Implemented code
useEffect(() => {
    checkLocalStorage(store, setStore, data, setData, setGameOver, setGameCompleted);
  },[])
import { PLAYERS } from "../assets/players"; 

export async function checkLocalStorage(store, setStore, data, setData, setGameCompleted, setGameOver) {
    const fullDate = new Date();
    const date = fullDate.getDate();
    const lastPlayed = localStorage.getItem('lastPlayed');
    
    if(lastPlayed == date){
        console.log('Welcome back');
        const temp = JSON.parse(localStorage.getItem('stat'));
        if(temp) setData(temp);
        
        const gc = localStorage.getItem('gameCompleted');
        if(gc === 'true') setGameCompleted(true);

        const go = localStorage.getItem('gameOver'); 
        if(go === 'true') setGameOver(true);
    } else {
        localStorage.removeItem('store')
        localStorage.removeItem('gameCompleted');
        localStorage.removeItem('gameOver');
        localStorage.setItem('lastPlayed', date);
    }
    
    const newData = localStorage.getItem('store');
    if(!newData) return;
    const newStore = JSON.parse(newData);
    setStore(newStore);
}

export async function updateLife(store, setStore) {
    if(store.lives <= 0) return console.log('Game Over');
    const newStore = {...store};
    newStore.lives -= 1;
    await setStore(newStore);
    localStorage.setItem('store', JSON.stringify(newStore));
}


export function updateStorePlayer(i, check, key, store, setStore) {
    const newStore = {...store};
    newStore.players[i][key] = check[key];
    setStore(newStore);
    localStorage.setItem('store', JSON.stringify(store));
}

export async function checkStat(store, data, setData, setGameOver, setGameCompleted) {
    const newData = JSON.parse(localStorage.getItem('stat'));
    if(!newData) return;
    const newStat = {...newData};
    if(store.lives <= 0) {
        newStat.totalGames += 1;
        setGameOver(true);
        localStorage.setItem('gameOver', 'true');
        return;
    }
    if(store.players.every((player) => player.playerName !== '')) {
        newStat.totalWins += 1;
        newStat.totalGames += 1;
        setGameCompleted(true);
        localStorage.setItem('gameCompleted', 'true');
        return;
    }
    setData(newStat);
    localStorage.setItem('stat', JSON.stringify(newStat));
}

export function compare(val, hero, store, setStore, data, setData ,gameCompleted, gameOver, setGameOver, setGameCompleted) {
    const check = PLAYERS.find((player) => player.playerName.toLowerCase() === val.playerName.toLowerCase());
    if(!check) return;
    checkStat(store, data, setData, setGameOver, setGameCompleted);
    let flag = false;
    for(let i=0; i<4; i++){
        if(hero[i].team.toLowerCase() === check.team.toLowerCase()) {
            updateStorePlayer(i, check, 'team', store, setStore);
        }
        if(hero[i].age === check.age) {
            updateStorePlayer(i, check, 'age', store, setStore);
        }
        if(hero[i].nation.toLowerCase() === check.nation.toLowerCase()) {
            updateStorePlayer(i, check, 'nation', store, setStore);
        }
        if(hero[i].playerName.toLowerCase() === check.playerName.toLowerCase()) {
            flag = true;
            updateStorePlayer(i, check, 'playerName', store, setStore);
        }
    }

    if(flag) {
        // incrementLife(store, setStore);
        flag = false;
    } else {
        updateLife(store, setStore);
    }

    localStorage.setItem('store', JSON.stringify(store));
}

Mac Vue Error: command failed: npm install –loglevel error –legacy-peer-deps

I’m on Mac.
Everytime I vue create project, it shows error:
‘Error: command failed: npm install –loglevel error –legacy-peer-deps’
enter image description here
Error: command failed: npm install –loglevel error –legacy-peer-deps
at ChildProcess. (/usr/local/lib/node_modules/@vue/cli/lib/util/executeCommand.js:138:16)
at ChildProcess.emit (node:events:519:28)
at maybeClose (node:internal/child_process:1105:16)
at ChildProcess._handle.onexit (node:internal/child_process:305:5)
Is it about mac access? How to do with it? Thanks a lot!

Vue3 how to minimize, maximize and close modal or component to bottom of page (like windows)

Let say in vue page has child component or a modal where user can minimize to bottom, maximize and close but keep state of those components until user close. (behave like windows)

I try to find a solution on how i can implement this logic but i didn’t get a solution after googling for a while.
please if you have any working example i will appreciate thank you.

see this image example
enter image description here

Strange problem with select option and inputs

`I got this strange problem with my scripts when i’m filling out select option and if i’m trying too push the button it sends me towards half validation process.

There nothing are really happening. I have tried too add email type for the email input so it’s kinda require the users too put a @ into the input that’s also failing, and i have also require on all of the inputs for input that’s also failing.

Why is this so buggy?

Could you try too help me?`

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/index.css">
  <title>Vasketjenester/renhold i Oslo</title>
  <meta name="description" content="Profesjonelle vasketjenester i Oslo. Vi tilbyr effektive rengjøringstjenester for hjem, husvask og bedrifter. Vi tilbyr vindusvask, vaske klær, garasjen, skap, kjøleskap, kjøkkenbenk.">
  <meta name="keywords" content="Renhold, vasketjenester, husvask, bedrift etc">
  <meta name="author" content="Lasse Skaansar">
  <script type="application/ld+json">
    {
      "@context": "http://schema.org",
      "@type": "LocalBusiness",
      "name": "Ditt Bedriftsnavn",
      "address": {
        "@type": "PostalAddress",
        "streetAddress": "Din Gateadresse",
        "addressLocality": "Oslo",
        "postalCode": "0010",
        "addressRegion": "Oslo",
        "addressCountry": "Norge"
      },
      "telephone": "46500809",
      "openingHours": "24"
    }
  </script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
    var containerContentHeight = document.querySelector('#container-content').clientHeight;
    document.querySelector('.right-box').style.height = containerContentHeight + 'px';
});
</script>
</head>
<body>


  <div class="top-menu">
    <a href="#" class="menu-item">Hjem</a>
    <a href="#" class="menu-item">Om oss</a>
    <a href="#" class="menu-item">FAQ</a>
    <a href="/index.php" class="menu-item">Vasketjenester</a>
  </div>

  <div id="default_everything">
    <div class="container" style="width: 1000px">

<div class="right-box" style="width: 250px; margin-top: 15px">
        <h1 style="margin-top: 22px; border-bottom: solid 1px #DEDEDE">Total kostnader:</h1>
        <div id="totalAmount">
          <div style="width: 100%; text-align: center">1300</div>
        </div>

        <div id="bookingSummary" style="margin-top: 20px;">
            <h2>Booking Summary:</h2>
                <ul id="selectedServices">
                </ul>
        </div>
</div>
      <div id="container-content" style="margin-top: 5px;">
        <div style="float: left; width: 100%; margin-top: 10px">
          <div class="pages_active" style="margin-left: 65px; margin-bottom: 5px; margin-right: 0px" onclick="location.href='/index.php';">Husvask</div>
          <div class="pages" style="margin-bottom: 5px; margin-left: 5px; margin-right: 5px" onclick="location.href='/bedrift.php';">Bedriftsvask</div>
          <div class="pages" style="margin-bottom: 5px" onclick="location.href='/bilvask.php';">Bilvask</div>
          <div class="pages" style="margin-bottom: 5px; margin-left: 5px" onclick="location.href='/wc.php';">WC - puplic</div>
        </div>

<div style="min-height: 900px">
<p style="text-align: center; font-size: 23px">Vi tar kun bestillinger i <b>Oslo</b><br>Vi tar kun <b>Vipps</b> (vipps godtar visa etc)</p>

<?php
session_start();
include_once 'connection.php'; // Include your database connection file

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Retrieve and trim form data
    $userFullName = trim($_POST["fullName"]);
    $userAddress = trim($_POST["address"]);
    $userhouseLetter = trim($_POST["houseLetter"]);
    $userEmail = trim($_POST["email"]);
    $userPhoneNumber = trim($_POST["phoneNumber"]);
    $userZipCode = trim($_POST["zipCode"]);
    $selectedDate = trim($_POST["selectedDate"]);

    $error = ""; // Initialize error message variable

    // Check if the entered ZIP code matches the allowed ZIP codes
    if (!in_array($userZipCode, $allowed_Zip_Codes)) {
        // ZIP code is not allowed, set error message
        $error = "Beklager, men vi tilbyr tjenester kun i Oslo. Vennligst oppgi en gyldig Oslo postnummer.";
    } else {
        // Prepare an SQL statement to insert data into the table
        $sql = "INSERT INTO table_order (fullName, address, email, phoneNumber, zipCode, selectedDate) 
                VALUES (?, ?, ?, ?, ?, ?, ?)";

        // Prepare the statement
        $stmt = mysqli_prepare($connection, $sql);

        // Check if the statement preparation was successful
        if ($stmt) {
            // Bind parameters
            mysqli_stmt_bind_param($stmt, "sssssss", $userFullName, $userAddress, $userEmail, $userPhoneNumber, $userZipCode, $selectedDate);

            // Execute the statement
            if (mysqli_stmt_execute($stmt)) {
                echo '<p>Bestilling av våre tjenester er mottatt. Bedriften er blitt varslet.<br />Takk for at du benytter deg av våre tjenester!</p>';
                echo '<dl>';
                echo '<dt>Fullt navn:</dt><dd>' . $userFullName . '</dd>';
                echo '<dt>Adresse:</dt><dd>' . $userAddress . '</dd>';
                echo '<dt>Email:</dt><dd>' . $userEmail . '</dd>';
                echo '<dt>Mobilnummer:</dt><dd>' . $userPhoneNumber . '</dd>';
                echo '<dt>Postkode:</dt><dd>' . $userZipCode . '</dd>';
                echo '<dt>Valgt dato:</dt><dd>' . $selectedDate . '</dd>';
                echo '</dl>';
            } else {
                echo "Error: " . mysqli_error($connection);
            }

            // Close the statement
            mysqli_stmt_close($stmt);
        } else {
            echo "Error: " . mysqli_error($connection);
        }
    }
}
?>

<?php
// Check if the success parameter is present in the URL
if (isset($_GET['success']) && $_GET['success'] == 'true') {
    // Display the success message
    echo "<div class='info_box' style='cursor: pointer' onclick='info_box()'>Din bestilling har blitt mottatt. Takk for at du valgte oss!</div>";
}
?>

        <?php if (!empty($error)): ?>
            <p class="error-message"><?php echo $error; ?></p>
        <?php endif; ?>

<div id="zipCodeError" style="color: red;"></div>

        <div style="float: left; width: 100%">
          <hr>
        </div>

    <form id="orderForm" action="process.php" method="POST">
        <div style="float: left; margin-left: 15px">
          Hva slags type vask?
        </div>
        <div style="float: left; width: 100%; margin: 15px">
            <select name="type" style="float: left; width: 570px; height: 30px" onchange="updateAmountFromDropdown()">
                <option data-amount="0" disabled selected>Hva slags type vask?</option>
                <option data-amount="0" value="Vanlig rengjøring">Vanlig rengjøring</option>
                <option data-amount="700" value="Grundig rengjøring">Grundig rengjøring</option>
            </select>
        </div>

        <div style="float: left; margin-left: 15px">
          Hva slags størrelse på hjemmet ditt?
        </div>
        <div style="float: left; width: 100%; margin: 15px">
            <select name="apartmentSize" style="float: left; width: 570px; height: 30px" onchange="updateAmountFromDropdown()">
                <option data-amount="" disabled selected>Størrelse på hjemmet ditt?</option>
                <option data-amount="" value="Mindre enn 40">40 kvm eller mindre</option>
                <option data-amount="" value="41-60">Mellom 41 og 60 kvm</option>
                <option data-amount="" value="61-80">Mellom 61 og 80 kvm</option>
                <option data-amount="" value="81-100">Mellom 81 og 100 kvm</option>
                <option data-amount="" value="101-120">Mellom 101 og 120 kvm</option>
            </select>
        </div>

<!-- starter på de små select option -->
        <div style="float: left; margin-left: 15px; margin-bottom: 10px">
          Fortell oss om hjemmet ditt
        </div>
        <div style="float: left; width: 100%">
                <div style="float: left">
                    <select name="kitchen" style="float: left; width: 245px; height: 30px; margin-left: 15px; margin-bottom: 10px" onchange="updateAmountFromDropdown()">
                        <option data-amount="0" disabled selected>Hvor mange kjøkken?</option>
                        <option data-amount="0" value="Kjøkken og stue">Kjøkken og stue (på samme rom)</option>
                        <option data-amount="0" value="1">1 kjøkken (hvis det ikke er på samme rom)</option>
                        <option data-amount="500" value="2">2 kjøkken</option>
                    </select>
                </div>
            <div style="float: right">
                <select name="livingRoom" style="float: left; width: 245px; height: 30px; margin-right: 65px" onchange="updateAmountFromDropdown()">
                    <option data-amount="0" disabled selected>Hvor mange stuer?</option>
                    <option data-amount="0" value="Stue og kjøkken">Stue og kjøkken (på samme rom)</option>
                    <option data-amount="0" value="1">1 Stue (hvis det ikke er på samme rom)</option>
                    <option data-amount="500" value="2">2 Stuer</option>
                    <option data-amount="1000" value="3">3 Stuer</option>
                </select>
            </div>
        </div>

        <div style="float: left; width: 100%">
                <div style="float: left">
                    <select name="bed" style="float: left; width: 245px; height: 30px; margin-left: 15px" onchange="updateAmountFromDropdown()">
                        <option data-amount="0" disabled selected>Hvor mange soverom?</option>
                        <option data-amount="0" value="0">0 soverom</option>
                        <option data-amount="0" value="1">1 soverom</option>
                        <option data-amount="500" value="2">2 soverom</option>
                    </select>
                </div>
            <div style="float: right">
                <select name="bathroom" style="float: left; width: 245px; height: 30px; margin-right: 65px" onchange="updateAmountFromDropdown()">
                    <option data-amount="0" disabled selected>Hvor mange bad?</option>
                    <option data-amount="0" value="1">1 bad</option>
                    <option data-amount="500" value="2">2 bad</option>
                    <option data-amount="1000" value="3">3 bad</option>
                </select>
            </div>
        </div>

<?php
/* 
// Check if there are missing fields from the previous submission
if (isset($_SESSION['missing_fields'])) {
    echo "<div style='float: left; width: 100%; color: #FF0000'><ul>";
    foreach ($_SESSION['missing_fields'] as $field) {
        echo "<li>$field mangler</li>";
    }
    echo "</ul></div>";
    
    // Unset the session variable to clear it
    unset($_SESSION['missing_fields']);
}*/ 
?>

        <div style="float: left; width: 100%; margin-top: 10px; margin-bottom: 10px">
            <hr></hr>
        </div>

         <div style="float: left; margin-left: 27px">
            Fullt navn:
          </div>

          <div style="float: left; width: 100%; margin-left: 27px; margin-top: 10px">
            <input type="text" name="fullName" id="fullName" required style="width: 570px; height: 30px">
          </div>

          <div style="float: left; margin-left: 27px">
            Adresse
          </div>

          <div style="float: left; width: 100%; margin-left: 27px; margin-top: 10px">
            <input type="text" name="address" id="address" required style="width: 430px; height: 30px">
          </div>

          <div style="float: left; margin-left: 27px">
            E-mail
          </div>

          <div style="float: left; width: 100%; margin-left: 27px; margin-top: 10px">
            <input type="email" name="email" id="email" required style="width: 570px; height: 30px">
          </div>

          <div style="float: left; margin-left: 27px">
            Mobilnummer:
          </div>

          <div style="float: left; width: 100%; margin-left: 27px; margin-top: 10px">
            <input type="text" name="phoneNumber" id="phoneNumber" required style="width: 570px; height: 30px">
          </div>

          <div style="float: left; margin-left: 27px">
            Postkode:
          </div>

          <div style="float: left; width: 100%; margin-left: 27px; margin-top: 10px">
            <input type="text" name="zipCode" id="zipCode" required style="width: 570px; height: 30px" onblur="validateZipCode()">
          </div>

           <div style="float: left; margin-left: 27px">
            By:
           </div>

           <div style="float: left; width: 100%; margin-left: 27px; margin-top: 10px">
            <input type="text" name="city" id="city" readonly style="width: 570px; height: 30px">
           </div>

          <div style="float: left; margin-left: 27px">
            Velg dato
          </div>

          <div style="float: left; width: 100%; margin-left: 27px; margin-top: 10px">
            <input type="date" name="selectedDate" id="selectedDate" required style="width: 570px; height: 30px">
          </div>

        <input type="hidden" name="totalAmount" id="totalAmountInput">
        <button type="submit" id="nextOrSubmitButton" onclick="validateForm()" onclick="handleNextStep()" style="margin-top: 15px; margin-left: 250px">Vipps hurtigkasse</button>
    </form>

</div>

</div>
</div>
</div>
<script>
// Function to handleFormSubmission
function handleFormSubmission() {
    var fullNameInput = document.getElementById("fullName");
    var addressInput = document.getElementById("address");
    var emailInput = document.getElementById("email");
    var phoneNumberInput = document.getElementById("phoneNumber");
    var zipCodeInput = document.getElementById("zipCode");
    var selectedDateInput = document.getElementById("selectedDate");
    var cityInput = document.getElementById("city");

    // Check if any of the required fields are empty
    if (!fullNameInput.value || !addressInput.value || !emailInput.value || !phoneNumberInput.value || !zipCodeInput.value || !selectedDateInput.value || !cityInput.value) {
        alert('Vennligst fyll ut alle obligatoriske felt.'); // Display alert message
        return; // Prevent further execution
    }

    // If all required fields are filled, submit the form
    document.getElementById("orderForm").submit();
}

// Function to handleNextStep
function handleNextStep() {
    // Check if the form is valid
    if (validateForm()) {
        // If form is valid, submit it
        document.getElementById("orderForm").submit();
    } else {
        // If form is not valid, move to the next step
        moveToNextStep();
    }
}

// select option become green when the select are filled with data
document.addEventListener("DOMContentLoaded", function() {
    var button = document.getElementById('nextOrSubmitButton');
    var dropdowns = document.querySelectorAll('select');

    function updateBorderColor(dropdown) {
        if (dropdown.selectedIndex !== 0) {
            dropdown.style.border = "2px solid #00CC99"; // Change the border to green when a selection is made
        } else {
            dropdown.style.border = ""; // Reset the border style to its default
        }
    }

    dropdowns.forEach(function(dropdown) {
        dropdown.addEventListener('change', function() {
            updateBorderColor(dropdown);
        });

        // Initial border color setup
        // Leave the border color unchanged initially
    });

    button.addEventListener('click', function(event) {
        var dropdownEmpty = Array.from(dropdowns).some(function(dropdown) {
            return dropdown.selectedIndex === 0;
        });

        // Check if any select dropdown is empty
        if (dropdownEmpty) {
            event.preventDefault(); // Prevent the default action of the button (i.e., preventing form submission)

            // Change the border color of empty dropdowns to red
            dropdowns.forEach(function(dropdown) {
                if (dropdown.selectedIndex === 0) {
                    dropdown.style.border = "2px solid #E87A61"; // Change the border color to red
                }
            });

        } else {
            // If all required fields are filled, submit the form
            document.getElementById("orderForm").submit();
        }
    });
});

function validateForm() {
    var inputs = document.querySelectorAll('input[required], select[required]');
    var isValid = true;

    inputs.forEach(function(input) {
        if (!input.value) {
            if (input.tagName === "SELECT") {
                input.style.border = "2px solid #E87A61"; // Change the border color to red for empty required selects
            } else {
                input.style.border = "2px solid #E87A61"; // Change the border color to red for empty required inputs
            }
            isValid = false;
        } else {
            input.style.border = ""; // Reset the border style to its default for filled required fields
        }
    });

    return isValid;
}

function moveToNextStep() {
    // Optionally, you can implement additional logic here based on your requirements
}

function handleNextStep() {
    // Check if the form is valid
    if (validateForm()) {
        // If form is valid, submit it
        document.getElementById("orderForm").submit();
    } else {
        // If form is not valid, move to the next step
        moveToNextStep();
    }
}
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var button = document.getElementById('nextOrSubmitButton');
    var inputs = document.querySelectorAll('input[required]');
    var selects = document.querySelectorAll('select[required]');

    function validateSelects() {
        selects.forEach(function(select) {
            select.reportValidity(); // This will trigger validation and apply the red border if the select is empty
        });
    }

    function validateInputs() {
        inputs.forEach(function(input) {
            if (!input.value.trim()) { // Check if the input value is empty or whitespace
                input.style.border = "2px solid #E87A61"; // Change the border color to red for empty required inputs
            }
        });
    }

    function resetInputBorder(input) {
        if (input.value.trim()) { // Check if the input value is not empty or whitespace
            input.style.border = ""; // Reset the border style to its default for filled fields
        }
    }

    button.addEventListener('click', function(event) {
        // Validate selects
        validateSelects();

        // Validate inputs
        validateInputs();

        var anyEmpty = false; // Flag to track if any required field is empty

        // Check if any input field is empty
        inputs.forEach(function(input) {
            if (!input.value.trim()) { // Check if input value is empty or whitespace
                anyEmpty = true;
            }
        });

        // Check if at least one select field is filled
        var anySelectFilled = false; // Flag to track if at least one select field is filled
        selects.forEach(function(select) {
            if (select.value.trim()) { // Check if select value is not empty or whitespace
                anySelectFilled = true;
            }
        });

        // Prevent form submission if any required field is empty and at least one select field is filled
        if (anyEmpty && anySelectFilled) {
            event.preventDefault();
        }
    });

    // Reset border color when input value changes
    inputs.forEach(function(input) {
        input.addEventListener('input', function() {
            resetInputBorder(input);
        });
    });
});
</script>


<!-- updating booking summary choosen the select and service costs combined -->
  <script>
    function updateTotalAmount() {
      var totalAmount = 1300; // Starting amount
      var selectedServices = document.querySelectorAll('select[name="apartmentSize"], select[name="kitchen"], select[name="livingRoom"], select[name="type"], select[name="bed"], select[name="bathroom"]');

      selectedServices.forEach(function (select) {
        var selectedOption = select.options[select.selectedIndex];
        if (selectedOption && selectedOption.dataset.amount) {
          totalAmount += parseInt(selectedOption.dataset.amount);
        }
      });

      document.getElementById('totalAmount').textContent = totalAmount; // Update total amount in the UI
      document.getElementById('totalAmountInput').value = totalAmount; // Set total amount in the hidden input field
    }

    document.addEventListener("DOMContentLoaded", function () {
      updateTotalAmount(); // Update total amount on page load

      var selects = document.querySelectorAll('select');
      selects.forEach(function (select) {
        select.addEventListener('change', function () {
          updateTotalAmount(); // Update total amount when any select option changes
        });
      });
    });
  </script>
  <script> // Can't order any earlier then previous dates
    document.addEventListener("DOMContentLoaded", function() {
    var selectedDateInput = document.getElementById("selectedDate");

    // Get today's date
    var today = new Date();
    var yyyy = today.getFullYear();
    var mm = String(today.getMonth() + 1).padStart(2, '0'); // January is 0!
    var dd = String(today.getDate()).padStart(2, '0');
    var currentDate = yyyy + '-' + mm + '-' + dd;

    // Set minimum date for selectedDate input
    selectedDateInput.setAttribute("min", currentDate);

    // Optional: You can also disable the input if you want to prevent manual entry of past dates
    // selectedDateInput.addEventListener("keydown", function(event) {
    //     event.preventDefault();
    // });

    // Optional: You can display a message to inform users about the minimum date restriction
    // var minDateMessage = "Please select a date on or after " + currentDate;
    // alert(minDateMessage);
});
</script>
<script> //
     document.addEventListener("DOMContentLoaded", function() {
        var infoBox = document.querySelector('.info_box');

        // Check if infoBox is found and if it's found you can click on it too remove it
        if (infoBox) {
            infoBox.addEventListener('click', function() {
                this.style.display = 'none'; // Hide the info box when clicked
            });
        }
    });
</script>
<script>
function validateZipCode() { // A hell alot of zipcodes that's allowed too order. Only Oslo and nearby Oslo can order services.
    var allowedZipCodes = ['1410', '0010', '0015', '0018', '0026', '0037', '0050', '0139', '0150', '0151', '0152', '0153', '0154', '0155', '0157', '0158', '0159', '0160', '0161', '0162', '0164', '0165', '0166', '0167', '0168', '0169', '0170', '0171', '0172', '0173', '0174', '0175', '0176', '0177', '0178', '0179', '0180', '0181', '0182', '0183', '0184', '0185', '0186', '0187', '0188', '0190', '0191', '0192', '0193', '0194', '0195', '0196', '0198', '0250', '0251', '0252', '0253', '0254', '0255', '0256', '0257', '0258', '0259', '0260', '0262', '0263', '0264', '0265', '0266', '0267', '0268', '0270', '0271', '0272', '0273', '0274', '0275', '0276', '0277', '0278', '0279', '0280', '0281', '0282', '0283', '0284', '0286', '0287', '0340', '0349', '0350', '0351', '0352', '0353', '0354', '0355', '0356', '0357', '0358', '0359', '0360', '0361', '0362', '0363', '0364', '0365', '0366', '0367', '0368', '0369', '0370', '0371', '0372', '0373', '0374', '0375', '0376', '0377', '0378', '0379', '0380', '0381', '0382', '0383', '0445', '0450', '0451', '0452', '0454', '0455', '0456', '0457', '0458', '0459', '0460', '0461', '0462', '0463', '0464', '0465', '0467', '0468', '0469', '0470', '0472', '0473', '0474', '0475', '0476', '0477', '0478', '0479', '0480', '0481', '0482', '0483', '0484', '0485', '0486', '0487', '0488', '0489', '0490', '0491', '0492', '0493', '0494', '0495', '0496', '0550', '0551', '0552', '0553', '0554', '0555', '0556', '0557', '0558', '0559', '0560', '0561', '0562', '0563', '0564', '0565', '0566', '0567', '0568', '0569', '0570', '0571', '0572', '0573', '0574', '0575', '0576', '0577', '0578', '0579', '0580', '0581', '0582', '0583', '0584', '0585', '0586', '0587', '0588', '0589', '0590', '0591', '0592', '0593', '0594', '0595', '0596', '0597', '0598', '0650', '0651', '0652', '0653', '0654', '0655', '0656', '0657', '0658', '0659', '0660', '0661', '0662', '0663', '0664', '0665', '0666', '0667', '0668', '0669', '0670', '0671', '0672', '0673', '0674', '0675', '0676', '0677', '0678', '0679', '0680', '0681', '0682', '0683', '0684', '0685', '0686', '0687', '0688', '0689', '0690', '0691', '0692', '0693', '0694', '0750', '0751', '0752', '0753', '0754', '0755', '0756', '0757', '0758', '0760', '0763', '0764', '0765', '0766', '0767', '0768', '0770', '0771', '0772', '0773', '0774', '0775', '0776', '0777', '0778', '0779', '0781', '0782', '0783', '0784', '0785', '0786', '0787', '0788', '0789', '0790', '0791', '0850', '0851', '0852', '0853', '0854', '0855', '0856', '0857', '0858', '0860', '0861', '0862', '0863', '0864', '0870', '0871', '0872', '0873', '0874', '0875', '0876', '0877', '0880', '0881', '0882', '0883', '0884', '0890', '0891', '0950', '0951', '0952', '0953', '0954', '0955', '0956', '0957', '0958', '0959', '0960', '0962', '0963', '0964', '0968', '0969', '0970', '0971', '0972', '0973', '0975', '0976', '0977', '0978', '0979', '0980', '0981', '0982', '0983', '0984', '0985', '0986', '0987', '0988', '1051', '1052', '1053', '1054', '1055', '1056', '1061', '1062', '1063', '1064', '1065', '1067', '1068', '1069', '1071', '1081', '1083', '1084', '1086', '1087', '1088', '1089', '1150', '1151', '1152', '1153', '1154', '1155', '1156', '1157', '1158', '1160', '1161', '1162', '1163', '1164', '1165', '1166', '1167', '1168', '1169', '1170', '1172', '1176', '1177', '1178', '1179', '1181', '1182', '1184', '1185', '1187', '1188', '1189', '1250', '1251', '1252', '1253', '1254', '1255', '1256', '1257', '1258', '1259', '1262', '1263', '1266', '1270', '1271', '1272', '1273', '1274', '1275', '1278', '1279', '1281', '1283', '1284', '1285', '1286', '1290', '1291', '1294', '1295', '1400', '1401', '1402', '1403', '1404', '1405', '1406', '1408', '1409', '1411', '1412', '1413', '1414', '1415', '1416', '1417', '1418', '1419', '1420', '1421', '1422', '1423', '1424', '1425', '1840', '1845'];
    var zipCodeInput = document.getElementById("zipCode");
    var zipCodeError = document.getElementById("zipCodeError");
    var userZipCode = zipCodeInput.value.trim();

    if (!allowedZipCodes.includes(userZipCode)) {
        // Display error code that's not within the range.
        zipCodeError.textContent = "Beklager, men vi tilbyr tjenester kun i Oslo. Vennligst oppgi en gyldig Oslo postnummer.";
        zipCodeInput.classList.add("invalid");
    } else {
        // zipCode is allowed, remove the error message automatically
        zipCodeError.textContent = "";
        zipCodeInput.classList.remove("invalid");
    }
}

</script>
</body>
</html>


`I have tried too put require into the inputs fields without success, email type for the input field that's also been failing.

I mean it's working when all of the input are filled up, but i wan't too make it easier for the users too see empty input are missing so they can see that easily instead of having this problem. This issue would annjoying me as a customer.`

how to create generic method in asp dot net

To declare a generic type, you can specify a type parameter in angle brackets after a type name. For example, TypeName<T> where T is a type parameter.

Here’s an example of using generics in a .NET application:
Create a new project in Visual Studio
Create two model classes to represent the Product and Seller entities
Create a context class to add the database settings
Create a generic repository
Add the dependency injections
Create the API endpoints
Generate the migrations
Test the application

Deprecated document.domain

Please find the below java class for the Cors Implementation.

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CORSFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        String requestOrigin = request.getHeader("Origin");
        LOGGER.info("Received request of method {}, with origin {}", request.getMethod(), requestOrigin);

        response.setHeader("Access-Control-Allow-Origin", requestOrigin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        chain.doFilter(req, res);
    }
}

Below is the error I’m getting in the console

**
• document,domain mutation is ignored CulatomerportalServle..-11T11:29:04.9852:7 Q because the surrounding agent cluster is origin-keyed. CR: FormInit – begins CustomerportalServle.11T11:29:04.9852:31
•Uncaught DOMException: Failed to read a CustomerportalServle.11T11:29:04.9852:47 named property ‘logo’ from ‘Window’: Blocked a frame with origin “some url” from accessing a cross-origin frame. at formInit (some url) at onload (some url)
**

Below is the jsp file that I’m using and getting error at “top.logo.getlanguage()” or any “top.logo.” things

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>Some Title</title>
    <script type="text/javascript">
        // JavaScript code
        try {
            document.domain = "something.net";
        } catch (e) {
            // handle the error
        }
    </script>
</head>
<body>
    <script type="text/javascript">
        // More JavaScript code
        try {
            var consoleOld = null;
            consoleOld = top.systemObj.getConsole();
        } catch (e) {
            // handle the error
        }
    </script>
</body>
</html>

I was told to add “Origin-Agent-Cluster: ?0” in the response header.

Can anyone tell me what is the solution here and if I have to add origin agent cluster what modification should I do?

JS: How to correctly use await for an asynchronous GraphQL data fetch within an async function? [duplicate]

I’m currently working on a project where I have an asynchronous function, fetchSomeData, which internally makes a call to an asynchronous GraphQL data fetching function, fetchGraphQLData. The fetchGraphQLData function returns a promise containing data, loading status, and potential errors.

import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';

const DEFAULT_URI = 'https://example.com/graphql';

const getGraphQLClient = (uri = DEFAULT_URI) => {
  const httpLink = createHttpLink({
    uri,
  });

  const client = new ApolloClient({
    link: httpLink,
    cache: new InMemoryCache(),
  });

  return client;
};

export default getGraphQLClient;
export const fetchGraphQLData = async <T,>({
  query,
  variables,
}: QueryOptions): Promise<TQueryResult<T>> => {
  const { data, loading, error } = await getGraphQLClient().query<T>({
    query,
    variables,
  });
  return { data, loading, error };
};

I’m wondering if using await for the fetchGraphQLData call is necessary in this context, or if there’s a more efficient or best-practice way to handle this scenario.

const fetchSomeData = async (): Promise<TQueryResult<TSomeData>> => {
    return fetchGraphQLData<TSomeData>({
        query: someQuery,
    });;
};

Can someone shed some light on the correct usage of await in this context and any potential pitfalls I should be aware of?

Preserve Scroll Position in React?

So I want to preserve scroll position after viewing an individual post. I can do this when I went to individual post, and then not scrolling in individual post, return back to home page. It will preserver the scroll position. But when I scrolled in the individual post page, and then return to home page, the scroll position is messed up. Here are snippets of the code:

Home.jsx

    const [posts, setPosts] = useState([]);
    const [startIndex, setStartIndex] = useState(0);
    const [range, setRange] = useState(6);
    const [loading, setLoading] = useState(true)


    useEffect(() => {
        const fetchPosts = async () => {
            try {
                const response = await axios.get(`/api/posts`);
                setPosts(response.data);
                console.log(response.data);
            } catch (e) {
                console.log(e);
            } finally {
                setLoading(false);
            }
        };

        fetchPosts();
        setRange(sessionStorage.getItem('range') ? parseInt(sessionStorage.getItem('range')) : 6);
    }, []);

    useEffect(() => {
        const attemptScrollRestore = () => {
            const savedPosition = parseInt(sessionStorage.getItem('HomeScroll') || '0');
            if (document.body.scrollHeight > savedPosition) {
                window.scrollTo(0, savedPosition);
            } else {
                setTimeout(attemptScrollRestore, 50); 
            }
        };

        if (loading === false) { 
            attemptScrollRestore();
        }
    }, [loading]); // This useEffect depends on the loading state


    useEffect(() => {
        const handleScroll = () => {
          sessionStorage.setItem('HomeScroll', window.scrollY.toString());
        }

        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, []);

Post.jsx

    const [post, setPost] = useState({});
    const [comment, setComment] = useState('');
    const [comments, setComments] = useState([]);
    const [honeypot, setHoneypot] = useState("");
    const [loading, setLoading] = useState(true)
    const {postID} = useParams();
    const navigate = useNavigate();

    useEffect(() => {
        window.scrollTo(0, 0);
    }, []);


    useEffect(() => {



        const fetchPosts = async () => {
            const response = await axios.get("/api/singlePost", {
                params: {
                    id: postID
                }
            });
            setPost(response.data);
        }

        const fetchComments = async () => {
            const response = await axios.get("/api/getComments", {
                params: {
                    id: postID
                }
            });
            setComments(response.data);
        }

        const updatePosts = async () => {
            const response = await axios.put(`/api/updatePost?id=${postID}`);
        }
        fetchPosts();
        fetchComments();

        const timer = setTimeout(() => {
            updatePosts();
        }, 1750);

        return () => clearTimeout(timer);

    }, [postID]);

I did try to not change scroll position in Post.jsx, but it still not working. Tried to use custom state also not working. It seems like something in Post.jsx messing up with the local storage? Or when I went back to homepage, it resetted to 0,0 without giving a chance to restore the scroll position. That what I can think of right now. Appreciate any help

How do I make a node package with an optional peerDependency it depends on in test code?

The official documentation for peerDependency‘s says (emphasis mine):

A plugin package is meant to be used with another “host” package, even though it does not always directly use the host package.

I’ve got a situation where my plugin does use the host package directly (in a test), even though this peerDependency is meant to be optional for the app. This is the relationship I want between these packages:

App --may depend on, but may not--> canvas
My package --optional peer dependency--> canvas
My package tests --depends on--> canvas

How should my package.json be written for this? Here’s what I’ve currently got, and I think it works?

{
  // ...
  "devDependencies": {
    "canvas": "^2.11.2"
  },
  "peerDependencies": {
    "canvas": "^2.11.2",
    "jsdom": "^24.0.0"
  },
  "peerDependenciesMeta": {
    "canvas": {
      "optional": true
    }
  }
}

Is this the correct way to write a package.json with an optional peerDependency that it uses in test code?

Any other ways to obtain the values of svg’s bounding-rect

I have SVG elements that must be processed inside a JSDOM and need to obtain their getBBox() value.

while using getBBox() , as there is not painting performed inside a JSDOM the values are not obtained.

As I have many svgs in files and am in need of a method that finds the x, y , min ,max coordinates as like getBBox() and return those values. I have also tried methods like getBoundingClientRect()

https://github.com/jsdom/jsdom/issues/2647
If getBBox() can’t be used inside a JSDOM , is there any alternative approach for the same.

How to make onChange work properly in FancyGrid?

I am using Fancy Grid, when ever some changes or update occurs in this cell I want to see it inside debugger, I have put debugger inside function and when I make any changes it does not pause inside this function nor it print anything in console. Please find the code below:

  {
                    index: 'fieldLength',
                    editable: editableLength,
                    title: 'Field Length',
                    flex: 1,
                    headerCls: 'header-cell-without-search-input',
                    filter:{
                        header:true
                    },
                    type: 'number',
                    vtype: {
                        before: ['notempty', 'notnan'],
                        type: 'min',
                        param: 0
                    },
                    events: [{
                        onchange : function (g,o) {
                            debugger
                            console.log("SOmething changed!!")
                        }
                    }]
                }

What is the proper solution here?

I have try many methods like before|after , update, save but still not found an proper solution.