How to get FedCM API working on localhost?

I am working with fedcm api for authentication. I am using this

if ('IdentityCredential' in window) {
    // AJAX call to login
    navigator.login.setStatus('logged-in');


    // TODO handle user canceling
    const credential = await navigator.credentials.get({
        identity: {
            // Specify the IdP (or multiple IdPs, supported from Chrome 136) this Relying Party supports
            providers: [
                {
                    configURL: 'https://accounts.google.com/gsi/fedcm.json',        
                    clientId: '<my-client-id>',
                    nonce: crypto.randomUUID() 
                }
            ]
        }
    });
    console.log(credential);
}

and the client id has 2 URL’s in the authorized JS domains. One is a public https server i am running. When I test this there, it works ok and I get the credential. But when I run this on localhost:3000, and I have http://localhost:3000 in the authorized JS domain, i still get

The fetch of the id assertion endpoint resulted in a network error: ERR_FAILED
localhost/:1 Server did not send the correct CORS headers.
main.js:26 Uncaught (in promise) IdentityCredential
Error: Error retrieving a token.

how do I get this to work?

Why does JavaScript recognize it as string and not number?

My HTML5 code is:

<span id="num1-el"></span>
<span id="num2-el"></span>

and my JavaScript code:

let num1 = prompt("Enter the first number !");
let num2 = prompt("Enter the second number !");

document.getElementById("num1-el").textContent = num1;
document.getElementById("num2-el").textContent = num2;

console.log(num1);
console.log(typeof num1);

console.log(num2);
console.log(typeof num1);

Why does JavaScript recognize my “input” of numbers as strings, not as numbers, like this:

Image of console.log resultus

why is this the case and how I can “force” JavaScript to recognize my input as numbers and not as strings?

How to safely load a blocking script in the head without risk of being slow

I’ve made some A/B testing software which requires website owners having to place a script in the head of their websites. This script must block the page from loading until it finishes executing, since it needs to fetch information needed before the body is rendered (e.g. CSS styles, JS), hence it cannot defer. I worry that if my server is down, slow or overloaded that it would prevent my customers’ websites from loading.

How can I overcome this, or is it not possible? It’s making me want to abandon my A/B testing software as I want no chance of the script preventing website owners’ websites from loading.

To give some context, website owners need to place a script like this in the head of their websites. The embed code:

<script src="https://example.com/track.js?sid=4d95c9fz"></script>

The script in the src itself also has async calls that may also take time, such as DB queries. This must also not be allowed to take too long.

Or could add the async attribute to the embedded script but somehow change it such that, if it has not fully fetched before the body starts to load, it just abandons any attempt to inject any changes? I.e. the script must:

  • either load and inject (e.g. styles, JS, anything a/b test related that affects how the page looks) fully before the body starts to load;
  • or not inject at all

I can change the embed code if needed, and I can change the script in the src attribute (i.e. track.ts) if needed.

AI seems to suggest either:

  • a race condition between (1) the browser downloading the src and (2) the script itself completing vs (3) a timeout for both 1 and 2; or
  • an async script attribute that checks whether the readystate has not started loading the body before trying to insert anything; it either inserts all or does nothing
  • AI conversation: https://chatgpt.com/share/6834c11e-7260-8002-9f28-7d2439bba220

I am ok with the script sometimes not injecting anything if it means the website owners websites’ are safe, but I want the A/B tests to inject most of the time.

WebRTC file transfer in React intermittently fails with ICE failed and Unknown ufrag errors

I’m building a simple peer-to-peer file transfer app using WebRTC in a React application. The goal is to allow direct file transfer between two devices without always relying on a TURN server.

However, I’m encountering a problem: most transfer attempts fail with the following errors in the browser console:

ICE failed

Uncaught (in promise) DOMException: Unknown ufrag

Despite these errors, occasionally the file does transfer successfully if I retry enough times.

Some key details:

-I’m using a custom signaling server over WebSockets to exchange offers, answers, and ICE candidates.

-I already have a TURN server set up, but I’d like to minimize its use for cost reasons and rely on STUN/direct connections when possible.

-Transfers from a phone to a PC work reliably, but the reverse (PC to phone) fails in most cases.

From my research, it seems like ICE candidates might be arriving before the remote description is set, leading to the Unknown ufrag issue.

What can I do to make the connection more stable and prevent these errors?

// File: src/lib/webrtcSender.ts

import { socket, sendOffer, sendCandidate, registerDevice } from "./socket";

interface Options {
    senderId: string;
    receiverId: string;
    file: File;
    onStatus?: (status: string) => void;
}

export function sendFileOverWebRTC({
                                       senderId,
                                       receiverId,
                                       file,
                                       onStatus = () => {},
                                   }: Options): void {
    const peerConnection = new RTCPeerConnection({
        iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
    });

    registerDevice(senderId);

    const dataChannel = peerConnection.createDataChannel("fileTransfer");

    let remoteDescriptionSet = false;
    const pendingCandidates: RTCIceCandidateInit[] = [];

    dataChannel.onopen = () => {
        onStatus("Sending file...");
        sendFileChunks();
    };

    peerConnection.onicecandidate = (event) => {
        if (event.candidate) {
            sendCandidate(receiverId, event.candidate);
        }
    };

    socket.off("receive_answer");
    socket.on("receive_answer", async ({ answer }) => {
        if (!remoteDescriptionSet && peerConnection.signalingState === "have-local-offer") {
            await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
            remoteDescriptionSet = true;

            // Drain pending candidates
            for (const cand of pendingCandidates) {
                await peerConnection.addIceCandidate(new RTCIceCandidate(cand));
            }
            pendingCandidates.length = 0;
        } else {
            console.warn("Unexpected signaling state:", peerConnection.signalingState);
        }
    });

    socket.off("ice_candidate");
    socket.on("ice_candidate", ({ candidate }) => {
        if (remoteDescriptionSet) {
            peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
        } else {
            pendingCandidates.push(candidate);
        }
    });

    peerConnection.createOffer()
        .then((offer) => peerConnection.setLocalDescription(offer))
        .then(() => {
            if (peerConnection.localDescription) {
                sendOffer(senderId, receiverId, peerConnection.localDescription);
                onStatus("Offer sent. Waiting for answer...");
            }
        });

    function sendFileChunks() {
        const chunkSize = 16_384;
        const reader = new FileReader();
        let offset = 0;

        dataChannel.send(JSON.stringify({
            type: "metadata",
            filename: file.name,
            filetype: file.type,
            size: file.size,
        }));

        reader.onload = (e) => {
            if (e.target?.readyState !== FileReader.DONE) return;

            const chunk = e.target.result as ArrayBuffer;

            const sendChunk = () => {
                if (dataChannel.bufferedAmount > 1_000_000) {
                    // Wait until buffer drains
                    setTimeout(sendChunk, 100);
                } else {
                    dataChannel.send(chunk);
                    offset += chunk.byteLength;
                    if (offset < file.size) {
                        readSlice(offset);
                    } else {
                        onStatus("File sent successfully!");
                    }
                }
            };

            sendChunk();
        };

        reader.onerror = () => onStatus("File read error");

        const readSlice = (o: number) => reader.readAsArrayBuffer(file.slice(o, o + chunkSize));
        readSlice(0);
    }

}
// File: src/lib/webrtcSender.ts
import { socket, registerDevice, sendAnswer, sendCandidate } from './socket';

export function initializeReceiver(
    fingerprint: string,
    onStatus: (status: string) => void,
    onFileReceived: (file: Blob, metadata: { name: string; type: string }) => void
) {
    registerDevice(fingerprint);

    let peerConnection: RTCPeerConnection | null = null;
    let remoteDescriptionSet = false;
    const pendingCandidates: RTCIceCandidateInit[] = [];

    let receivedChunks: Uint8Array[] = [];
    let receivedSize = 0;
    let metadata: { name: string; type: string; size: number } | null = null;

    socket.off('receive_offer');
    socket.on('receive_offer', async ({ sender, offer }) => {
        if (peerConnection) {
            peerConnection.close(); // Prevent reuse
        }

        onStatus('Offer received. Creating answer...');
        peerConnection = new RTCPeerConnection({
            iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
        });

        peerConnection.onicecandidate = (event) => {
            if (event.candidate) {
                sendCandidate(sender, event.candidate);
            }
        };

        peerConnection.ondatachannel = (event) => {
            const channel = event.channel;

            channel.onopen = () => onStatus('Data channel open. Receiving file...');
            channel.onmessage = async (event) => {
                if (typeof event.data === 'string') {
                    try {
                        const msg = JSON.parse(event.data);
                        if (msg.type === 'metadata') {
                            metadata = {
                                name: msg.filename,
                                type: msg.filetype,
                                size: msg.size,
                            };
                            receivedChunks = [];
                            receivedSize = 0;
                            onStatus(`Receiving ${msg.filename} (${msg.size} bytes)`);
                        }
                    } catch {
                        console.warn('Invalid metadata message');
                    }
                } else {
                    const chunk = event.data instanceof Blob
                        ? new Uint8Array(await event.data.arrayBuffer())
                        : new Uint8Array(event.data);

                    receivedChunks.push(chunk);
                    receivedSize += chunk.byteLength;

                    if (metadata && receivedSize >= metadata.size) {
                        const blob = new Blob(receivedChunks, { type: metadata.type });
                        onFileReceived(blob, metadata);
                        onStatus('File received and ready to download.');
                    }
                }
            };
        };

        await peerConnection.setRemoteDescription(offer);
        remoteDescriptionSet = true;

        const answer = await peerConnection.createAnswer();
        await peerConnection.setLocalDescription(answer);
        sendAnswer(sender, answer);
        onStatus('Answer sent.');

        // Drain buffered ICE candidates
        for (const cand of pendingCandidates) {
            await peerConnection.addIceCandidate(new RTCIceCandidate(cand));
        }
        pendingCandidates.length = 0;
    });

    socket.off("ice_candidate");
    socket.on("ice_candidate", ({ candidate }) => {
        if (remoteDescriptionSet && peerConnection) {
            peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
        } else {
            pendingCandidates.push(candidate);
        }
    });
}
// File: src/dash/page.tsx

'use client';
import { useEffect, useState, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '../../store/useAuthStore';
import api from '../../lib/axios';
import FingerprintJS from '@fingerprintjs/fingerprintjs';
import { sendFileOverWebRTC } from '../../lib/webrtcSender';
import { initializeReceiver } from '../../lib/webrtcReceiver';

export default function DashPage() {
    const { user, checkAuth, loading } = useAuthStore();
    const router = useRouter();
    const [devices, setDevices] = useState([]);
    const [deviceName, setDeviceName] = useState('');
    const [fingerprint, setFingerprint] = useState('');
    const [status, setStatus] = useState('Idle');
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [selectedDevice, setSelectedDevice] = useState('');
    const fileInputRef = useRef<HTMLInputElement>(null);

    // Initial auth check
    useEffect(() => {
        checkAuth();
    }, [checkAuth]);

    useEffect(() => {
        if (!loading && !user) {
            router.replace('/auth');
        }
    }, [loading, user, router]);

    // Fetch user's devices
    useEffect(() => {
        if (!loading && user) {
            api
                .get('/devices/')
                .then((res) => setDevices(res.data))
                .catch((err) => console.error('Device fetch failed', err));
        }
    }, [loading, user]);

    // Fingerprint only
    useEffect(() => {
        const loadFingerprint = async () => {
            setStatus('Loading fingerprint...');
            const fp = await FingerprintJS.load();
            const result = await fp.get();
            setFingerprint(result.visitorId);
            setStatus('Ready to add device');
        };

        loadFingerprint();
    }, []);

    // Initialize receiver
    useEffect(() => {
        if (fingerprint) {
            initializeReceiver(
                fingerprint,
                (newStatus) => setStatus(newStatus),
                (fileBlob, metadata) => {
                    const url = URL.createObjectURL(fileBlob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = metadata.name;
                    a.click();
                    URL.revokeObjectURL(url);
                }
            );
        }
    }, [fingerprint]);

    const handleAddDevice = async () => {
        if (!deviceName || !fingerprint) {
            alert('Missing fingerprint or device name');
            return;
        }

        try {
            await api.post('/add-device/', {
                fingerprint,
                device_name: deviceName,
            });

            setDeviceName('');
            setStatus('Device added successfully');

            // Refresh device list
            const res = await api.get('/devices/');
            setDevices(res.data);
        } catch (error) {
            console.error('Error adding device:', error);
            setStatus('Failed to add device');
        }
    };

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            setSelectedFile(e.target.files[0]);
        }
    };

    const handleSendFile = () => {
        if (!selectedFile || !selectedDevice) {
            alert('Please select a file and a target device.');
            return;
        }

        sendFileOverWebRTC({
            senderId: fingerprint,
            receiverId: selectedDevice,
            file: selectedFile,
            onStatus: setStatus,
        });
    };

    if (loading) return <p className="text-center mt-10">Loading dashboard...</p>;
    if (!user) return null;

    return (
        <div className="p-6 max-w-3xl mx-auto">
            <h1 className="text-2xl font-bold mb-4">Welcome, {user.username}</h1>
            <p>Your email: {user.email}</p>

            <h2 className="text-xl font-semibold mt-6">Your Devices:</h2>
            <ul className="mt-2 list-disc list-inside">
                {devices.length === 0 && <p>No devices found.</p>}
                {devices.map((device: any) => (
                    <li key={device.fingerprint}>
                        {device.device_name} ({device.fingerprint})
                    </li>
                ))}
            </ul>

            <hr className="my-6" />

            <h2 className="text-xl font-semibold mb-2">Add This Device</h2>
            <div className="space-y-2">
                <p>
                    <strong>Status:</strong> {status}
                </p>
                <input
                    type="text"
                    className="border p-2 w-full"
                    placeholder="Device Nickname"
                    value={deviceName}
                    onChange={(e) => setDeviceName(e.target.value)}
                />
                <button
                    onClick={handleAddDevice}
                    className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                >
                    Add This Device
                </button>
            </div>

            <hr className="my-6" />

            <h2 className="text-xl font-semibold mb-2">Send a File</h2>
            <div className="space-y-2">
                <input type="file" ref={fileInputRef} onChange={handleFileChange} />
                <select
                    className="border p-2 w-full"
                    value={selectedDevice}
                    onChange={(e) => setSelectedDevice(e.target.value)}
                >
                    <option value="">Select a device</option>
                    {devices.map((device: any) => (
                        <option key={device.fingerprint} value={device.fingerprint}>
                            {device.device_name}
                        </option>
                    ))}
                </select>
                <button
                    onClick={handleSendFile}
                    className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
                >
                    Send File
                </button>
            </div>
        </div>
    );
}

how react-hook-form can make to dirty when user complete all changes?

I m new to react . i m using below provider for capturing dirty state.

import { FormProvider, Form } from 'react-hook-form';

I m using react form what I m looking is.
I want to trigger my event after user made or complete his all change and after x sec my event should trigger and i should get all dirty values.
I don’t have any button on page to submit this changes.

I m trying dirty state and different events but its not working as expected.
Any suggestion on this.

TradingView Ticker Tape widget is not scrolling/animating on my website

Hello everyone!

I’m trying to embed the TradingView Ticker Tape widget on my webpage,
but it’s not animating or scrolling as it should.

I used the official code with the tag and also tried the
iframe method,

Configured the JSON options according to TradingView’s instructions,

The widget loads and shows the symbols, but it stays static — no
automatic scrolling,

Tested both locally and on GitHub Pages, but the issue remains,

I’ve tried adjusting CSS, widths, zoom, but nothing makes the ticker
animate,

I need the ticker to scroll like it does on the official TradingView
site.

Has anyone experienced this or knows what might be blocking the
animation? Could it be a widget limitation or missing parameter?

Thanks in advance for any help!

<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <title>Widget do TradingView</title>
</head>
<body style="background-color:#000; color:#fff;">

  <!-- TradingView Widget BEGIN -->
  <div class="tradingview-widget-container">
    <div class="tradingview-widget-container__widget"></div>
    <div class="tradingview-widget-copyright">
      <a href="https://www.tradingview.com/" rel="noopener nofollow" target="_blank">
        <span class="blue-text">Track all markets on TradingView</span>
      </a>
    </div>
    <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-ticker-tape.js" async>
    {
      "symbols": [
        {
          "description": "Bitcoin",
          "proName": "COINBASE:BTCUSD"
        },
        {
          "description": "Ethereum",
          "proName": "CRYPTO:ETHUSD"
        },
        {
          "description": "XRP",
          "proName": "COINBASE:XRPUSD"
        },
        {
          "description": "Doge",
          "proName": "COINBASE:DOGEUSD"
        },
        {
          "description": "Solana",
          "proName": "COINBASE:SOLUSD"
        },
        {
          "description": "Nvidia",
          "proName": "NASDAQ:NVDA"
        },
        {
          "description": "Amazon",
          "proName": "NASDAQ:AMZN"
        }
      ],
      "showSymbolLogo": true,
      "isTransparent": true,
      "largeChartUrl": "",
      "displayMode": "adaptive",
      "colorTheme": "dark",
      "locale": "en"
    }
    </script>
  </div>
  <!-- TradingView Widget END -->

</body>
</html>

How to add a superscript to an array in Javascript

In an array for a calculator, I have: x^y (in HTML it would be xy) Likewise I have x^-1 Or x-1. I can’t figure out how to add it to the array for only those two buttons in the array so it displays xy and x-1 respectively instead of x < sup>y< /sup> (without the spaces, obviously) x < sup>-1< /sup>

js (missing the listeners, etc, but gives you the idea of what I’m aiming for):

const display = document.getElementById("display");

const buttonValues = [
"Rad", "º", "x!", "(", ")", "%", "AC",
"Inv", "sin", "log", "7", "8", "9", "÷",
"π", "cos", "ln", "4", "5", "6",  "x",
"e", "tan", "√", "1", "2", "3",  "+",
"Ans", "EXP", "^", "0", ".", "=", "-", "+/-", "x^-1",

]

const rightSymbols = [ "÷", "x", "-", "+", "="]
const topSymbols = ["(", ")", "%", "AC"]
const leftSymbols = ["Rad", "º", "x!", "Inv", "sin", "log", "π", "cos", "ln", "e", "tan", "√", "Ans", "EXP", "^", "+/-", "x^-1",]

//A+B, A×B, A-B, A÷B
let A = 0;
let operator = null;
let B = null;

function clearAll() {
A = null;
operator = null;
B = null;
}

for (let i = 0; i < buttonValues.length; i++) {
let value = buttonValues[i];
let button = document.createElement("button");
button.innerText = value;

//styling button colors
if (value == "=") {
    button.style.backgroundColor = "brown";
}

else if (rightSymbols.includes(value)) {
    button.style.backgroundColor = "orange";
}

else if (leftSymbols.includes(value)) {        
    button.style.backgroundColor = "darkorange";
    button.style.color = "white";
}

else if (topSymbols.includes(value)) {        
    button.style.backgroundColor = "orange";
    button.style.color = "white";
}

javascript function not working for string values

ASP.net webform
ListView itemtemplate passing a value to a javascript function works correctly if the item_id is numeric. But I get a this error if the item_id is alpha-numeric.

Uncaught ReferenceError: pf10001 is not defined
at HTMLAnchorElement.onclick (Products.aspx:1182:163)

<a href="#" class="btn btn-sm btn-success" onclick='<%# "javascript:AddToCart(" + DataBinder.Eval(Container.DataItem, "item_id") + ");return false;" %>'>Add to Cart</a>

function AddToCart(item) {
    PageMethods.AddToCart(item, 0, onRequestComplete);
};

Have tried various hidden fields to pass the item_id value without success. But I’m wondering if there’s a simple answer to this error.

Cómo automatizar la validación de OTP enviado por correo y SMS en Cypress [closed]

Buen día,

Estoy trabajando en una automatización E2E con Cypress para un sistema que valida un OTP. El sistema envía un OTP tanto al correo electrónico como al número de celular que el usuario tiene registrado en la base de datos.

Mi duda es cómo automatizar esta parte de la validación para que, al ejecutar la prueba en Cypress, pueda obtener automáticamente el OTP enviado (tanto por correo como por SMS) y luego insertarlo en los campos correspondientes para completar la validación.

¿Alguien ha implementado una solución para automatizar la obtención del OTP en casos similares? ¿Qué métodos o herramientas podrían usar para extraer esos códigos de manera confiable dentro de un flujo de prueba automatizado?

Gracias de antemano por cualquier ayuda o sugerencia.

How can i have spa application with form based on post working?

So i have spa app inside of wordpress it just loads php files in my theme:

Functions.php

add_action('wp_ajax_wczytaj_sekcje_profilu', 'ajax_wczytaj_sekcje_profilu');
function ajax_wczytaj_sekcje_profilu() {
    if (!is_user_logged_in()) {
        wp_die('Musisz być zalogowany.');
    }
    
    $current_user = wp_get_current_user();
    $stripe_id = get_field('stripe_id_klienta', 'user_' . $current_user->ID);
    set_query_var('current_user', $current_user);
    set_query_var('stripe_id', $stripe_id);


    $sekcja = sanitize_text_field($_POST['sekcja']);

    switch ($sekcja) {
        case 'materialy':
            get_template_part('user-profile-components/client-asetss');
            break;
        case 'kontakt':
            get_template_part('user-profile-components/kontakt');
            break;
        case 'faktury':
            get_template_part('user-profile-components/fakturownia-invoices');
            break;
        case 'platnosci':
            get_template_part('user-profile-components/stripe-subscription');
            get_template_part('user-profile-components/stripe-payments');
            break;
        case 'raporty':
            get_template_part('user-profile-components/seo-raports');
            break;
        case 'profil':
        default:
            get_template_part('user-profile-components/user-info');
            break;
    }

    wp_die();
}

profil.js (ajax file)

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('#profil-menu a').forEach(link => {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            const sekcja = this.dataset.sekcja;
            const contentDiv = document.getElementById('profil-content');
            contentDiv.innerHTML = '<div><div class="loader"></div></div>';

            const newUrl = new URL(window.location);
            newUrl.searchParams.set('sekcja', sekcja);
            window.history.pushState({}, '', newUrl);

            const formData = new FormData();
            formData.append('action', 'wczytaj_sekcje_profilu');
            formData.append('sekcja', sekcja);

            fetch('/wp-admin/admin-ajax.php', {
                method: 'POST',
                body: formData
            })
                .then(res => res.text())
                .then(html => contentDiv.innerHTML = html)
                .catch(err => contentDiv.innerHTML = 'Błąd ładowania sekcji.');
        });
    });

    // Załaduj sekcję na podstawie parametru URL przy pierwszym załadowaniu strony
    const initialSekcja = new URL(window.location).searchParams.get('sekcja');
    if (initialSekcja) {
        const formData = new FormData();
        formData.append('action', 'wczytaj_sekcje_profilu');
        formData.append('sekcja', initialSekcja);

        const contentDiv = document.getElementById('profil-content');
        contentDiv.innerHTML = '<div><div class="loader"></div></div>';

        fetch('/wp-admin/admin-ajax.php', {
            method: 'POST',
            body: formData
        })
            .then(res => res.text())
            .then(html => contentDiv.innerHTML = html)
            .catch(err => contentDiv.innerHTML = 'Błąd ładowania sekcji.');
    }
});

In one of my sections (files) i try to upload file to google drive via post form but when i click submit page refreshes and nothing happens because of above code.

<form id="gdrive-upload-form" method="post" enctype="multipart/form-data">
    <input type="file" name="gdrive_file[]" multiple required>
    <button type="submit" name="upload_gdrive">Wyślij na Google Drive</button>
</form>
<div id="gdrive-upload-result"></div>

I tried to create function to upload files in functions.php and js ajax file to handle it but result is the same – page just refreshes. Is there any way i can find another solution to this problem?

Incorrect operation of the filter function on the data array

I am making a simple application that includes a user search. In general, the search works, but not as it should. When searching, users are divided into two blocks – friends from the user’s list and global users. Friends from the friends list should not appear in global users.

My current solution only works if there is one friend in the friends list, but if there are many, they will be displayed in the global users list. I don’t understand why this happens.

const searchResult = [
  {
    _id: '682dc4b5c6c0975928d2c5a8',
    nickname: 'Test1'
  },
  {
    _id: '682dc4c3c6c0975928d2c5a9',
    nickname: 'Test2'
  },
  {
    _id: '682a1294943779a5f41e3e26',
    nickname: 'GlobalUser1'
  },
  {
    _id:'682dc4a6c6c0975928d2c5a7',
    nickname: 'Test3'
  },
  {
    _id: '682edc075fa9f243b2cef5d5',
    nickname: 'Test4'
  },
  {
    _id: '682eebee62c0c2de682f0644',
    nickname: 'GlobalUser2'
  },
  { _id: '682edc675fa9f243b2cef5dd', nickname: 'Test5' }
];
const userFriend = [
  {
    _id: '682dc4b5c6c0975928d2c5a8',
    nickname: 'Test1'
  },
  {
    _id: '682dc4c3c6c0975928d2c5a9',
    nickname: 'Test2'
  },
  {
    _id: '682dc4a6c6c0975928d2c5a7',
    nickname: 'Test3'
  },
  {
    _id: '682edc075fa9f243b2cef5d5',
    nickname: 'Test4'
  },
  { _id: '682edc675fa9f243b2cef5dd', nickname: 'Test5' }
]
const searchTest = () => {
   let globalUsers = [];
   let userFriends = [];

   if (userFriend.length === 0) {
      globalUsers = searchResult;
   } else {
     userFriends = searchResult.filter(
       (item) => userFriend.some((friend) => friend._id === item._id
     ))
     if (userFriends.length > 0) {
       globalUsers = searchResult.filter(
         (item) => userFriends.some(
           (friend) => friend._id !== item._id,
              ),
            );
          } else {
            null;
          }
        }
        const foundedList = { globalUsers, userFriends };
        console.log(foundedList);
        }

searchTest();

Why does canvas.toDataURL() return a very short base64 string when exporting Chart.js canvas?

I’m using Chart.js to render a line chart inside a <canvas> element. After the chart is rendered, I want to export it as a base64 PNG string using canvas.toDataURL("image/png").

However, the base64 string I get is very short (~6,000 characters), which is too small for a full image and looks incomplete or transparent.

Here is my HTML:

<div style="width:100%;height:306px;" id="canvasDivId1"><div class="chartjs-size-monitor" style="position: absolute; inset: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;"><div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"><div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div></div><div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"><div style="position:absolute;width:200%;height:200%;left:0; top:0"></div></div></div>
                        <canvas id="lineChartMain" width="712" height="306" style="display: block; width: 712px; height: 306px;" class="chartjs-render-monitor"></canvas>
                      </div>
function convertLineChartAsBinaryImage(canvasDiv, targetBase64Div){ 
  html2canvas(document.getElementById(canvasDiv), {
    useCORS: true,
    onrendered: function(canvas) {
         var img = canvas.toDataURL("image/png"); 
         img = img.replace('data:image/png;base64,', '');
         var finalImageSrc = 'data:image/png;base64,' + img;
         if($$D(targetBase64Div) !=null && $$D(targetBase64Div).value ==""){
        $$D(targetBase64Div).value = finalImageSrc;
         }  
    }
  });
}

CSS Cursor Not Showing on Clickable Component (Chrome Mac ARM)

I’m experiencing a strange cursor behavior where clickable components don’t show a pointer cursor in certain areas, but the onClick functionality still works perfectly. This issue appears to be specific to the topmost component when multiple components are stacked.
Critical Detail: The bug only occurs when Chrome is in full screen mode AND scaled (either via Cmd+ zoom or when browser font size is configured to be larger). When Chrome is scaled but not in full screen, everything works perfectly.

  1. Browser: Chrome on Mac ARM (everything latest)
  2. CSS Reset: Using modern-normalize v3.0.1 with custom reset via CSS
    @layer
  3. Framework: React with CSS Modules
  4. Trigger Condition: Issue only occurs when Chrome is both full screen
    AND scaled (Cmd+ or larger font configured)

What I’ve Tried

  1. Multiple Component Test: I placed multiple clickable components in
    the same position using absolute positioning

  2. Observation: Only the topmost component exhibits the cursor issue

  3. Functionality Check: Added onClick handler to the entire component –
    the click events fire correctly even in areas where the cursor
    doesn’t change to pointer

Expected Behavior

Hovering over clickable elements should show cursor: pointer.
The pointer cursor should appear consistently across the entire clickable area.

Actual Behavior

  • Some areas of the component show the default cursor instead of
    pointer
  • Click functionality works everywhere, but cursor visual feedback is
    inconsistent
  • Only affects the topmost component in a stack
function Sidebar({
    isCollapsed,
    currentOrganization,
    organizations,
    navLinks,
}: SidebarProps) {
    return (
        <div
            className={`${styles.sidebar} ${isCollapsed ? styles.collapsed : styles.expanded}`}
            data-collapsed={isCollapsed}
        >
            <SidebarHeader>
                <SidebarButton variant="dropdown" size="lg" icon={HomeIcon}>
                    <span>Company</span>
                    <span>Starter</span>
                </SidebarButton> // <-- Only this component has issues.
                <SidebarButton variant="dropdown" size="lg" icon={HomeIcon}>
                    <span>Company</span>
                    <span>Starter</span>
                </SidebarButton>
                <SidebarButton variant="dropdown" size="lg" icon={HomeIcon}>
                    <span>Company</span>
                    <span>Starter</span>
                </SidebarButton>
                <SidebarButton variant="dropdown" size="lg" icon={HomeIcon}>
                    <span>Company</span>
                    <span>Starter</span>
                </SidebarButton>
            </SidebarHeader>
            <SidebarContent>
                <SidebarMenu>
                    <SidebarButton
                        variant="default"
                        size="md"
                        icon={LayoutPanelTopIcon}
                    >
                        <p>Dashboard</p>
                    </SidebarButton>
                </SidebarMenu>
            </SidebarContent>
        </div>
    );
}

Component itself:

function SidebarButton({
    variant,
    size,
    children,
    className,
    icon: Icon,
}: CombinedSidebarButtonProps) {
    switch (size) {
        case "lg":
            return (
                <button
                    type="button"
                    className={clsx(
                        sidebarButtonVariants({ variant, size }),
                        styles.base,
                        className,
                    )}
                >
                    <div className={styles.leftIconWrapper}>
                        <Avatar
                            contentType="icon"
                            size="md"
                            icon={HomeIcon}
                            variant="circular"
                        />
                    </div>
                    <div className={styles.collapsibleWrapper}>
                        <div className={styles.textWrapper}>{children}</div>
                        <div className={styles.rightIconWrapper}>
                            <ChevronsUpDown />
                        </div>
                    </div>
                </button>
            );
        case "md":
            switch (variant) {
                case "default":
                    return (
                        <button
                            type="button"
                            className={clsx(
                                sidebarButtonVariants({ variant, size }),
                                styles.base,
                                className,
                            )}
                        >
                            <div className={styles.leftIconWrapper}>
                                <Icon className={styles.leftIcon} />
                            </div>
                        </button>
                    );
            }
    }
    return null;
}

It’s CSS:

.base {
    display: flex;
    align-items: center;
    align-self: stretch;
    background: var(--color-sidebarbutton-bg);
    cursor: pointer;
    overflow: hidden;
    background: yellow;

    .leftIconWrapper {
        display: flex;
        align-items: center;
        background: blue;

        .leftIcon {
            width: 1rem;
            height: 1rem;
        }
    }

    .collapsibleWrapper {
        width: 12rem;
        display: flex;
        align-items: center;
        flex: 0 0 auto;
        background: green;

        .textWrapper {
            display: flex;
            padding: 0 0.5rem;
            flex-direction: column;
            align-items: flex-start;
            flex: 1 0 0;
            background: cyan;
            cursor: pointer !important;

            span {
                font-size: 0.75rem;
                line-height: 1rem;
            }

            span:nth-child(2) {
                color: var(--color-text-placeholder);
                background: red;
            }
        }

        .rightIconWrapper {
            display: flex;
            padding: 0.5rem;
            justify-content: center;
            align-items: center;

            svg {
                width: 1rem;
                height: 1rem;
            }
        }
    }

    &:hover {
        background: var(--color-sidebarbutton-bg-hover);
    }
}

.md {
    padding: 0;
    border-radius: 0.375rem;

    .leftIconWrapper {
        padding: 0.5rem;
    }
}

.lg {
    padding: 0.5rem;
}

Debugging Steps Taken

  • Confirmed onClick works everywhere in the component
  • Verified cursor: pointer is applied via dev tools
  • Tested with cursor: pointer !important – no change
  • Confirmed issue only affects topmost component in stack
  • Tried removing CSS reset – issue persists
  • Discovered issue only occurs in full screen + scaled Chrome
  • Confirmed bug disappears when Chrome is windowed (even when still
    scaled)
  • Not seeing this bug in Safari and Firefox under the same conditions

Questions

  • Is this a known Chrome bug on Mac ARM? Specifically related to full
    screen mode with browser scaling?
  • Why would scaling + full screen affect cursor rendering? The issue
    doesn’t occur in windowed mode with the same scaling
  • Why would only the topmost component be affected? Lower components in
    the same stack work fine
  • Could this be related to CSS reset/normalize interference?
  • Any workarounds to force consistent cursor behavior in full screen
    scaled Chrome?

New to coding. So need better suggestions to continue and sustain in this journey [closed]

Before starting my query I would request you guys to take time to read and give suitable answers as it may give a good and best career path to me. I am new to coding. I am from non tech, CS/IS branch. Graduated in the year 2021 and worked in the fields of teaching, Business development. Just started with Java and MySQL couple of months ago. Theory part very very clearly. But when it comes to coding I struggle. I googled it many times. But can I get any better ideas, workable strategies that help me to get a good hold on this ? To learn these theory part of the coding I took much more time like 6 to 8 months. Not yet started practicing in Leetcode and similar coding practicing platforms because I easily give up or suddenly go for looking direct answers.

As I already mentioned that I googled and enquired in AI chatbots and tools regarding this, I know few things about how to improve in coding as a beginner but the thing is, as this is the pool of experts I am expecting some real life tips, strategies that helped and worked for them to get better and best in the field of coding. What more I expect from this is though I am in this situation, I want to get better at these things. I want to be such a coder who can crack any tech giant company interviews such as MAANG, ADOBE,NVIDIA,MICROSOFT and all. Currently I am jobless. And completely rely on Java and SQL just to enter into the IT field. So what are the possible and best ways out there to get my first tech job? I am fully focusing on Java full stack web development role but only learnt the theory part of Java and MySQL not yet touched HTML,CSS,JAVASCRIPT (Just went through HTML simply layer wise)

I’m working on a rental management system, i’ve used express js and postgre sql, i’ve sucessfully connected the parts but I can’t add items to my db [closed]

after running my api on localhost:/5000 and also successfully connected to my frontend, when I try adding a properties or even tenants names, it’s added but when I refresh my browser they disapear; meaning they are not added on my database. Any Idea or help or anyone who has encounted the same

I tried using debugging tools like console.log database connected successfully, modules synced, server running and all were successful, but when I try adding items or tenants from the UI, they are not stored in the database yet the add-on are made