How can I display a custom error message when a Jest snapshot test fails?

I have a simple Jest snapshot test, and upon failure, I would like to print a custom error message to remind the developer that if they intentionally failed the test, they need to ensure they update a related constant that’s used in the page/component. Here is my test:

describe('My Page', () => {
  it('matches the snapshot', () => {
    const { asFragment } = render(<MyComponent />)

    expect(asFragment()).toMatchSnapshot()
  })
})

I’ve tried to wrap the expect in a try/catch, however, the test fails immediately at toMatchSnapshot() and the catch block is never reached:

try {
  expect(asFragment()).toMatchSnapshot()
} catch (error) {
  error.message +=
    'nNOTE: The snapshot for the page has changed. If this is intentional, please remember to update the MY_CONSTANT constant accordingly.'
  throw error
}

Is there any way to print a custom error message when a Jest snapshot test fails?

Struggling with Multi-Line Input Field for Combined User and AI Text

I’m working on an input field that combines user input (userText) and AI-generated suggestions (aiText). The goal is to make them appear as part of the same sentence, even when the user hasn’t accepted the AI’s suggestions yet.
input field
Currently, the input field is single-line, and when aiText is longer, it breaks awkwardly in the middle of the input field, making it look disjointed. Ideally, if aiText needs to wrap to a new line, it should start from the very left of the input component, not from the middle where userText ends.

Here’s the current implementation:

<div
  onClick={focusContentEditable}
  className="relative flex justify-start items-start p-3 border border-border
             bg-[#FFFFFF] text-[#1F1F1F] dark:bg-[#2A2A40] dark:text-[#EAEAEA] 
             focus-within:outline focus-within:outline-[#9462fd] 
             cursor-text rounded-2xl text-left w-full h-20 mx-auto 
             overflow-hidden"
>
  {/* Placeholder */}
  {userText.trim() === "" && !isFocused && (
    <span className="text-gray-400 text-xs">Ask me anything...</span>
  )}
  <div className="inline-flex items-baseline">
    <span
      ref={contentEditableRef}
      className="text-xs border-0 outline-none whitespace-nowrap break-words inline-flex min-h-[20px] w-full"
      contentEditable={true}
      suppressContentEditableWarning={true}
      onInput={handleInput}
      onKeyDown={handleKeyDown}
    >
      {/* {userText} */}
    </span>
    <span
      className={`text-xs text-gray-400 dark:text-gray-600 transition-opacity whitespace-normal inline-flex duration-500 ${
        aiText ? "opacity-100" : "opacity-0"
      }`}
      contentEditable={false}
    >
      {aiText.length > 0 && userText.trim() !== "" && <>{aiText}</>}
    </span>
  </div>
</div>

Problem:

  1. The input field is single-line, and I’m not enforcing line breaks.
  2. When aiText is present and long, it breaks mid-line, which disrupts the flow of the text.
  3. I want the input field to expand in height to accommodate a second line if needed, so aiText can wrap cleanly to the next line starting from the left edge.

What I’ve Tried:

  • Using contentEditable for dynamic text input.
  • Combining userText and aiText in a single container with inline-flex to keep them aligned.

Desired Behavior:

  • The input field should expand in height to allow multi-line text.
  • aiText should wrap to the next line starting from the left edge if it doesn’t fit in the current line.
  • userText and aiText should appear as part of the same sentence.

Any suggestions on how to achieve this? Thanks in advance!

Pact gRPC consumer test in node.js

I am evaluating Pact and i fail to get a running grpc consumer test in node.js.
I installed the protobuf plugin with the Pact CLI tool.

My mocha test looks like this:

'use strict';
const { PactV4, SpecificationVersion } = require('@pact-foundation/pact');
const path = require('node:path');

describe.only('PactTest', function () {
    let provider;

    before(async function () {
        provider = new PactV4({
            dir: path.resolve(process.cwd(), 'pacts'),
            consumer: 'some.consumer',
            provider: 'some.provider',
            port: '50073',
            spec: SpecificationVersion.SPECIFICATION_VERSION_V4
        });
    });

    it('shall create contract file', async function () {
        await provider
            .addSynchronousInteraction('Call scheduler service')
            .usingPlugin({
                plugin: 'protobuf',
                version: '0.5.4'
            })
            .withPluginContents(
                JSON.stringify({
                    'pact:proto': '/Users/path/to/some/proto/scheduler.proto',
                    'pact:proto-service': 'ElsaSchedulerService/GetTaskExecutionById',
                    'pact:message-type': 'GetTaskExecutionByIdResponse',
                    'pact:content-type': 'application/protobuf',
                    success: true,
                    taskFullName: 'egon'
                }),
                'application/grpc'
            )
            .startTransport('grpc', '127.0.0.1')
            .executeTest(async mockServer => {
                //mockServer.port === 55312

                // do some stuff which triggers the grpc call
            });
    });
});

It even starts a mockServer but it has a random port (55312) and i need the mock server to listen to port 50073.
Why does Pact ignore the port i specified in line 13?

Thanks in advance,
Thomas

Can’t load a local file in react

I’m trying to load a local html file in react. I’ve tried multiple ways, including fetch, axios, and raw-loader. I can get raw-loader to work, but only if I hard code the filename. If I use a filename variable, it doesn’t work.

Using fetch, it returns “[object Object]”. Here’s the code:

  function getHtmlFile(filename:string){
    const [myTextFile, setMyTextFile] = useState('');

    useEffect(() => {
      fetch(filename)
        .then(response => response.text())
        .then(text => setMyTextFile(text));
    }, []);
  
    return (
      <div>
        <p>{myTextFile}</p>
      </div>
    );
  }

If I use raw-loader, it works if it’s hard-coded. For example, this works

const pageContent = require('raw-loader!./human_biology.html');
console.log('pageContent=', pageContent.toString());

but this produces error

Cannot find module ‘raw-loader!./human_biology.html’

const filename = './human_biology.html';
const pageContent = require('raw-loader!'+filename);
console.log('pageContent=', pageContent.toString());

Isn’t that bizarre?!!

I did a search for webpack.config.js and 3 of them showed up…

C:UsersWindowsOneDriveDocumentsProjectsmedaverter_projectsmedaverter-toolpad-noauth-approuternode_modulesreact-scriptsconfig
C:UsersWindowsOneDriveDocumentsProjectsmedaverter_projectsmedaverter-toolpad-noauth-approuternode_modulesfast-json-patch
C:UsersWindowsOneDriveDocumentsProjectsmedaverter_projectsmedaverter-toolpad-noauth-approuternode_modulesistanbul-reportslibhtml-spa

I could show the contents of those, but it seems beside the point if the hard-coded version works.

Change in the way textContent returns text with carriage return in DOMParser in Chromium

Recently I noticed a change in the way DOMParser created XMLDocuments returned text with carriage returns in textContent. Namely, carriage returns are not longer being returned in textContent.

On the left is version 120.0.6095.0 of Chromium. On the right is version 132.0.6834.162 of Chrome. The behaviour on the right is seen in Edge as well.

Change in carriage return

The behaviour on the left was the same as what was happening last year but it appears that it has recently changed to the right.
I was trying to look for when this change occurred but could not find it.
I wonder if anyone out there knows the reason for this change? (My assumption is that the new behaviour is to make it follow the spec?)

Trying to select option element by it’s value attribute based on a variable’s data

Am having a select element containing bunch of options with an attribute of value, what i want to do is to grab one of those options by its Value attribute but the value attribute needs to have a data equal to the data coming from my variable the code below will demonstrate what i mean

<option value="8">Preston Sharpe</option>
<option value="9">Margaret Cochran</option>

const serviceID = 8;
document.querySelector(`[value="${serviceID}"]`);

so what i want is to grab the option with a value of whatever equals to the variable of serviceID

Bing Maps passing lat lng from database to markers

Hi all i am testing code and have created a VS 2012 app with a webrowser the code is html to open a Bing Map and place a marker. i can hard code the Lat Long okay.
howether i need to add multiple markers from a database. i can query the DB okay and get the LAT LNG but can’t seem to replace the hard code -0.13335, 51.56507 with
var newlonLat = new OpenLayers.LonLat(LAT, LNG) when running the code i can see that the LAT and LNG do hold the 51.55824 -0.10599 stepping throgh but can’t place the markers.
apologies if i am a bit vague

<script>
  var newlonLat = new OpenLayers.LonLat(LAT, LNG).transform(fromProjection, toProjection);

  function addAllMarker(LAC, SiteName, LNG, LAT) {
    markers.addMarker(new OpenLayers.Marker(newlonLat)).transform(fromProjection, toProjection);
  }
</script>

A-FRAME and collision detection between two tubes

How to detect a collision between 2 tubes?

This one doesn’t work. As far as I know, these libraries use cannon.js. And cannon.js doesn’t have tube shape.

<script src="https://aframe.io/releases/1.5.0/aframe.min.js"></script>
<script src="https://stemkoski.github.io/A-Frame-Examples/js/parser.js"></script>
<script src="https://stemkoski.github.io/A-Frame-Examples/js/aframe-parametric-curve.js"></script>
<script src="https://cdn.rawgit.com/donmccurdy/aframe-physics-system/v4.0.1/dist/aframe-physics-system.min.js"></script>
<script src="https://stemkoski.github.io/A-Frame-Examples/js/aframe-tube-geometry.js"></script>
<script src="https://aframe.io/releases/1.5.0/aframe.min.js"></script>
<script src="https://cdn.rawgit.com/donmccurdy/aframe-physics-system/v4.0.1/dist/aframe-physics-system.min.js"></script>

<a-scene physics="gravity: -9.8">
  <a-entity id="objId-1_path" parametric-curve="xyzFunctions: (1 - t) * (1 - t) * (1 - t) * (9.866869455043389) + 3 * (1 - t) * (1 - t) * t * (9.296747637261328) + 3 * (1 - t) * t * t * (-5.081858662029424) + t * t * t * (0), (1 - t) * (1 - t) * (1 - t) * (3.448332289736946) + 3 * (1 - t) * (1 - t) * t * (3.342113628013926) + 3 * (1 - t) * t * t * (0) + t * t * t * (0), (1 - t) * (1 - t) * (1 - t) * (1.1538943718962802) + 3 * (1 - t) * (1 - t) * t * (2.528342153338074) + 3 * (1 - t) * t * t * (4.713655696327929) + t * t * t * (0); tRange: 0, 1;"></a-entity>

  <a-entity id="objId-2_path" parametric-curve="xyzFunctions: (1 - t) * (1 - t) * (1 - t) * (-8.255694973427389) + 3 * (1 - t) * (1 - t) * t * (-8.176697626601747) + 3 * (1 - t) * t * t * (-5.081858662029424) + t * t * t * (0), (1 - t) * (1 - t) * (1 - t) * (5.352404450414396) + 3 * (1 - t) * (1 - t) * t * (5.592985477997834) + 3 * (1 - t) * t * t * (0) + t * t * t * (0), (1 - t) * (1 - t) * (1 - t) * (-7.1757925398181355) + 3 * (1 - t) * (1 - t) * t * (-8.11555796776703) + 3 * (1 - t) * t * t * (4.713655696327929) + t * t * t * (0); tRange: 0, 1;"></a-entity>

  <!-- Objekti s fizičkim svojstvima -->
  <a-entity id="one" position="0 0 -4" class="orange" tube-geometry="curveData: #objId-1_path; type: parametric-curve; tubeSegments: 100; radius: 0.43395090103149414; tubeColor: orange; opacity: 1;" dynamic-body  material="side: double"></a-entity>
  <a-entity id="two" position="0 0 -3" class="orange" tube-geometry="curveData: #objId-2_path; type: parametric-curve; tubeSegments: 100; radius: 0.43395090103149414; tubeColor: red; opacity: 1;" dynamic-body  material="side: double"></a-entity>

  <a-sky color="#ECECEC"></a-sky>
</a-scene> 

<script>
  // Detekcija sudara koristeći aframe-physics-system
  document.querySelector("#one").addEventListener("collide", function (e) {
    console.log('Objekt 1 je u sudaru s: ', e.detail.body.el);
  });

  document.querySelector("#two").addEventListener("collide", function (e) {
    console.log('Objekt 2 je u sudaru s: ', e.detail.body.el);
  });
</script> 

I’m looking to get IBM courses in web development [closed]

“I’m looking to take IBM courses in web development, and there are three courses available: a backend course, a frontend course, and a full-stack course. For those who have taken IBM courses, is the full-stack course sufficient and comprehensive, or do I need to take one of the other courses for more specialization?”

I didn’t get start yet

Issue with Hue-Saturation Affecting Background in Latest IFC Sheet Module

I am working with the latest sheet module of IFC, but when I try to add hue and saturation adjustments, it also affects the background of the image.

How can I apply hue-saturation adjustments without altering the background?

Here’s the tool I am using: Infinite Fusion Calculator.

Any help would be appreciated!

when use saturation i want ot show an custom background in image and only saturate image

I am having a lot of errors in browser console, mentioned below. i am using axios for handling https and using react for frontend [closed]

dynamic-media-cdn.tripadvisor.com/media/photo-o/17/0d/1e/c6/adina-apartment-hotel.jpg?w=900&h=-1&s=1:1

   GET https://dynamic-media-cdn.tripadvisor.com/media/photo-o/17/0d/1e/c6/adina-apartment-hotel.jpg?w=900&h=-1&s=1 404 (Not Found)

requests.js:1

   POST https://places.googleapis.com/v1/places:searchText 403 (Forbidden)

Error fetching place details: AxiosError {message: ‘Request failed with status code 403’, name: ‘AxiosError’, code: ‘ERR_BAD_REQUEST’, config: {…}, request: XMLHttpRequest, …}

this is the two files that are responsible for handling this:

  useEffect(() => {
    if (trip?.userSelection?.location?.label) {
      getPlacePhoto();
    }
  }, [trip]);

  const getPlacePhoto = async () => {
    if (!trip?.userSelection?.location?.label) return;

    setIsLoading(true);
    try {
      const data = {
        textQuery: trip.userSelection.location.label,
        languageCode: 'en'
      };

      const response = await getPlaceDetails(data);
      console.log('Place Details Response:', response.data);
      
      // Handle the response data to get the image URL
      if (response.data?.places?.[0]?.photos?.[0]) {
        const photoReference = response.data.places[0].photos[0].name;
        // Set the photo URL
        setPlaceImage(photoReference);
      }
    } catch (error) {
      console.error('Error fetching place details:', error);
      setPlaceImage(null); // Reset image on error
    } finally {
      setIsLoading(false);
    }
  };

and, this is for the api and axios:

import axios from 'axios';

const apiKey = import.meta.env.VITE_GOOGLE_PLACES_API_KEY;

export const getPlaceDetails = (data) => {
  return axios.post(
    'https://places.googleapis.com/v1/places:searchText',
    data,
    {
      headers: {
        'Content-Type': 'application/json',
        'X-Goog-Api-Key': apiKey,
        'X-Goog-FieldMask': 'places.displayName,places.formattedAddress,places.photos'
      }
    }
  );
};

i am stuck on this from 2 hours. how to fix.

firstly, for testing, i was trying to console.log the place details and then try to use the images from google places api.
but i am getting the axios errors like 400, 401, 403, 404 etc.

Access dynamic route parameter from Layout

I am trying to access a dynamic route parameter from the layout but the usual params object is undefined.

I have this URL: http://localhost:3000/Site.com/about-us

And this is my file structure:

  • app
    • (site)
      • [siteUrl]
        • about-us
          • page.tsx
      • layout.tsx

Currently, I can access the page on app/(site)/[siteUrl]/about-us/page.tsx because I am fetching some data from the database there. But I want to do it from /app/(site)/layout.tsx and pass it to the child components, context I guess?

This is my layout.tsx file right now:

import { notFound } from "next/navigation"
import "./globals.css"
import prisma from "@/lib/prisma"

export default async function SiteLayout({
    children,
    params
}: {
    children: React.ReactNode,
    params: Promise<{ siteUrl: string }>
}) {
    const siteUrl = (await params).siteUrl
    if (!siteUrl) {
        notFound()
    }

    const site = await prisma.site.findUnique({
        where: {
            siteUrl
        }
    })

    if (!site) {
        notFound()
    }

    return (
        <html lang="es">
            <body>
                {children}
            </body>
        </html>
    )
}

I have multiple issues here, but the main issue is that I can’t access the siteUrl variable. Any suggestions?

Electron preload.js is not imported

I have these two file configured but when mainWindow is open and in the browser’s console there’s these error message. it started after I converted the code from CommonJS to ES Module.
enter image description here

main.js

import { app, BrowserWindow } from 'electron';
import path from 'path';
import { fileURLToPath } from "url";

let mainWindow;

function createWindow() {
    const __dirname = fileURLToPath(new URL(".", import.meta.url));

    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: false,
            contextIsolation: true
        }
    });

    mainWindow.loadFile(path.join(__dirname, 'index.html'));

    mainWindow.on('closed', () => {
        mainWindow = null;
    });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

preload.js

import { contextBridge, ipcRenderer } from 'electron';

console.log("Renderer process is running!");

// Example of sending a message to the main process
// Using `window.ipcRenderer` in Electron if you need inter-process communication

Facing too much delay in microsoft-cognitiveservices-speech-sdk speech to text

I’m using the Azure AI Speech Service for speech-to-text functionality with the Microsoft Cognitive Services Speech SDK in Angular. However, I’m experiencing a significant delay in receiving the speech-to-text results. Upon inspecting the WebSocket connection, I noticed that the result is provided within 50 milliseconds; however, the recognizer delivers the result in the recognized event after 3 to 4 seconds.

Can anyone help me resolve this issue? Is there any configuration or step that I may have missed?

FormatDistance without “hours ago”

When using date-fns, how can I use intlFormatDistance such that for a duration less than 24 hours, it displays “today” or “yesterday”, instead of “x hours ago”.

Example:

intlFormatDistance(myDate, new Date());
// Default output: 13 hours ago
// Desired output: Today