minIndex always = i even after changing its value multiple times?

i’m new to javascript and programming (3 months) and am trying to make a sorting algorithm visualizer like the ones you see on youtube. i had an issue where the for loops usually used were just way to quick to actually visualize so i just replaced the for loops with intervals. this has worked for bubble, insertion, quick and a few other sorting algorithms but i cant for the life of me get selection to work. for some reason when the swap(index1, index2) function is called minIndex and selectionI are always the same. i did the good old console.log and everything seems to work right until the swap function. its been 3 days of suffering and no progress please i need help or pointers

function selectionSort2() {
    let selectionI = 0;
    const selectionIloop = setInterval(() => {
        if(selectionI > arr.length) {
            clearInterval(selectionIloop);
        }
        let minIndex = selectionI;
        let selectionJ = selectionI+1;
        const selectionJloop = setInterval(() => { 
            if(selectionJ > arr.length) {
                clearInterval(selectionJloop);
            }
            if(arr[selectionJ] < arr[minIndex]) {
                minIndex = selectionJ;
            }
            selectionJ++;
        }, 100);
        swap(minIndex, selectionI);
        selectionI++;
    }, 100)
}

i was able to get it partially working by changing the selectionJloop to a for loop like this

function selectionSort() {
    let selectionI = 0;
    const selectionIloop = setInterval(() => {
        if(selectionI > arr.length) {
            clearInterval(selectionIloop);
        }
        let minIndex = selectionI;
        for(let j = selectionI+1; j < arr.length; j++) {
            if(arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        } 
        swap(minIndex, selectionI);
        selectionI++;
    }, 100)
}

but because the for loop doesnt have the 0.1s delay this version has an unfair advantage against the other algorithms whose for loops are restricted. also note that when i put a 0.1s delay inside the for loop as a setTimeout() that it resulted in the same issue as before.

at first i thought that it could be the delay time like the intervals cant have the same delay time but even after changing both of them many many times it just refuses to work.

and just incase heres my swap function:

function swap(index1, index2) {
    temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
}

i tried changing the interval times to be different from eachother. i tried replacing the intervals with for loops with timeouts instead. i tried completely rewriting it in a different way. whats supposed to happen is minIndex should be the index of the smallest number in the arr whose index isnt less then i+1 but instead minIndex always becomes the same value as i

Import results in null

I am trying to import fs (node file system), but when I try to run some methods from fs, I get an error saying:

Uncaught TypeError: null has no properties

I am using Vite to run my code, and I needed to install a pollyfill plugin for Vite so fs will run, but all fs results in is null.

Is the plugin doing this? Is there a better way I can import fs?

import fs from 'node:fs';
fs.readFile('../../../hello.txt', (err, data) => {
if (err) {
    console.error(err);
    return;
}
console.log(data);
});

I wouldn’t be surprised if it was the Pollyfill plugin since it just makes it more compatible for older versions of browsers.

How to Add Bearer Token for Authentication in Video.js Using Nuxt 3?

I’m developing a Nuxt 3 application where I need to play videos using Video.js. The video files are protected and require a bearer token for authentication. I’m trying to add the token to the request headers in the Video.js setup, but I’m not sure if I’m doing it correctly.

<template>
  <div :class="id ? 'w-72 h-auto' : ''">
    <video
      ref="videoPlayer"
      class="video-js vjs-default-skin w-full h-full"
      controls
      preload="auto"
      :poster="poster"
    >
      <source :src="videoSrc" type="video/mp4" />
    </video>
    {{ videoSrc }}
  </div>
</template>

<script setup>
import { useNuxtApp } from '#app'
import { ref, onMounted, onBeforeUnmount } from 'vue'

const userAccessToken = useCookie('user_access_token')

const props = defineProps({
  videoSrc: { type: String, required: false },
  poster: { type: String, default: '' },
  id: { type: String, default: '' }
})

const videoPlayer = ref(null)
const { $videojs } = useNuxtApp()
const poster = ref()

const fetchPosterAsBlob = async (posterUrl) => {
  if (!posterUrl) return ''

  try {
    const response = await fetch(posterUrl, {
      headers: {
        Authorization: `Bearer ${userAccessToken.value}`
      }
    })
    if (!response.ok) {
      console.error('Failed to fetch poster image')
      return ''
    }
    const blob = await response.blob()
    return URL.createObjectURL(blob)
  } catch (error) {
    console.error('Error fetching poster image:', error)
    return ''
  }
}

onMounted(async () => {
  if (!userAccessToken.value) {
    console.error('Missing user access token for video playback.')
    return
  }

  const posterBlobUrl = await fetchPosterAsBlob(props.poster)
  poster.value = posterBlobUrl

  const player = $videojs(videoPlayer.value, {
    autoplay: false,
    controls: true,
    responsive: true,
    fluid: true
  })

  player.ready(() => {
    const vhsOptions = player.tech()?.vhs || player.tech()?.hls;

    if (vhsOptions) {
      vhsOptions.xhr.beforeRequest = (options) => {
        options.headers = options.headers || {}
        options.headers.Authorization = `Bearer ${userAccessToken.value}`
        return options
      }
    } else {
      console.error('VHS or HLS is not properly initialized.')
    }
  })

  onBeforeUnmount(() => {
    if (player) {
      player.dispose()
    }
  })
})
</script>

<style scoped>
.video-js {
  width: 100%;
  height: 100%;
}
</style>

Any advice or guidance on how to properly add a bearer token for video playback in this setup would be greatly appreciated!

Is there a way to repeat an observable until other observable emits?

I’m trying to run an observable repeatedly until some other observable is emitted.
I don’t want to stop currently unfinished observable, I only want it not to repeat again.

ts/rxjs

I tried using takeUntil, but this closes the stream$, without it actually finishing (it cuts it before 1000ms timer).

const stream$ = interval(1).pipe(takeUntil(timer(1000)));
stream$.pipe(repeat(), takeUntil(timer(1500)));

If we agree that stream$ runs for 1000ms before closing, what I expect to happen is that it should run 2 times 1000ms in this case. I need some sort of operator that would stop repeating the observable upon some event$.

Something like this:

const stream$ = interval(1).pipe(takeUntil(timer(1000)));
stream$.pipe(repeatUntil(timer(1500)));

sketch

Is possible override js widget?

I have js saas widget for integration on page. The page works as spa. I don’t like some behavior and want override it. For example, product search pop up in new modal, and when click on search result there is another one modal with product card. How I can override that, modals opens in another browser tab. Any suggestions?

MutableObserver,onclick

`function onload(){}` is not the same as `window.onload=function(){}` – the former doesn’t fire on page load. Why?

Context: I’m trying to detect if the page has a window.onload function set (via window.onload=foo, not addEventListener).

I thought that I could simply check if typeof window.onload === "function", but that is true for this case:

<script>
  function onload() {
    console.log('onload called'); // this is *not* triggered on page load
  }
  typeof window.onload === "function"; // is true
  window.onload === onload; // is`true`
  window.hasOwnProperty("onload"); // is`true`
</script>

And yet that function is not automatically called during page load. I’ve tested in latest versions of Chrome and Firefox.

I thought that would be ~equivalent to this:

<script>
  window.onload = function() {
    console.log('onload called'); // this *is* triggered on page load
  };
</script>

But it seems that’s not the case (and it’s not due to the anonymity of the function).

How can I robustly detect whether an arbitrary page has an actual window.onload set (one that is triggered on page load, I mean), and not just e.g. a global function called onload?

Creating a web worker in a Stackblitz Lit Element Project?

I’m trying to create a web worker in a Lit Element Stackblitz Project.

This is the worker (worker.js):

onmessage = (e) => {
  console.log(e.data);
  postMessage(e.data);
};

And this is the code that creates it ( In my-element.ts` ):

  constructor() {
    super();
    const worker: Worker = new Worker('worker.js');
    console.log(worker);
    worker.postMessage('hello');
    worker.onmessage = (e) => {
      console.log(`The worker posted back ${e.data}`);
    };
  }

And the demo, when viewed with developer tooling, does not log any messages inside or from the worker, however it does log:

SyntaxError: Unexpected token ‘<‘ (at worker.js:1:1)

And I’m trying to figure out whether this is a Stackblitz bug and if there are any ways of getting around it?

Thoughts?

How to show the sibling with a specific class?

I have the following html

<div class = "template">
  <img src = "test" />
  <dic class = "rendition">Test 1</div>
</div>

When the img errors out, I want to show the rendition element which is hidden by default (using CSS).

Here’s what I have as the code so far:

I want to add an onerror handler and than have it call the below:

I’m using typescript.

private _onImageError(event: ErrorEvent) {
    const imageElement = event.target as HTMLImageElement;
    imageElement.onerror = null;
    imageElement.style.display = "none";
    let nextElement = this.nextElementSibling as HTMLElement;
    while (nextElement) {
        if (nextElement.classList.contains('asset-loading-error-state')) {
            nextElement.style.display = 'block'; // Hide the element
            break; // Stop after hiding the first match
        }
        nextElement = nextElement.nextElementSibling as HTMLElement;
    }
}

The issue is this is not working. When the image errors out, it’s not showing the rendition DIV.

Open barcode reader application from web page on IOS devices

I have a web page, on android devices when you press a button it gives you the option to read a barcode using an application and then the result of the reading is returned to the web page.

For example on android this application works very well to read barcodes: https://play.google.com/store/apps/details?id=com.teacapps.barcodescanner&hl=en_US

Java script code

        function redirect_to_scanner() {
            let current_url = window.location.href.split('?')[0];
            let new_url = "zxing://scan/?ret=" + encodeURIComponent(current_url + "?barcode={CODE}");
            window.location.href = new_url;
        }

This codiog works perfectly on android devices but not on ios devices, in that case a message appears “An error occurred can not open the application”

Is there any other URI that I can use and that works on ios devices? or any way to make it work on ios devices?

The other option would be to open a barcode reader inside the web page written in java script like quagga js but I would like to avoid this option because it does not work very well to read 20 digit barcodes. Any recommendation?

undefined array keys in PHP

i’m trying to get information submitted from a table with rows that are dynamically added using javascript, i can’t get my PHP working, i keep getting undefined array key errors.
My input names are alright, what am i missing because i can’t see it?
Below are screenshots of my code and my errors, HELP.

PHP page 1
I did have my first job information submitting to my job info table working but can not get the amounts working, i have previously managed to get the first row submitting to the database but have never managed to get multiple rows submitting under one job number

PHP page 2

My add row button works
JS

DEV tools errors

any insight would be greatly appreciated.

tried changing the number that the loops start on and the numbers they stop on. The post data seems right, variables with increasing index numbers appended on the end of the variable names.

Redirecting Issue with Shortened URLs – Possible Database/Query Issue

I’m facing an issue with the URL shortening feature in my application. Specifically, valid shortCode entries are sometimes redirecting to incorrect URLs. I suspect there might be an issue with the way the database is handling the shortCode field or how the query logic is retrieving the URLs.

Here’s a quick summary of the problem:

Problem: When a user tries to access a shortened URL (e.g., https://myapp.com/abc123), the app redirects to the wrong original URL.
What I’ve Checked:
The shortCode entries in the database appear to be correct.
Environment variables seem to be set up correctly since authentication and other features are working fine.
The URL shortening process generates and saves shortCode as expected, but the retrieval goes wrong.

pages/[shortCode].tsx – Handles the redirect logic

import { GetServerSideProps } from 'next';

import dbConnect from '../utils/dbConnect';

import Url from '../models/Url';


// this to handle the URL redirection based on a shortCode parameter.

export const getServerSideProps: GetServerSideProps = async (context) => {
    try {
        await dbConnect();

        const { shortCode } = context.params;
        console.log('Fetching URL for shortCode:', shortCode);
        const urlEntry = await Url.findOne({ shortCode }).exec();
        console.log('URL Entry:', urlEntry);

        // use tenary operator that determines the value of the baseUrl variable 
        // based on the environment in which the application is running. Here's a breakdown of what it does:
        if (urlEntry) {
            const originalUrl = urlEntry.originalUrl.startsWith('http')
                ? urlEntry.originalUrl
                : `http://${urlEntry.originalUrl}`;
            console.log('Redirecting to:', originalUrl);

            return {
                redirect: {
                    destination: originalUrl,
                    permanent: false,
                },
            };
        } else {
            console.log('No URL entry found for shortCode:', shortCode);
            return {
                notFound: true,
            };
        }
    } catch (error) {
        console.error('Error in getServerSideProps:', error);
        return {
            notFound: true,
        };
    }
};

const RedirectPage = () => {
    return null;
};

export default RedirectPage;

**pages/api/shorten.ts - Manages the URL shortening process and database interaction.**

import { NextApiRequest, NextApiResponse } from 'next';

import { nanoid } from 'nanoid';

import QRCode from 'qrcode';

import dbConnect from '../../utils/dbConnect';

import Url from '../../models/Url';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    await dbConnect();

    // The code fetches the original URL from the database

    if (req.method === 'POST') {
        const { originalUrl, customDomain, customUrl } = req.body;

        if (!originalUrl || typeof originalUrl !== 'string') {
            return res.status(400).json({ error: 'Invalid URL' });
        }

        try {

            // he nanoid library is used to generate a short code. 
            // The base URL is determined by checking if the environment is production

            let shortCode = customUrl || nanoid(7);
            const baseUrl = process.env.NODE_ENV === 'production'
                ? process.env.NEXTAUTH_URL
                : 'http://localhost:3000';

            const shortUrl = customDomain
                ? `${customDomain}/${shortCode}`
                : `${baseUrl}/${shortCode}`;

            // generates a QR code for the shortened URL.

            const qrCode = await QRCode.toDataURL(shortUrl);

            const newUrl = new Url({
                originalUrl,
                shortUrl,
                shortCode,
                qrCode,
            });

            await newUrl.save();

            res.status(201).json({ message: 'URL shortened successfully', shortUrl, qrCode });
        } catch (error) {
            console.error('Error saving URL:', error);
            res.status(500).json({ message: 'Internal Server Error' });
        }
    } else {
        res.status(405).json({ message: 'Method not allowed' });
    }
}


   **utils/dbConnect.ts - Handles the database connection logic** 

import mongoose from 'mongoose';

const MONGODB_URI: string = process.env.MONGODB_URI as string;

if (!MONGODB_URI) {
    throw new Error('Please define the MONGODB_URI environment variable inside .env.local');
}

let cached = (global as any).mongoose;

if (!cached) {
    cached = (global as any).mongoose = { conn: null, promise: null };
}

async function dbConnect() {
    if (cached.conn) {
        return cached.conn;
    }

    if (!cached.promise) {
        const opts = {
            bufferCommands: false,
        };

        cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => mongoose);
    }
    cached.conn = await cached.promise;
    return cached.conn;
}

export default dbConnect;

**env.local - Environment variables setup (with sensitive information redacted)**

  MONGODB_URI=mongodb+srv://user:[email protected]/myDatabase?retryWrites=true&w=majority

  NEXTAUTH_URL=https://shorty-sigma.vercel.app/

  GOOGLE_CLIENT_ID=1234567890-abcde1234.apps.googleusercontent.com

  GOOGLE_CLIENT_SECRET=ABCDEF1234567890

  GITHUB_CLIENT_ID=gh1234567890abcdef

  GITHUB_CLIENT_SECRET=ghabcdef1234567890

  [email protected]

  EMAIL_PASS=myemailpassword

  JWT_SECRET=myjwtsecretkey

  NEXTAUTH_SECRET=myNextAuthSecretKey


**NOTE: the env.local values are generated for demonstration purpose except for NEXTAUTH_URL**

Could you help me diagnose and fix this issue? I’ve attached the relevant files below for your review. <

/kbd>

How to handle null in `findOne()` correctly?

This is how I do return a single mongodb document in my backend application

  const result = Data.findOne({}, { sort: { date: -1 } })
  if (result == null) throw new Error('No dataset existing')
  return result

But with this I do get this ts error:

  Type 'WithId<Data> | null' is not assignable to type 'Data'.
  Type 'null' is not assignable to type 'Data'.

How should I handle this correctly?

type Data {
  id: ID!
  date: String!
}

How to share data between concurrently executed promises in NodeJS

I want to share data between the two concurrent method calls shown below.

async generateSuggestedSparks(userId: GraphID, friends: Person[], latLng: LatLng) {
    let suggestions = await this.generateAndMergeListsInParallel([
      this.generateHardCodedSparks(userId, friends, latLng),
      this.generateRandomActivitySparks(userId, friends, latLng, 6),
    ]);
    suggestions = this.filterDuplicateSuggestions(suggestions);

    return suggestions.slice(0, 7);
  }

  async generateAndMergeListsInParallel<T>(promises: Promise<T[]>[]): Promise<T[]> {
    let lists = await Promise.all(promises);
    return lists.flat();
  }

Each method generates a number of artifacts for a randomly selected subset of friends. In both methods, I remove selected friends from the friends list to avoid selecting the same friend multiple times. I would like to generalize this logic to share data across the two concurrent promises to avoid one choosing a friend already used in the other.

What is the canonical way to share data across the concurrently running methods in NodeJS?

node js $strLenCP requires a string argument, found: missing’,

router.get("/find", async function (req, res) {
  // var regex = new RegExp("react", "i");
  var date1 = new Date("2024-08-22");
  var date2 = new Date("2024-08-23");
  let userData = await userModel.find({
    $expr: {
      $and: [
        { $gte: [{ $strLenCP: "$name" }, 0] },
        { $lte: [{ $strLenCP: "$name" }, 30] },
      ],
    },
  });
  res.send(userData);
});
});

why showing error this starlamcp is a string why it show why it showing

$strLenCP requires a string argument, found: missing’,