Cannot access ‘id’ from debugger

I’m building React app and I’ve got an error “Cannot access ‘id’ from deugger” but I have no idea from where it comes. Here is how the error looks like:

enter image description here

And here is how the code menu-button look like:

enter image description here

Does anyone have an idea to what it might be related?

Google Chrome is consuming a lot of CPU on a video call?

We’ve been running a video application in a web browser and we are facing quite a lot complaints about the performance of the video calls.

90% of the complaints are when the user uses a virtual background and we use a library for that and it uses WebGL2 for the rendering.

We’ve performed the following options to debug the problem.

  • Capturing a performance profile and we saw some long running tasks.
  • Enabling the performance monitor to see the CPU consumption on the specific chrome tab which was running the video call and we sometimes see it’s more than 90% but on the system level it’s not.
  • Enabling hardware acceleration.

We figured out that there is some issue with the library that we use but I want to workaround the problem in some way, until there is a fix available.

I’m also not quite sure if chrome does some resource saving within the tabs to not bombard the CPU usage on system level.

My question here is: Can we somehow workaround this problem by letting the chrome tab use more CPU when a specific tab is running a video call?

Or maybe some other approach which can improve the performance?

Any help would be greatly appreciated!

How to delay a function that finishes when event is triggered

I need to await the func1 that is finished only when transitionend event is triggered. I can calculate the time when the event will be triggered, but there has to be a better way of doing this

Simplified code:

function func1() {
    document.getElementById("div1").classList.add("rotate")

    function transitionEndHandler() {
        document.getElementById("div1").removeEventListener("transitionend", transitionEndHandler)
        //stuff
    }
    document.getElementById("div1").addEventListener("transitionend", transitionEndHandler)
}

func1()
//code that should run after the transition is done

CSS:

.div {
  position: absolute;
  width: 150px;
  height: 10px;
  opacity: 1;
  transition: 2s;
}
.rotate {
  transform-origin: center;
  transform: rotateY(-180deg);
}

I tried using promises, but since the func1 can’t return anything when the transitionend event is handled i dont know how to implement them here

V8 and big string comparison performance affected a lot by hashing the strings?

Context: I was building a piece of the back end in node end and optimizing for bandwidth. Basically I was trying to not send thumbnails (stored as 10KiB strings) that the client already had and yada yada, for a brief time I resorted to comparing the thumbnail data directly since I couldn’t be sure whether they had been updated but have moved to a different solution since. This is just a curiosity and bears no real relevance anymore.

Okay so I’ve discovered this behaviour by V8 where large string comparisons are slow by default but upon (presumably) hashing these strings, for instance by sticking them into a Set, the comparisons speed up a lot. I’ve confirmed this to be happening in both node as well as the chromium based electron front end.

Example:

    (()=>{
        //  making 10k character strings
        const big_strings = [];
        const palette = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        for (let i = 0; i < 100; i++) {
            let big_string = "";
            for (let i = 0; i < 10_000; i++) {
                big_string += palette[Math.floor(Math.random() * palette.length)];
            }
            big_strings.push(big_string);
        }

        //  comparison functions
        function cmp1(a, b) {
            return a === b;
        }

        function cmp2(a, b) {
            const lol = new Set();
            lol.add(a);
            lol.add(b);
            return a === b;
        }

        //  tests
        let sorted_1, sorted_2;

        console.time("Test 1");
        for (let i = 0; i < 100; i++) {
            sorted_1 = big_strings.slice();
            sorted_1.sort(cmp1);
        }
        console.timeEnd("Test 1");

        console.time("Test 1");
        for (let i = 0; i < 100; i++) {
            sorted_1 = big_strings.slice();
            sorted_1.sort(cmp1);
        }
        console.timeEnd("Test 1");

        console.time("Test 1");
        for (let i = 0; i < 100; i++) {
            sorted_1 = big_strings.slice();
            sorted_1.sort(cmp1);
        }
        console.timeEnd("Test 1");

        console.time("Test 2");
        for (let i = 0; i < 100; i++) {
            sorted_2 = big_strings.slice();
            sorted_2.sort(cmp2);
        }
        console.timeEnd("Test 2");

        console.time("Test 1");
        for (let i = 0; i < 100; i++) {
            sorted_1 = big_strings.slice();
            sorted_1.sort(cmp1);
        }
        console.timeEnd("Test 1");

        //  sanity check
        let good = 0;
        const total = Math.max(sorted_1.length, sorted_2.length);
        for (let i = 0; i < total; i++) {
            if (sorted_1[i] === sorted_2[i]) {
                good++;
            } else {
                throw("Results do not match.");
            }
        }
        console.log(`Sanity check OK ${good} / ${total}`);


    })();

In the example, there are two comparison functions, one that simply does a === b and another that first sticks both a and b into a disposable Set. I can run tests with the first comparison function as many times as I like (3 in this example) and it will always be slow. Then I run the test with the second comparison function just once and afterwards, all tests on those particular strings will be blazing fast.

What gives with such behaviour? Why won’t V8 hash the strings itself in the background?

How to get to write query on Express.js and mysql2?

I’m in the process of creating a server using Express and MySQL.

Problem: When I send a select query with PK, data is received, but when I search by a different column, like ‘name’, no data is retrieved.

Problematic Query: SELECT * FROM item WHERE name = ?
Working Query: SELECT * FROM item WHERE id = ?

Attempts:

Checked if the query works in the DB => Both queries work fine.

Tried using backticks for the ‘name’ inside the execute statement => Didn’t work.

Checked if parameters are being passed correctly => Parameters are being passed.

Code:
item.repository.js

import { DatabaseConnection } from '../db.js';

export class ItemsRepository {
  connection;

  constructor() {
    this.connection = new DatabaseConnection().getConnection();
  }

  getItems = async () => {
    const [allItems] = await this.connection.execute('SELECT * FROM item');
    return allItems;
  };

  getItemById = async id => {
    const [row] = await this.connection.execute(
      'SELECT * FROM item WHERE id = ?',
      [id],
    );
    return row[0];
  };

  getItemByName = async name => {
    const findByNameItem = await this.connection.execute(
      'SELECT * FROM item WHERE name = ?',
      [name],
    );
    return findByNameItem;
  };

  getItems = async type => {
    if (type === 'all') {
      const [result] = await this.connection.execute('SELECT * FROM item');
      return result;
    } else {
      const [findByTypeItems] = await this.connection.execute(
        'SELECT * FROM item WHERE `type` = ?',
        [type],
      );
      return findByTypeItems;
    }
  };
}

place.order.items.service.js

import { PlaceOrderItemsRepository } from '../repository/place.order.items.repository';
import { ItemsRepository } from '../repository/items.repository';
import { Messages } from '../error/messages';
import { ValidationCheck } from '../utils/validationCheck';
import orderItemState from '../constants/orderItemState.js';

export class PlaceOrderItemsService {
  _placeOrderItemsRepository = new PlaceOrderItemsRepository();
  _itemRepo = new ItemsRepository();

  create = async (name, amount) => {
    if (!name) {
      return {
        code: 400,
        message: Messages.WrongName,
      };
    }
    if (!amount || amount <= 0) {
      return {
        code: 400,
        message: Messages.WrongAmount,
      };
    }
    const findItem = await this._itemRepo.getItemByName(name);
    if (!findItem) {
      return {
        code: 400,
        message: Messages.NoneExist,
      };
    }
    return {
      code: 200,
      data: await this._placeOrderItemsRepository.create(
        findItem.id,
        amount,
        orderItemState.ordered,
      ),
    };
  };
}

Error Message:

Error: Bind parameters must not contain undefined. To pass SQL NULL specify JS null
.... {
code: undefined,
errno: undefined,
sql: undefined,
sqlState: undefined,
sqlMessage: undefined
}

Environment: Express, mysql2, Not using ORM”

If you happen to know a solution, please let me know. Thank you.

I want to know why the query isn’t being sent to the database.

Google Appscript insert column in array

I’d like to know how to insert a column into an array. I know the push function to add a row but not how to add a column like that:

A ; 1
B ; 2
C ; 3
D ; 4

To:

A ; A1 ; 1
B ; B2 ; 2
C ; C3 ; 3
D ; D4 ; 4

I guess I will have to loop between each row to add an item between two item but is there a way to do it as a bulk?

Perspective Scrolling Effect (Three Instances)

I have this perspective scrolling effect and I want to make three instances of it.
Each of the instances ultimately will have different content. And each instance would be in a modal popup.

The modal popup should be triggered by a link and they’re closeable by an ‘x’ in the corner, and the key ESC. Ideally i would like to avoid bootstrap.

CSS

const dom = {
    container: document.getElementById('container'),
    perspective: document.getElementById('perspective'),
    zoom: document.getElementById('zoom')
};

const totalScrollDistance = 10000; // Scroll distance to reach max zoom
const maxZoomDistance = 40000; // Maximum depth of images, based on what you've set in CSS
let looping = false;

dom.container.style.height = `${totalScrollDistance}px`;

window.addEventListener('scroll', update);

function update() {
    // Check if we are waiting for a frame to render
    if (!looping) {
        looping = true;
        raf(zoom);
    }
}

function zoom() {
    const rect = dom.container.getBoundingClientRect(); // Get bounding rect of container, .top is relative to top of viewport

    if (rect.top <= 0 && rect.top > -rect.height) { // Update zoom only when container is in viewport 
        dom.perspective.classList.add('perspective--is-fixed');

        const scrollPos = -rect.top; // Get scroll position relative to zoom container
        const progress = scrollPos / (totalScrollDistance - window.innerHeight); // Turn this into a number between 0 and 1 (0 is when top of zoom container is at top of viewport, 1 is when bottom of zoom container is at bottom of viewport)

        dom.zoom.style.transform = `translate3d(0, 0, ${progress * maxZoomDistance}px)`; // Apply transform
    } else {
        dom.perspective.classList.remove('perspective--is-fixed');
    }

    looping = false;
}

// Runs callback on next available animation frame
function raf(cb) {
    const raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (cb) { window.setTimeout(cb, 1000 / 60); };

    raf.call(window, () => {
        return cb();
    });
}
html,body,address,blockquote,div,form,fieldset,caption,h1,h2,h3,h4,h5,h6,hr,ul,li,ol,ul,dl,dt,dd,table,tr,td,th,p,img{margin:0;padding:0}
html{width:100%;height:100%;overflow-x:hidden}
body{font-family:'Times';position:relative;width:100%;min-height:100%;color:#272935;padding:0;margin:0}
body::before,body::after{display:flex;justify-content:center;width:100%;height:25vh;color:#000}
html{overflow:none;overflow-x:hidden;scroll-behavior:smooth;scrollbar-width:none}
::-webkit-scrollbar{width:0;background:transparent}
::-webkit-scrollbar-thumb{background:red}
*,:before,:after{box-sizing:border-box}
.container{position:relative;overflow:hidden}
.perspective{width:100vw;height:100vh;background:none;position:fixed;perspective:200px}
.perspective--is-fixed{position:fixed;top:0;left:0}
.caption{color:#000;font-size:1rem;text-align:center;padding-top:20px}
p{color:#000;text-align:left;}
.zoom{width:100%;height:100%;transform-style:preserve-3d}
video{position:relative;width:45%;box-shadow:26px 33px 121px 0 rgba(119,0,0,0.4)}
img{position:relative;width:45%;box-shadow:26px 33px 121px 0 rgba(119,0,0,0.4)}
.right{float:right}
.image{position:absolute;text-align:center}
.image:nth-child(1){width:100vw;height:100vh;transform:translate3d(1vw,1vh,-200px)}
.image:nth-child(2){width:100vw;height:100vw;transform:translate3d(2vw,6vh,-1700px)}
.image:nth-child(3){width:100vw;height:100vw;transform:translate3d(0vw,6vh,-3723px)}
.image:nth-child(4){width:100vw;height:100vw;transform:translate3d(7vw,13vh,-4835px)}
.image:nth-child(5){width:100vw;height:100vw;transform:translate3d(10vw,-1vh,-6791px)}
<div class="container" id="container">
  <div class="perspective" id="perspective">
    <div class="zoom" id="zoom">

      <!--Content01-->
      <div class="image"><img src="https://dummyimage.com/700x600/4a1bf5/ffffff" />
        <div class="caption">One</div>
      </div>

      <!--Content02-->
      <div class="image"><video autoplay loop muted>
          <source src="https://upload.wikimedia.org/wikipedia/commons/8/87/Schlossbergbahn.webm" type="video/webm"></video>
        <div class="caption">Two</div>
      </div>

      <!--Content02-->
      <div class="image"><img src="https://dummyimage.com/700x600/4a1bf5/ffffff" />
        <div class="caption">Three</div>
      </div>

    </div>
  </div>
</div>

Codemirror How Can I Change Search Key Bindings

I want to use Codemirror in my project and need a search implementation. Initially I simply followed the example here.

All works well except for the Alt-F command which should open up a persistent search dialogue, which is what I need.

The documention tells me to change the keybinding using so called custom keymaps and I have no idea how to set this up. This is the keymaps documentation which I don’t really understand and don’t know what to do with..

This is how my setup currently looks like:

const code = getCodeFromDB()
const codemirror

element.innerHTML = `<textarea id="editor-1">${code}</textarea>`
codemirror = CodeMirror.fromTextArea(document.getElementById('editor-1'), {
    mode: 'javascript',
    theme: 'material-ocean',
    indentUnit: 4,
    lineNumbers: true,
    autoCloseTags: true,
    autoCloseBrackets: true
})

Basically I just want the keymap of Ctrl-F to open the persitent search dialogue instead of the default one.

How can I remap the keybindings of these two functionalities?

remove particle animation on javascript

So i have a template that i’m using on wordpress and doing small adjustments to make it the way i want
although now there is an animation on the header done with javascript and i wanted to “eliminate”
i will post the code for the mentioned event:

// Breadcrumb effect  
    if ($(".dt_pagetitle .canvas").length) {
        let cnvs = document.getElementById("canvas"),
        c2d = cnvs.getContext("2d");
        cnvs.width = window.innerWidth, cnvs.height = window.innerHeight;
        let particlesArray = [];
        window.addEventListener("resize", function() {
            cnvs.width = window.innerWidth, cnvs.height = window.innerHeight
        });
        let cursor = {
            x: null,
            y: null
        };
        cnvs.addEventListener("click", function(e) {
            cursor.x = e.x, cursor.y = e.y;
            for (let t = 0; t < 10; t++) particlesArray.push(new particles)
        }), cnvs.addEventListener("mousemove", function(e) {
            cursor.x = e.x, cursor.y = e.y;
            for (let t = 0; t < 10; t++) particlesArray.push(new particles)
        });
        class particles {
            constructor() {this.x = cursor.x, this.y = cursor.y, this.size = 10 * Math.random() + 1, this.speedX = 3 * Math.random() - 1.5, this.speedY = 3 * Math.random() - 1.5, this.color = "#ffffff"}
            update() {this.x += this.speedX, this.y += this.speedY, this.size > .2 && (this.size -= .1)}
            draw() {c2d.strokeStyle = this.color, c2d.lineWidth = .4, c2d.beginPath(), c2d.arc(this.x, this.y, this.size, 0, 2 * Math.PI), c2d.stroke()}
        }
        let hndlParticles = () => {
            for (let e = 0; e < particlesArray.length; e++) particlesArray[e].update(), particlesArray[e].draw(), particlesArray[e].size <= .3 && (particlesArray.splice(e, 1), e--)
        }
        let anim = () => {
            c2d.clearRect(0, 0, cnvs.width, cnvs.height), hndlParticles(), requestAnimationFrame(anim)
        }
        anim();
    }

i was able to remove it using the development of the browser by turning off both events (mouseclick and mousemove), although wanted to make it in a permanent way

things i have tried:

  1. delete the code from the mentioned file, although i don’t want this approach due to the fact if the templates does get some update i would had eventually to delete the code manually once again

although it is important to refer that even though i eliminated this code from the file the animation still was running and inspecting the file on the browser i still could see the code (strange i know) thought initially was a cache issue, so cleared it and still ended with the same result

  1. tried using a removeEventListener although to the lack of knowledge i have on javascript wasn’t successfull either

with this said i’m trying to look for some help on this matter, where i could implement some js code and import it on the functions.php child theme

ExpressJS behaves differently when API requested with and without PORT number

experts im newbie in backend topics and i have 2 flutter apps, one is working perfectly fine when i request the url and the other works only when i do include the port xxxxx:4000/nexus-vote but when removing the port the status code 200 comes and i can see that the index.html is coming in the payload(checked with postman) but not really showing anything in the browser..

I thought it’s something related to nginx, but the forwarding is happening fine as i see the request in the log of the JS app but have no idea what is the problem though…

Here’s my code for the nginx :

    location = /nexus-vote/ {
    #proxy_set_header Host $http_host:4000;
    #proxy_set_header X-Real-IP $remote_addr;
    #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #proxy_set_header X-NginX-Proxy true;
    proxy_set_header X-Forwarded-Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_redirect https://$server_name/nexus-vote/ https://$server_name:4000/nexus-vote/;
    #proxy_redirect https://$server_name/ https://$server_name:4000/;
    proxy_pass https://localhost:4000/nexus-vote/;
    #proxy_redirect off;
}
  location /iframe/ {
    proxy_set_header Host $http_host:$server_port;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass https://localhost:3000/iframe/;
    proxy_redirect off;
}

and here’s the express code served:

  app.get("/nexus-vote", async (req, res) => {
  try {
    console.log(`serving from js ${__dirname}`);
    res.status(200)
      .set("Content-Security-Policy", "default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'")
      .sendFile(path.join(__dirname + "/web/index.html")); // "/privacy_and_terms.html"));
  } catch (e) {
    console.log(e);
  }
});

Maintaining search and sort state across paginated results in web application

I’m working on a web application where users can search for data and paginate through the results. I’ve implemented search functionality, allowing users to search for specific data and sorting functionality to sort the results based on certain criteria.

However, I’m facing two main issues:

Search State Persistence: When users navigate to the next page of results, the search query gets reset, and they lose the search context. How can I ensure that the search query persists across pagination so that users can continue browsing results based on their original search?

Sorting State Issue: Additionally, although sorting works fine on the first page of results, when users navigate to subsequent pages, the sorting seems to reset, and the results are not consistently sorted as expected. How can I maintain the sorting state across all pages of results?

I’ve checked my code thoroughly, but I’m unable to identify the exact issue causing these problems. Could someone please provide insights or suggestions on how to address these issues and ensure a seamless user experience with search and sorting functionality across paginated results?

adminUserList.php

session_start();
if (!isset($_SESSION['sort_order'])) {
    $_SESSION['sort_order'] = ''; // Set default sort order if not set
}

// Store sorting order in session
if (isset($_POST['sort_order'])) {
    $_SESSION['sort_order'] = $_POST['sort_order'];
var_dump($_SESSION);
}

$limit = 5;
$searchValue = isset($_POST['search']) ? $_POST['search'] : '';
$sortOrder = isset($_POST['sort_order']) ? $_POST['sort_order'] : '';

$page = isset($_POST["page_no"]) ? $_POST["page_no"] : 1;
$sno = ($page - 1) * $limit + 1;

if ($searchValue !== "") {
    $result = $database->searchUser($searchValue, (int)$limit);
    $total_record = $database->getTotalRecords(['f_name'], $searchValue);
    $total_page = ceil($total_record / $limit);
    echo $twig->render('adminUserList.twig', ['result' => $result, 'total_page' => $total_page, 'current_page' => $page, 'sno' => $sno, 'searchValue' => $searchValue, 'email' => $email, 'sortOrder' => $_SESSION['sort_order']]);
} elseif ($_SESSION['sort_order']) {
    $result = $database->getUsersSorted($_SESSION['sort_order'], $limit); // Corrected 
    $total_record = $database->getTotalRecords();
    $total_page = ceil($total_record / $limit);
    echo $twig->render('adminUserList.twig', ['result' => $result, 'total_page' => $total_page, 'current_page' => $page, 'sno' => $sno, 'email' => $email, 'sortOrder' => $_SESSION['sort_order']]);
} else {
    // Handle case when neither search nor sorting is applied
    $result = $database->selectAllUser($limit, $page);
    $total_record = $database->getTotalRecords();
    $total_page = ceil($total_record / $limit);

admin.js file for handel ajax

    // Function to load table data
    function loadTable(page = 1, fn) {
        $.ajax({
            url: "adminUserList.php",
            type: "POST",
            data: {
                page_no: page,
            },
            success: function (data) {
                $("#table-data").html(data);
                fn?.();
            }
        });
    }
   
    // Search code
    function loadSearch(page = 1,oder) {
        var search_term = $("#searchInput").val();
        $.ajax({
            url: "adminUserList.php",
            type: "POST",
            data: {
                search: search_term,
                page_no: page,
                sortOrder:oder,

            },
            success: function (data) {
                $("#table-data").html(data);
            }
        });
    }

    // Trigger search on keyup
    $(document).on("keyup", "#searchInput", function () {
        loadSearch();
    });

    // Code for pagination search
    $(document).on("click", ".page-item a", function (e) {
        e.preventDefault();
        var page_id = $(this).attr("id");
        console.log(page_id)
        loadSearch(page_id);
    });

    // Sorting code
    $(document).on("change", "#sort-order", function () {
        var sortOrder = $(this).val();
        sortTable(sortOrder);
    });

    // Function to sort table
    function sortTable(order) {
        console.log(order);
        var page_id = $(".pagination .active").find("a").attr("id");
        console.log(page_id);
        $.ajax({
            url: "adminUserList.php",
            type: "POST",
            data: {
                page_no: page_id,
                sort_order: order
            },
            success: function (data) {
                $("#table-data").html(data);
            }
        });
    }

twig file

                  <select id="sort-order" class="btn btn-secondary">
                <option value="ASC">Ascending</option>
                        <option value="DESC">Descending</option>
                    </select>
                </th>
                <th scope='col'>Email-Id</th>
                <th scope='col'>Phone-No</th>
                {% if result is not empty %}
                    {% for row in result %}
                        <tr>
                            <td>{{ sno }}</td>
                            <td>{{ row['f_name'] }} {{ row['l_name'] }}</td>
                            <td>{{ row['email'] }}</td>
                            <
                                <button type='button' class='btn btn-info' data-eid='{{ row['uid'] }}'>view</button>
                                <button type='button' class='btn btn-danger' data-id='{{ row['uid'] }}'>Delete</button>
                            </td>
                        </tr>
                        {% set sno = sno + 1 %}
                    {% endfor %}
                {% else %}
                    <tr>
                        <td colspan="8">
                            <h2>No Records Found</h2>
                        </td>
                    </tr>
                {% endif %}
            </tr>
        </table>
        <!-- Pagination controls -->
<nav aria-label="Page navigation">
    <ul class="pagination">
        {% if total_page > 0 %}
            {% for page_num in 1..total_page %}
                {% if searchValue != "" %}
                    <li class='Search-item {% if page_num == current_page %}active{% endif %}'>
                        <a class="page-link" href="?page={{ page_num }}&search={{ searchValue }}" id="{{ page_num }}">
                            {{ page_num }}
                        </a>
                    </li>
                {% else %}
                    <li class='page-item {% if page_num == current_page %}active{% endif %}'>
                        <a class="page-link" href="?page={{ page_num }}" id="{{ page_num }}">
                            {{ page_num }}
                        </a>
                    </li>
                {% endif %}
            {% endfor %}
        {% else %}
            <li class="page-item disabled">
                <span class="page-link">
                    No Records Found
                </span>
            </li>
        {% endif %}
    </ul>
</nav>

Change react-hook-form input value with custom hook

For a registered input, I failed to update it using my own custom hook. In my sample codes as shown below, the result2 didn’t set to “bar” when the button was clicked, although r2 was updated correctly.

import { useForm } from "react-hook-form";
import { useBar } from "./useBar";

function App() {
  const { register, setValue } = useForm({
    defaultValues: { result1: "foo", result2: "foo" },
  });

  const [r2, setBar] = useBar("foo");

  const showResults = () => {
    setValue("result1", "bar");
    setBar();
    setValue("result2", r2);
  };

  return (
    <div>
      <button onClick={showResults}>Show results</button>
      <form>
        <div>
          <label>Result 1</label>
          <input type="text" {...register("result1")} />
        </div>
        <div>
          <label>Result 2</label>
          <input type="text" {...register("result2")} />
        </div>
        <div>
          <label>R 2</label>
          <input type="text" value={r2} />
        </div>
      </form>
    </div>
  );
}

export default App;

My useBar hook:

import { useState } from "react";

export const useBar = (initialValue = "") => {
  const [state, setState] = useState(initialValue);

  const setBar = () => {
    setState("bar");
  };

  return [state, setBar];
};

What is the proper way to change result2 value using setBar? Kindly advise.

Why are the css images or js not loading in my laravel project?

This is a follow up question of lasat one I gott ittt to worrking the site is opening and all & at first it was loading the css, js & images too but now it has stopped loading the files and in the console I’m getting these errors =>

GET http://127.0.0.1:8000/assets/css/bootstrap.min.css net::ERR_ABORTED 404 (Not Found)
127.0.0.1/:35

   GET http://127.0.0.1:8000/assets/css/fontawesome.min.css net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:37

   GET http://127.0.0.1:8000/assets/css/magnific-popup.min.css net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:39

   GET http://127.0.0.1:8000/assets/css/slick.min.css net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:41

   GET http://127.0.0.1:8000/assets/css/style.css net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:225

   GET http://127.0.0.1:8000/assets/img/hero/hero_shape_1.png 404 (Not Found)

127.0.0.1/:833

   GET http://127.0.0.1:8000/assets/js/vendor/jquery-3.6.0.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:835

   GET http://127.0.0.1:8000/assets/js/slick.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:837

   GET http://127.0.0.1:8000/assets/js/bootstrap.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:839

   GET http://127.0.0.1:8000/assets/js/jquery.magnific-popup.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:841

   GET http://127.0.0.1:8000/assets/js/jquery.counterup.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:843

   GET http://127.0.0.1:8000/assets/js/jquery-ui.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:845

   GET http://127.0.0.1:8000/assets/js/imagesloaded.pkgd.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:846

   GET http://127.0.0.1:8000/assets/js/isotope.pkgd.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:849

   GET http://127.0.0.1:8000/assets/js/main.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:857

   GET http://127.0.0.1:8000/public/panel/plugins/toastr/toastr.min.css net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:859

   GET http://127.0.0.1:8000/public/panel/plugins/jquery/jquery.min.js net::ERR_ABORTED 404 (Not Found)

127.0.0.1/:861

   GET http://127.0.0.1:8000/public/panel/plugins/toastr/toastr.min.js net::ERR_ABORTED 404 (Not Found)

typed.js:617 Uncaught TypeError: Cannot read properties of null (reading ‘tagName’)
at t.value (typed.js:617:31)
at new t (typed.js:92:33)
at (index):867:5
value @ typed.js:617
t @ typed.js:92
(anonymous) @ (index):867
(index):898 Uncaught ReferenceError: $ is not defined
at (index):898:5
(anonymous) @ (index):898
127.0.0.1/:281

   GET http://127.0.0.1:8000/assets/img/bg/feature-card_bg1.png 404 (Not Found)

127.0.0.1/:284

   GET http://127.0.0.1:8000/assets/img/icon/feature-icon1-1.svg 404 (Not Found)

127.0.0.1/:298

   GET http://127.0.0.1:8000/assets/img/icon/feature-icon1-2.svg 404 (Not Found)

127.0.0.1/:312

   GET http://127.0.0.1:8000/assets/img/icon/feature-icon1-3.svg 404 (Not Found)

127.0.0.1/:333

   GET http://127.0.0.1:8000/assets/img/normal/about_1-1.png 404 (Not Found)

127.0.0.1/:334

   GET http://127.0.0.1:8000/assets/img/normal/about_1-2.png 404 (Not Found)

127.0.0.1/:353

   GET http://127.0.0.1:8000/assets/img/icon/about-icon.svg 404 (Not Found)

127.0.0.1/:383

   GET http://127.0.0.1:8000/assets/img/bg/sec-shape-top.png 404 (Not Found)

127.0.0.1/:398

   GET http://127.0.0.1:8000/assets/img/normal/wcu_1-2.png 404 (Not Found)

127.0.0.1/:400

   GET http://127.0.0.1:8000/assets/img/normal/wcu_1-1.png 404 (Not Found)

127.0.0.1/:404

   GET http://127.0.0.1:8000/assets/img/icon/wcu-icon_1-1.svg 404 (Not Found)

127.0.0.1/:476

   GET http://127.0.0.1:8000/assets/img/bg/sec-shape-bottom.png 404 (Not Found)

127.0.0.1/:495

   GET http://127.0.0.1:8000/assets/img/icon/service-icon_2-1.svg 404 (Not Found)

127.0.0.1/:507

   GET http://127.0.0.1:8000/assets/img/icon/service-icon_2-2.svg 404 (Not Found)

127.0.0.1/:74

   GET http://localhostpublic/logo-b1.png net::ERR_NAME_NOT_RESOLVED

127.0.0.1/:104

   GET http://localhostpublic/logo-b.png net::ERR_NAME_NOT_RESOLVED

127.0.0.1/:715

   GET http://localhostpublic/logo-w.png net::ERR_NAME_NOT_RESOLVED

127.0.0.1/:519

   GET http://127.0.0.1:8000/assets/img/icon/service-icon_2-3.svg 404 (Not Found)

127.0.0.1/:581

   GET http://127.0.0.1:8000/assets/img/icon/counter-icon_1-1.svg 404 (Not Found)

127.0.0.1/:592

   GET http://127.0.0.1:8000/assets/img/icon/counter-icon_1-2.svg 404 (Not Found)

127.0.0.1/:603

   GET http://127.0.0.1:8000/assets/img/icon/counter-icon_1-3.svg 404 (Not Found)

127.0.0.1/:614

   GET http://127.0.0.1:8000/assets/img/icon/counter-icon_1-4.svg 404 (Not Found)

manifest.json:1

   GET http://127.0.0.1:8000/assets/img/favicons/manifest.json 404 (Not Found)

manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.

I tried changing the file path style but it did not work as expected nothing is being loaded what could bee the reason for it?

Node.js Discord bot works in localhost, but not when deployed to firebase hosting

The exact project works in localhost, but not when deployed to Firebase.

With postman, when I send post request to /new-sub in localhost with a body, the bot messages to a specific channel in a specific server. When I send the same request to the live url, I get 404 instead.

Why does it behave differently when deployed?

my code:

const { Client, GatewayIntentBits } = require('discord.js');
const express = require("express");
const app = express();
app.use(express.json());

const token = "xxx";

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages
    ]
});
client.login(token); 

const port = process.env.POST || 443;
app.listen(port, () => {
    console.log(`Project is running. Listening on port ${port}`);
});

app.get("/", (req, res) => {
    res.send(`hello world. Port: ${port}}`);
});

app.post("/new-sub", (req, res) => {
    const [body, query] = [req.body, req.query];


    const guildId = query.guildId || "1234";// server id
    const channelId = query.channelId || "5678";
    const guild = client.guilds.cache.get(guildId);
    if (!guild) {
        const errMsg = `<p>Guild ${guildId} not found</p>`;
        console.log(errMsg);
        res.send(errMsg);
        return;
    }

    const channel = guild.channels.cache.get(channelId);
    if (!channel) {
        const errMsg = `<p>Channel ${channelId} not found in ${guild.name} (${guildId})</p>`;
        console.log(errMsg);
        res.send(errMsg);
        return;
    }

    const newMessage = `New sub! Title: ${body.title}, time: ${new Date(Date.now())}`;
    console.log(newMessage);
    channel.send(newMessage);

    console.log(`message sent to ${channel.name} channel in ${guild.name}`);
    res.send(newMessage);
});

app.use(express.static('public'));

Create the original download link after checking the domain

I have put such a code in the functions.php file for the download links of my site:

// Define the function to generate the shortcode
 function generate_download_shortcode( $atts ) {

  // Get the file path from the shortcode attributes
  $file_path = $atts['file'];

  // Get the upload directory information
  $upload_dir = wp_upload_dir();

  // Get the base URL of the upload directory
  $base_url = $upload_dir['baseurl'];

  // Get the filename without extension
  $filename = basename($file_path, '.' . pathinfo($file_path)['extension']);

  // URL encode the filename
  $encoded_filename = urlencode($filename);

  // Combine base URL, index.php, and encoded filename
  $download_link = $base_url . '/index.php/' . $encoded_filename . '.' . pathinfo($file_path)['extension'] . '?token=' . md5( time() . rand() ) . '&rate=500kbps';

  return '<a href="' . $download_link . '" class="download-link">Download</a>';
}

// Add the shortcode to WordPress
add_shortcode( 'dow', 'generate_download_shortcode' );

// Add the JavaScript to handle the download link click
add_action( 'wp_footer', 'download_link_script' );

function download_link_script() {
  ?>
  <script>
  // Add event listener to the window load event
  window.addEventListener('load', function() {

  // Get all elements with the "download-link" class
  var downloadLinks = document.getElementsByClassName('download-link');

  // Add click event listener to each download link
  for (var i = 0; i < downloadLinks.length; i++) {
  downloadLinks[i].addEventListener('click', downloadLinkClickHandler);
  }

  // Function to handle download link click
  function downloadLinkClickHandler(event) {

  // Prevent default link action
  event.preventDefault();

  // Get the download link element
  var linkElement = event.target;

  // Start countdown
  var countdown = 3;
  var interval = setInterval(function() {
  linkElement.textContent = 'Download (' + countdown + ')';
  countdown--;
  if (countdown === 0) {
  clearInterval(interval);

  // Update the link element with the original download link without parameters
  linkElement.href = linkElement.href.split('?')[0];
  linkElement.textContent = 'Download';
  }
  }, 1000);

  }

  });
  </script>
  <?php
}

// Add rewrite rule to handle download requests
add_rewrite_rule('^download/([^/]+)/?', 'index.php?page_id=123&file=$matches[1]', 'top');

  
  // Function to handle download requests
  function handle_download_request() {
  
  if ( !isset($_GET['download_file']) ) {
  return; // No download request
  }
  
  $file_path = urldecode($_GET['download_file']);
  
  // Check if user has permission to access the file
  if ( !user_can( 'edit_files' ) && !file_exists($file_path) ) {
  wp_die('You do not have permission to download this file.');
  }
  
  // Generate the download link with parameters
  $download_link = generate_download_link( $file_path );
  
  // Start the download process
  startDownload($file_path);
  
  }
  
  // Add the action to handle download requests
  add_action( 'init', 'handle_download_request' );

This code will correctly apply the new link and apply the download speed to the download link I want.

Using scripting, I have created a condition that if the user clicks on the link from the main address of the site, after three seconds the token and speed limit will be removed from the link and the main link will be displayed for the user.

But my code has two big problems:
1- When the seconds count ends and a new link is created, the file must be downloaded immediately, which does not happen.

2- When the link is clicked again, the seconds counter starts counting again, which is completely wrong. If the user clicks a second time or a few more times, the file should be downloaded instead of the seconds counting down.

Please help me to solve this problem.