bootstrap 5 mega menu disappears really quick

I have this bootsrap 5 mega dropdown, I have an issue with it as it disappears quickly when I try to select the contents. I believe I have a css affecting this but just can’t figure it out. Reference https://mdbootstrap.com/docs/standard/extended/mega-menu/

HTML:

<header id="alaid-header" class="d-flex align-items-center bg-white shadow header">
  <div class="container d-flex justify-content-between">
  <div class="logo">
      <h1 class="text-light"><a href="index.php">
          <img src="./assets/img/logo.png" class="w-100" />
      </a></h1>
  </div>
    <nav id="navbar" class="navbar alaid-navbar">
      <ul>
        <li><a class="nav-link active" href="">Home</a></li>
        <li class="nav-item dropdown dropdown-hover position-static">
          <a class="nav-link" href="#" id="navbarDropdown" role="button"
            data-mdb-toggle="dropdown" aria-expanded="false">
            Impact<i class="bi bi-chevron-down"></i>
          </a>
          <!-- Dropdown menu -->
          <div class="dropdown-menu w-100 mt-0" aria-labelledby="navbarDropdown" style="border-top-left-radius: 0; border-top-right-radius: 0;">
            <div class="container mr-auto mx-0">
              <div class="row my-4">
                <div class="col-md-6 col-lg-3 mb-3 mb-lg-0">
                  <div class="list-group list-group-flush">
                    <h6><strong>Interest</strong></h6>
                    <hr />
                    <a href="">Cars</a>
                    <a href="">Houses</a>
                  </div>
                </div>
                <div class="col-md-6 col-lg-4 mb-3 mb-lg-0">
                  <div class="list-group list-group-flush">
                    <h6><strong>Lorem</strong></h6>
                    <hr />
                    <a href="">Lorem</a>
                    <a href="">Lorem</a>
                  </div>
                </div>
                <div class="col-md-6 col-lg-5 mb-3 mb-lg-0">
                  <div class="list-group list-group-flush">
                    <h6><strong>lorem</strong></h6>
                    <hr />
                    <a href="">lorem</a>
                    <a href="">lorem</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </nav>
  </div>
</header>

CSS:

.dropdown-menu {
  width: 100%;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translate(-50%, 10px); 
  padding: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  transition: all 5s ease;
}

.dropdown-hover:hover>.dropdown-menu {
  display: block;
  opacity: 1;
  visibility: visible;
  z-index:200;
}


.dropdown-hover>.dropdown-toggle:active {
  pointer-events: none;
}


.dropdown .dropdown-menu a {
  font-size: 13px !important;
  margin-left: -29px;
}
.nav-item {
  padding: 0.5rem 0xp;
}

.dropdown-menu .container{
  margin-bottom: -30px;
}

I have tried increasing the transition time and increase the z-index value but to no avail. I cant figure what css property I need to add to enable the hover effect stay up.

Trying to join two collections together, array in collection map to other collection. MongoDB

In MongoDB with two collection, trying to get a course with the “courseCode”.
In the course collection “assignedTutors” is a array of users._id in the course collection.
Want to want the array of “assignedTutors” IDs to get their user info in the users collection.

Problem: With the current code I am not getting the user data in the users collection using the array of “assignedTutors” IDs. In the current example there are 3 user IDs in the “assignedTutors” array I would like to use aggregate to get the user data from the users collection.

If there is better way to do this i am open to that too.

course collection:

{
    "_id": {
        "$oid": "66e765c04ce5539d7f7362c2"
    },
    "courseCode": "ACB123",
    "courseName": "ABC",
    "courseImgUrl": "https://ABC.png",
    "coursePrice": "123",
    "assignedTutors": ["66f9a09505e0ca3203870633", "66f9a07e05e0ca3203870630", "66f9a05005e0ca320387062d"],
    "description": "This course ABC",
    "published": true,
    "school": "ABC school"
}

users collection:

{
    "_id": {
        "$oid": "66f9a09505e0ca3203870633"
    },
    "userName": "tutor3",
    "password": "xxx",
    "email": "[email protected]",
    "userType": "tutor",
    "firstName": "Tutor",
    "lastName": "Three",
    "teachingCourse": ["66f9adbb05e0ca3203870732", "66e765c04ce5539d7f7362c2"],
    "certificates": [],
    "purchasedCourse": [],
    "__v": {
        "$numberInt": "0"
    }
}

current code:

    module.exports.getCourseByCode = function (courseCode) {
        return new Promise((resolve, reject) => {
          Course.aggregate([
            {
              $match: { courseCode: courseCode }
            },
            {
              $lookup: {
                from: 'users',
                localField: 'assignedTutors',
                foreignField: '_id',
                as: 'assignedTutors'
              }
            },
            {
              $unwind: '$assignedTutors'
            },
            {
              $lookup: {
                from: 'users',
                localField: 'assignedTutors._id',
                foreignField: '_id',
                as: 'assignedTutors.tutorData'
              }
            },
            {
              $project: {
                _id: 1,
                courseCode: 1,
                courseName: 1,
                courseImgUrl: 1,
                coursePrice: 1,
                school: 1,
                description: 1,
                published: 1,
                assignedTutors: { $arrayElemAt: ['$assignedTutors', 0] }
              }
            }
          ])
            .then((courses) => {
                console.log(courses)
              if (courses.length === 0) {
                reject(`Course with code ${courseCode} not found.`);
              } else {
                resolve(courses[0]);
              }
            })
            .catch((err) => {
              reject(`Error while retrieving course with code ${courseCode}: ${err.message}`);
            });
        });
      };

Current output:

{
    "_id": {
        "$oid": "66e765c04ce5539d7f7362c2"
    },
    "courseCode": "ABC123",
    "courseName": "Test",
    "courseImgUrl": "abc.png",
    "coursePrice": "123",
    "assignedTutors": ["66f9a09505e0ca3203870633", "66f9a07e05e0ca3203870630", "66f9a05005e0ca320387062d"],
"description": "XYZ.",
"published": true,
"school": "ABC school"
}

I want it to return a course and with the assignedTutors data on the users collection.

{
    "_id": {
        "$oid": "66e765c04ce5539d7f7362c2"
    },
    "courseCode": "ABC123",
    "courseName": "Test",
    "courseImgUrl": "abc.png",
    "coursePrice": "123",
    "assignedTutors": [{
            "_id": {
                "$oid": "66f99b8005e0ca32038705f6"
            },
            "userName": "user1",
            "password": "zzz",
            "email": "[email protected]",
            "userType": "xxx",
            "firstName": "userF",
            "lastName": "userL",
            "teachingCourse": [],
            "certificates": [],
            "purchasedCourse": [],
            "__v": {
                "$numberInt": "0"
            }
        } {
            "_id": {
                "$oid": "66f99b8005e0ca32038705f6"
            },
            "userName": "user2",
            "password": "zzz",
            "email": "[email protected]",
            "userType": "xxx",
            "firstName": "userF",
            "lastName": "userL",
            "teachingCourse": [],
            "certificates": [],
            "purchasedCourse": [],
            "__v": {
                "$numberInt": "0"
            }
        }, {
            "_id": {
                "$oid": "66f99b8005e0ca32038705f6"
            },
            "userName": "user3",
            "password": "zzz",
            "email": "[email protected]",
            "userType": "xxx",
            "firstName": "userF",
            "lastName": "userL",
            "teachingCourse": [],
            "certificates": [],
            "purchasedCourse": [],
            "__v": {
                "$numberInt": "0"
            }
        }
    }],
"description": "XYZ.",
"published": true,
"school": "ABC school"
}

How can I avoid recursion in this JavaScript function that uses Promises?

I have a JavaScript function that generates an endless slideshow. The code works, but I’m concerned about each iteration ending in a recursive call to itself. Using developer tools, it appears that the call stack is growing.

I tried removing the recursive call to show_slides and wrapping the body of the function in a while (true) loop, but this caused the browser to lock up, burning lots of CPU and displaying nothing.

I assume I’ve missed waiting for the resolution of a Promise somewhere, and have tried appending .then(() => {}) to both the inner and the outer chains, without success.

Assuming that this is growing the stack (infinitely), rather than being treated as tail recursion and actually executing as a loop, what do I need to turn the body of the function into a loop?

const duration = 2000; // time (msec) to display each slide
const sizes = [
  [4000, 500],
  [1000, 4000],
  [600, 400],
  [100, 200],
  [4000, 4000]
];
const sleep = ms => new Promise(r => setTimeout(r, ms));
let n = 0;

function show_slides(duration) {
  const my_parent = document.querySelector('#slide-div');
  let size_index = n++ % sizes.length;
  let w = sizes[size_index][0];
  let h = sizes[size_index][1];

  let my_randomizer = `https://placehold.co/${w}x${h}?text=${w}+x+${h}npx`;
  fetch(my_randomizer)
    .then(my_response => my_response.blob())
    .then(my_blob => {
      let my_url = URL.createObjectURL(my_blob);
      sleep(duration)
        .then(() => {
          URL.revokeObjectURL(my_parent.querySelector('img').src);
          my_parent.querySelector('img').src = my_url;
          // A recursive call to iterate??
          show_slides(duration);
        });
    })
    .catch(my_error => console.error('Error: ', my_error));
}
* {
  box-sizing: border-box;
}

html {
  height: 100%;
  width: 100%;
}

body {
  background-color: #dbd2c3;
  font-family: Arial, Helvetica, sans-serif;
  /* prevent body from displacing */
  margin: 0;
  /* body should perfectly superimpose the html */
  height: 100%;
  width: 100%;
}

.outer-div {
  display: flex;
  flex-flow: column;
  height: 100%;
  /* Now create left/right margins */
  margin: 0 0;
}

.inner-fixed-div {
  margin-top: 0.5em;
}

.inner-remaining-div {
  margin-bottom: 0;
  flex-grow: 1;
  /* hints the contents to not overflow */
  overflow: hidden;
}

.picture-div {
  /* force the div to fill the available space */
  width: 100%;
  height: 100%;
  /* center child elements */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.picture-div-img {
  max-width: calc(100% - 0.5em);
  /* included 0.5em * 2 margin on parent */
  max-height: calc(100% - 0.5em);
  /* included 2em margin on parent, may need adjust this further */
  border: 2px solid black;
}
<!DOCTYPE html>
<html lang="en">
<!-- Self-contained slideshow demo -->

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body onload="show_slides(duration);">
  <div class="outer-div">
    <div class="inner-fixed-div">
      <h1>Lorem Ipsum</h1>
    </div>
    <div class="inner-remaining-div">
      <div id="slide-div" class="picture-div">
        <!-- Placeholder <img> element for slides -->
        <img class="picture-div-img">
      </div>
    </div>
  </div>
</body>

</html>

OneSignal Initialization Blocks User Data Saving Logic in React App

I’m working on a Firebase-based chat app using React and implementing OneSignal for push notifications. However, I’m facing an issue where initializing OneSignal seems to block the execution of the code that comes afterward, including saving user data to Firestore.

Problem:

  • I successfully initialize OneSignal in my app.
  • After the initialization, the code (specifically saving user data) does not execute, and no error is thrown.
  • If I remove the initialization, I get an error OneSignal.getUserId is not a function.

Error Logs:
When OneSignal is initialized, no logs appear after this point, meaning the saving logic isn’t executed. If OneSignal is removed, I get the error:

OneSignal.getUserId is not a function.

Code

const SaveUserData = ({ onSaveComplete }) => {
  useEffect(() => {
    const saveUserData = async () => {
      try {
        console.log("Before initializing OneSignal");
        await OneSignal.init({
          appId: "01163343-b315-4598-a898-5cbd1e421eac",
          safari_web_id: "web.onesignal.auto.064b44a8-1dd7-4e10-9d87-452ef5b9c9dd",
          notifyButton: { enable: true },
        });

        console.log("OneSignal initialized");
        let playerId = await OneSignal.getUserId();

        console.log("Player ID received:", playerId);

        const { uid, displayName, photoURL } = auth.currentUser;
        const userDocRef = doc(dataBase, "Users", uid);

        // Save the user data along with the OneSignal player ID
        await setDoc(userDocRef, {
          userId: uid,
          displayName: displayName,
          photoUrl: photoURL,
          oneSignalPlayerId: playerId,
        });

        console.log("User data successfully saved with UID as document ID:", uid);

        onSaveComplete && onSaveComplete(true);

      } catch (error) {
        console.error("Error saving user data:", error.message);
        onSaveComplete && onSaveComplete(false);
      }
    };

    saveUserData();

  }, [onSaveComplete]);
};

`

What I’ve Tried:

  • I ensured OneSignal is only initialized once in the app.
  • I tried adding retries to ensure getUserId() fetches the playerId correctly.
  • I’m testing on both localhost and a deployed version (Netlify), and on both, the issue persists.
  • Notifications work (I see the notification icon and get subscription messages), but saving logic does not proceed.

What I’m Expecting:
I am looking for guidance on the following points:

Debugging the OneSignal Initialization:
I expect help understanding why the OneSignal SDK initialization might be failing or not returning the expected Player ID and causing the rest of the code not to execute.

Any help or suggestions would be greatly appreciated.

Fullcalendar events on vertical overlap?

im use Fullcalendar,an i ask if its possible to put all events on same hour thats overlap in vertical like in image bellow ? The color its only an explample to be more clear.

What i have tried ?
I already tried saw in the documentation, but i cant find nothing that helps me to solve this problem, but i can solve this.

If anyone has tried this before or knows a possible solution I look forward to hearing from you.

calendar example

CouchDB Connection Refused Error on Jetstream2 Access Server (Ubuntu 20.04 LTS)

I’m running a Python script that connects to a CouchDB database and subscribes to an MQTT topic. The script works fine on my laptop (Ubuntu 24.04.1 LTS), but when I try to run it on a Jetstream2 Access server (Ubuntu 20.04 LTS), I get a connection refused error when trying to access/create a database.
Here’s the relevant part of my code:

import paho.mqtt.client as mqtt
import couchdb
import json
from datetime import datetime
from urllib.parse import quote

# CouchDB setup
username = "admin"
password = ""  # Your actual password
host = "localhost"
port = "5984"

# URL encode the username and password
encoded_username = quote(username, safe='')
encoded_password = quote(password, safe='')

couch_url = f"http://{encoded_username}:{encoded_password}@{host}:{port}"

try:
    couch = couchdb.Server(couch_url)
    print("Successfully connected to CouchDB")
except Exception as e:
    print(f"Error connecting to CouchDB: {e}")
    exit(1)

db_name = 'weather_data'
try:
    if db_name not in couch:
        db = couch.create(db_name)
    else:
        db = couch[db_name]
    print(f"Successfully accessed/created database: {db_name}")
except Exception as e:
    print(f"Error accessing/creating database: {e}")
    exit(1)

# MQTT setup
mqtt_broker = "iotwx.ucar.edu"
mqtt_port = 1883
# mqtt_topic = "ncar/iotwx/hi/maui/mauiNNN"
mqtt_topic = "ncar/iotwx/co/rmnp/neon000"


def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe(mqtt_topic)

def on_message(client, userdata, msg):
    print(f"Received message on topic: {msg.topic}")
    payload = msg.payload.decode()
    print(f"Raw payload: {payload}")
    
    lines = payload.split('n')
    
    data = {}
    for line in lines:
        if ':' in line:
            key, value = line.split(':', 1)
            data[key.strip()] = value.strip()
    
    print(f"Parsed data: {data}")
    
    if 'sensor' in data and 'm' in data and 't' in data:
        doc = {
            'device': data.get('device', ''),
            'sensor': data['sensor'],
            'measurement': float(data['m']),
            'timestamp': int(data['t']),
            'received_at': datetime.now().isoformat()
        }
        print(f"Prepared document for CouchDB: {doc}")
        try:
            doc_id, doc_rev = db.save(doc)
            print(f"Saved document to CouchDB. ID: {doc_id}, Rev: {doc_rev}")
        except Exception as e:
            print(f"Error saving document to CouchDB: {e}")
    else:
        print("Received message does not contain all required fields (sensor, m, t)")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

try:
    client.connect(mqtt_broker, mqtt_port, 60)
    print(f"Connected to MQTT broker: {mqtt_broker}")
except Exception as e:
    print(f"Error connecting to MQTT broker: {e}")
    exit(1)
    
print(f"Listening for messages on topic: {mqtt_topic}")
client.loop_forever()

The error message I get is:

Successfully connected to CouchDB
Error accessing/creating database: [Errno 111] Connection refused

I’m not sure what’s causing the connection refused error, especially since the script works fine on my laptop. Has anyone else encountered this issue on Jetstream2 Access servers or Ubuntu 20.04 LTS? Any help would be appreciated!

Environment:
Jetstream2 Access server (Ubuntu 20.04 LTS)
CouchDB 3.2.2
Python 3.8.10
couchdb library version 1.1.1

Mongoose .create function returning an error

Im trying to build a car selling website with MERN but while building the backed it sems that my .create function is not working even though the imports seem to be correct here is the error with the files:-

const newCar = await Car.create({
                              ^

TypeError: Car.create is not a function

here are the respective files:-

Car.js

const express= require('express');
const mongoose= require('mongoose');
const Car = require('../Models/Models.js');


const router = express.Router();

router.get ('/create', async function (req, res) {
     const newCar = await Car.create({
        name: "Porche",
          model: "911",
          color: "Blue",
          year: 1981,
          mileage: 500,
          price: 200000,
        })
         

})

module.exports = router;

index.js

const express = require('express');

const app = express();

const port = 3000
const car = require("./routes/Car");

app.use("/cars", car);

app.listen(port, ()=>{
    console.log(`Server is running on port ${port}`);
});

Models.js

const mongoose = require('mongoose');


const Schema = mongoose.Schema;

const carSchema = new Schema({
name: String,
  model: String,
  color: String,
  year: Number,
  mileage: Number,
  price: Number,
})

const UserSchema = new Schema({ 
name: String,
  email: { type: String, unique: true },
  password: String,
  cars: [carSchema],
  admin: Boolean,

})

const Car = mongoose.model('Car', carSchema)
const User = mongoose.model('User', UserSchema)

module.exports = { Car, User };

access property of an object using hash-vault-js

following the documentation of the hash-vault-js node package I am trying to use I should be able to get the token from the response using:

const token = await vault.loginWithAppRole(RoleId, SecretId).client_token;

but

console.log(token);

returns undefined.
The full response is:

{
    client_token: 'hvs.CAESIBbqO37msc9GKEMnYLm0B40tSeA1VuOQtkOqzx4q47BTGh4KHGh2cy50MUZra3V4UFYwSXZNdkhaYjJPTEtMY2M',
    accessor: 'L321k60IkDv7QDJPS8yBurBM',
    policies: [ 'default' ],
    token_policies: [ 'default' ],
    metadata: { role_name: 'liveslowsailfast' },
    lease_duration: 1200,
    renewable: true,
    entity_id: '079a8b50-8177-f044-c99d-690ef269db9d',
    token_type: 'service',
    orphan: true,
    mfa_requirement: null,
    num_uses: 0
}

So the question now is: what is the correct way to retrieve the client_token value?

Cannot figure out the calculation for Object Grid Snapping in ThreeJS

I have a grid snapping logic which works on grid with size 4 columns 2 rows even if I rotate the grid and in 3 columns 2 rows too but in the second grid when rotated the modelSelected(object that is snapped) snaps it self to the points where grid lines intersect and not to the center of the cells.

Below is the logic I’m using. I just don’t understand how it works on 4×2, 2×4 and 3×2 too but not with 2×3.

if (modelSelected.position) {
    const intersectedPosition = intersectedObject.position;
    // Calculate grid cell dimensions
    const gridCellWidth = gridSize.width / seletedGridDimension[0];
    const gridCellHeight = gridSize.height / seletedGridDimension[1];
    
    // Calculate the offset from the origin of the grid
    const offsetX = (gridSize.width % gridCellWidth) / 2;
    const offsetY = (gridSize.height % gridCellHeight) / 2;
    
    // Calculate the snapped position for X
    const snappedX = Math.floor((intersect.point.x - intersectedPosition.x + offsetX) / gridCellWidth) * gridCellWidth - offsetX + (gridCellWidth / 2);
    let snappedY;
    // Special case for grids with 1 row (no need to snap on Y axis)
    if (seletedGridDimension[1] === 1) {
    snappedY = 0; // No snapping on Y if it's a single row grid
    } else {
    // Calculate the snapped position for Y
    snappedY = Math.floor((intersect.point.y - intersectedPosition.y + offsetY) / gridCellHeight) * gridCellHeight - offsetY + (gridCellHeight / 2);
    }
    
    // Set the new position of the model
    modelSelected.position.set(
    intersectedPosition.x + snappedX,
    intersectedPosition.y + snappedY,
    intersect.point.z
    );
    
    Render();

How to create a walking route plan app that allows you to specify the range and time [closed]

I’m creating a web app for walking using Google’s JavaScript Map API. However, I’m having trouble because I don’t know how to suggest a route with a specified time and range. I would appreciate it if you could let me know if you know.

① Encircle a certain area on the map with a freehand circle (convert to Polygon)
② User selects the required time (30, 60, 90 minutes)
③ Display a walking route that passes through preset spots based on the specified range and time.

I was able to create a Polygon on the map in ①, but I don’t know how to implement ② and ③.

A predetermined spots has its latitude and longitude registered in a CSV file.

mongodb bulkWrites update behaves differently from normal update

I have a document with an order array that contains ids.
Sometimes I want to set specific indexes in that array:

db.getCollection('myCollection').update(
  {
    _id: 'someId',
  },
  {
    $set: {
      'order.1': 'foo2',
    },
  },
);

This works correcly and updates the second array element. If the array is empty, the 0th element is null.

Trying the same with bulkWrite leads to really weird behavior:

db.getCollection('myCollection').bulkWrite([
  {
    updateOne: {
      filter: { _id: 'eager' },
      update: [
        {
          $set: {
            'order.1': 'foo3',
          },
        },
      ],
    },
  },
]);

If the array in the db is empty this does nothing.
However, if there are elements in the array, this replaces every array element with an object of the form { '1': 'foo3' }.

Does anyone have any idea why this happens and how to make bulkWrite behave? 😀

Get nth position of the child component in React?

I have a PagesContainer component that renders multiple Page components like this:

<PagesContainer>
  <Page />
  <Page />
  <Page />
  <Page />
</PagesContainer>

I want each Page component to know its respective page number (e.g., 1, 2, 3, 4).

I preferably do not want to pass it down as a prop (e.g., <Page number={1} />) because I will be programatically generating some <Page /> through loops, but not all of them. I also want to be able to reorder these pages freely and have each render the right number just by moving its position in the parent.

Ideally, I’d like a hook like so: const currentPage = useGetCurrentPage().

How do I get the <Page />‘s position in the parent?

Finding non-shortest paths between two points

I am currently working on a new project that is somewhat inspired by Tower Defence games. My aim is to randomly generate a “map” where everything will take place. Just to visualise things, I am using a Canvas element.

There are four main components at this stage:

  • A start (red on the map)
  • An end (yellow on the map)
  • Walls that paths cannot go through (black)
  • Paths

I very specifically do not want the shortest possible path, otherwise I would be using one of the many algorithms designed with that in mind. I wrote some JavaScript to try and brute-force every possible path and then pick one of median length of the outcomes. This worked on small maps but caused my browser tab to hang on larger ones.

I added some optimisations:

  • Ending the recursion chain once a determined max length had been surpassed
  • Ending the search if a single path of a perfect length had been found (may make this ±1 or so)

However, I’m still brute-forcing, and it’s honestly not great.

Here is an example of a generated map. A lot of things aren’t final and there’s currently nothing stopping a map from generating will walls blocking any path from the start to end.
Example of a generated map

Here are some relevant snippets from my code:

const canvasWidth = 1920
const canvasHeight = 720
const cellSize = 30

const wallCount = 350

const horizontalCells = canvasWidth / cellSize
const verticalCells = canvasHeight / cellSize

const idealPathLength = horizontalCells * 1.5
const pathLengthCancelPoint = horizontalCells * 3

class Position {
    constructor(x, y) {
        this.x = x
        this.y = y
        this.adjacent = []
    }
    
    add(position) {
        if (position instanceof Position) {
            this.adjacent.push(position)
        }
    }
}

function generateGraph() {
    const N = []
    for (let x = 0; x < horizontalCells; x++) {
        for (let y = 0; y < verticalCells; y++) {
            N.push(new Position(x, y))
        }
    }
    
    const inBounds = (x, y) => x >= 0 && x < horizontalCells && y >= 0 && y < verticalCells
    const isStart = (x, y) => x === startPosition.x && y === startPosition.y
    const isWall = (x, y) => wallPositions.filter(wp => wp.x === x && wp.y === y).length > 0
    const f = (x, y) => N.find(p => p.x === x && p.y === y)
    
    for (let i = 0; i < N.length; i++) {
        const pos = N[i]
        const {x, y} = pos
        for (let xM = -1; xM <= 1; xM++) {
            for (let yM = -1; yM <= 1; yM++) {
                if (xM === yM || Math.abs(xM - yM) === 2) continue
                const newCoords = [x + xM, y + yM]
                if (inBounds(...newCoords) && !isWall(...newCoords) && !isStart (...newCoords)) {
                    pos.add(f(...newCoords))
                }
            }
        }
    }
    
    return N
}

function clone(arr) {
    return [...arr]
}

const N = generateGraph()
const startPosition = N.find(p => p.x === startPosition.x && p.y === startPosition.y)
const validPaths = []

let idealPathFound = false

function traverse(position, path) {
    if (position === undefined) {
        position = startPosition
    }
    if (path === undefined) {
        path = []
    }
    path.push(position)
    if (position.x === gatePosition.x && position.y === gatePosition.y) {
        validPaths.push(clone(path))
        console.log('Found valid path', path)
        if (validPaths.length === idealPathLength) {
            idealPathFound = true
        }
        return
    }
    if (idealPathFound || path.length >= pathLengthCancelPoint) {
        return
    }
    position.adjacent.forEach(p1 => {
        if (path.filter(p2 => p2.x === p1.x && p2.y === p1.y).length === 0) {
            traverse(p1, clone(path))
        }
    })
}

function findPath() {
    traverse()

    let deviation = 0
    let filteredPaths = []
    do {
        filteredPaths = validPaths.filter(path => path.length >= idealPathLength - deviation && path.length <= idealPathLength + deviation)
        deviation++
    } while (filteredPaths.length === 0)
    const sortedPaths = filteredPaths.sort((a, b) => a.length - b.length)
    const chosenPath = sortedPaths[Math.floor(sortedPaths.length / 2)]
    
    console.log(chosenPath)
    
    ctx.lineWidth = cellSize / 2
    ctx.strokeStyle = '#c99e87'
    
    const offset = cellSize / 2
    for (let i = 0; i < chosenPath.length - 1; i++) {
        let {x: x1, y: y1} = chosenPath[i]
        let {x: x2, y: y2} = chosenPath[i + 1]
        ctx.beginPath()
        ctx.moveTo(x1 * cellSize + offset, y1 * cellSize + offset)
        ctx.lineTo(x2 * cellSize + offset, y2 * cellSize + offset)
        ctx.stroke()
    }
}

Path finding isn’t something I’ve done before and I’m attempting to learn this as I go but this is obviously not the way to go about it.

Without getting the absolute shortest path (unless it’s the only path), what should I be doing here? Thanks in advance.

http HEAD request returns the prototype

My HTTP GET request works perfectly, returning body data and response headers. The exact same request with the extra paramter , { method: "HEAD" } as per the docs and response.header to console but it only returns the prototype of the headers not the response header. Server side I can see there was a sucessful HEAD request that was returned with a status 200.

async function getHead() {
    const url = document.getElementById('url').value;
    if(url.slice(0, 4) != 'http') {
        alert("URL must start with http or https!")
        document.getElementById("responseCode").innerHTML = "ERROR"
        document.getElementById("responseBody").innerHTML = ""
    };
    try {
        const response = await fetch(url, { method: "HEAD" });
        if (!response.ok) {
        throw new Error(`Response status: ${response.status}`);
    }

    console.log(response.headers.entries());
    document.getElementById("responseCode").innerHTML = response.status;
    document.getElementById("responseBody").innerHTML = JSON.stringify(json);
    } catch (error) {
        console.error(error.message);
        document.getElementById("responseBody").innerHTML = error.message;
    }
}

I’m expecting a response exactly the same as the GET fetch but without the body, but I’m just getting the prototype & constructor? Picture of the console:

enter image description here

Full HTML & JS here