Syntax on accessing authorization header of an API request in node

const authHeader = req.headers["authorization"];
Apologies if this question may seem basic, but I am curious why we use [“authorization”] and not just .authorization

I did some research and found that it had to do with the lower/upper casing, but the answers I found were not clicking well with me. I was wondering if someone had a better explanation.

FixedColumn Not Functioning in DataTables

I am a total noob when it comes to web design and would like to create a datatable with a fixed (frozen) left two columns. I am reading in my data successfully from a JSON file and the information is displayed successfully. However, when I try to set the columns to fixed, it just doesn’t happen.

Below is a test example from my html file. My input into JSFiddle works just fine, but the fixed columns are not rendering at all on my website.

I am using Hugo as my framework for my website, so if information from other files is needed, please let me know. The code snippet below is from a partial that gets called.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fixed Columns Example</title>


    <link href="https://cdn.datatables.net/2.1.0/css/dataTables.dataTables.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/v/dt/dt-2.1.0/fc-5.0.1/datatables.min.css" rel="stylesheet">
    <style>
        table {
            width: 20%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
        }
        th {
            background-color: #f4f4f4;
        }
    </style>
</head>
<body>
    <table id="example" class="stripe row-border order-column" style="width:100%">
        <thead>
            <tr>
                <th>First name</th>
                <th>Last name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
                <th>Extn.</th>
                <th>E-mail</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger</td>
                <td>Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011-04-25</td>
                <td>$320,800</td>
                <td>5421</td>
                <td>[email protected]</td>
            </tr>
            <tr>
                <td>Garrett</td>
                <td>Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011-07-25</td>
                <td>$170,750</td>
                <td>8422</td>
                <td>[email protected]</td>
            </tr>
            <tr>
                <td>Ashton</td>
                <td>Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009-01-12</td>
                <td>$86,000</td>
                <td>1562</td>
                <td>[email protected]</td>
            </tr>
           
        </tbody>
    </table>



    <!-- jQuery first -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/v/dt/dt-2.1.0/datatables.min.js"></script>
    <!-- FixedColumns JS -->
    <script src="https://cdn.datatables.net/v/dt/dt-2.1.0/fc-5.0.1/datatables.min.js"></script>
    <script>
        $(document).ready(function() {
            // Initialize DataTable with FixedColumns
            $('#example').DataTable({
                scrollX: true,
                scrollY: '400px',
                scrollCollapse: true,
                paging: false,
                fixedColumns: {
                    left: 1 // Number of columns to fix
                }
            });
        });
    </script>
</body>
</html>

NextJS 14 not consistently loading scripts

On NextJS 14.1.3 I am seeing some strange behavior I do not understand. When I am visiting a page that loads JS from a file the application does not pull the JS every time. Like maybe doesn’t load them 1/10 loads. I am thinking it is some race condition on the script loading vs hydration but I cannot seem to figure it out. I have tried every <Script strategy="beforeInteractive | afterInteractive | lazyOnload" /> and I also tried using next/dynamic to load the specific component and it still wouldn’t work. Any ideas?

Layout.tsx

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {

  return (
    <html lang="en">
      <Script strategy="afterInteractive" src="https://cdn.jsdelivr.net/npm/apexcharts" />
      <Script strategy="afterInteractive" src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js" />
      <Script strategy="afterInteractive" src="/hs-apexcharts-helpers.js" />
      <body>
        ...
      </body>
    </html>
  );
}

Chart.tsx

export default function NetWorthChart() {
  useEffect(() => {
    if (typeof window !== "undefined") {
      buildChart('#hs-sales-line-chart');
    }
  }, []);

  return ();
}

public/hs-apexcharts-helpers.js

function buildChart(...) {...}

I tried swapping the script strategies. I tried next/dynamic loading the component.

terser-webpack-plugin and uglifyjs-webpack-plugin

Since webpack 4 is using terser-webpack-plugin by default in production mode or when we specify -p argument which is a shortcut for specifying --optimize-minimize --define process.env.NODE_ENV="production" , in both of these cases it uses terser-webpack-plugin for minimizing JS bundle.
Now my question is if someone did not go through the documentation or might have missed it somehow (which actually happened in a major application), and specified uglifyjs-webpack-plugin in the plugin array like this

    plugins: [
      new CleanWebpackPlugin([TARGET_SERVER], {
        root: BASE_PATH + '/' + OUTPUT_PATH
      }),
      new UglifyJsPlugin(),
   ]

Now this plugin also do the same thing which is optimizing the bundle, now we have specified both of the plugins, one is used by default and another one we specified in plugin array (if it would have been specified as optimization.minimizer , it would have overridden the behavior of terser plugin) , but what will happen in this case

Now in my case what happened is that, it was configured like this, and was working fine for last 3 years , and suddenly it started giving error which is stated in this question, i have already solved it by removing UglifyJsPlugin from the plugin array

Please help me to understand what could have caused this problem

Change site name

I can’t change the site name, I tried adding a tag
<meta property="og:site_name" content="sitename">
tried schema.org

    <head>
      <script type="application/ld+json">
        {JSON.stringify({
          "@context": "https://schema.org",
          "@type": "WebSite",
          "url": "https://sitename.com",
          "name": "sitename",
          "description": "description",
          "image": "https://sitename.com/logo_small.png",
        })}
      </script>
      <link rel="canonical" href="https://sitename.com"/>
    </head>

none of this helped, instead of the site name it just shows a link to it
it’s about displaying the site name as it appears as you type, example:
enter image description here
for example, here the site name is displayed correctly (X Twitter), in my case a link is displayed instead of the name (as if in the case of Twitter it was displayed (https://twitter.com/instagram)

W3.CSS Tab Navigation Issue

In the code below I have two sections of a table that have three tabs each. They are based of the Tabs example on W3 Schools page, hence why it still refers to “city” instead of something like “sport”. The issue that I am having is that when I activate one tab in one section, it completely deactivates the tab in the other table section SITE LINK WITH PROBLEM. code posted below.

<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<div class="w3-container">
<h2>Trojan Athletic Fund</h2>

<table border="1" cellpadding="1" cellspacing="1" style="height:100%;width:100%;">
    <tbody>
        <tr>
            <td style="vertical-align: middle; width: 50%;">
            <div class="sidearm-story-image-align-center" style="text-align:center; margin:0px; padding:0px"><img alt="Baseball TAF Photo" height="333" src="/images/2024/7/19/AU_Baseball_0251-2-1024x683__1_.jpeg" style="display: inline-block;" width="500" /></div>
            </td>
            <td>
            <div class="sidearm-story-image-align-center" style="text-align:center"><img alt="WBB TAF Photo" height="333" src="/images/2024/7/19/AU_WBB_379-1024x617__1_.jpeg" style="display: inline-block;" width="500" /></div>
            </td>
        </tr>
        <tr>
            <td style="width: 50%; vertical-align: top;">
            <div class="parent_target">
            <div class="w3-row">
            <div class="w3-third w3-bottombar w3-hover-light-grey w3-padding"><a href="javascript:void(0)" onclick="openCity(this, 'Baseball1');">Baseball One</a></div>

            <div class="w3-third w3-bottombar w3-hover-light-grey w3-padding"><a href="javascript:void(0)" onclick="openCity(this, 'Baseball2');">Baseball Two</a></div>

            <div class="w3-third w3-bottombar w3-hover-light-grey w3-padding"><a href="javascript:void(0)" onclick="openCity(this, 'Baseball3');">Baseball Three</a></div>
            </div>

            <div class="w3-container city" id="Baseball1">
            <h2>Team Website</h2>

            <p>Stay up to date with how your Trojans are doing this season! <a href="www.autrojans.com/sports/baseball">Trojans Baseball</a></p>
            </div>

            <div class="w3-container city" id="Baseball2" style="display:none">
            <h2>Coaches Letter</h2>

            <p><strong>Dear Trojan Army,</strong> Greetings from Anderson University Baseball! On behalf of our Trojans, I would like to thank you for supporting our mission of providing an exceptional academic and athletic experience for our student-athletes. As the Baseball coach, your generosity ensures that each student-athlete can have fun, explore their faith, form relationships, and build accountability within their teams. Additionally, Anderson University Athletics continually leads the South Atlantic Conference in academic standing and consistently breaks school records in competition and in the classroom each year! Over the last few years, gifts to the Trojan Athletic Fund and Baseball have supported us as we have continued to improve and make waves in the SAC. We ousted third-seed Catawba from the first round of the SAC tournament in 2023 and are looking forward to an exciting 2024 season! Anderson University Baseball thanks you and we look forward to seeing you at our games soon! <strong>Go Trojans!</strong> Coach PJ Zocchi Anderson University Baseball</p>
            </div>

            <div class="w3-container city" id="Baseball3" style="display:none">
            <h2>Projects</h2>

            <p>Equipment</p>

            <ul>
                <li>Bats</li>
                <li>Baseballs</li>
                <li>Gloves</li>
            </ul>

            <p>Technology</p>

            <ul>
                <li>Trackman Baseball</li>
                <li>Rapsodo Baseball</li>
                <li>New Scoreboard</li>
            </ul>
            </div>
            </div>
            </td>
            <td style="width: 50%; vertical-align: top;">
            <div class="parent_target">
            <div class="w3-row">
            <div class="w3-third w3-bottombar w3-hover-light-grey w3-padding"><a href="javascript:void(0)" onclick="openCity(this, 'WBB1');">WBB One</a></div>

            <div class="w3-third w3-bottombar w3-hover-light-grey w3-padding"><a href="javascript:void(0)" onclick="openCity(this, 'WBB2');">WBB Two</a></div>

            <div class="w3-third w3-bottombar w3-hover-light-grey w3-padding"><a href="javascript:void(0)" onclick="openCity(this, 'WBB3');">WBB Three</a></div>
            </div>

            <div class="w3-container city" id="WBB1">
            <h2>Team Website</h2>

            <p>Stay up to date with how your Trojans are doing this season! <a href="www.autrojans.com/sports/baseball">Trojans Baseball</a></p>
            </div>

            <div class="w3-container city" id="WBB2" style="display:none">
            <h2>Coaches Letter</h2>

            <p><strong>Dear Trojan Army,</strong> Greetings from Anderson University Baseball! On behalf of our Trojans, I would like to thank you for supporting our mission of providing an exceptional academic and athletic experience for our student-athletes. As the Baseball coach, your generosity ensures that each student-athlete can have fun, explore their faith, form relationships, and build accountability within their teams. Additionally, Anderson University Athletics continually leads the South Atlantic Conference in academic standing and consistently breaks school records in competition and in the classroom each year! Over the last few years, gifts to the Trojan Athletic Fund and Baseball have supported us as we have continued to improve and make waves in the SAC. We ousted third-seed Catawba from the first round of the SAC tournament in 2023 and are looking forward to an exciting 2024 season! Anderson University Baseball thanks you and we look forward to seeing you at our games soon! <strong>Go Trojans!</strong> Coach PJ Zocchi Anderson University Baseball</p>
            </div>

            <div class="w3-container city" id="WBB3" style="display:none">
            <h2>Projects</h2>

            <p>Equipment</p>

            <ul>
                <li>Bats</li>
                <li>Baseballs</li>
                <li>Gloves</li>
            </ul>

            <p>Technology</p>

            <ul>
                <li>Trackman Baseball</li>
                <li>Rapsodo Baseball</li>
                <li>New Scoreboard</li>
            </ul>
            </div>
            </div>
            </td>
        </tr>
    </tbody>
</table>
<br />
<script> function openCity(elem, cityName) { var i, x, tablinks; x = document.getElementsByClassName("city"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } document.getElementById(cityName).style.display = "block"; evt.currentTarget.firstElementChild.className += " w3-border-red"; } </script></div>

I’ve tried changing the city names, adding a parent-element feature and still am having the issue.

Node – `url.startWith()` is not a function [closed]

I have a url returned in url as a string.

I want to check if the url sent start with a specific path.

However, the console returns that url.startWith is not a function.

I am using Node.js.

function fun(url){
console.log(url) //returns https://www.example.com /page_1/12

const checkString = "https://www.example.com /page_1/"
console.log(checkString) //returns https://www.example.com/page_1/

if(url.startWith(checkString)){
console.log("true")
}else{
console.log("false")
}
}

Can you see what I am doing wrong?

I found a few posts with a similar topic, however the errors detailed in other posts seem to be related to the fact the variable was a value and not a string.

Iframe with html is refreshing itself after a submission. In original html this is not occuring

In newsletter.html (lets call that my file) I have created a newsletter, user submits an email, then its in my JSON file.

I have my homepage.html, I put iframe from newsletter.html, it all working, except after I submit my email, page refreshes itself in no time.

This is a video: https://gyazo.com/d67ec1745e2ee041380c98d836403f82

I do not know how to prevent that.

The only thing that will prevent iframe automatically from reloading the page its this:

window.addEventListener("beforeunload", function(event) {
  event.preventDefault();
  event.returnValue = '';

  
});

But this creates a window alert about reloading the page. I tried to disable that window alert, but I dont think that is a possibility.

So my desired outcome is to prevent iframe from reloading after successful submission. I want my iframe to display this ‘Thanks ${emailName} for signing up!’. Ideally I would want my iframe to display this for like 5 seconds and that just disappear but I can life without it.

In newsletter.html its working like I want it to work, so I have gathered that its must be the iframe

I tried to write some js code in my homepage.js, but it did not work.

This is my html.

   <div class="container23">
      <iframe id="iframe2" src="http://localhost:3000"></iframe>
      <button type="button" id="close-button" class="close-button">&times;</button>
  </div>

Thanks.

How to submit data split into multiple children components without unnecessary re-renders

The challenge I’m facing in my React project is about submitting data that is split into multiple children.
Basically, I’m developing a recipe app, and I have the sub-root component RecipeCreator. This parent component renders some children components, deputed to collect the infos from the user to create a recipe to be stored in the database. The children all have different duties: one is deputed to ask the user for a recipe image, another one handles the “body” of the recipe, another one takes care of gathering the ingredients required.
Each one of them is quite complex, since for example the IngredientsSelector implements a logic to generate accordions based on the ingredients the user chooses, implementing an autocomplete mechanism based on the already existing ingredients on the DB and such; the RecipeEditor implements a custom react-quill text editor, and so on.

Now, after coding and testing such children components, I’m clueless on what’s the best approach to put together all the pieces and send the infos to the database.

I’m thinking about three different approaches:

  • Declare a single / multiple state in the parent component (RecipeCreator), with a complex data structure tha should store all the data from the children, and pass the state setters appropriately to each child component. The button “Submit” is placed in the parent’s logic, therefore it just needs to create an object from the big state objects (or multiple states) and call the POST API. I’m very dubious about this, because each time a child changes its state, the parent captures the change and re-renders, re-rendering all the children. While I can wrap the children in a React.Memo wrapper, I don’t think this is the best solution. Take for example the “extreme case” of the child RecipeEditor. The react-quill input is controlled by the state, and each keystroke would end up triggering a re-render of the component plus the parent, since the latter provided the state setter to get what’s been typed.

  • Make use of the Redux store I already implemented: not only I find unnecessary to store all the infos the user is typing into the store, but the problem of the parent’s re-rendering after each keystroke would still be present, because it needs to subscribe to that piece of the store with a useSelector() hook that would in fact act very similarly to the state setter passed through props to the children as discussed previously.

  • Putting a “save changes” button in each child component, so the parent would see the edits only if the user clicked on the save button in each section (ingredients component, recipe editor component, image uploader component…). While this could work to cut out unnecessary re-renders, I don’t like the style of this approach and I’m not a fan of multiple “save” buttons in the same page / forms.

Jest react test : API call failed TypeError: Cannot read properties of undefined (reading ‘json’)

I am going to test the components below through the jest and react test library.

I want to test if the API is called normally when I press the button, So I made the API calling part mock.

However, this error appears.

console.log
  API call failed TypeError: Cannot read properties of undefined (reading 'json')

I tried because there was advice to remove the .json() part from wait response.json(); but failed to resolve the error.

Below is the detailed code.

MyButton.js

const MyButton= ({incrementFn, decrementFn}) => {
    const apiFunction = async() => {
        const dataToSend = { key: 'value' };
        try {
            const response = await fetch('https://api.example/data', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify(dataToSend),
              });
            const data = await response.json();
            console.log(data);
            return data;
          } catch (error) {
            console.log('API call failed', error);
          }
    };

    return (
        <div>
            <button onClick={apiFunction} data-testid="apiButton">API</button>
            <h1>value</h1>
        </div>
    )
};

export default MyButton;

button.test.js

import {render, screen, fireEvent, waitFor} from '@testing-library/react'
import MyButton from './MyButton'

const fakeData = {
    name: "Joni Baez",
    age: "32",
    address: "123, Charming Avenue"
  };

global.fetch = jest.fn().mockImplementation(()=>{
    Promise.resolve({
        ok: true, 
        json: () => Promise.resolve(fakeData),
    })
});


afterEach(() => {
    jest.clearAllMocks();  
});

describe('<MyButton/>', () => {
    it('calls API mock', async () => {
        render(<MyButton/>);

        const apiButton = screen.getByTestId('apiButton');
        fireEvent.click(apiButton);
        
        await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));

        expect(fetch).toHaveBeenCalledWith('https://api.example/data', expect.objectContaining({
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
        }));
    })
})

Links not longer working when navigating to another view

So, when I used this code to go from the view to another with props.

this my first view :

  <template>
  
  <Spinner />
  <Header />
  <main class="main">

  <Heading />
  <LatestJobs />
  <JobsByCategory />
</main>
  <Footer />

</template>

<script>
import Header from "@/components/generic/Header.vue";
import Footer from "@/components/generic/Footer.vue";
import Heading from "@/components/home/Heading.vue";
import LatestJobs from "@/components/home/LatestJobs.vue";
import JobsByCategory from "@/components/home/JobsByCategory.vue";

Inside <LatestJobs /> I have this code :

<h5>
<router-link :to="{ name: 'JobDetail', 
                    params: { id: item.id } }">
              {{ item.title }}</router-link>
</h5>

So by clicking on the title I want to open this view :

 {
path: '/job/:id',
name: 'JobDetail',
component: JobDetailView,  
props: true
 }

and this is my view :

 <template>    
    <Header />
    <JobDetail :jobId="Number(id)" />
    <Footer />
  </template>
  
  <script setup>
  import Header from "@/components/generic/Header.vue";
  import Footer from "@/components/generic/Footer.vue";
  import JobDetail from "@/components/generic/JobDetail.vue";
  import { useRoute } from 'vue-router';
  import { onMounted } from "vue";
  
  const route = useRoute();
  const id = route.params.id;
  console.log("route",route.params.id)
  </script>

The view is loaded and the id is being passed like it should be and I’m getting the job informations by that id. But the problem is that the header component that has links are not working .. seems like the page is stuck.

Same header component is working on the other views. I even have some css style when I hover with my mouse , it doesn’t work. the console is not showing any error.

error with the path to import GLTF loader on threeJs

I had a problem who persist with a test project with three js…

i made my 3d models on blender anbd export him to .glb format and now try to imoport it to my scene with GLTF Loader but always the same error on the console.

this is my html :

<html lang="en">
<head>
   <meta charset="utf-8">
   <title>My first three.js app</title>
   <script type="module">
       window.onload = () => {
           const canvas = document.getElementById('canvas');
           canvas.width = window.innerWidth / 4;
           canvas.height = window.innerHeight / 2;
       }
   </script>
   <script type="module" src="./index.js"></script>
   <link rel="stylesheet" href="style.css">
</head>
<body>
   <h1>Salut</h1>
   <div id="canvasPlace">
       <canvas id="canvas"></canvas>
   </div>
</body>
</html>

this is my js :

import * as THREE from '/node_modules/three/build/three.module.js'
import { GLTFLoader } from '/node_modules/three/examples/jsm/Addons.js';

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight)

const loader = new GLTFLoader();

loader.load( '/models/logoFini.glb', function ( gltf ) {

    scene.add( gltf.scene );

}, undefined, function ( error ) {

    console.error( error );

} );

camera.position.set(0, 0, 4)

const renderer = new THREE.WebGLRenderer({ canvas })

loop()
function loop() {
    requestAnimationFrame(loop)
    mesh.rotation.y += 0.01
    renderer.render(scene, camera)
}

and this is my console error :

Uncaught TypeError: Failed to resolve module specifier “three”. Relative references must start with either “/”, “./”, or “../”.

I upload my folder architecture too :

folder architecture

i Think the solution is in the path to import my gltf loader but idk how too fix it…

i try the path from the THREEjs docs but nothing happend

Error processing user query: TypeError: Cannot read properties of undefined (reading ‘0’)

I want to select data from my supabase DB using a function ( calling it with rpc ). However Im getting this problem: Error processing user query: TypeError: Cannot read properties of undefined (reading ‘0’)
this is my code :

// Import necessary libraries and initialize Supabase client
import { createClient } from '@supabase/supabase-js';
import axios from 'axios';
import { PDFDocument } from 'pdf-lib';
const pdfjsLib = await import('pdfjs-dist/legacy/build/pdf.mjs');


const url = "my url is here";
const key = "my key is here";
const supabase = createClient(url, key);

const API_KEY = "my key is in write permettion ";
const model = 'sentence-transformers/paraphrase-MiniLM-L6-v2';


// Encode text sentences
async function encodeTextSentences(sentences) {
    try {
        const response = await axios.post(
            `https://api-inference.huggingface.co/models/${model}`,
            { inputs: sentences },
            {
                headers: {
                    'Authorization': `Bearer ${API_KEY}`,
                    'Content-Type': 'application/json'
                }
            }
        );
        return response.data;
    } catch (error) {
        console.error('Error encoding sentences:', error);
    }
}

// Store embeddings in Supabase
async function storeEmbeddings(embeddingsData) {
    const { error } = await supabase
        .from('embeddings_table')
        .insert(embeddingsData);
    return error;
}

// Extract text from PDF
async function extractText(pdfUrl) {
    const response = await fetch(pdfUrl);
    const pdfBuffer = await response.arrayBuffer();
    const pdfDoc = await PDFDocument.load(pdfBuffer);
    const pdf = await pdfjsLib.getDocument({ data: pdfBuffer }).promise;
    let text = '';
    for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
        const page = await pdf.getPage(pageNum);
        const textContent = await page.getTextContent();
        text += textContent.items.map(item => item.str).join(' ') + 'n';
    }
    return text;
}

// Process user query and fetch relevant files
async function processUserQuery(processedQueryText, similarityThreshold) {
    try {

        const queryEmbedding = (await encodeTextSentences([processedQueryText]))[0];

        const { data, error } = await supabase.rpc("filter_embeddings", {
            query_embedding: queryEmbedding,
            similarity_threshold: similarityThreshold
        });

        if (error) {
            console.error("Error fetching embeddings from Supabase:", error);
            return;
        }

        if (data && data.length > 0) {
            data.sort((a, b) => b.similarity - a.similarity);
            return data;
        } else {
            console.log("No relevant files found with the specified similarity threshold.");
        }
    } catch (error) {
        console.error("Error processing user query:", error);
    }
}

// Get best similarity threshold
async function bestSimilarity(queryText) {
    try {
        const results = await processUserQuery(queryText, 0);
        if (!results || results.length === 0) {
            console.error("No results found.");
            return null;
        }
        let similarityThreshold = 0;
        const firstFile = results[0].file;

        for (let i = 1; i < results.length; i++) {
            if (results[i].file !== firstFile) {
                similarityThreshold = results[i - 1].similarity;
                break;
            }
        }
        return similarityThreshold;
    } catch (error) {
        console.error("Error in bestSimilarity:", error);
    }
}

// Main function
(async () => {
    try {
        const queryText = "what is a robot";
        const similarityThreshold = await bestSimilarity(queryText);
        const sentences = await processUserQuery(queryText, similarityThreshold);

        console.log("Most pertinent files:");
        if (sentences) {
            sentences.forEach(sentence => {
                console.log(`PdfName: ${sentence.file}, Similarity: ${sentence.similarity}`);
            });
        }
    } catch (error) {
        console.error("Error in main execution:", error);
    }
})();


I was expecting to see most pertinent files for a user query and I got no result
What should I do ??

How to layout child elements so they will not move when parent element resizes or moves?

I have a parent div and place three svg ellipses and a image inside it. They need to have a certain position on top of the div. This position needs to be always the same no matter where the div moves or if it shrinks/grows (i want to execute an event when a certain position on the image gets clicked).

So far i was able to make the child elements shrink/grow with the parent div. They have a stable position inside the div, as long as top and left attribute is zero. As this is not possible, i am not sure how to accomplish it.

export const Example = () => {
  const hello1 = () => {
    // Add your event handling logic here
    window.alert("Hello 1!");
  };
  const hello2 = () => {
    // Add your event handling logic here
    window.alert("Hello 2!");
  };

  const hello3 = () => {
    // Add your event handling logic here
    window.alert("Hello 3!");
  };

return (
    <div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", position: "relative" }}>
        <img src={VillageBack} alt="Village Back" style={{ flex: 1, objectFit: "contain" }} />
        <svg width="100%" height="100%" viewBox="0 0 100 100" style={{ position: "absolute", top: -250, left: 0 }} >
          <ellipse cx="50" cy="50" rx="10" ry="15" fill="blue" style={{ cursor: "pointer" }} onClick={hello1} />
        </svg>
        <svg width="100%" height="100%" viewBox="0 0 100 100" style={{ position: "absolute", top: 0, left: -190 }} >
          <ellipse cx="50" cy="50" rx="10" ry="15" fill="blue" style={{ cursor: "pointer" }} onClick={hello2} />
        </svg>
        <svg width="100%" height="100%" viewBox="0 0 100 100" style={{ position: "absolute", top: -140, left: 280 }} >
          <ellipse cx="50" cy="50" rx="10" ry="15" fill="blue" style={{ cursor: "pointer" }} onClick={hello3} />
        </svg>
     
    </div>
  );
};

I am using it in react, but should be applicable for plain js as well.

My second problem is, that only the lowest svg is clickable. All others do not get recongized. Why? They are not overlapping

GOOD, because not shrinked
good state

BAD, because shrunk
bad state