testing an useState change inside a callback

I have a component like this to test:

import {doSomethingMocked} form 'mockedLibrary';

const TheComponent = (props) => {
  const [isToTest, setIsToTest] = useState(false);
  const handleClick = useCallback(()=>{
    if(isToTest) return;
    setIsToTest(true);
    doSomethingMocked();
  }, [isToTest]);
  return (
    <button onClick={handleClick}>Click me</button>
  );
}

The Unit Test is something like this

import {render, fireEvent, act} form '@testing-library/react';
import {doSomethingMocked} form 'mockedLibrary';
jest.mock('mockedLibrary');

describe('The Component', ()=>{
  beforeEach(async ()=>{
    const sut = render(<MyProvider value={{}}><TheComponent/></MyProvider>);
    await act(async()=> await fireEvent.click(sut.getByText('Click me'))); // in theory the act now is unnecesary, any way still the state dows not toggle
    await act(async()=> await fireEvent.click(sut.getByText('Click me')));
  });
  it('Should only doSomething once', sync ()=>{
    expect(doSomethingMocked).toHaveBeenCalledTimes(1); // but it's called twice
  })
})

How can I test the boolean useState toggles?

I already run the component and works fine, but test wise, the useState change never happens.
Previously with enzyme after the wraper.update() was enought to test it.

Karma + Jasmin mock query param

I am new to ts and to frontend. I want to write test that mocks query param in uri.

it('should read the query parameter', () => {
  const stub = sinon.stub(window.location, 'search').get(() => '?query=test');

  const getQueryParam = () => {
    return new URLSearchParams(window.location.search).get('query');
  };

  const query = getQueryParam();

  assert.strictEqual(query, 'test');

  stub.restore();
});

I have googled that sinon can help me with this but i get: TypeError: Cannot redefine property: search. My intuition says that it shouldn’t be so complicated. Any best practices to accomplish it?

How can I prevent the second digit from shifting when deleting the first digit when editing a day in a date imask?

I am using IMaskJS. When you delete the first digit of the day of the date, the second one shifts to the left and takes its place, please tell me how to prevent this behavior.

{
          mask: Date,
          pattern: '`DD.`MM.`YYYY',
          format: date => moment(date).format('DD.MM.YYYY'),
          parse: str => moment(str, 'DD.MM.YYYY'),
          lazy: false,
          blocks: {
            DD: {
              mask: IMask.MaskedRange,
              from: 1,
              to: 31
            },
            MM: {
              mask: IMask.MaskedRange,
              from: 1,
              to: 12
            },
            YYYY: {
              mask: IMask.MaskedRange,
              from: 1000,
              to: 2999
            }
          }
        }

I tried to change the pattern field in the imask settings. Correct behavior is expected without shifting the numbers.

How to send a print command from a web application to a Bluetooth Brother label printer?

I am developing a mobile web application (React/JavaScript) that needs to send print commands to a Brother label printer (model TD-2120N / QL series) connected via Bluetooth.

  1. Using the browser’s window.print() – not suitable since it opens the system dialog and doesn’t support direct label formatting.

  2. Checking Brother’s SDK – seems focused on native apps (Android/iOS/Windows), not web.

  3. Looking into Web Bluetooth API – limited documentation on integrating with Brother printers.

Goal

Allow users to print labels (text + barcodes) directly from a mobile web app to a Bluetooth-connected Brother label printer without installing a native app..

Questions

  1. Can the Web Bluetooth API be used on mobile browsers (Chrome/Android or Safari/iOS) to connect and send print commands to Brother printers?

  2. Is a bridge app or service (like a small native companion app) required?

  3. Any JavaScript examples of successfully sending label data to a Brother printer over Bluetooth?

Meshes not loading in

In my game ive updated the rendering to be more optimized but that led to some errors and not nothing is loading, when checking the f12 menu it shows this and i have no idea what it means

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'mergeBufferGeometries')
    at greedyMesh ((index):570:52)
    at rebuildWorldMesh ((index):619:16)
    at Socket.<anonymous> ((index):779:3)
    at Emitter.emit (index.js:136:20)
    at Socket.emitEvent (socket.js:553:20)
    at Socket.onevent (socket.js:540:18)
    at Socket.onpacket (socket.js:508:22)
    at Emitter.emit (index.js:136:20)
    at manager.js:217:18

Heres the code

Ive tried searching it up and at first i thought it was something with the buffer geometries utils but i tried changing it and it didnt work

Writing tests in Jasmine for functions with dependancy on data from remote host whithout making actual fetch request

I apologize beforehand for this post, but I am struggling to figure out how to mock data from fetch request without making request itself and then test functions which have this data as dependency in Jasmine.

Here is my JavaScript code:

let products = []; //Array where transformed data from fetch request is stored for further use

function getProduct(productId) {//function to get product with certain id

  let matchProduct = products.find(product => product.id === productId)

  return matchProduct;

}


class Product { /*Example of classes used in function below, I can test them fine and they pass tests*/

  id;
  image;
  name;
  rating;
  priceCents;
  keywords;

  constructor(productDetails) {

    this.id = productDetails.id;
    this.image = productDetails.image;
    this.name = productDetails.name;
    this.rating = productDetails.rating;
    this.priceCents = productDetails.priceCents;
    this.keywords = productDetails.keywords;

  }

  getStars() {
    return `images/ratings/rating-${this.rating.stars * 10}.png`;
  }

  getPrice() {
    return `$${formatCurrency(this.priceCents)}`;
  }

  extraInfoHTML() {
    return ''
  }
}



function loadProducts() {

  const promise = fetch('link to host').then(response => {
    
    return response.json(); //host responds with array of objects if translated in json

  }).then(productData => { /*manipulating received array of objects to transform objects into classes and saving in new array*/

    products = productData.map(productDetails => {

      if (productDetails.keywords.includes('appliances')) {

        productDetails.type = 'appliance';
        productDetails.instructionLink = 'images/appliance-instructions.png';
        productDetails.warrantyLink = 'images/appliance-warranty.png';

        return new Appliance(productDetails);

      }

      if (productDetails.type === 'clothing') {

        return new Clothing(productDetails);

      }

      return new Product(productDetails);

    });

  }).catch(error => {

    console.error(error.message);

  });

  return promise;
}

All code works well and does what it does outside of test environment, but I got interested in how to test function getProduct() without making actual fetch request to remote host and how to test if remote host responded with correct data on request itself and/or request used correct link using Jasmine.

How can I reliably detect and apply only user-edited text changes to the original static HTML?

I’m building a tool that allows users to edit text directly on a live webpage. The goal is to let users change only the visible text content (e.g., in <p>, <h1>, <span>, etc.), and then apply those changes to the original static HTML structure — without affecting scripts or dynamic content.

What I’ve implemented so far:
1.Fetch original HTML via fetch(window.location.href) and parse it using DOMParser.
2.Enable inline editing by setting contentEditable=true on certain elements (h1–h6, p, div, span).
3.Compare the original and live DOMs, and if a text node has changed, replace it in the original DOM.
4.Export the updated original DOM as static HTML for download.

Even though users only change a few pieces of text, my script ends up modifying more text nodes than expected — even ones that the user did not change.

What I’m looking for:

A reliable way to compare and update only user-modified text content.
A method to ignore false positives caused by whitespace, formatting, or DOM reflows.
An approach that works even when parts of the page are rendered dynamically but should be excluded from export.

Any suggestions to improve text diffing accuracy, DOM mapping strategies, or handling dynamic vs static content separation would be very helpful.

Thank you!

gradlew build – FAILURE: Build failed with an exception

Unable to launch Gradlew build. I’ve tried everything, but it won’t launch. It works fine, but as soon as I want to create a mod for Minecraft, it doesn’t work.
I’m attaching a Google Drive link with all the configurations.

https://drive.google.com/drive/folders/1aauhnYdlnvQjEY7ppI938XknCmpWwSlI?usp=drive_link

Unable to launch Gradlew build. I’ve tried everything, but it won’t launch.

FAILURE: Build failed with an exception.

  • Where:
    Settings file ‘C:Usersraneeterencioothil96Downloadsforge-1.20.1-47.4.0-mdksettings.gradle’ line: 14

  • What went wrong:
    An exception occurred applying plugin request [id: ‘net.minecraftforge.gradle’, version: ‘6.0.25’]

Failed to apply plugin ‘net.minecraftforge.gradle’.
class org.gradle.initialization.DefaultSettings_Decorated cannot be cast to class org.gradle.api.Project (org.gradle.initialization.DefaultSettings_Decorated and org.gradle.api.Project are in unnamed module of loader org.gradle.internal.classloader.VisitableURLClassLoader @4cc77c2e)

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.
Get more help at https://help.gradle.org.

BUILD FAILED in 11s

C:Usersraneeterencioothil96Downloadsforge-1.20.1-47.4.0-mdk>

Javascript Help – Article Counter Function

I’m trying to figure out how to have a little counter for my journal entries and something isn’t right (I’m still learning javascript and this is me trying to mess with some code I found, so I’m likely missing something obvious. sorry!)
The way I want it to work is by having a counter for the number of articles in any given year section. I think the issue is that it doesn’t recognise that there are articles already in the section, but I’m not entirely sure.

Any help is appreciated!

This is the display counter:

<section id="home">
  <p>choose the year you want to view!</p>
  <button onclick="goToYear('2025')">
    <span class="year">2025</span>
    <br>
    <span id="logs2025">total logs: </span>
  </button>
</section>

Here is the article section:

<section id="y2025">
  <article><p> test article test test test </p></article>
</section>

And here’s the counter:

function totalLog(year) {
  let articles = "#y" + year + "article";
  let articlesSelected = document.querySelectorAll(articles);
  let currentSpan = "logs" + year;
  let currentSpanSelected = document.getElementById(currentSpan);
  currentSpanSelected.innerText = "total logs: " + articlesSelected.length;
}

How to deselect all selected options in a multiple select?

I have an select autocomplete, that has multiple true. I would like to clear all selected items with javascript. This is the code I’m using:

const $sel = $('#' + selectId);
if (!$sel.length) {return;}
$sel.find('option:selected').prop('selected', false);
$sel[0].dispatchEvent(new Event('change', { bubbles: true }));

But is not working. This code is only working for multiple = false.

This is code of form element:

// View selections to show on booking options overview.
        $options = array(
            'multiple' => true
        );
        $mform->addElement(
            'autocomplete',
            'showviews',
            get_string('showviews', 'booking'),
            $whichviewopts,
            $options
        );
        $mform->setType('showviews', PARAM_TAGLIST);
        $defaults = array_keys($whichviewopts);
        $mform->setDefault('showviews', $defaults);

Is there a way to programmatically clear selected items from java script and the programmatically select? It’s working only for single item. If I use multiple => true is not working.

can’t connect to mongodb docker replica sets

i’am trying to connect to docker mongodb replica sets from my nodejs application that is not an docker container but anytime i try connecting to mongodb replica set i get an error saying ,

db-connection-error MongooseServerSelectionError: getaddrinfo ENOTFOUND mongo3

or

Unable to connect: getaddrinfo ENOTFOUND mongo1

below is command i use to run docker mongodb containers

C:Usersshubham>docker run -d --name mongo1 --net mongoNetwork -p 27017:27017 -v "C:datadb" mongo:latest --replSet rs0
da575dbb8f73184fdaeaa05e5d30ffbc9d2b103f3fe8aee1a9621476313ee904

C:Usersshubham>docker run -d --name mongo2 --net mongoNetwork -p 27018:27017 -v "C:datadb1" mongo:latest --replSet rs0
df3c5f4ad73c21d6eaf23db0c3e0bd019f4c0bed2ba56570a5006d99e3741b3e

C:Usersshubham>docker run -d --name mongo3 --net mongoNetwork -p 27019:27017 -v "C:datadb2" mongo:latest --replSet rs0
eec0ca83533a47f7ed06060973d8ffcd8847d8be8d427e04139b49a2b8f92b04

C:Usersshubham>

below initializing the replica set

test> config = {_id:"rs0", members:[{_id:0, host:"mongo1:27017"},{_id:1, host:"mongo2:27017"},{_id:2, host:"mongo3:27017"}]}
{
  _id: 'rs0',
  members: [
    { _id: 0, host: 'mongo1:27017' },
    { _id: 1, host: 'mongo2:27017' },
    { _id: 2, host: 'mongo3:27017' }
  ]
}
test> rs.initiate(config)
{
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1756458399, i: 1 }),
    signature: {
      hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
      keyId: Long('0')
    }
  },
  operationTime: Timestamp({ t: 1756458399, i: 1 })
}
rs0 [direct: secondary] 

list of urls i used to connect

  • mongodb://mongo1:27017
  • mongodb://localhost:27017
  • mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0
  • mongodb://mongo1:27017,mongo2:27018,mongo3:27019/?replicaSet=rs0

none of the above urls connected to the mongodb replica set

i’ve tried changing hosts ports in

C:windowssystem32driversetchosts

127.0.0.1 mongo1
127.0.0.1 mongo2
127.0.0.1 mongo3

unfortunately nothing did worked out

i’ve tried so many ways to fix it but still i’am unable to connect to docker mongodb replica sets from outside of docker container to an docker mongodb replica set

please kindly tell help explain why is it happening
what step should i take to connect to replica sets
is it because i’am trying to connect from outside of docker network of something else it the reason

Next.js App Built with Node 20 Breaks When Served with Node 21 – Runtime Compatibility Issue

Problem Description

I have a Next.js application that works perfectly when built and served with Node.js 20, but some sections stop working when I serve the same built version with Node.js 21. This appears to be a runtime compatibility issue between different Node.js versions.

Current Setup

  • Framework: Next.js 14.2.26
  • Build Environment: Node.js 20.x
  • Target Deployment: Cloudflare Workers (which runs Node 21/22+ runtime)
  • Package Manager: pnpm 8.x

What Works vs What Doesn’t

✅ Working Scenario

# Build with Node 20
node --version  # v20.x.x
npm run build
npm run start   # Everything works perfectly

❌ Broken Scenario

# Build with Node 20, serve with Node 21
node --version  # v20.x.x
npm run build

# Switch to Node 21
nvm use 21      # or any method to switch to Node 21
node --version  # v21.x.x
npm run start   # Some sections of the site stop working

Specific Issue

When serving the Node 20-built application with Node 21 runtime:

  • Site loads – Main pages render correctly
  • Some sections break – Certain components/features malfunction
  • Inconsistent behavior – Not a complete crash, but partial functionality loss

Current Configuration

package.json

{
  "engines": {
    "node": "20.x",
    "pnpm": "8.x"
  },
  "scripts": {
    "build": "next build",
    "start": "next start",
    "build:cf": "npx @opennextjs/cloudflare build",
    "deploy:cf": "wrangler deploy"
  },
  "dependencies": {
    "@opennextjs/cloudflare": "^1.6.5",
    "next": "14.2.26",
    "wrangler": "^4.32.0"
  }
}

.npmrc

engine-strict=true

Why This Matters

I need to deploy to Cloudflare Workers, which automatically runs the latest Node.js runtime (21/22+). I cannot control the runtime version on Cloudflare Workers, but I’m constrained to build with Node 20 locally.

Questions

  1. What specific changes between Node 20 and Node 21 could cause partial functionality loss?

  2. How can I identify which sections are breaking and why?

  3. Are there runtime compatibility techniques to make a Node 20 build work reliably on Node 21?

  4. Is this a common issue with Next.js applications when there’s a Node version mismatch between build and runtime?

  5. What debugging approaches can help identify the root cause of the partial failures?

What I’ve Tried

  • ✅ Confirmed the app works perfectly on Node 20 (build + runtime)
  • ✅ Confirmed the same build fails partially on Node 21 runtime
  • ✅ Researched Node 20 vs 21 breaking changes
  • ❌ Haven’t identified the specific cause of partial failures

Environment Details

  • OS: Linux

  • Build Tool: Next.js built-in build system

  • Deployment Target: Cloudflare Workers (via @opennextjs/cloudflare)

  • Package Manager: pnpm with engine-strict enforcement

  • Diagnostic techniques to identify which specific features break

  • Understanding of Node 20 → 21 changes that cause runtime issues

  • Solutions to ensure build/runtime compatibility across Node versions

  • Best practices for handling Node version mismatches in production

This runtime compatibility issue is blocking my Cloudflare Workers deployment. Any help identifying and resolving these partial functionality failures would be greatly appreciated!

What kind of algorithm does betting website use to determined winners probability? [closed]

Well, I’m from the Philippines, where there are a lot of online betting games. I play these games, and I’m curious about what algorithms programmers use to determine the probability of winning. Or is it more like you win a lot of prizes the first time you play, but the more you play, the more you lose?

I tried to talk to other programmers but they said they are different kinds of algorithm they are using and somewhat I’m still confused

How to add +1 each year in the footer copyright each year? [duplicate]

i’ve one part of code that I use before my </body> for each page of my website and it works perfectly. Each year i just need to change 2024 to 2025, 2025 by 2026… manualy.

But i’m wondering if it’s not possible to add something in this code to change it automatically by using my time zone for example and adding +1 to 2025, 2026, 2027… each year from 01/01 at 00.01am?

Here is my actual code:

<script>
$('.footer-copyright, .links-copyright').html("<div style='margin: 0 auto; font-size: 10px;'>all rights reserved 2025 I made by <a target='_blank' href='...'><span style='font-weight:bold'>my name</span></a></div>");
</script>

Output not displaying on mobile

First year student here. Group project. This works how it’s supposed to but when I sent my assignment partner the file, the button does not work. Nothing is displayed.
works great on desktop even with the screen made smaller.

This happens when the file is opened from an email as in the HTML file.

Any help is appreciated!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Child Support Calculator</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f0f2f5;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
        }
        .container {
            max-width: 500px;
            width: 90%;
            background-color: #ffffff;
            border-radius: 1rem;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            padding: 2rem;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }
        .input-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: #374151;
        }
        .input-group input, .input-group select {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 0.5rem;
            font-size: 1rem;
            color: #4b5563;
        }
        .input-group input:focus, .input-group select:focus {
            outline: none;
            border-color: #2563eb;
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2);
        }
        .btn {
            background-color: #2563eb;
            color: #ffffff;
            font-weight: 600;
            padding: 0.85rem 1.5rem;
            border-radius: 0.5rem;
            text-align: center;
            cursor: pointer;
            transition: background-color 0.2s ease-in-out;
            border: none;
            font-size: 1rem;
        }
        .btn:hover {
            background-color: #1d4ed8;
        }
        .result-box {
            background-color: #eff6ff;
            border: 1px solid #bfdbfe;
            border-radius: 0.5rem;
            padding: 1rem;
            text-align: center;
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e40af;
            min-height: 3rem; /* Ensure consistent height */
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .error-message {
            color: #dc2626;
            font-size: 0.875rem;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-3xl font-bold text-center text-gray-800 mb-4">Child Support Calculator</h1>

        <div class="input-group">
            <label for="adjustedGrossIncome">Adjusted Gross Income (Monthly)</label>
            <input type="number" id="adjustedGrossIncome" placeholder="e.g., 3000" min="0" step="0.01" class="rounded-lg p-2 focus:ring-blue-500 focus:border-blue-500 block w-full border-gray-300">
        </div>

        <div class="input-group">
            <label for="numberOfChildren">Number of Children</label>
            <select id="numberOfChildren" class="rounded-lg p-2 focus:ring-blue-500 focus:border-blue-500 block w-full border-gray-300">
                <option value="1">1 Child</option>
                <option value="2">2 Children</option>
                <option value="3">3 Children</option>
                <option value="4">4 Children</option>
                <option value="5">5+ Children</option>
            </select>
        </div>

        <button id="calculateBtn" >Calculate Support</button>

        <div id="errorMessage" class="error-message hidden"></div>

        <div id="result" class="result-box">
            
        </div>

       
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const adjustedGrossIncomeInput = document.getElementById('adjustedGrossIncome');
            const numberOfChildrenSelect = document.getElementById('numberOfChildren');
            const calculateBtn = document.getElementById('calculateBtn');
            const resultDiv = document.getElementById('result');
            const errorMessageDiv = document.getElementById('errorMessage');

            const supportPercentages = {
                '1': 0.14, // 14% for 1 child
                '2': 0.20, // 20% for 2 children
                '3': 0.22, // 22% for 3 children
                '4': 0.24, // 24% for 4 children
                '5': 0.26  // 26% for 5 or more children
            };

            /**
             * Calculates the estimated child support based on  guidelines.
             * @param {number} income - The adjusted gross income (monthly).
             * @param {number} childrenCount - The number of children.
             * @returns {number} The estimated monthly child support amount.
             */
            function calculateChildSupport(income, childrenCount) {
                if (income < 0) {
                    return 0; // Income cannot be negative
                }

                let percentage;
                if (childrenCount >= 5) {
                    percentage = supportPercentages['5']; // Use 26% for 5 or more
                } else {
                    percentage = supportPercentages[childrenCount.toString()];
                }

                if (percentage === undefined) {
                    return 0; // Should not happen with valid input, but as a safeguard
                }

                return income * percentage;
            }

            // Event listener for the calculate button
            calculateBtn.addEventListener('click', function() {
                const income = parseFloat(adjustedGrossIncomeInput.value);
                const children = parseInt(numberOfChildrenSelect.value, 10);

                // Input validation for valid positive income
                if (isNaN(income) || income < 0) {
                    errorMessageDiv.textContent = 'Please enter a valid positive adjusted gross income.';
                    errorMessageDiv.classList.remove('hidden');
                    
                    return;
                }

                

                const estimatedSupport = calculateChildSupport(income, children);

                // Display the result
                if (estimatedSupport >= 0) {
                    resultDiv.textContent = `Estimated Monthly Support: $${estimatedSupport};
                } 
            });

            // Optional: Clear error message when input changes
            adjustedGrossIncomeInput.addEventListener('input', function() {
                if (!errorMessageDiv.classList.contains('hidden')) {
                    errorMessageDiv.classList.add('hidden');
                }
            });
        });
    </script>
</body>
</html>

I expected it to display the amount as it does on the desktop.

Does opening an HTML file from an email directly change anything? Or is our code off?