Bootstrap in Custom HTMLElement using shadow DOM / Template-Slot

i want to have my own xy-bootstrap tag element within my application. I want to encapsulate the bootsrap styles within this element.

Can you help, why this Code does not work properly?

<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Scoped Bootstrap in Custom Element</title>
</head>
<body>

  <xy-bootstrap>
    <button type="button" class="btn btn-primary">Primary</button>
    <button type="button" class="btn btn-secondary">Secondary</button>
    <button type="button" class="btn btn-success">Success</button>
    <button type="button" class="btn btn-danger">Danger</button>
  </xy-bootstrap>

  <script>
    class XYBootstrap extends HTMLElement {
      constructor() {
        super();
        debugger;
        // Shadow DOM anlegen
        const shadow = this.attachShadow({ mode: 'open' });

        // Bootstrap-CSS importieren
        const link = document.createElement('link');
        link.setAttribute('rel', 'stylesheet');
        // hier z.B. die CDN-URL von Bootstrap 5
        link.setAttribute('href', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css');
        shadow.appendChild(link);

        // Slot für den Light DOM
        const slot = document.createElement('slot');
        shadow.appendChild(slot);
      }
    }
    customElements.define('xy-bootstrap', XYBootstrap);
  </script>

</body>
</html>

Remove Zone.Identifier files showing in VS Code moving from WSL setup

Remove Zone.Identifier files showing in VS Code moving from WSL setup

enter image description here

Some Zone.Identifier files were randomly generated in VS Code but not shown in other IDE’s. Windows has been using the Zone. Identifier tag since Windows XP SP2. Whenever you download a file from the Internet to an NTFS drive, an alternate data stream (ADS) gets added to it. This extra data doesn’t change the file itself but contains useful information about its origin.

How can I verify the ownership of an NFT using a smart contract on Ethereum?

I’m trying to verify whether a specific wallet address owns a given NFT on the Ethereum blockchain. I’m working with ERC-721 tokens and using Web3.js in a Node.js backend.

Here’s what I need:

Check if a specific wallet (e.g. 0x123…) owns an NFT with a given token ID.

I’m using Infura to connect to Ethereum mainnet.

What would be the correct way to do this using Web3.js?

Any best practices to avoid performance issues when checking large batches of token ownership would also be appreciated.

Websocket cannot add string to new Set()

I am facing some issues of adding a key to my new Set property in a websocket (Nest.js) function, here is the function:

  @SubscribeMessage('message:opened')
  handleMessageOpened(client: Socket) {
    const userId = this.websocketService.extractUserIdFromSocket(client);
    const user = this.activeUsers.get(userId);

    if (user) user.openViews.add('messages');
  }

I’ve double checked the user is well retrieved but ‘messages’ is not add to my openViews.

Here is my activeUsers state:

private activeUsers = new Map<number,{socketId: string; openViews: Set<string>}>();

I have tested the code in a sandbox and it is working so it seems that the code is not the issue itself. Do you have any ideas of what could be causing this?

Mixed Content error with local CSS/JS files in PHP website (no external HTTP links used) [closed]

I’m experiencing a strange and frustrating issue with my PHP-based website. Everything was working fine until a few days ago, but now I’m seeing Mixed Content errors in the browser console related to my local CSS and JS files.

Website overview:

  • It’s a simple blog-like site where users can view posts.
  • There’s an admin panel with a secure login.
  • The site is responsive (desktop and mobile).
  • I’m using Bootstrap and other local CSS/JS files (stored in the website’s directory).
  • No external HTTP resources are being loaded – all stylesheets and scripts are local.

The issue:

  • Chrome DevTools console shows Mixed Content errors.
  • CSS and JS files don’t load, and the site appears broken.
  • The error suggests some resources are being loaded via HTTP instead of HTTPS, but I’m not using any http:// links in my code.
  • Sometimes the site works fine for me, but not for others. Other times, it breaks completely for everyone (styles and scripts only – the site remains accessible).

Website URL:

My guesses:

  • Could this be an issue with the hosting provider (atwebpages.com)?
  • Maybe a problem with HTTPS redirection or caching?

If anyone has faced something similar or can help me figure out why these local files are being treated as HTTP, I’d really appreciate it.

Shared types between back end and front end [closed]

This is my folder structure.

Folder Structure

Now I have shared interfaces for both front end and back end. Thing is vs code not auto suggestion those shared interfaces.

tsconfig.base.json –

    {
      "compileOnSave": false,
      "compilerOptions": {
        "rootDir": ".",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "importHelpers": true,
        "target": "es2015",
        "module": "esnext",
        "lib": ["es2017", "dom"],
        "skipLibCheck": true,
        "skipDefaultLibCheck": true,
        "baseUrl": ".",
        "paths": {
          "@online-store/interfaces": ["libs/interfaces/src/index.ts"]
        }
      },
      "exclude": ["node_modules", "tmp"]
}

The feature file can’t read the steps from the step definition file

I tried every way I can but for some reason, the feature file still can’t read the step from the step definition file. Can someone help?

cypress.config.js file

const {defineConfig} = require("cypress");
const createBundler = require("@bahmutov/cypress-esbuild-preprocessor")
const addCucumberProprocessorPlugin = require("@badeball/cypress-cucumber-preprocessor").addCucumberPreprocessorPlugin;
const createEsbuildPlugin = require("@badeball/cypress-cucumber-preprocessor/esbuid").createEsbuildPlugin;
module.exports = defineConfig({
e2e:{
    async setupNodeEvents(on,config){
    const bundler = createBundler({plugins:[createEsbuildPlugin(config)],});
    on("file:preprocessor",bundler);
    await addCucumberPreprocessorPlugin(on,config);
    return config;},
    specPattern: "cypress/features/**/*.feature",
    baseURl: "..."
    env:{
        stepDefinitions:"cypress/features/step_definitions",
    },
   },
});

package.json file:

"devDependencies":{
"@badeball/cypress-cucumber-preprocessor":"^22.0.1",
"@bahmutov/cypress-esbuild-preprocessor":"^2.2.4",
"@cucumber/cucumber":"^11.2.0",
"@cypress/webpack-preprocessor": "^6.0.4",
"cypress":"^14.3.3",
"esbuild":"^0.25.4"
},
"cypress-cucumber-preprocessor":{
"nonGlobalStepDefinitions":true,
"step_definitions":"cypress/features/step_definitions"
}
- cypress
    - features
        - step_definitions 
             - stepdefinitions.js
        - LoginFeature.feature

stepdefinitions.js:

const {Given} = require('@cucumber/cucumber');

Given('I visit the login page', () =>{
cy.visit("/login",{timeout:5000});
});

LoginFeature.feature:

Feature: Login
    Scenario:Successful login
        Given I visit the login page

The feature file can’t read the steps from the step definition file (Cypress, Javascript)

I tried every way I can but for some reason, the feature file still can’t read the step from the step definition file. Can someone help?

Cypress.config.js file

const {defineConfig} = require("cypress");
const createBundler = require("@bahmutov/cypress-esbuild-preprocessor")
const addCucumberProprocessorPlugin = require("@badeball/cypress-cucumber-preprocessor").addCucumberPreprocessorPlugin;
const createEsbuildPlugin = require("@badeball/cypress-cucumber-preprocessor/esbuid").createEsbuildPlugin;
module.exports = defineConfig({
e2e:{
    async setupNodeEvents(on,config){
    const bundler = createBundler({plugins:[createEsbuildPlugin(config)],});
    on("file:preprocessor",bundler);
    await addCucumberPreprocessorPlugin(on,config);
    return config;},
    specPattern: "cypress/features/**/*.feature",
    baseURl: "..."
    env:{
        stepDefinitions:"cypress/features/step_definitions",
    },
   },
});

package.json file

"devDependencies":{
"@badeball/cypress-cucumber-preprocessor":"^22.0.1",
"@bahmutov/cypress-esbuild-preprocessor":"^2.2.4",
"@cucumber/cucumber":"^11.2.0",
"@cypress/webpack-preprocessor": "^6.0.4",
"cypress":"^14.3.3",
"esbuild":"^0.25.4"
},
"cypress-cucumber-preprocessor":{
"nonGlobalStepDefinitions":true,
"step_definitions":"cypress/features/step_definitions"
}
  • cypress
    • features
      • step_definitions
        • stepdefinitions.js
      • LoginFeature.feature

stepdefinitions.js

const {Given} = require('@cucumber/cucumber');

Given('I visit the login page', () =>{
cy.visit("/login",{timeout:5000});
});

LoginFeature.feature

Feature: Login
    Scenario:Successful login
        Given I visit the login page

Element does not fully collapse, div/table

I have a div containing a collapsed table. But the div still keeps the table width. Looks like table does not fully collapse, but only partially. So when I click the button to toggle table visibility the div expands or shrinks to table height, but the table width remains the same.

function showmenu(btn)
{
   switch (btn.value)
   {
   case "expand":
      btn.innerText = "x";
      btn.value = "hide";
      document.getElementById("show_lines").style.visibility = "visible";
      break;
   case "hide":
      btn.innerText = "+";
      btn.value = "expand";
      document.getElementById("show_lines").style.visibility = "collapse";
      break;
   }
}
<div class="menu" style="position:absolute;z-index:10;border:1px solid black;">
   <button value="expand" onclick="javascript:showmenu(this)">+</button>
   <table id="show_lines" style="visibility:collapse;">
      <tr><td><input type="checkbox">Show lines</input><td></tr>
   </table>
</div>

externalizing customElement svelte styles

I have a large website that is making use of custom webcomponents created with svelte.

This works fairly well, but there is a small issue, which is that at least some elements gets mounted to the dom before their style gets added to <head>. So for instance I have an IconButton component which is basically just a button (with borders removed). When it gets added for the first time (by another component) it renders the default button css (with an ugly border) for a really short while before its’ style has gotten parsed and applied.

I would prefer to preload all my css for the entire application. i.e. set the compilerOptions.css to external which is sort of the default, but as the docs state

‘external’: the CSS will only be returned in the css field of the compilation result. Most Svelte bundler plugins will set this to ‘external’ and use the CSS that is statically generated for better performance, as it will result in smaller JavaScript bundles and the output can be served as cacheable .css files. This is always ‘injected’ when compiling with customElement mode.

I don’t fully understand why that restriction is there, and is there any way (hacky or not) to move around it?

also, sadly I can’t create any small replications, as I am not entirely sure why the css isn’t parsed before the DOM. could potentially be because of the large size of the DOM tree or the css files?

Why do paddles move unexpectedly in my multiplayer pong game after a long game or when the ball speeds up?

I’m building a multiplayer pong game using WebSockets for real-time communication between the client and server. The game works fine initially, but after a long game or when the ball speeds up, the paddles start moving up unexpectedly, even when no keys are pressed.

Setup:

Client: Sends keypress states (“w” for up, “s” for down`) to the server.
Server: Processes the keypress states and updates the paddle positions accordingly.

Issue: When two players are connected (e.g., in two browser tabs), the paddles sometimes move up on their own after prolonged gameplay or when the ball speed increases.

Client-Side Code:
Here’s how I handle keypress events on the client:

window.addEventListener("keydown", (key: KeyboardEvent) => {
  keys[key.key] = true;
});

window.addEventListener("keyup", (key: KeyboardEvent) => {
  keys[key.key] = false;
});

private keysFunction(): void {
  if (this.keys["w"]) {
    this.gameState.keypressd = "w";
  } else if (this.keys["s"]) {
    this.gameState.keypressd = "s";
  } else {
    this.gameState.keypressd = "";
  }
}

Server-Side Code:
Here’s how I process paddle movement on the server:

function gameLogic(gameState) {
  let step = 8;

  if (gameState.keypressd === "w" && gameState.playerId === 1) {
    gameState.paddleLeftY -= step;
  }
  if (gameState.keypressd === "s" && gameState.playerId === 1) {
    gameState.paddleLeftY += step;
  }
  if (gameState.keypressd === "w" && gameState.playerId === 2) {
    gameState.paddelRightY -= step;
  }
  if (gameState.keypressd === "s" && gameState.playerId === 2) {
    gameState.paddelRightY += step;
  }

  gameState.keypressd = ""; // Reset key state
  return gameState;
}

What I’ve Tried:

  • Rate Limiting Key Updates: I added throttling on the client to send key updates at a controlled interval (e.g., every 50ms).
    Boundary Enforcement: I ensured paddle positions are clamped within valid ranges (0 to 450).
  • Separate Key States: I made keypressd player-specific (e.g., keypressdPlayer1 and keypressdPlayer2).
  • Ball Speed Cap: I capped the ball speed to prevent extreme game states.

Despite these changes, the issue persists. It seems to occur more frequently when:

  • Two browsers are connected.
  • The ball speed increases after multiple hits.

Questions:

  • Could this issue be caused by desynchronization between the client and server?
  • Is my logic for handling keypress states flawed?
  • How can I debug and fix this issue to ensure smooth paddle movement?

Additional Context:

  • The server uses WebSockets to broadcast the updated game state to both players.
  • The ball speed increases after every two hits, which might be contributing to the issue.

Any help or suggestions would be greatly appreciated!

Checking presence of media file in local folder

I’m developing a Web application (vanilla Javascript) aimed to work fully locally at the client side (i.e. there is nothing being retrieved from any external server; in fact, the whole application can be stored into a memory stick or external storage device and invoked even if there is no internet connection at all). The application is aimed to manage media files (pictures as well as video clips, all stored locally).

As part of its functionality, I’m trying to write a piece of code that, upon user’s request, will scan and check that each and every media file reference contained within an index file does have a matching media file within a repository folder.

Following some hints I found in the internet it would appear that the solution would be to create a img and video elements (including a source element as a child of the video element), try to set their respective source to point to the file within the repository and catch an event when the load attempt fails (i.e. there is no such file in repository).

So far, neither type of media file is properly handled:

  1. missing mpg files are not detected (message are not shown),
  2. All the mp4 files are shown as missing.

The loop (that scans through the index file) is using an interval to allow some time for the loading to execute. This interval is set to 1ms since (and this is my assumption), if the searched file is missing, the error will be immediately triggered.

The relevant part of the code handling this scanning process follows.

var l_Tempo_Image_Element = document.createElement("img"  ) ;
var l_Tempo_Clip_Element  = document.createElement("video") ;
var l_Tempo_Clip_Source   = document.createElement("source") ;

function f_Progress_1_Step() {
    if ((l_Progress_Bar_Width_seed >  l_Albums_Count) || 
        (G_Halt_Consistency_Check  == true          )    ){

        clearInterval(l_Interval);

        G_Halt_Consistency_Check = false ;

        l_Progress_Bar_OBJ.style.width = (l_Progress_Bar_Width_seed / l_Albums_Count) * 100 + "%";
        l_Progress_Num_OBJ.textContent = (l_Progress_Bar_Width_seed - 1) + " / " + l_Albums_Count ;
        
        l_Scan_Index = 0;
    } else {

        l_Scan_Index = l_Scan_Index + 1

        l_Update_Steps_Counter = l_Update_Steps_Counter + 1 ;
        l_Progress_Bar_Width_seed = l_Progress_Bar_Width_seed + 1 ;

        if (l_Update_Steps_Counter == l_Update_Steps) {

            l_Progress_Bar_OBJ.style.width = (l_Progress_Bar_Width_seed / l_Albums_Count) * 100 + "%";
            l_Progress_Num_OBJ.textContent = l_Progress_Bar_Width_seed + " / " + l_Albums_Count ;

            l_Update_Steps_Counter = 0 ;
        }
    }

    try{

        if (l_Album_ID != G_Display_List[l_Scan_Index].Album_ID){
            l_Album_ID = G_Display_List[l_Scan_Index].Album_ID ;
            console.log("Checking Index consistency for Album " + G_All_Albums[G_Display_List[l_Scan_Index].Album_ID].Album_Title) ;
        }

        if (G_Display_List[l_Scan_Index].Type.toUpperCase() == "JPG") {

            l_Tempo_Image_Element.setAttribute("onerror" , "console.log('Missing file Image'") ;
            l_Tempo_Image_Element.setAttribute ("src", G_All_Media_Files_Location + G_Display_List[l_Scan_Index].File) ;

        }
        else if (G_Display_List[i].Type.toUpperCase() == "MP4") {

            l_Tempo_Clip_Element.setAttribute("onerror"  , "console.log('Missing file Video!')" ) ;
            l_Tempo_Clip_Source.setAttribute("onerror"  , "console.log('Missing file Video!')" ) ;

            l_Tempo_Clip_Element.setAttribute ("src", G_All_Media_Files_Location + G_Display_List[l_Scan_Index].File) ;

            console.log("Checking file: " + G_All_Media_Files_Location + G_Display_List[l_Scan_Index].File)
        }
    }
    catch {

        console.log("Missing file index is: " + l_Scan_Index + " - File: " + G_Display_List[l_Scan_Index].File)
    }
}

Any help will be much appreciated.
Cheers.

How to get last login date & time for the logged in user in azure ad?

I’m using Azure AD for authentication in a React.js application. I need to retrieve the last login time of the currently logged-in user and store it in the database for use on the user management page.

Users are already being saved in the database, and I want to track the last login timestamp for each user. However, since authentication is handled by Azure AD, I don’t have direct control over the login process to record this timestamp myself. Therefore, I need to fetch the user’s last login time from Azure AD.

How can I add refresh token functionality at server side?

I want to add refresh token functionality at server side in nextjs. From the server side I means that the api that I call at server in page.js file. I am not using nextjs inbuilt backend.
Basically I am using nextjs with custom server (reference link) with nodejs and expressjs.

Below is my code with I call a server side api and server axios interceptor for refresh logic.

The main problem that I am facing is I cannot set cookies.

The error is –
Error: Cookies can only be modified in a Server Action or Route Handler.

page.js file

const fetchMembersData = async () => {
    let returnData = {status: false, data: [], statusCode: null};
    try {
        const { data } = await serverAxios.post(MEMBERS.LIST, {
            page: 1, limit: 12, sortOrder:"ASC", sortBy:"name"
        });        
        if(data.status == API_STATUS.SUCCESS) {
            returnData = data;
            returnData.statusCode = API_STATUS.SUCCESS;
        }
    } catch (e) {
        console.log(`error `, e);
        returnData.statusCode = e?.status || null;
    } 
    finally {
        return returnData;
    }
}

const page = async () => {

    const data = await fetchMembersData();

      if(!data.status) {
        handleServerAction(data.statusCode);
        return;
      }


  return (
    <Main data={data} />
  )
}

export default page

serverAxios.js file

import { API_STATUS, BASE_URL, COOKIE_DEFAULT_EXPIRE } from "../constant";
import momentTimezone from 'moment-timezone';
import { AUTH } from "../apiConstant";
import axios from "axios";
import createAuthRefreshInterceptor from "axios-auth-refresh";
import { cookies } from "next/headers";

// Create an Axios instance
const AxiosInstance = axios.create({ baseURL: BASE_URL });


// Intercept request
AxiosInstance.interceptors.request.use(async (request) => {
    const cookieStore = await cookies();
    const token = cookieStore.get("token")?.value || "";

    if (token) {
        request.headers.Authorization = `Bearer ${token}`;
    }
    request.headers.tz = momentTimezone.tz.guess();
    return request;
}, (error) => {
    return Promise.reject(error);
});

// Refresh token function
const refreshTokenFunction = async (failedRequest) =>
    axios.post(`${BASE_URL}/${AUTH.REFRESH_TOKEN}`, {}, {
        headers: {
            // "refresh-token": Cookies.get("the-50-group-refresh-token") || ""
            "refresh-token": await cookieStore.get("refresh-token")?.value || ""
        }
    }).then(resp => {
        console.log(`respo data --> `, resp.data); //DEBUGGING
        if (resp.data.status == API_STATUS.SUCCESS) {
            const { access_token: token, refresh_token } = resp.data;

            // Set the new token globally
            AxiosInstance.defaults.headers.Authorization = `Bearer ${token}`;

            /**
             * Set access tokena and refresh token in cookies
             * But got error that cookies can only be set in server action or route handler
             */

            // Update the failed request's Authorization header
            failedRequest.response.config.headers.Authorization = `Bearer ${token}`;

            return Promise.resolve();
        } 
        else {

            cookieStore.delete('token');
            cookieStore.delete('refresh-token');

            throw new UnauthorizedError('Unauthorized');
        }
    }).catch((error) => {
        console.log(`refreshTokenFunction error --> `, error); //DEBUGGING

        throw new UnauthorizedError('Unauthorized');
});

// Create axios interceptor
createAuthRefreshInterceptor.default(AxiosInstance, refreshTokenFunction);


// Intercept response
AxiosInstance.interceptors.response.use((response) => {
    return Promise.resolve(response);
}, async (error) => {
    return Promise.reject(error);
});

export default AxiosInstance;

Error: Cannot access contents of the page. Extension manifest must request permission to access the respective host

I am trying to create a chrome extension which summarizes the selected text from a webpage by using Gemini API. But whenever i try to run the extension an error occurs :
Error: Cannot access contents of the page. Extension manifest must request permission to access the respective host.
I don’t think there’s any issues with the backend.
I have tried all possible fixes but couldn’t resolve it.
Another issue is that sidepanel is missing from my chrome and not showing up by any mean. Therefore i tried building it as a popup window.

Here’s my frontend code:
manifest.json

{
  "manifest_version":3,
  "name":"Research Assistant",
  "version":"1.0",
  "description":"AI Powered Research Assistant",
  "permissions":[
      "activeTab",
      "storage",
      "scripting"
  ],
  "action":{
      "default_title":"Reasearch Assistant"
  },
  "side_panel":{
      "default_path":"sidepanel.html"
  },
  "background":{
      "service_worker":"background.js"
  },
  "host_permissions":[
      "http://localhost:8080/*",
      "<all_urls>",
      "http://*/",
      "https://*/"
  ],
  "content_security_policy":{
      "extension_pages":"script-src 'self'; object-src 'self'"
  }
}

sidepanel.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Research Assistant</title>
    <link rel="stylesheet" href="sidepanel.css">
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>Research Assistant</h2>
        </div>
        <div class="actions">
            <button id="summarizeBtn">Summarize</button>
        </div>
        <div id="results"></div>
    </div>
    <script src="sidepanel.js"></script>
</body>
</html>

sidepanel.js

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('summarizeBtn').addEventListener('click', summarizeText);
});

async function summarizeText() {
    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        const [{ result }] = await chrome.scripting.executeScript({
            target: { tabId: tab.id },
            function: () => window.getSelection().toString()
        });

        if (!result) {
            showResult("Please Select Some Text First!");
            return;
        }

        const response = await fetch('http://localhost:8080/api/research/process', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ content: result, operation: 'summarize' })
        });

        if (!response.ok) {
            throw new Error(`API Error: ${response.status}`);
        }

        const text = await response.text();
        showResult(text.replace(/n/g, '<br>'));
    } catch (error) {
        showResult('Error: ' + error.message);
    }
}

function showResult(content) {
    document.getElementById('results').innerHTML = `<div class="result-item"><div class="result-content">${content}</div></div>`;
}
    

background.js

chrome.action.onClicked.addListener(async () => {
    try {
      await chrome.windows.create({
        url: "sidepanel.html",
        type: "popup",
        width: 400,
        height: 600
      });
    } catch (error) {
      console.error('Failed to create window:', error);
    }
  });
  
  async function getCurrentTab() {
    try {
      const queryOptions = { active: true, lastFocusedWindow: true };
      const [tab] = await chrome.tabs.query(queryOptions);
      return tab;
    } catch (error) {
      console.error('Failed to get current tab:', error);
      return null;
    }
  }