Why am I keep getting error “GET /installHook.js.map 404” when working with swiper in React

I’m trying to work with carousels (SwiperJS and EmblaCarousel) on React that requires Hooks, but when I’m previewing it in Firefox, I get a

Source map error: Error: request failed with status 404
Stack in the worker:networkRequest@resource://devtools/client/shared/source-map-loader/utils/network-request.js:43:9

Source URL: http://localhost:3000/%3Canonymous%20code%3E
Source map URL: installHook.js.map

error in the browser console, what could possibly cause this? I have been spinning my head around looking for answers, and I tried running the preview in Google Chrome, it sends an error, but this time it’s on layout.js. My code snippet that involves the carousel:

"use client";

import { Swiper, SwiperSlide } from 'swiper/react';

import 'swiper/css';

export default function MenuCarousel() {
    return (
        <div className="lg:grid grid-cols-2 gap-4 mx-4">
        <div>
            <p className="mb-4">MAKANAN</p>
            <Swiper>
                <SwiperSlide>1</SwiperSlide>
                <SwiperSlide>2</SwiperSlide>
                <SwiperSlide>3</SwiperSlide>
            </Swiper>
        </div>
        <div>
            <p className="mb-4">MINUMAN</p>
            <Swiper>
                <SwiperSlide>1</SwiperSlide>
                <SwiperSlide>2</SwiperSlide>
                <SwiperSlide>3</SwiperSlide>
            </Swiper>
        </div>
      </div>
    )
}

package.json:

{
  "name": "bsiduta-web",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "15.0.1",
    "react": "19.0.0-rc-69d4b800-20241021",
    "react-dom": "19.0.0-rc-69d4b800-20241021",
    "swiper": "^11.1.15"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.4.20",
    "eslint": "^8",
    "eslint-config-next": "15.0.1",
    "postcss": "^8.4.49",
    "tailwindcss": "^3.4.15",
    "typescript": "^5"
  }
}

React pro sidebar hover style is not working

I am using react pro sidebar version ^1.1.0, the hover style on sidebar menu items is not working properly. Here is the code, I need to add a hover style on each menu item. I tried adding my custom hover style to it but that’s not working.

export default function Sidebar() {
    let navigate = useNavigate();
    
  const [collapsed, setCollapsed] = React.useState(false);

  // Menu items list

  return (
    <div className="flex min-h-screen">
      {/* Sidebar */}
      <Sidebar
        collapsed={collapsed}
        className="fixed top-0 left-0 h-full max-h-[85vh] rounded-[30px] border border-zinc-800 bg-green-250"
      >
        {/* Header with logo and collapse button */}
        <HStack className="justify-between px-4 py-2 mt-3">
          {!collapsed && (
            <ImageComponent
              src={mainLogo}
              alt="Logo"
              className="h-[50px] w-[80px] object-contain"
            />
          )}
          {collapsed ? (
            <TbLayoutSidebarRightCollapse
              className="p-1 w-10 h-10 text-zinc-700 cursor-pointer"
              onClick={() => setCollapsed(!collapsed)}
            />
          ) : (
            <TbLayoutSidebarLeftCollapse
              className="p-1 w-10 h-10 text-zinc-700 cursor-pointer"
              onClick={() => setCollapsed(!collapsed)}
            />
          )}
        </HStack>

        {/* Dynamically rendered menu items */}
        <Menu>
          {menuItems.map((item) => (
            <MenuItem
              key={item.id}
              icon={item.icon}
              className="font-semibold text-lg text-green-700 hover:text-white hover:bg-green-600 transition-all duration-200"
              onClick={()=>navigate(`/owner/${item.route}`)}
            >
              {item.name}
            </MenuItem>
          ))}
        </Menu>
      </Sidebar>
    </div>
  );
}

only redeem lead show in my purchase leads

<?php foreach ($viewLeads as $vl) { ?> <tr class="gradeX"> <td style="padding:7px;"> <input type="checkbox" class="child_present" name="custom_delete" value="<?php echo $vl['lead_id']; ?>" /></td> <td><?php echo $vl['name']; ?></td> <td><?php echo $vl['email']; ?></td> <td><?php echo $vl['phone']; ?></td> <td class="center"><?php echo $vl['city']; ?></td> <td class="center"><?php echo $vl['state']; ?></td> <td class="center <?php echo ($vl['looking_for'] =='PCD Pharma Franchise') ? 'pcd-enquiry' : 'third-party-enquiry' ?>"><?php echo $vl['looking_for']; ?></td> <td class="center"><?php echo ucfirst(str_replace('_', ' ', $vl['requirement'])); ?></td> <td class="center"><?php echo ucfirst(str_replace('_', ' ', $vl['call_time'])); ?></td> <td class="center"><?php echo $vl['status']; ?></td> <td class="center"><a href="<?php echo site_url('seller/leads-purchases/' . $vl['lead_id']) ?>" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> View</a> </td> </tr> <?php } ?>

please resolve this issue in my seller dashboard

Error Java: Uncaught TypeError: Cannot read properties of undefined (reading ‘Image’)

Help with error

` var graphic = new ol.Layer.Image(
“Image”,
“2024-11-25_09-41-16.png”,
new OpenLayers.Bounds(68.96002,60.01974, 69.09123,61.95860),
new OpenLayers.Size(1500,1000),
{numZoomLevels: 13}
);

map.addControl(new ol.Control.LayerSwitcher());
map.addLayers([map, graphic]);
map.zoomToExtent(new OpenLayers.Bounds(68.96002,61.01974, 69.09123,60.95860));`

correct error pls I can’t fix this error 5 days

Understanding Next.js and NextUI

On the instruction of some Next.js documentation and the default Next.js app that gets created when running create-next-app, I have the following in layout.tsx:

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body>
        {children}
      </body>
    </html>
  );
}

Then, I have this in my root page.tsx (so in ./app/page.tsx):

'use client';

import { NextUIProvider } from "@nextui-org/react";
import MyClassComponent from "./my-class-component";

export default function Page() {
  return (
    <NextUIProvider>
      <main className="dark text-foreground bg-background">
        <span>
          <h3>Enter prompt</h3>
          <MyClassComponent />
        </span>
      </main>
    </NextUIProvider>
  );
}

My questions are:

  1. How do the page.tsx and layout.tsx intersect and work together? Is there a call hierarchy where one is calling the other? I know that page.tsx is a special filename in Next.js such that whatever is rendered by that component will be displayed on the page at that directory (so my page.tsx file corresponds to /), but idk what the layout is doing. It feels like the layout is higher in the hierarchy than the page, meaning that it sets up the layout of every page within the directory and each page’s component will take the place of {children}. Is that right?
  2. How does styling work with NextUI in this thing? On the recommendation of this page I wrote page.tsx like the above, but I’m not sure where the text color or background color are actually coming from. My background is currently white, not dark like the className would suggest.

How to make music player play globally

I write a music box on my website, but as soon as I refresh the page, the music reloads. Is there any way to keep the music playing without reloading? Use javascript and PHP

I used localStorage, but it didn’t have the desired effect.

Cypress can’t seem to get the URL value after removing target attribute, despite the page loading fine

I want Cypress to check that the link to a page is correct by clicking that links and seeing if the URL contains a certain string.

For that, I’ve created the function:

checkLink = (linkEl, expectedPath) => {
    let pathString = linkEl.prop('href') ? linkEl.prop('href') : 'no-href';
    if (expectedPath && (pathString != 'no-href')) {
        cy.task('log', 'Checking link: '  + pathString + ' ' + expectedPath);
        cy.get(linkEl).click();
        cy.url().should('include', expectedPath);
        cy.go('back');
    }
}

For most cases this worked fine.

However, it would not work if the link had a target="_blank" attribute. So I added .invoke('removeAttr', 'target') and changed the function to be the following:

checkLink = (linkEl, expectedPath) => {
    let pathString = linkEl.prop('href') ? linkEl.prop('href') : 'no-href';
    if (expectedPath && (pathString != 'no-href')) {
        cy.task('log', 'Checking link: '  + pathString + ' ' + expectedPath);
        cy.get(linkEl).invoke('removeAttr', 'target').click();
        cy.url().should('include', expectedPath);
        cy.go('back');
    }
}

However, now it can’t seem to get the URL of the page it visits. Eg I get the error:

 AssertionError: Timed out retrying after 4000ms: expected '' to include 'mystring'

If I run the test as headed I can see the page (with the expected string in the URL) load fine. It just seem that Cypress is getting nothing from cy.url() anymore for some reason.

Would anyone know why this is at all?

Why won’t this program display correctly?

I have this HTML page which is meant to display a to-do list and allow users to add tasks to it

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>To-Do List</title>
        <link rel="stylesheet" href="styles.css">
        <script src="/todolist.js" defer></script>
    </head>
    <body>
        <a href="index.html">Homepage</a>
        
        <ul class="todo-list">
            <!-- List items will go here -->
        </ul>
        
        <input type="text" id="new-todo" placeholder="Add a new item">
        <button type="button" id="add-todo">Add To Do</button>
    </body>
</html>

and this script which should use the button from the HTML page to create an array of to-dos and display them on the webpage

// get list from local storage
const todos = JSON.parse(localStorage.getItem('todo-list')) || []

// create consts
const todoList = document.getElementById('todo-list')
const input = document.getElementById('new-todo')
const addButton = document.getElementById('add-todo')

// create/add list items
const renderTodos = () => {
    // clear li's before we recreate them
    todoList.innerHTML = ''
    // loop through list of items and create li elements
    todos.forEach(todo => {
        const li = document.createElement('li')
        li.textContent = todo.text
        li.className = 'todo'
        todoList.append(li)
    })
}

// button event listener
addButton.addEventListener('click', () => {
    if (input.value) {
        todos.push({ text: input.value, completed: false });
        localStorage.setItem('todo-list', JSON.stringify(todos));
        input.value = '';
        renderTodos();
    }
});
renderTodos()

Goal is for the user to type and submit a todo, and it will show up on the webpage. The page will display all the HTML elements, but the javascript doesn’t add elements. Or at least the javascript doesn’t display the elements that were put in local storage.

Seems like this code should work, I must be missing something.

Directly calling a method in JS works, but not with .call or .apply

I have a node resulting from a call

let node = document.getElementById('myID');

node is a Node, which has a classList object that has a remove() method

This works for me:

node.classList.remove('alert');

However, this does not work:

let method = node['classList']['remove'];
method.call(node, ['myclass']);

I receive the error in this second case:

Uncaught TypeError: 'remove' called on an object that does not implement interface DOMTokenList.

What am I doing wrong?

How can I make a provier script for an extension to connect it with Web Apps?

I have created an unpacked extension that is working fine I want it to be injected and be able to connect it with apps like MetaMask wallet does.

I have created a provider.js script to do it. I want to know if that is the correct approach to do what I want because when trying to connect with a vue app I am running on localhost in Chrome I get Failed to connect extension not installed error

This is the provider script:

// Verus Web Wallet Provider Implementation
export const createVerusProvider = () => ({
  isVerusWallet: true,
  version: '1.0.0',
  _isConnected: false,
  _address: null,
  _listeners: new Map(),
  _connecting: null,
  
  // Request account access (legacy method)
  requestAccounts: function() {
    console.log('requestAccounts called');
    return this.connect().then(result => [result.address]);
  },
  
  // Connect to the wallet (new method)
  connect: function() {
    console.log('connect called');
    
    // Return existing connection if already connected
    if (this._isConnected && this._address) {
      return Promise.resolve({ address: this._address });
    }
    
    // Return existing connection attempt if in progress
    if (this._connecting) {
      return this._connecting;
    }
    
    const that = this;
    this._connecting = new Promise((resolve, reject) => {
      const timeoutId = setTimeout(() => {
        window.removeEventListener('message', handler);
        reject(new Error('Connection request timed out'));
      }, 30000); // 30 second timeout
      
      function handler(event) {
        if (event.source !== window) return;
        if (event.data.type === 'VERUS_CONNECT_RESPONSE') {
          clearTimeout(timeoutId);
          window.removeEventListener('message', handler);
          
          if (event.data.error) {
            that._connecting = null;
            reject(new Error(event.data.error));
          } else {
            that._isConnected = true;
            that._address = event.data.result.address;
            that._emitEvent('connect', { address: event.data.result.address });
            resolve(event.data.result);
          }
        }
      }
      
      window.addEventListener('message', handler);
      window.postMessage({ type: 'VERUS_CONNECT_REQUEST' }, '*');
    }).finally(() => {
      this._connecting = null;
    });
    
    return this._connecting;
  },
  
  // Get connected account
  getAccount: function() {
    console.log('getAccount called');
    if (!this._isConnected) {
      throw new Error('Wallet not connected');
    }
    return Promise.resolve(this._address);
  },
  
  // Send transaction
  sendTransaction: function(params) {
    console.log('sendTransaction called');
    if (!this._isConnected) {
      throw new Error('Wallet not connected');
    }
    
    return new Promise((resolve, reject) => {
      window.addEventListener('message', function handler(event) {
        if (event.source !== window) return;
        if (event.data.type === 'VERUS_SEND_TRANSACTION_RESPONSE') {
          window.removeEventListener('message', handler);
          if (event.data.error) {
            reject(new Error(event.data.error));
          } else {
            resolve(event.data.result);
          }
        }
      });
      window.postMessage({
        type: 'VERUS_SEND_TRANSACTION_REQUEST',
        params
      }, '*');
    });
  },
  
  // Event handling
  on: function(eventName, callback) {
    console.log('on called:', eventName);
    if (!this._listeners.has(eventName)) {
      this._listeners.set(eventName, new Set());
    }
    this._listeners.get(eventName).add(callback);
  },
  
  off: function(eventName, callback) {
    console.log('off called:', eventName);
    if (this._listeners.has(eventName)) {
      this._listeners.get(eventName).delete(callback);
    }
  },
  
  _emitEvent: function(eventName, data) {
    console.log('_emitEvent called:', eventName, data);
    if (this._listeners.has(eventName)) {
      this._listeners.get(eventName).forEach(callback => {
        try {
          callback(data);
        } catch (error) {
          console.error('Error in event listener:', error);
        }
      });
    }
  }
});

It is a MetaMask style wallet that I am working on for Layer 1 blockchain Verus:

In my other App this is how I am trying to connect with the extension:

import { ref, onMounted } from 'vue';

export function useVerusWallet() {
    const address = ref(null);
    const isConnected = ref(false);
    const error = ref(null);

    // Check if Verus wallet is installed
    const checkWalletInstalled = () => {
        return window.isVerusWalletInstalled === true;
    };

    // Connect to wallet with timeout
    const connectWallet = async () => {
        try {
            if (!checkWalletInstalled()) {
                throw new Error('Verus Wallet extension not installed');
            }

            // Add timeout to the connection request
            const timeoutPromise = new Promise((_, reject) => {
                setTimeout(() => reject(new Error('Connection timeout')), 30000); // 30 second timeout
            });

            const connectionPromise = window.verus.requestAccounts();
            const accounts = await Promise.race([connectionPromise, timeoutPromise]);

            if (!accounts || accounts.length === 0) {
                throw new Error('No accounts found');
            }

            address.value = accounts[0];
            isConnected.value = true;
            error.value = null;
            return accounts[0];
        } catch (err) {
            error.value = err.message;
            isConnected.value = false;
            throw err;
        }
    };

    // Get current account
    const getAccount = async () => {
        try {
            if (!checkWalletInstalled()) {
                throw new Error('Verus Wallet extension not installed');
            }

            const accounts = await window.verus.getAccounts();
            if (!accounts || accounts.length === 0) {
                throw new Error('No accounts found');
            }

            address.value = accounts[0];
            isConnected.value = true;
            return accounts[0];
        } catch (err) {
            error.value = err.message;
            isConnected.value = false;
            throw err;
        }
    };

    // Listen for account changes
    onMounted(() => {
        if (checkWalletInstalled()) {
            // Check initial connection status
            window.verus.getAccounts().then(accounts => {
                if (accounts && accounts.length > 0) {
                    address.value = accounts[0];
                    isConnected.value = true;
                }
            }).catch(() => {
                isConnected.value = false;
            });

            // Listen for account changes
            window.verus.on('accountsChanged', (accounts) => {
                if (accounts && accounts.length > 0) {
                    address.value = accounts[0];
                    isConnected.value = true;
                } else {
                    address.value = null;
                    isConnected.value = false;
                }
            });

            // Listen for disconnect events
            window.verus.on('disconnect', () => {
                address.value = null;
                isConnected.value = false;
            });
        }
    });

    return {
        address,
        isConnected,
        error,
        connectWallet,
        getAccount,
        checkWalletInstalled
    };
}

How to remove striping from JS Datatables after applying custom styling

To remove striping on Datatables you add:

stripeClasses:[]

But I have the following styling added to change background cell color depending on the value of the cell:

        var table = $('#driverTable').DataTable({
            paging: false,
            scrollX: true,
            order: [[2, 'desc']],
            drawCallback: function (settings) {
                applyConditionalFormatting(this.api());
            },
            stripeClasses: []
        });
        $('input.toggle-vis').on('change', function (e) {
            e.preventDefault();

            var column = table.column($(this).attr('data-column'));
            column.visible($(this).prop('checked'));
        });
        function applyConditionalFormatting(table) {
            var higherIsBetter = {
                1: true,  // Races Count
                2: true,  // Rating
                3: false, // Start Position
            };
            for (var colIndex = 1; colIndex <= 17; colIndex++) {

                // Get all data in this column
                var data = table.column(colIndex, { search: 'applied' }).data();

                if (values.length > 0) {
                    var min = Math.min.apply(null, values);
                    var max = Math.max.apply(null, values);

                    // For each cell in this column
                    table.column(colIndex, { search: 'applied' }).nodes().each(function (cell, i) {
                       
                            }
                            // Set background color
                            var color = 'hsl(' + hue + ', 100%, 75%)'; // Adjust lightness as needed


And it adds the striping overtop the custom styling I added.

How do I remove the striping?

Can I determine from JavaScript or from the user-agent string if browser is “Developer” version?

Chrome, Mozilla and MS-Edge all have “Developer” versions of their products … essentially early release versions.

Can I tell from JavaScript if a browser is a “Developer” version? The “User-Agent” strings do not explicitly say “dev” or “developer”. An on-line database may have that information but I have not been able to find one that does.

Reason: I would like to display diagnostic info if a user is accessing a page using a “Developer” version of a browser. Our regular users are not able to install “Developer” browser versions.

Error: TypeError: request is not iterable, Gemini API

im making clone of gemini AI using react and javascript, at first glance it seems works, but after i inspect my project at the browser i got these errors, can anyone explain to me? newbie here

@google_generative-ai.js?v=1f858b71:559 Uncaught (in promise) TypeError: request is not iterable
    at formatNewContent (@google_generative-ai.js?v=1f858b71:559:32)
    at ChatSession.sendMessage (@google_generative-ai.js?v=1f858b71:730:24)
    at async run (gemini.js:24:18)

this is my current code

import { GoogleGenerativeAI } from "@google/generative-ai";

const apiKey = "AIzaSyDBBrhCK33iSPdt8RXJF6ev_6pPBthW57w";
const genAI = new GoogleGenerativeAI(apiKey);

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
});

const generationConfig = {
  temperature: 1,
  topP: 0.95,
  topK: 40,
  maxOutputTokens: 8192,
  responseMimeType: "text/plain",
};

async function run(prompt) {
  const chatSession = model.startChat({
    generationConfig,
    history: [],
  });

  const result = await chatSession.sendMessage(prompt);
  console.log(result.response.text());
}

run();

export default run;

Returning an Ajax response which consists of HTML and JavaScript to the front end to be rendered

been trying for days to figure this out…im trying to call a shortcode via php, process it via Ajax and return the response to a frontend but has been unable to do so.
It seems that the script just wont run despite the do_shortcode correctly outputs the correct response. the codes as below: (Enqueue of JS has been done in a separate php)

PHP

add_action('wp_ajax_get_amelia_shortcode', 'get_amelia_shortcode');
add_action('wp_ajax_nopriv_get_amelia_shortcode', 'get_amelia_shortcode');

function get_amelia_shortcode() 
{
    if (defined('DOING_AJAX') && DOING_AJAX) 
    {
          include_once WP_PLUGIN_DIR . '/ameliabooking/ameliabooking.php';
           $output = do_shortcode('[ameliaeventscalendarbooking location=2]');
            error_log('Shortcode Output: ' . $output);
            echo $output;
    }
    wp_die();
}

JAVA

jQuery(document).ready(function ($) {
    $('#call-amelia-button').on('click', function () {
        const $ameliaContent = $('#amelia-content');

        $ameliaContent.text('Loading...').addClass('loading');

        // Perform AJAX request
        $.ajax({
            type: 'POST',
            url: customAjax.ajaxurl, // Defined via wp_localize_script
            data: { action: 'get_amelia_shortcode' },
            success: function (response) {
    // Extract the script content and HTML content
    const $responseHTML = $('<div>').html(response); // Wrap response in a jQuery object

    // Insert the non-script parts of the response into the target
    const $ameliaContent = $('#amelia-content');
    $ameliaContent.html($responseHTML.find('*').not('script').clone()).removeClass('loading');

    // Execute scripts in the response
    $responseHTML.find('script').each(function () {
        const scriptContent = this.text || this.textContent || this.innerHTML;
        try {
            console.log("Response Content:", response);
            $.globalEval(scriptContent);
        } catch (error) {
            console.error("Error executing script:", error);
        }
    });
},
            error: function (xhr, status, error) {
                // Handle errors gracefully
                $ameliaContent.text('An error occurred. Please try again later.').removeClass('loading');
            }
        });
    });
});

any help would be highly appreciated.
many thanks!

The aim is to trigger the Amelia booking plugin using do_shortcode() and update the frontend in realtime, the above is a simple execution to make sure the code works before implementing more complex logics and criteria to trigger the plugin with different params.