How to do algorithms? [closed]

I want to do algorithmic analysis of an iPhone 16 how do I go about it

Um new to coding.i tried coding using js but I couldn’t debugSo I came to learn on algorithms and debugging.I hope this place would be of help.thank you!

Check for if a potentially primitive value has a given property

How do I check if a variable contains a certain property?

Let’s assume:

var x = 'some string';

Then I would like to do:

if ('trim' in x)

but that gives me a:

Uncaught TypeError: Cannot use 'in' operator to search for 'trim' in string

I can make it work by using:

'trim' in x.__proto__

but according to MDN __proto__ is deprecated and its use is (quote) “controversial and discouraged”.

How can I achieve this then?

I have tried to use Object.keys(x) but that only lists the keys that are valid as indexes, not the properties.

I know that, in this specific example, I could simply use typeof x === 'string' but that’s not a universal solution.

Time complexity of a BFS of a graph

I am unable to comprehend how the time complexity of the BFS of a graph is O(v+2E),
where V is the number of vertices and E being the number of edges.

/**
 * @param {number} V
 * @param {number[][]} adj
 * @returns {number[]}
*/
class Solution {
    // Function to return Breadth First Traversal of given graph.
    bfsOfGraph(V, adj) {
        const queue=new Queue();
        
        const visited=Array.from({length:V},()=>false);
        const ans=[];
        
        queue.add(0);
        visited[0]=true;

        
        while(!queue.isEmpty()){
            const el=queue.remove();
            ans.push(el);
            
            for(const v of adj[el]){
                if(!visited[v]){
                    queue.add(v);
                    visited[v]=true;
                }
            }
        }
        
        return ans;
    }
}


class Queue {
    constructor() {
        this.arr = [];
        this.start = 0;
        this.end = -1;
    }


    add(el) {
        this.arr.push(el);
        this.end++;
    }


    remove() {
        if (this.isEmpty())
            return;

        let el = this.arr[this.start];
        this.start++;

        return el;
    }

    isEmpty() {
        return this.start > this.end;
    }

    get length() {
        return this.end - this.start < 0 ? 0 : this.end - this.start + 1;
    }
}

In the above javascript implementation of the BFS of a graph, since the queue only holds the
vertices that haven’t been visited which makes the outer loop run for exactly V times and for each
vertex, we check if it’s neigbouring nodes have been visited by looking at the visited array, which in
itself is an O(1) operation. So, technically for each vertex we make O(1) operations equal to the degree
of that vertex. So, why isn’t the TC of the algorithm equal to O(V*avg. degree of a graph).

I tried everything but still don’t have a clue. I checked a similar question on stack overflow but it didn’t help.
Can someone explain me why it’s O(V+E) instead of O(V*avg. degree of graph).

CSS Custom Highlight API with underlined text on Safari

I’m working on a project where users can highlight content by selecting text and choosing a highlight style. I’m using the CSS Custom Highlight API, which is relatively new in terms of browser support. For my purposes, I only need to support recent versions of Safari and Chrome.

In the highlight API, highlights are created in JavaScript based on a range, then registered in CSS. They can then be styled using the ::highlight() pseudo-element. This is much easier than other methods of drawing highlights in HTML (such as hard-coding spans, programmatically traversing text nodes and inserting spans, or drawing absolutely-positioned rectangles behind the text) – especially when the highlight needs to continue through formatting tags and other elements.

When styling a highlight, the available set of CSS properties is limited. One option is underlining text with text-decoration and its related properties. This works great in Chrome, but I’m unable to get text-underline-offset and text-decoration-thickness to work with highlights in Safari. This makes the underline hard to see. Those properties work great when directly styling a span, but not when styling a highlight.

const span1 = document.getElementById('span-1');

range = document.createRange();
range.selectNodeContents(span1);

let h = new Highlight(range);
CSS.highlights.set('my-highlight', h);
body {
  margin: 1em 3em;
  font-size: 1.5em;
  line-height: 1.3em;
}

::highlight(my-highlight) {
  text-decoration: underline;
  text-decoration-color: yellowgreen;
  text-decoration-skip-ink: none;
  text-underline-offset: 0.1em;
  text-decoration-thickness: 0.2em;
}

#span-2 {
  text-decoration: underline;
  text-decoration-color: yellowgreen;
  text-decoration-skip-ink: none;
  text-underline-offset: 0.1em;
  text-decoration-thickness: 0.2em;
}
<p>This is a <b>paragraph</b> with many <i>text nodes,</i> <span id="span-1">which is <b>easy</b> to highlight in an <i>underline</i> style</span> thanks to the Highlight API.</p>
<p>This is another paragraph with <span id="span-2">directly underlined</span> text to compare.</p>

Chrome version 129 (what I want):
enter image description here

Safari version 18.0 (broken):
enter image description here

I’m assuming this is either a bug in Safari, or a feature that’s not fully implemented yet.

Is there a workaround that would allow me to get the style I want in Safari, within the bounds of the Custom Highlight API? Maybe some way to simulate an underline with a well-tuned text shadow or background color?

Editing a table using JavaScript using contentEditable attribute

After editing the data and clicking on the save changes button, the data is altered in the screen but it is not updated in the database

<?php

$con = mysqli_connect("localhost", "root", "", "myDB");

if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['data'])) {
    $data = json_decode($_POST['data'], true);
    
    foreach ($data as $row) {
        $vegName = htmlspecialchars($row['vegName']);
        $price = htmlspecialchars($row['price']);
        $isnew = $row['isnew'];
        $id = intval($row['id']); 

        if ($isnew === 'true') {
            $query = "INSERT INTO priceList (vegetable, price) VALUES (?, ?)";
            $stmt = mysqli_prepare($con, $query);
            if (!$stmt) {
                echo "Prepare failed: (" . mysqli_error($con) . ")"; 
                continue; 
            }
            mysqli_stmt_bind_param($stmt, "ss", $vegName, $price);
        } else {
            $query = "UPDATE priceList SET vegetable = ?, price = ? WHERE id = ?";
            $stmt = mysqli_prepare($con, $query);
            if (!$stmt) {
                echo "Prepare failed: (" . mysqli_error($con) . ")"; 
                continue; 
            }
            mysqli_stmt_bind_param($stmt, "ssi", $vegName, $price, $id);
        }

        if (!mysqli_stmt_execute($stmt)) {
            echo "Execute failed: (" . mysqli_stmt_error($stmt) . ")"; 
        } else {
            echo "Changes saved for $vegName!";
        }
        mysqli_stmt_close($stmt); 
    }
    
    exit; 
}

?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vegetable Price List</title>
    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
            padding: 10px;
            text-align: left;
        }
    </style>
</head>
<body style="background-color:#FAEBD7">
    <div>
    <h1>Vegetable Price List</h1>
    <table id="vegTable">
        <tr>
            <th>ID</th>
            <th>Vegetable</th>
            <th>Price</th>
        </tr>
        <?php 
        
        $sql = "SELECT vegetable, price, id FROM priceList"; 
        $result = mysqli_query($con, $sql);

        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                echo "<tr data-isnew='false'>
                        <td contenteditable='true'>" . htmlspecialchars($row["id"]) . "</td>
                        <td contenteditable='true' data-vegname='" . htmlspecialchars($row["vegetable"]) . "'>" . htmlspecialchars($row["vegetable"]) . "</td>
                        <td contenteditable='true'>" . htmlspecialchars($row["price"]) . "</td>
                      </tr>";
            }
        } else {
            echo "<tr><td colspan='3'>No vegetables found.</td></tr>";
        }
        ?>
    </table>
    <button type="button" onclick="saveChanges()">Save Changes</button>
    <button type="button" onclick="addRow()">Add Vegetable</button>

    <script>
        function saveChanges() {
            var table = document.getElementById('vegTable');
            var rows = table.getElementsByTagName('tr');
            var data = [];

            for (var i = 1; i < rows.length; i++) { 
                var vegName = rows[i].cells[1].getAttribute('data-vegname') || rows[i].cells[1].innerText;
                var price = rows[i].cells[2].innerText;
                var id = rows[i].cells[0].innerText;
                var isnew = rows[i].getAttribute('data-isnew') === 'true';
                data.push({ vegName: vegName, price: price, isnew: isnew, id: id });
            }

            console.log(JSON.stringify(data));

            var xhr = new XMLHttpRequest();
            xhr.open('POST', "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>", true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function () {
                alert(xhr.responseText);
            };
            xhr.send('data=' + JSON.stringify(data));
        }
        
        function addRow() {
            var table = document.getElementById('vegTable');
            var newRow = document.createElement("tr");
            newRow.setAttribute('data-isnew', 'true');

            var idCell = document.createElement('td');
            idCell.textContent = ""; 
            newRow.appendChild(idCell);

            var vegCell = document.createElement('td');
            vegCell.contentEditable = "true";
            vegCell.textContent = "";
            newRow.appendChild(vegCell);

            var priceCell = document.createElement("td");
            priceCell.contentEditable = "true";
            priceCell.textContent = "";
            newRow.appendChild(priceCell);

            table.appendChild(newRow);
        }
    </script>
    </div>
</body>
</html>

<?php

mysqli_close($con);
?>

I was trying to create a user friendly editable vegetable management system and failed. The issue is with the db since it not getting update once the table is edited and the save changes button is pressed.

How to resolve this Axios network error which seems to be a CORS error [closed]

When I fill register form I get an axios network error, this started happening after I began to use the CORS library,
I have the following files.

the following i m getting in network panel

register xhr register.jsx:24 0 B 2.37 s
register preflight Preflight 0 B 2.35 s

the following is the error when I use console.log(err.toJSON())

{message: ‘Network Error’, name: ‘AxiosError’, description: undefined, number: undefined, fileName: undefined, …}
code
:
“ERR_NETWORK”
columnNumber
:
undefined
config
:
{transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
description
:
undefined
fileName
:
undefined
lineNumber
:
undefined
message
:
“Network Error”
name
:
“AxiosError”
number
:
undefined
stack
:
“AxiosError: Network Errorn at XMLHttpRequest.handleError (http://localhost:5173/node_modules/.vite/deps/axios.js?v=b6b0c7b9:1634:14)n at Axios.request (http://localhost:5173/node_modules/.vite/deps/axios.js?v=b6b0c7b9:2156:41)n at async handleSubmit (http://localhost:5173/src/routes/register/register.jsx?t=1728282523152:34:19)”
status
:
undefined
[[Prototype]]
:
Object

the following is the error in the console:

AxiosError {message: ‘Network Error’, name: ‘AxiosError’, code: ‘ERR_NETWORK’, config: {…}, request: XMLHttpRequest, …} code : “ERR_NETWORK” config : {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : “Network Error” name : “AxiosError” request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} stack : “AxiosError: Network Errorn at XMLHttpRequest.handleError (http://localhost:5173/node_modules/.vite/deps/axios.js?v=b6b0c7b9:1634:14)n at Axios.request (http://localhost:5173/node_modules/.vite/deps/axios.js?v=b6b0c7b9:2156:41)n at async handleSubmit (http://localhost:5173/src/routes/register/register.jsx?t=1728273841083:34:19)” [[Prototype]] : Error constructor : ƒ AxiosError(message, code, config, request, response) toJSON : ƒ toJSON() isAxiosError : true [[Prototype]] : Object

This is my Register.jsx

import "./register.scss";
import { Link } from "react-router-dom";
import axios from "axios";
import { useState } from "react";
import { useNavigate } from "react-router-dom";

function Register() {
  const [error, setError] = useState("");

  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);

    const username = formData.get("username");
    const email = formData.get("email");
    const password = formData.get("password");

    try {
      const res = await axios.post(
        "http://localhost:8000/api/auth/register",
        {
          username,
          email,
          password,
        },
        { withCredentials: true },
      );
      /*navigate("/login")*/ console.log(res.data);
    } catch (err) {
      console.log(err);
      setError(err.response.data.message);
    }
  };
  return (
    <div className="register">
      <div className="formContainer">
        <form onSubmit={handleSubmit}>
          <h1>Create an Account</h1>
          <input name="username" type="text" placeholder="Username" />
          <input name="email" type="text" placeholder="Email" />
          <input name="password" type="password" placeholder="Password" />
          <button>Register</button>
          {error && <span>{error}</span>}
          <Link to="/login">Do you have an account?</Link>
        </form>
      </div>
      <div className="imgContainer">
        <img src="/bg.png" alt="" />
      </div>
    </div>
  );
}

export default Register;

This is my app.js

import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import { postRoute } from "./routes/post.route.js";
import authRoute from "./routes/auth.route.js";

const app = express();

app.use(
  cors({
    origin: process.env.CLIENT_URL, // Make sure this matches the frontend URL
    credentials: true,
    methods: ["GET", "POST", "PUT", "DELETE"],
  }),
);

app.use(express.json());
app.use(cookieParser());

app.use("/api/posts", postRoute);
app.use("/api/auth", authRoute);

app.listen(8000, () => {
  console.log("server is running");
});

This is my .env file

CLIENT_URL = http://localhost:5173

This is the auth.controller.js

import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import prisma from "../lib/prisma.js";

export const register = async (req, res) => {
  const { username, email, password } = req.body;

  try {
    //Hash the pw

    const hashedPassword = await bcrypt.hash(password, 10);
    //create new user

    //save it to db

    const newUser = await prisma.user.create({
      data: {
        username,
        email,
        password: hashedPassword,
      },
    });

    console.log(newUser);

    res.status(201).json({ message: "User Created Successfully" });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "Failed to Create User!" });
  }
};

export const login = async (req, res) => {
  const { username, password } = req.body;

  try {
    //check if user exists
    const user = await prisma.user.findUnique({
      where: { username },
    });

    if (!user) return res.status(401).json({ message: "Invalid Credentials!" });
    //check if the password is correct
    const isPasswordValid = await bcrypt.compare(password, user.password);

    if (!isPasswordValid)
      return res.status(401).json({ message: "Invalid Credentials!" });
    //Generate cookie token and send to the user
    //res.setHeader("Set-Cookie", "test=" + "myValue").json("success")
    const age = 1000 * 60 * 60 * 24 * 7;

    const token = jwt.sign(
      {
        is: user.id,
      },
      process.env.JWT_SECRET_KEY,
      { expiresIn: age },
    );

    res
      .cookie("token", token, {
        httpOnly: true,
        //secure:true,
        maxAge: age,
      })
      .status(200)
      .json({ message: "Login Successful!" });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "Failed to Logion" });
  }
};

export const logout = (req, res) => {
  res.clearCookie("token").status(200).json({ message: "Logout Successful" });
};

When I fill out the form I want “User logged in successfully” in the console, however, I am getting an axios error, please help me if you know what should be corrected.

editing a table using javasctipt using contentEditable attribute

After editing the data and clicking on the save changes button, the data is altered in the screen but it is not updated in the database

<?php

$con = mysqli_connect("localhost", "root", "", "myDB");

if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['data'])) {
    $data = json_decode($_POST['data'], true);
    
    foreach ($data as $row) {
        $vegName = htmlspecialchars($row['vegName']);
        $price = htmlspecialchars($row['price']);
        $isnew = $row['isnew'];
        $id = intval($row['id']); 

        if ($isnew === 'true') {
            $query = "INSERT INTO priceList (vegetable, price) VALUES (?, ?)";
            $stmt = mysqli_prepare($con, $query);
            if (!$stmt) {
                echo "Prepare failed: (" . mysqli_error($con) . ")"; 
                continue; 
            }
            mysqli_stmt_bind_param($stmt, "ss", $vegName, $price);
        } else {
            $query = "UPDATE priceList SET vegetable = ?, price = ? WHERE id = ?";
            $stmt = mysqli_prepare($con, $query);
            if (!$stmt) {
                echo "Prepare failed: (" . mysqli_error($con) . ")"; 
                continue; 
            }
            mysqli_stmt_bind_param($stmt, "ssi", $vegName, $price, $id);
        }

        if (!mysqli_stmt_execute($stmt)) {
            echo "Execute failed: (" . mysqli_stmt_error($stmt) . ")"; 
        } else {
            echo "Changes saved for $vegName!";
        }
        mysqli_stmt_close($stmt); 
    }
    
    exit; 
}

?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vegetable Price List</title>
    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
            padding: 10px;
            text-align: left;
        }
    </style>
</head>
<body style="background-color:#FAEBD7">
    <div>
    <h1>Vegetable Price List</h1>
    <table id="vegTable">
        <tr>
            <th>ID</th>
            <th>Vegetable</th>
            <th>Price</th>
        </tr>
        <?php 
        
        $sql = "SELECT vegetable, price, id FROM priceList"; 
        $result = mysqli_query($con, $sql);

        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                echo "<tr data-isnew='false'>
                        <td contenteditable='true'>" . htmlspecialchars($row["id"]) . "</td>
                        <td contenteditable='true' data-vegname='" . htmlspecialchars($row["vegetable"]) . "'>" . htmlspecialchars($row["vegetable"]) . "</td>
                        <td contenteditable='true'>" . htmlspecialchars($row["price"]) . "</td>
                      </tr>";
            }
        } else {
            echo "<tr><td colspan='3'>No vegetables found.</td></tr>";
        }
        ?>
    </table>
    <button type="button" onclick="saveChanges()">Save Changes</button>
    <button type="button" onclick="addRow()">Add Vegetable</button>

    <script>
        function saveChanges() {
            var table = document.getElementById('vegTable');
            var rows = table.getElementsByTagName('tr');
            var data = [];

            for (var i = 1; i < rows.length; i++) { 
                var vegName = rows[i].cells[1].getAttribute('data-vegname') || rows[i].cells[1].innerText;
                var price = rows[i].cells[2].innerText;
                var id = rows[i].cells[0].innerText;
                var isnew = rows[i].getAttribute('data-isnew') === 'true';
                data.push({ vegName: vegName, price: price, isnew: isnew, id: id });
            }

            console.log(JSON.stringify(data));

            var xhr = new XMLHttpRequest();
            xhr.open('POST', "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>", true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function () {
                alert(xhr.responseText);
            };
            xhr.send('data=' + JSON.stringify(data));
        }
        
        function addRow() {
            var table = document.getElementById('vegTable');
            var newRow = document.createElement("tr");
            newRow.setAttribute('data-isnew', 'true');

            var idCell = document.createElement('td');
            idCell.textContent = ""; 
            newRow.appendChild(idCell);

            var vegCell = document.createElement('td');
            vegCell.contentEditable = "true";
            vegCell.textContent = "";
            newRow.appendChild(vegCell);

            var priceCell = document.createElement("td");
            priceCell.contentEditable = "true";
            priceCell.textContent = "";
            newRow.appendChild(priceCell);

            table.appendChild(newRow);
        }
    </script>
    </div>
</body>
</html>

<?php

mysqli_close($con);
?>

I was trying to create a user friendly editable vegetable management system and failed. The issue is with the db since it not getting update once the table is edited and the save changes button is pressed.

How to resolve this Axios network error which seems to be a CORS error

When I fill register form I get an axios network error, this started happening after I began to use the CORS library,
I have the following files. the following is the error in the console:

AxiosError {message: ‘Network Error’, name: ‘AxiosError’, code: ‘ERR_NETWORK’, config: {…}, request: XMLHttpRequest, …} code : “ERR_NETWORK” config : {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : “Network Error” name : “AxiosError” request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} stack : “AxiosError: Network Errorn at XMLHttpRequest.handleError (http://localhost:5173/node_modules/.vite/deps/axios.js?v=b6b0c7b9:1634:14)n at Axios.request (http://localhost:5173/node_modules/.vite/deps/axios.js?v=b6b0c7b9:2156:41)n at async handleSubmit (http://localhost:5173/src/routes/register/register.jsx?t=1728273841083:34:19)” [[Prototype]] : Error constructor : ƒ AxiosError(message, code, config, request, response) toJSON : ƒ toJSON() isAxiosError : true [[Prototype]] : Object

This is my Register.jsx

import "./register.scss";
import { Link } from "react-router-dom";
import axios from "axios";
import { useState } from "react";
import { useNavigate } from "react-router-dom";

function Register() {
  const [error, setError] = useState("");

  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);

    const username = formData.get("username");
    const email = formData.get("email");
    const password = formData.get("password");

    try {
      const res = await axios.post(
        "http://localhost:8000/api/auth/register",
        {
          username,
          email,
          password,
        },
        { withCredentials: true },
      );
      /*navigate("/login")*/ console.log(res.data);
    } catch (err) {
      console.log(err);
      setError(err.response.data.message);
    }
  };
  return (
    <div className="register">
      <div className="formContainer">
        <form onSubmit={handleSubmit}>
          <h1>Create an Account</h1>
          <input name="username" type="text" placeholder="Username" />
          <input name="email" type="text" placeholder="Email" />
          <input name="password" type="password" placeholder="Password" />
          <button>Register</button>
          {error && <span>{error}</span>}
          <Link to="/login">Do you have an account?</Link>
        </form>
      </div>
      <div className="imgContainer">
        <img src="/bg.png" alt="" />
      </div>
    </div>
  );
}

export default Register;

This is my app.js

import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import { postRoute } from "./routes/post.route.js";
import authRoute from "./routes/auth.route.js";

const app = express();

app.use(
  cors({
    origin: process.env.CLIENT_URL, // Make sure this matches the frontend URL
    credentials: true,
    methods: ["GET", "POST", "PUT", "DELETE"],
  }),
);

app.use(express.json());
app.use(cookieParser());

app.use("/api/posts", postRoute);
app.use("/api/auth", authRoute);

app.listen(8000, () => {
  console.log("server is running");
});

This is my .env file

CLIENT_URL = http://localhost:5173

This is the auth.controller.js

import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import prisma from "../lib/prisma.js";

export const register = async (req, res) => {
  const { username, email, password } = req.body;

  try {
    //Hash the pw

    const hashedPassword = await bcrypt.hash(password, 10);
    //create new user

    //save it to db

    const newUser = await prisma.user.create({
      data: {
        username,
        email,
        password: hashedPassword,
      },
    });

    console.log(newUser);

    res.status(201).json({ message: "User Created Successfully" });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "Failed to Create User!" });
  }
};

export const login = async (req, res) => {
  const { username, password } = req.body;

  try {
    //check if user exists
    const user = await prisma.user.findUnique({
      where: { username },
    });

    if (!user) return res.status(401).json({ message: "Invalid Credentials!" });
    //check if the password is correct
    const isPasswordValid = await bcrypt.compare(password, user.password);

    if (!isPasswordValid)
      return res.status(401).json({ message: "Invalid Credentials!" });
    //Generate cookie token and send to the user
    //res.setHeader("Set-Cookie", "test=" + "myValue").json("success")
    const age = 1000 * 60 * 60 * 24 * 7;

    const token = jwt.sign(
      {
        is: user.id,
      },
      process.env.JWT_SECRET_KEY,
      { expiresIn: age },
    );

    res
      .cookie("token", token, {
        httpOnly: true,
        //secure:true,
        maxAge: age,
      })
      .status(200)
      .json({ message: "Login Successful!" });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "Failed to Logion" });
  }
};

export const logout = (req, res) => {
  res.clearCookie("token").status(200).json({ message: "Logout Successful" });
};

When I fill out the form I want “User logged in successfully” in the console, however, I am getting an axios error, please help me if you know what should be corrected.

How to Auto Login Power BI HTML Static Application

How to Login automatically the PowerBI embedded using LDAP (active directory) credentials.
Using Power BI JavaScript API. I am using below embed code. (Iframe embedding)
I want to avoid Login button and popup.

url = "https://app.powerbi.com/reportEmbed?reportId=GUID&autoAuth=true&ctid=GUID"

document.write(
    "<iframe class='hero' title='Power BI Dashboard' id='myiframe'  src='"+ url +"' frameborder='0' allowFullScreen='true'></iframe>"
  )
  

enter image description here

unable to update array without updating other array inside of graalvm

why is this updating two arrays at once when I only updated one?

I tried the spread operator when setting the arrays from the original array.
I tried doing a for loop and populating the array separately.
not sure whats going on.

I didnt see a stack overflow with graalvm and arrays not copying.
chatgpt/claude dont know either

code1:

    s.print("sys_imported_saved_configuration_id: " + sys_imported_saved_configuration_id);
                            const sys_imported_saved_configuration_data = new SysRecord({
                                sys_table_name: 'sys_imported_saved_configuration_data',
                                where: [
                                    [{
                                        "sys_column": "sys_imported_saved_configuration_id",
                                        "sys_operator": "=",
                                        "sys_value": sys_imported_saved_configuration_id
                                    }]
                                ],
                                select_columns: ['sys_id', 'sys_data', 'sys_operation']
                            });

                            const is_data_available = await sys_imported_saved_configuration_data.query();

code2:


class SysRecord {
    constructor({ sys_table_name, select_columns = null, where = null, where_sys_id = null, sort_column = null, sort_direction = null }) {
        this.sys_table_name = sys_table_name;
        this.select_columns = select_columns || [];
        this.where = where || {};
        this.where_sys_id = where_sys_id;
        this.sort_column = sort_column;
        this.sort_direction = sort_direction;
        this.results = [];
        this.currentIndex = -1;
        this.originalResults = []; // To track the original records
    }



    toMap() {
        const queryParams = {};
        if (this.sys_table_name) queryParams['sys_table_name'] = this.sys_table_name;
        if (this.select_columns.length > 0) queryParams['select_columns'] = JSON.stringify(this.select_columns);
        if (Object.keys(this.where).length > 0) queryParams['where'] = JSON.stringify(this.where);
        if (this.where_sys_id) queryParams['where_sys_id'] = this.where_sys_id;
        if (this.sort_column) queryParams['sort_column'] = this.sort_column;
        if (this.sort_direction) queryParams['sort_direction'] = this.sort_direction;
        return queryParams;
    }

    async query() {
        s.print("nnquery()");
        // Check and add sys_id and sys_table_name to select_columns if not present
        if (!this.select_columns.includes('sys_id')) {
            this.select_columns.push('sys_id');
        }
        if (!this.select_columns.includes('sys_table_name')) {
            this.select_columns.push('sys_table_name');
        }

        // Execute the query
        const records = await s.get(this.toMap());
        s.print("RECORDS: "+records);

        for( var record of records){
            s.print("record: "+record);

              this.originalResults.push(record);
              this.results.push(record);

        }


//                    this.originalResults = [...records];
//                    this.results = [...records];

        s.print("originalResults: "+this.originalResults);
        s.print("results: "+this.results);


//        this.originalResults = [...records];
//        this.results = [...records];


        this.currentIndex = 0;

        this.set('sys_create',true);


               s.print("noriginalResults2: "+this.originalResults);
                s.print("results2: "+this.results);


//                    s.print("updated data20: "+this.results[this.currentIndex]);
//                    s.print("originalResults20: "+JSON.stringify(this.originalResults[this.currentIndex]));
//                    s.print("");

        return this.results.length > 0;
    }


    get(fieldName) {
        if (this.currentIndex >= 0 && this.currentIndex < this.results.length) {
            return this.results[this.currentIndex][fieldName];
        }
        return null;
    }

    set(fieldName, value) {
//        s.print("set called with "+fieldName+" :: "+value+ " at index = "+this.currentIndex);
        if (this.currentIndex >= 0 && this.currentIndex < this.results.length) {

            this.results[this.currentIndex][fieldName] = value;
        }
    }

}

Web Components custom parsedCallback method is not working

Important NOTE: almost all IDEs will defer the execution of javascript automatically which means you might not be able to replicate this issue using them

When working with the Web Components API in a scenario where the script defining the component executes before the documents HTML is parsed, you end up with the unfortunate issue that the element’s innerHTML will not yet be parsed during the native connectedCallback lifecycle method. This is because the method executes on the opening tag of the custom element before parsing of its children has begun.

<script>
  customElements.define('my-element', MYElement);
</script>
<my-element>
  <span>Content</span>
</my-element>

In order to fix this, I wish to implement my own parsedCallback method, however, what I have so far is not working.

The idea is that because the browser will parse the HTML synchronously, we can know that everything inside the component is done parsing as soon a “younger” sibling element is parsed.

Therefore, I am adding a mutation observer to the parent element of the component in order to listen to when a new child node, which is not the component itself, has been added.

Furthermore, because it could be there are no “natural” siblings in the markup, I also append a commentNode after the component to ensure it always works.

class MYElement extends HTMLElement {

    static counter = 0;

    constructor() {
        super();
        this._id = MYElement.counter++;
    }

    connectedCallback() {
        console.log(`${this._id} connected`);
        console.log(`${this._id} has innerHTML on connected = ${this.innerHTML !== ""}`);
        const parent = this.parentElement;
        const marker = document.createComment(this._id);
        const observer = new MutationObserver((mutations) => {
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node !== this) {
                        console.log(`${this._id} younger sibling detected`);
                        this.parsedCallback();
                        marker.remove();
                        observer.disconnect();
                    }
                });
            });
        });
        observer.observe(parent, { childList: true });
        parent.appendChild(marker);
    }

    parsedCallback() {
        console.log(`${this._id} parsed`);
        console.log(`${this._id} has innerHTML on parsed = ${this.innerHTML !== ""}`);
    }
}

My expected output would of course be

0 connected
0 has innerHTML on connected = false
0 younger sibling detected
0 parsed
0 has innerHTML on parsed = true

However, instead I am seeing the same except for the last console log being:

0 has innerHTML on parsed = false

react-query useMutation does not update new changes on the UI

I have a React 18 app. I am using @tanstack/react-query, version 5 for state management.

Firstly, when I click the like button, my UI does not change. Typical behavior should be that the number of likes should increase by one.

clicking like button does not update ui

Secondly, when I reload my page I get the below errors in my browser console and my browser view is blank.

error on reload

Not sure, what I am doing wrong here.

Below is my code:

App.jsx file:

import { useState } from "react";
import MenuBar from "./components/MenuBar";
import Notification from "./components/Notification";
import BlogsPage from "./pages/BlogsPage";
import LoginPage from "./pages/LoginPage";
import UsersPage from "./pages/UsersPage";
import { Route, Routes, useMatch } from "react-router-dom";
import User from "./components/User";
import { useQueryClient } from "@tanstack/react-query";
import Blog from "./components/Blog";

const App = () => {
  const queryClient = useQueryClient();
  const allBlogs = queryClient.getQueryData(['blogs']);
  const allUsers = queryClient.getQueryData(['users']);

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const userMatch = useMatch("/users/:id");
  console.log('userMatch', userMatch);
  const singleUserInfo = userMatch
    ? allUsers.find(user => user.id === userMatch.params.id)
    : null;
  console.log('singleUserInfo', singleUserInfo);

  const blogMatch = useMatch("/blogs/:id");
  console.log('blogMatch', blogMatch);
  const singleBlogInfo = blogMatch
    ? allBlogs.find(blog => blog.id === blogMatch.params.id)
    : null;
  console.log('singleBlogInfo', singleBlogInfo);

  return (
    <div>
      <h1>Blogs App</h1>

      <MenuBar setUsername={setUsername} setPassword={setPassword} />

      <Notification />

      <LoginPage 
        username={username} 
        password={password} 
        setUsername={setUsername} 
        setPassword={setPassword} 
      />

      <Routes>
        <Route path="/users/:id" element={<User user={singleUserInfo} />} />
        <Route path="/blogs/:id" element={<Blog blog={singleBlogInfo} />} />
        <Route path="/users" element={<UsersPage />} />
        <Route path="/" element={<BlogsPage />} />
      </Routes>
    </div>
  );
};

export default App;

Blog.jsx file:

import PropTypes from "prop-types";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNotificationDispatch } from "../context/NotificationContext";
import blogService from "../services/blogs";
import { removeNotificationAfterFiveSeconds, setNotification } from "../helper/notificationSetOrRemove";
import { useUserValue } from "../context/UserContext";
import { Link } from "react-router-dom";

const Blog = ({ blog }) => {
  console.log('Blog.jsx', blog);

  const queryClient = useQueryClient();
  const notificationDispatch = useNotificationDispatch();
  const userLoggedIn = useUserValue();
  
  const updateBlogMutation = useMutation({
    mutationFn: blogService.updateBlog,
    // mutationFn: (blog) => blogService.updateBlog(blog),
    onSuccess: (updatedBlog) => {
      // queryClient.invalidateQueries('blogs');
      queryClient.invalidateQueries({ queryKey: ['blogs'] }, updatedBlog);
    },
    onError: (error, blogData) => {
      console.error(`UPDATE MUTATION ERROR: ${error.message}`);
      setNotification(notificationDispatch, `UPDATE MUTATION ERROR: Blog '${blogData.title}' was already removed from server`, true);
      removeNotificationAfterFiveSeconds(notificationDispatch);
    }
  });

  const handleIncreaseLikes = () => {
    updateBlogMutation.mutate({ ...blog, likes: blog.likes + 1 });
  };

  return (
    <div>
      <h1 data-testid="title">{blog.title}</h1>
      <h4 data-testid="author">Author: {blog.author}</h4>

      <div data-testid="url">
        <Link to={blog.url} target="_blank">{blog.url}</Link>
      </div>

      <div>
        <div>
          <div>
            <span data-testid="likes">Likes: {blog.likes}</span>
            <button onClick={handleIncreaseLikes} className="likeBtn">
              like
            </button>
          </div>

          <div data-testid="addedBy">Added by: {blog.user.name}</div>
        </div>
      </div>
    </div>
  );
};

Blog.propTypes = {
  blog: PropTypes.shape({
    id: PropTypes.string,
    title: PropTypes.string.isRequired,
    author: PropTypes.string.isRequired,
    url: PropTypes.string.isRequired,
    likes: PropTypes.number,
    user: PropTypes.shape({
      id: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
      username: PropTypes.string.isRequired,
    }),
  }),
};

export default Blog;

/src/services/blogs.js file:

import axios from 'axios';
const baseUrl = '/api/blogs';

const updateBlog = async (updatedBlog) => {
  const response = await axios.put(`${baseUrl}/${updatedBlog.id}`, updatedBlog);
  return response.data;
};

export default { updateBlog };

Owl carousel show double image in items:1 responsive view settings

owl carousel not working on mobile view or responsive settings items:1

<div class="owl-carousel owl-theme pt-16 xxl:pt-20 h-full" id="carousel8">
   <div class="group flex justify-around items-center centerwrap">
     <div class="centerwidth">
        <Img class="object-cover w-full" src="images/car/carslide1.png"></Img>
     </div>
     /* other content stuff */         
   </div>
   <div class="group flex justify-around items-center centerwrap">
     <div class="centerwidth">
        <Img class="object-cover w-full" src="images/car/carslide1.png"></Img>
     </div>
     /* other content stuff */         
   </div>
   <div class="group flex justify-around items-center centerwrap">
     <div class="centerwidth">
        <Img class="object-cover w-full" src="images/car/carslide1.png"></Img>
     </div>
     /* other content stuff */         
   </div>
</div>

owl-item.center centerwrap given height 50rem , owl-item .centerwidth image container width given 50% owl-item.center .centerwidth given 100% width .. everythings fine but when , items:1 configuration gives in mobile view it show double image like provided image example..
example image
trying to understand or solve problems