bind data dynamically to p-table(column wise)

I have a json data like following,and I am trying to present this data in the table format but unable to bind in the expected way. can someone please let me know if we can achieve this with p-table ?

here is what I am trying, but duplicate records can be seen row wise as let-car is loop thhrough the data.

stackblitz

data:

   {
        Year: 2023,
        InputData: {
          OilProduction: 0,
          GasProduction: 0,
          NGLProduction: 0,
        },
      },
      {
        Year: 2024,
        InputData: {
          OilProduction: 1,
          GasProduction: 2,
          NGLProduction: 3,
        },
      },
    ];

Expected design of the table:

parameter 2023 2024
oil production 0 1
gas production 0 2
NGL production 0 3

button element undefined out of foreach, why?

My question is why I can console.log() the Boolean value in the isOperator function, but if I try to return it, I get an error?

allButtons.forEach((button) => {
  if (isNumber(+button.value)) {
    button.addEventListener("click", () => handleNumberClick(button.value));
    button.addEventListener("onkeyDown", () => handleNumberClick(button.value));
  }
  /*It detects when i press the operators.*/
  if (isOperator(button)) {
    button.addEventListener("click", () => handleOperatorClick(button));
  }
});

function isOperator(operator) {
  console.log(operator.classList.contains("operator")); //prints true or false
  return operator.classList.contains("operator"); 
}

Error –> Uncaught TypeError: Cannot read properties of undefined (reading ‘contains’)

I was expecting it to work as i pass the parameter but it didn’t. First, i thought it is because of the DOMElement doesn’t exist outside of foreach element (i’m not so sure just guess), but i think this is not an issue, because i can console.log() it.

Webpack ProvidePlugin import before CSS Modules?

I’m using Webpack’s ProvidePlugin to auto-import common components such as a <Button /> component. I’m also using CSS Modules. A typical component might look like:

import styles from './Component.scss';

export default function Component() {
  return <Button className={styles.btn} />
}

This works 99% of the time. But I noticed that if I try to override Button‘s styles in the first imported component that uses Button, the styles don’t override without !important. It overrides if I manually import Button above the Component.scss import. It seems like ProvidePlugin is importing Button below Component.scss.

In other words, ProvidePlugin is equivalent to:

import styles from './Component.scss';
import Button from 'components/Button';

But I’d like it to be:

import Button from 'components/Button';
import styles from './Component.scss';

In the second example, the CSS order is correct. Is it possible to do this with ProvidePlugin or another Webpack plugin?

In mac os i can’t able to edit the original file which i was stored in folder which is created by app.getPath(‘userData’) in electron

Closed. This question is off-topic. It is not currently accepting answers.
Questions about software development are off-topic here, but can be asked on Stack Overflow.

Closed 2 hours ago.

in my electron app i will download a file in cache folder using const appPath = app.getPath(‘userData’) const directory = path.join(appPath, sub_folder_under_app_dir); but i cant able to edit the original file after opening the file, it is showing that “original file cant be changed and the duplicate file will be created with modified data”

How to fix “Failure – Unknown” while using Speculative Rules in Google Chrome?

Using javascript I insert next script

<script type="speculativerules">
  {
    "prerender":[{
      "source":"list",
      "urls":["/cart"]
    }]
  }
</script>

My server correctly responds with the cart page and 200 HTTP status. However I see an error “Failure – Unknown” in chrome devtools. I see no way how I can investigate this trouble further and make Speculation Rules work.

One thing I noticed: sometimes it helps to toggle Preload Pages tumbler in browser’s settings.

enter image description here

Crowd performance / kinematic controller in rapier.js

I’m currently building an auto-shooter / zombie game on the web ( WIP )

And I came across a few perfs issues regarding the kinematic controller / setNextKinematicPosition

Context :

enter image description here

I’ve got zombies / which are capsuled kinematic entities. They spawn randomly and move across the terrain to attack us.

I’m using a single kinematic player controller for all the zombies and applying kinematic forces so each of them does not pass through actual collided objects + does not pass through other zombies

// set the velocity of the zombie toward the actual direction, and applying gravity in Y position
tempVec.set ( -v31.x * dt * this.targets[i].speed, -9.81 * dt * 2, - v31.z * dt * this.targets[i].speed )


// this is the part that calculate the new position of the zombie

this.characterController.computeColliderMovement(
    this.targets[i].collider._collider,           // The collider we would like to move.
    tempVec, // The movement we would like to apply if there wasn’t any obstacle.
    null,
    null,
    ( collider )=>{

        // this is filter from the collision solver : 
        // if the colliding object is a sensor => no collision

        const isSensor = collider.isSensor()

        return isSensor == false
    }
)

let correctedMovement = this.characterController.computedMovement();

const rpos = this.targets[i].collider.rigidBody.translation()

this.targets[i].position.set(

    rpos.x + correctedMovement.x,
    rpos.y + correctedMovement.y,
    rpos.z + correctedMovement.z
)

this.targets[i].collider.rigidBody.setNextKinematicTranslation(this.targets[i].position)

Problem :

Getting 20 zombies into kinematic forces leads a big drop of performances. I analysed the situation here and did a few check and realised that each zombie performs 10 to a 100 times a collision in the filter by logging the zombieCollisions value in the filter :

enter image description here

let zombieCollisions = 0

this.characterController.computeColliderMovement(
    this.targets[i].collider._collider,           // The collider we would like to move.
    tempVec, // The movement we would like to apply if there wasn’t any obstacle.
    null,
    null,
    ( collider )=>{

        // this is filter from the collision solver : 
        // if the colliding object is a sensor => no collision

        const isSensor = collider.isSensor()

        console.log( zombieCollisions )

        return isSensor == false
    }
)

Solution ?

Well, I’ve tried so many things, my best bet was to skip the collision test when there are more than a X value using but it ultimately leads to weird behavior and break the simulation kind of :

let zombieCollisions = 0

this.characterController.computeColliderMovement(
    this.targets[i].collider._collider,           // The collider we would like to move.
    tempVec, // The movement we would like to apply if there wasn’t any obstacle.
    null,
    null,
    ( collider )=>{

        // this is filter from the collision solver : 
        // if the colliding object is a sensor => no collision
        // if the current zombie colliders with other zombie more than 6 times => stop colliding

        const isSensor = collider.isSensor()

        const c =  (collider.parent().userData).mesh.componentType
       
        if( c == 'avatar'){

            zombieCollisions++
        }

        return isSensor == false && (c != 'avatar' || zombieCollisions < 6 )
    }
)

Questions :

Is having from 10 to a 100 collision tests per zombie using a kinematic control a standard behavior ?

Is there another way than using the kinematic controller to get the zombie to collide between each other ?

Has there been some benchmarks and tests that I’m not aware of about a kind of “crowd simulation” using rapier.js ? I’ve been crawling the web to get a solution on this but no chances yet.

Is there a way to spread the collision tests across multiples frame and somehow accepts than sometimes the capsules are merging / passing through for a few frames, without breaking the physics / the perfs ?

It is a long a long post I’m sorry.

Thank you very much for your time

how can i show iframe from m3u8, when user hover the player’s timeline

i was able to open m3u8 format using hls.js, but i have problem, i need to show preview images from m3u8 when user hover the timeline, how to do this, thanks in advance for your answers)

 <div
          className="timeline-container"
          onMouseMove={handleTimeLineUpdate}
          onMouseDown={toggleScrubbing}
          ref={timelineContainer}
        >
          <div className="timeline">
            <img className="preview-img" ref={previewImgRef} alt="previewImg" />
            <div className="thumb-indicator"></div>
          </div>
        </div>

there is my functions for getting iframe from m3u8:

const getIframePlaylistUrlsFromM3U8 = async () => {
    try {
      const response = await fetch(movie.transcode_file);
      const m3u8Content = await response.text();

     
      const iframePlaylistUrls = extractIframePlaylistUrls(m3u8Content);

 
      return iframePlaylistUrls;
    } catch (error) {
      console.error("Error fetching or parsing M3U8 file", error);
      return [];
    }
  };

there i have problem, when i log iframePlaylistUrls it has values, but when another function receives it it shows empty

  const extractIframePlaylistUrls = (m3u8Content) => {
    const iframePlaylistUrls = parseM3U8(m3u8Content);
    return iframePlaylistUrls;
  };

  const parseM3U8 = (m3u8Content) => {
    const regex = /EXT-X-I-FRAME-STREAM-INF:.*URI="(.+)"/g;
    const matches = m3u8Content.matchAll(regex);
    return Array.from(matches, (match) => match[1]);
  };
  const updatePreviewImageOnHover = async (e) => {
    const rect = timelineContainer.current.getBoundingClientRect();
    const percent =
      Math.min(Math.max(0, e.clientX - rect.x), rect.width) / rect.width;

    const iframePlaylistUrls = await getIframePlaylistUrlsFromM3U8();
   
    const iframeIndex = Math.max(
      0,
      Math.floor(percent * iframePlaylistUrls.length)
    );
   
    const thumbnailImageUrl = await extractThumbnailImageUrl(
      iframePlaylistUrls[iframeIndex]
    );
    previewImgRef.current.src = thumbnailImageUrl;
   
  };
  const extractThumbnailImageUrl = async (iframePlaylistUrl) => {
    try {
      const response = await fetch(iframePlaylistUrl);
      const iframePlaylistContent = await response.text();

      const thumbnailImageUrl = parseIframePlaylist(iframePlaylistContent);

      return thumbnailImageUrl;
    } catch (error) {
      console.error("Error fetching or parsing iframe playlist", error);
      return "";
    }
  };
  const parseIframePlaylist = (iframePlaylistContent) => {
    const thumbnailImageUrl = parseIframePlaylistUrl(iframePlaylistContent);
    return thumbnailImageUrl;
  };
  const parseIframePlaylistUrl = (iframePlaylistContent) => {
    const regex = /#EXT-X-IMAGE:(.+)/;
    const match = iframePlaylistContent.match(regex);
    return match ? match[1] : "";
  };

when i hover timeline this function runs

  const handleTimeLineUpdate = (e) => {
    const rect = timelineContainer.current.getBoundingClientRect();
    const percent =
      Math.min(Math.max(0, e.clientX - rect.x), rect.width) / rect.width;


    updatePreviewImageOnHover(e);

    timelineContainer.current.style.setProperty("--preview-position", percent);

    if (isScrubbing.current) {
      e.preventDefault();
      // thumbnailImgRef.current.src = previewImgSrc;
      timelineContainer.current.style.setProperty(
        "--progress-position",
        percent
      );
    }
  };

Which APIs are charged by Google maps? [closed]

  • I am using google maps api in reactjs with @react-google-maps/api.
  • I open f12 on chrome and see many requests of Google Maps.
  • I was deducted a lot of money by Google for making many requests.
  • I don’t know which one is charged by google. Can you point it out for me?

image 1
image 2

Thanks a lot.

I want to know which apis are charged by google.

How to change the style/skin of the TinyMCE pop up window?

I am currently using TinyMCE editor to insert text which has been configured differently than the TinyMCE default style using CSS:
Image of styled Tiny MCE Content

When clicking the link button, a pop up occurs on how to insert or edit the link, which is correct but I would like to change the style of this in contrast to the TinyMCE default style as it’s not maintaining consistency with the rest of the web application that is being used.

TinyMCE link pop up style

The only relevant code I have seen is the following below:

    const makeDialog = (settings, onSubmit, editor) => {
  const urlInput = [{
      name: 'url',
      type: 'urlinput',
      filetype: 'file',
      label: 'URL',
      picker_text: 'Browse links'
    }];
  const displayText = settings.anchor.text.map(() => ({
    name: 'text',
    type: 'input',
    label: 'Text to display'
  })).toArray();
  const titleText = settings.flags.titleEnabled ? [{
      name: 'title',
      type: 'input',
      label: 'Title'
    }] : [];
  const defaultTarget = Optional.from(getDefaultLinkTarget(editor));
  const initialData = getInitialData(settings, defaultTarget);
  const catalogs = settings.catalogs;
  const dialogDelta = DialogChanges.init(initialData, catalogs);
  const body = {
    type: 'panel',
    items: flatten([
      urlInput,
      displayText,
      titleText,
      cat([
        catalogs.anchor.map(ListOptions.createUi('anchor', 'Anchors')),
        catalogs.rels.map(ListOptions.createUi('rel', 'Rel')),
        catalogs.targets.map(ListOptions.createUi('target', 'Open link in...')),
        catalogs.link.map(ListOptions.createUi('link', 'Link list')),
        catalogs.classes.map(ListOptions.createUi('linkClass', 'Class'))
      ])
    ])
  };
  return {
    title: 'Insert/Edit Link',
    size: 'normal',
    body,
    buttons: [
      {
        type: 'cancel',
        name: 'cancel',
        text: 'Cancel'
      },
      {
        type: 'submit',
        name: 'save',
        text: 'Save',
        primary: true
      }
    ],
    initialData,
    onChange: (api, {name}) => {
      dialogDelta.onChange(api.getData, { name }).each(newData => {
        api.setData(newData);
      });
    },
    onSubmit
  };
};

Main to Renderer seemingly breaking at Preload

When the app is launched, I am trying to send some data from main to the renderer so that the renderer can begin rendering some elements. I have no idea what is happening, but it seems communication breaks down at preload.js. I have checked Electron’s documentation and my code looks fine. I have no problem communicating from renderer.js to main.js to renderer.js, but communicating from main.js to renderer.js does not want to work. Any help would be very much appreciated.

// main.js

async function readJSON(filePath) {
  try {
    const data = await fs.readFile(filePath, 'utf-8')
    return JSON.parse(data)
  } catch (error) {
    if (error.code === 'ENOENT') return []
    else throw error
  }
}

async function loadData() {
  try {
    const
      configFilePath = path.join(app.getPath('userData'), 'List of Data Points.json'),
      dataList = await readJSON(configFilePath)
    if (dataList.length) {
      console.log(dataList.length) //## THIS LOGS CORRECTLY ##//
      mainWindow.webContents.send('data:dataList', dataList)
      console.log('Sent data from main.js') //## THIS LOGS TO MAIN.JS CONSOLE ##//
    }
  } catch (error) {
    console.error('Error reading configuration file:', error)
  }
}

app.whenReady().then(()=>{
  createWindow()
  loadFontData()
  ...
// preload.js

contextBridge.exposeInMainWorld('myAPI',
  {
    onDataListReady: (callback) => ipcRenderer.on('data:dataList', (_event, value) => {
      console.log('Why does this not work?') //## THIS DOES NOT LOG TO EITHER CONSOLE ##//
      return callback(value)
    }),
    ...
// renderer.js

window.myAPI.onFontListReady((value) => {
  console.log(value) //## THIS DOES NOT LOG TO BROWSER CONSOLE ##//
  try {
    dataList.forEach(it=>console.log(it))
  } catch (error) {
    console.error('Error in onFontListReady:', error)
  }
})

How to dynamically change the value of a variable from an imported JS file to Vue

There is an app file.the js in which YmapsComponent.vue is declared and imported ymaps.js . `

import '../js/ymaps.js';
import { createApp } from 'vue';

const app = createApp({});

import YmapsComponent from './components/YmapsComponent.vue';
app.component('ymaps-component', YmapsComponent) ;

app.mount('#app');

In ymaps.js the route is being built at the specified points using the API. In this file, the length variable is specified globally and then exported to YmapsComponent.vue.

var length;
ymaps.ready(init);

function init() {
    // Стоимость за километр.
    var DELIVERY_TARIFF = 30,
    // Минимальная стоимость.
        MINIMUM_COST = 500,
        myMap = new ymaps.Map('map', {
            center: [55.7549792211111,37.61615189062498],
            zoom: 10,
            controls: []
        }),
    // Создадим панель маршрутизации.
        routePanelControl = new ymaps.control.RoutePanel({
            options: {
                maxWidth: '500px',
                minWidth: '200px',
            }
        }),
        zoomControl = new ymaps.control.ZoomControl({
            options: {
                size: 'small',
                float: 'none',
                position: {
                    bottom: 145,
                    right: 10
                }
            }
        });
    // Пользователь сможет построить только автомобильный маршрут.
    routePanelControl.routePanel.options.set({
        types: {auto: true}
    });

    myMap.controls.add(routePanelControl).add(zoomControl);

    // Получим ссылку на маршрут.
    routePanelControl.routePanel.getRouteAsync().then(function (route) {

        // Зададим максимально допустимое число маршрутов, возвращаемых мультимаршрутизатором.
        route.model.setParams({results: 1}, true);

        // Повесим обработчик на событие построения маршрута.
        route.model.events.add('requestsuccess', function () {

            var activeRoute = route.getActiveRoute();
            if (activeRoute) {
                // Получим протяженность маршрута.
                length = route.getActiveRoute().properties.get("distance")
                var duration = route.getActiveRoute().properties.get("duration"),
                // Вычислим стоимость доставки.
                    price = calculate(Math.round(length.value / 1000)),
                // Создадим макет содержимого балуна маршрута.
                    balloonContentLayout = ymaps.templateLayoutFactory.createClass(
                        '<span>Расстояние: ' + length.text + '.</span><br/>' +
                        // '<span style="font-weight: bold; font-style: italic">Стоимость доставки: ' + price + ' р.</span>' +
                        '<span>Время в пути: ' + duration.text + '</span>');
                        
                // Внешний вид маршрута
                route.options.set({
                    // Цвет метки начальной точки.
                    // wayPointStartIconFillColor: "#B3B3B3",
                    // Цвет метки конечной точки.
                    // wayPointFinishIconFillColor: "red",     
                    // Внешний вид линий.
                    routeActiveStrokeColor: "#ff4f1e"
                });

                // Зададим этот макет для содержимого балуна.
                route.options.set('routeBalloonContentLayout', balloonContentLayout);


                // Откроем балун.
                activeRoute.balloon.open();
            }
        });

    });
    // Функция, вычисляющая стоимость доставки.
    function calculate(routeLength) {
        return Math.max(routeLength * DELIVERY_TARIFF, MINIMUM_COST);
    }
}
export {length}

The length value is output in YmapsComponent.

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <h1 class="card-header color-red">{{  messages }}</h1>
                    <div class="card-body">
                        Length  {{ delivery }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { length } from '../ymaps';

    export default {
        data() {
            return {
                messages:  "test",
                deliveryLength: 0,
            }
        },
        computed: {
            delivery() {
                if (length) {
                    this.deliveryLength = length.text;
                    return this.deliveryLength;
                } else {
                    return 0;
                }
            }
        },
    }
</script>

The problem is that the deliveryLength value only changes when something is changed in the Vue file. For example, it selects points, the map idles the route, but its length is not displayed in the component, and if, for example, you change the value of messages, then the length will change.

I searched for information on the Internet, tried different ways, but could not solve the problem

Auto scroll function shows a part of previous image on left with current image

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll Container</title>
    <style>
                .scroll-container {
          overflow: hidden;
          white-space: nowrap;
          width: 100%;
          height: auto;
          scroll-behavior: smooth;
        }

        div.scroll-container img {
          padding: 0.5px;
          width: 100%;
          height: auto;
        }

        div.hz-scroll {
          position: relative;
        }

        .dots-container {
          display: flex;
          justify-content: left;
          margin-bottom: 1.2em;
        }

        .dot {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          background-color: #ccc;
          margin: 0 5px;
          transition: background-color 0.3s ease-in-out;
        }

        .dot.active {
          background-color: #2d2d86;
          /* Highlight color */
        }

        .images {
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          gap: 2em;
        }

    </style>
  </head>

  <body>
    <div class="hz-scroll">
      <div class="images">
        <div class="scroll-container" id="scroll-container">
          <img src="https://bsmedia.business-standard.com/_media/bs/img/article/2023-11/26/full/1701018131-7486.jpg?im=FeatureCrop,size=(826,465)" alt="Cinque Terre">
          <img src="https://bsmedia.business-standard.com/_media/bs/img/article/2023-11/26/full/1701018131-7486.jpg?im=FeatureCrop,size=(826,465)" alt="Cinque Terre">
          <img src="https://bsmedia.business-standard.com/_media/bs/img/article/2023-11/26/full/1701018131-7486.jpg?im=FeatureCrop,size=(826,465)" alt="Cinque Terre">
          <img src="https://bsmedia.business-standard.com/_media/bs/img/article/2023-11/26/full/1701018131-7486.jpg?im=FeatureCrop,size=(826,465)" alt="Cinque Terre">
          <img src="https://bsmedia.business-standard.com/_media/bs/img/article/2023-11/26/full/1701018131-7486.jpg?im=FeatureCrop,size=(826,465)" alt="Cinque Terre">
        </div>
        <div class="dots-container" id="dots-container">
          <div class="dot"></div>
          <div class="dot"></div>
          <div class="dot"></div>
          <div class="dot"></div>
          <div class="dot"></div>
        </div>
      </div>
    </div>
  </body>
  <script>
            let scrollInterval;
            const firstimage_scrollContainer = document.getElementById('scroll-container');
            const imageWidth = firstimage_scrollContainer.querySelector('img').clientWidth;

            function scrollItems(direction) {
            if (direction === 'left') {

                if (firstimage_scrollContainer.scrollLeft === 0) {
                firstimage_scrollContainer.scrollLeft = firstimage_scrollContainer.scrollWidth - firstimage_scrollContainer.clientWidth;
                } else {
                firstimage_scrollContainer.scrollLeft -= imageWidth;
                }
            } else if (direction === 'right') {

                if (firstimage_scrollContainer.scrollLeft + firstimage_scrollContainer.clientWidth >= firstimage_scrollContainer.scrollWidth - imageWidth) {
                firstimage_scrollContainer.scrollLeft = 0;
                } else {
                firstimage_scrollContainer.scrollLeft += imageWidth;
                }
            }
            }


            function startAutoScroll() {
            scrollInterval = setInterval(function() {
                scrollItems('right');
            }, 2000); // Adjust the interval as needed (e.g., 3000 milliseconds for 3 seconds)
            }

            startAutoScroll();

            function updateActiveDot() {
            const dotsContainer = document.getElementById('dots-container');
            const dots = dotsContainer.querySelectorAll('.dot');
            const activeIndex = Math.round(firstimage_scrollContainer.scrollLeft / imageWidth);

            dots.forEach((dot, index) => {
                dot.classList.toggle('active', index === activeIndex);
            });
            }

            firstimage_scrollContainer.addEventListener('scroll', updateActiveDot);

    updateActiveDot();

  </script>

</html>

https://jsfiddle.net/Ds9999/3nk0zxg1/6/

I have been playing around in jsfiddle and I really cannot figure out why am I seeing a part of the remaining image on the left of the current image and the part of image increases gradually with each image scrolling towards right side.

Should I use jquery for this?

Is there a way to figure out Date format for the selected Country

I have a requirement of changing the date format based on selected country .
As an example,

If We select America as country, date should be formatted in MM-DD-YYYY.
If We choose India , It should be changed to DD-MM-YYYY format.

I understand Using Locale we can achieve this. But unfortunately there is no library supporting coutry-locale or timezone-Locale mapping.
It will be a great help to know if there is any javascript library which supports or gives any way to get the date format for the selected Country.

I have checked most of famous libarries like luxon,Day.js,moment,day-fnz,moment-timezone. But couldn’t see a way to Auto Format date for the selected Country.

Any leads will be highly appreciated !!.

How do I execute a swap on Orca (solana)?

I’m having trouble executing a swap between the native SOL token and devUSDC on Devnet.

Despite following the documentation and using the Orca Whirlpools SDK, I encounter errors when trying to retrieve the pool information or send the swap transaction. Could someone provide guidance on executing swaps with SOL in a Devnet environment using the Orca Whirlpools SDK?

const { PublicKey, Keypair, Connection } = require("@solana/web3.js");
const { AnchorProvider, Wallet } = require("@coral-xyz/anchor");
const { DecimalUtil, Percentage } = require("@orca-so/common-sdk");
const {
  WhirlpoolContext, buildWhirlpoolClient, ORCA_WHIRLPOOL_PROGRAM_ID,
  PDAUtil, swapQuoteByInputToken, IGNORE_CACHE
} = require("@orca-so/whirlpools-sdk");
const Decimal = require("decimal.js");

async function main() {
  const secretKey = Uint8Array.from([]); // hidden private key
  const keypair = Keypair.fromSecretKey(secretKey);

  const provider = new AnchorProvider(
    new Connection("https://api.devnet.solana.com"), 
    new Wallet(keypair), 
    { commitment: "confirmed" }
  );

  const ctx = WhirlpoolContext.withProvider(provider, ORCA_WHIRLPOOL_PROGRAM_ID);
  const client = buildWhirlpoolClient(ctx);

  console.log("endpoint:", ctx.connection.rpcEndpoint);
  console.log("wallet pubkey:", ctx.wallet.publicKey.toBase58());

  const SOL = { mint: new PublicKey("So11111111111111111111111111111111111111112"), decimals: 9 };
  const devUSDC = { mint: new PublicKey("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"), decimals: 6 };

  const DEVNET_WHIRLPOOLS_CONFIG = new PublicKey("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR");

  const tick_spacing = 64;
  const whirlpool_pubkey = PDAUtil.getWhirlpool(
    ORCA_WHIRLPOOL_PROGRAM_ID,
    DEVNET_WHIRLPOOLS_CONFIG,
    devUSDC.mint, SOL.mint, tick_spacing).publicKey;
  console.log("whirlpool_key:", whirlpool_pubkey.toBase58());
  const whirlpool = await client.getPool(whirlpool_pubkey);

  const amount_in = new Decimal("1");

  const quote = await swapQuoteByInputToken(
    whirlpool,
    SOL.mint,
    DecimalUtil.toBN(amount_in, SOL.decimals),
    Percentage.fromFraction(10, 1000),
    ctx.program.programId,
    ctx.fetcher,
    IGNORE_CACHE,
  );

  console.log("estimatedAmountIn:", DecimalUtil.fromBN(quote.estimatedAmountIn, SOL.decimals).toString(), "SOL");
  console.log("estimatedAmountOut:", DecimalUtil.fromBN(quote.estimatedAmountOut, devUSDC.decimals).toString(), "devUSDC");
  console.log("otherAmountThreshold:", DecimalUtil.fromBN(quote.otherAmountThreshold, devUSDC.decimals).toString(), "devUSDC");

  const tx = await whirlpool.swap(quote);
  const signature = await tx.buildAndExecute();
  console.log("signature:", signature);

  const latest_blockhash = await ctx.connection.getLatestBlockhash();
  await ctx.connection.confirmTransaction({ signature, ...latest_blockhash }, "confirmed");
}

main();

Error

endpoint: https://api.devnet.solana.com
wallet pubkey: 7hFWw6SXZcG6bmwojV83eeQ185qc2mtPo9MShWFh9Cz2
whirlpool_key: HXwmqC2YGGUFFneeqcYJKw2J65qQA84FVkPTgnYMRp7L
/Users/xxx/node_modules/@orca-so/whirlpools-sdk/dist/impl/whirlpool-client-impl.js:36
            throw new Error(`Unable to fetch Whirlpool at address at ${poolAddress}`);
                  ^

Error: Unable to fetch Whirlpool at address at HXwmqC2YGGUFFneeqcYJKw2J65qQA84FVkPTgnYMRp7L
    at WhirlpoolClientImpl.getPool (/Users/xxx/node_modules/@orca-so/whirlpools-sdk/dist/impl/whirlpool-client-impl.js:36:19)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async main (/Users/xxx/solbuy.js:47:21)

How to get the id of a form while scrolling through a document of forms

I have a form container that holds many forms stacked on top of each other. I want to get the id of the form closest to the scroll position as the user scrolls through the forms. I have tried using

let element = document.elementFromPoint(left, top);
let id = element.id;

I have also tried

let id = element.getAttribute('id');

All I get is an empty string, even though each form as a unique id.