How to limit new Google Maps Autocomplete suggestions to only return street addresses

Problem Description

I’m having an issue with the new Google Autocomplete API not returning street addresses as in earlier versions:

  • Previous Behavior: The API accepted a type: [“address”] parameter
    which returned only full addresses
  • Current Behavior: When I type “V”,
    I get countries like “Vietnam” instead of street addresses starting
    with “V”
  • Desired Outcome: I want to list only full street addresses
    to users

What I’ve Tried

Looking at Google’s documentation, there’s a property called includedPrimaryTypes which accepts values like “street_address” or “street_number”, but this doesn’t seem to be working correctly it returns only specific street addresses not all that Google offers.

My Current Code

     const { AutocompleteSuggestion } = await google.maps.importLibrary("places");

     const { suggestions: fetchedSuggestions } = await AutocompleteSuggestion.fetchAutocompleteSuggestions({
          input,
          sessionToken: token.value,
          // includedPrimaryTypes: ["street_address", "street_number", "premise"],
        });
    
    suggestions.value = await Promise.all(
      fetchedSuggestions.map(
        async (suggestion: google.maps.places.AutocompleteSuggestion) => {
          const place = suggestion.placePrediction.toPlace();
    
          await place.fetchFields({
            fields: ["formattedAddress"],
          });
    
          return {
            placePrediction: suggestion.placePrediction,
            formattedAddress: place.formattedAddress,
          };
        },
      ),
    );
  1. How can I filter results to only include street addresses?
  2. Is there a replacement for the previous type: [“address”] parameter?
  3. What’s the correct way to use includedPrimaryTypes if that’s the right approach?

Error on setting up locally a brave browser, unable to setup the brave browser locally

After git clone and when I:
npm i

It shows the error like this:

npm warn EBADENGINE   required: { node: '>=20.0.0 <22.0.0', npm: '>=10.0.0' },
npm warn EBADENGINE   current: { node: 'v22.11.0', npm: '11.2.0' }
npm warn EBADENGINE }

added 6 packages, and audited 7 packages in 2s

2 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

I understand that it is related to the node version and npm version, which are above what is required, but why is the error, like the error should come when the version is lower and the required is higher? Why is it asking about downgrading the version?
Can also tell me how browser locally work, with step by step

Enter Key Not Working with in Edge Browser

Problem Statement

When using the <datalist> element in an input field in Microsoft Edge, pressing the Enter key does not trigger any event while the datalist options are displayed.

Steps to Reproduce

  1. Create an HTML file with an <input> field that uses a <datalist> for suggestions.
  2. Attach an event listener to detect when the Enter key is pressed.
  3. Open the file in Microsoft Edge.
  4. Click on the input field, type a partial value (e.g., "Opt"), and press Enter while the datalist suggestions are visible.

Expected Behavior

If the user types a partial value that does not match an option (e.g., "Opt"), pressing Enter should trigger validation, showing an “Invalid Input” message.

Actual Behavior in Edge

  • When the datalist options are displayed, pressing Enter does
    nothing—no event is fired. The expected validation or event
    handling does not occur.

Example Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Datalist Enter Key Issue</title>
</head>
<body>
    <input list="options" id="inputField">
    <datalist id="options">
        <option value="Option 1"></option>
        <option value="Option 2"></option>
        <option value="Option 3"></option>
        <option value="Option 4"></option>
    </datalist>

    <script>
        document.getElementById("inputField").addEventListener("keydown", function(event) {
            if (event.key === "Enter") {
                console.log("Enter key pressed");
                if (!this.value) {
                    alert("Invalid Input");
                }
            }
        });
    </script>
</body>
</html>

Working in Chrome but Not in Edge

  • This works as expected in Chrome (the Enter key fires the event).
  • In Edge, the Enter key seems to be ignored when the datalist dropdown is open.

Question

Is there a known workaround or fix for this behavior in Edge? Is it a bug in Edge’s handling of <datalist>?

SPA application User’s relative perfomance index

I’m encountering rare (but nasty) complaints from some users of React SPA application on poor performance and some weird errors. Very often, their complaints start with “doesn’t work on my pc” and ends with “works on pc of my colleague”.

Somehow I’ve managed to reproduce that error by throttling CPU performance 6x slowdown on my local Chrome browser.

So basically my bet is that their PC was under high load at that moment.
In order to discover that possible case, I want to add some “relative performance index” that would show some abstract points and compare that with index of PCs where we normally do not see that errors. Ideally, I would like to attach that index to system requirements of my app – since app is used in inner infrastructure and is not available on web.

My first try was to calculate square root of number for a specific chunk of time (CALC_PERFORMANCE_DELAY) n times (CALC_PERFORMANCE_COUNT).

private async _calculateIndex() {
    const measureIndex = (): Promise<number> =>
      new Promise(resolve =>
        setTimeout(() => {
          const beginTime = performance.now();
          let currentTime = beginTime;
          let index = 0;
          do {
            void Math.sqrt(currentTime);
            index++;
            currentTime = performance.now();
          } while (currentTime - beginTime < CALC_PERFORMANCE_DELAY);
          resolve(index);
        }, 0),
      );

    let sumIndex = 0;
    for (let i = 0; i < CALC_PERFORMANCE_COUNT; i++) sumIndex += await measureIndex();
    this.setIndex(_.ceil(sumIndex / CALC_PERFORMANCE_COUNT / 1000));
  }

But it turned out that that metrics are very specific to OS (results differ for Windows and Ubuntu) and browsers used.

So are there some universal metrics (discoverable by JS means) that would allow me to say that user’s PC is significantly slower than required?

Copy HTML to the clipboard and preserve leading spaces when pasting into PowerPoint

I’m using the Clipboard API to copy styled HTML content to the clipboard. When pasting into Microsoft PowerPoint, I want to retain leading spaces for formatting purposes. However, PowerPoint trims those spaces on paste.

Here’s a simplified version of my code:

/* Simplified example of the HTML code that I'm trying to copy */
const htmlText = '<pre><p><span style="mso-spacerun:yes">  </span><span>Test</span></pre>';

async function copyToClipboard() {
  try {
    const data = [
      new ClipboardItem({
        'text/html': new Blob([htmlText], { type: 'text/html' })
      })
    ];
    await navigator.clipboard.write(data);
    console.log('Plain text and HTML copied to clipboard'); 
  } catch (err) {
    console.error('Failed to copy both formats:', err);
  }
}

What I’ve tried:

  • Using <pre> and style="mso-spacerun:yes" (Source) — with no success.
  • Replacing spaces with &nbsp; does preserve spacing in PowerPoint, but those become non-breaking spaces (U+00A0), which causes issues when copying the content out of PowerPoint (e.g., into a code editor like IntelliJ), where you’d want regular spaces.

My goal:

I need a way to preserve leading spaces when pasted into PowerPoint, without converting them to non-breaking spaces (so they stay regular spaces when copied out again).

Is there a specific structure, style, or workaround that PowerPoint expects to retain normal leading spaces properly? Has anyone solved this?

Unfortunately, I can’t share a live demo here because the Clipboard API is blocked in iframes (like StackBlitz).

Any tips would be greatly appreciated!

How to Update Google Search Result Snippet for My Website? [closed]

I want to update the search result snippet for my website on Google. The current snippet shows outdated content and metadata. I have already tried using Google Search Console’s URL Inspection tool and requested indexing, but the search result remains unchanged.

I have also updated the meta title and description in my website’s HTML and sitemap. Despite these efforts, Google still displays the old snippet.

Steps I’ve Taken So Far:

Updated meta title and description in the webpage source code.
Requested reindexing via Google Search Console.
Cleared cache and checked using different devices/browsers.
Submitted an updated sitemap in Google Search Console.
Questions:

How long does it usually take for Google to reflect the updated snippet?
Are there additional steps I can take to speed up the process?
Could structured data or schema markup impact the snippet update?
Is there a way to force Google to refresh the snippet faster?
Any insights or troubleshooting steps would be appreciated.

VTU USN number validation in jQuery

A VTU (Visvesvaraya Technological University) USN (University Seat Number) is a 10-digit code to identify students.

  1. First Digit:- Represents the region to which the college belongs.
  2. Second and Third Digits:- Represent the college code.
  3. Fourth and Fifth Digits: Represent the batch the student joined.
  4. Sixth and Seventh Digits: Represent the student’s chosen course.
  5. Last Three Digits: Represent the student’s roll number.
  6. Set the Limit to 10 digits
RegEx : ^(([0-9]){1}([a-zA-Z]){2}([0-9]){2}([a-zA-Z]){2}([0-9]){3}){0,10}$

Example

var usn = '4GE01CS001'
var reg = '^(([0-9]){1}([a-zA-Z]){2}([0-9]){2}([a-zA-Z]){2}([0-9]){3}){0,10}$'
if(usn.match(reg)){
  console.log('true')
}else{
  console.log('false')
}

Is there any way I can tell if a function called a parameter or not in JavaScript?

I have a some form components that take a list of validator function, each of these validator functions has two parameters, the current value of form control and the form model. I am wondering if there is a way to tell if any of the functions called the form model. If none of my validator functions accessed the form model then I know all the validators were not cross field validators and next round I don’t need to run validation on form model changes as none of the validators are accessing it.

const formModel = {
  firstname: 'Bill',
  lastname: 'Gates',
  departureDate: new Date(),
  returnDate: new Date()
};

const value = 'Test';

const nonAccessValidators = [
  v => v ? null : 'required',
  v => v?.length ?? 0 > 1 ? null : 'incomplete' 
];

const accessValidators = [
  v => v ? null : 'required',
  (v, m) => v > m.departureDate ? null : 'before-date'
];

const runValidators = (value, formModel, validators) => validators
  .reduce((acc, validator) => {
    const error = validator(value, formModel);
    // this is where I want to set acc.formModelAccessed
    if (error) {
      acc.errors.push(error);
    }
    return acc;
   },
   { formModelAccessed: false, errors: [] }
);

const nonAccessErrors = runValidators(value, formModel, nonAccessValidators);
const accessErrors = runValidators(value, formModel, accessValidators);

I am looking for a way to tell if any of those functions use the second parameter, if not then I know I can skip validation on model changes if the validators haven’t changed.

The only thing I can think of is to wireup a proxy object and copy the formModel key to getters that log their access but seems like overkill to recreate that proxy object on every formModel change. I want to keep the validators simple and don’t want to have to wrap the formModel in another object.

@rollup/plugin-typescript TS2307: Cannot find module ‘../xxx/HelloWorld.svelte’ or its corresponding type declarations

TS FILE

import App from "../xxx/HelloWorld.svelte";

const app = new App({
  target: document.body,
});

export default app;

I imported typescript from “@rollup/plugin-typescript” and it cant find the .svelte file that the TS file imports for some reason.
I’ve tried all of the solutions from previous related questions but none worked

full error message in cmd

tried downgrading to an older Typescript
tried adding: “enable-ts-plugin”: true to rollup.config.json file

Firebase Cloud Messaging – Grouping and Dismissing

I have successfully sent and recieved push notifications using the following code.

server code

const admin = require('firebase-admin');
const message1 = {
   token: '<Token>',
   data: {
      title: "Test",
      body: "Test",
   },
   webpush: {
      fcmOptions: {
         link: '/',
      }
   }
};
const messages = [message1];

try {
   const result = await admin.messaging().sendEach(messages);
   console.log(result?.responses);
} catch (error) {
   console.log(error);
}

Service Worker Code

importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');

const firebaseApp = firebase.initializeApp({
    <AUTHORISATION DATA>
});

const messaging = firebase.messaging();

messaging.onMessage(m, (payload) => {
    console.log('Foreground Message recieved', payload);
});

messaging.onBackgroundMessage(m, (payload) => {
    console.log('Background Message recieved', payload);

    const notificationTitle = payload.data.title;
    const notificationOptions = {
        body: payload.data.body,
        icon: '/images/icons-192.png',
        data: {
            url: "/"
        }
    }
    self.registration.showNotification(notificationTitle, notificationOptions);
});

self.addEventListener('notificationclick', function (event) {
    event.notification.close();

    event.waitUntil(
        clients.matchAll({
            type: "window"
        })
            .then(function (clientList) {
                for (var i = 0; i < clientList.length; i++) {
                    var client = clientList[i];
                    if (client.url == '/' && 'focus' in client)
                        return client.focus();
                }
                if (clients.openWindow) {
                    return clients.openWindow('/');
                }
            })
    );
});

What i have yet to figure out is the next steps.

  1. Group messages so users are not flooded
  2. Dismiss messages when the app is opened

Group messages so users are not flooded

For this my research has uncovered that it is somthing to do with the collapse_key tag. Though the documentation does not give an example and nothing ive found works (I assume because they are for the previous version of FCM).

https://firebase.google.com/docs/cloud-messaging/concept-options#delivery-options

From what i can tell this collapse key is meant to group messages using the same key so instead of recieving seperate push messages you have one push message saying that you have recieved X messages. Which is the behaviour that i want.

Dismiss messages when the app is opened

Im guessing that to achieve this i need to send a push notification from the app when it opens that when processed by the service worker dismisses all current messages. I have yet to find any information on how to do this.

Conclusion

Im sure that these features would be things that people would like to commonly do. Does anyone know where to look to find information on these two processes?

Electron webContents.print Prints Oversized Image on 6×4 Photo Paper

Electron Version

33.2.1

What operating system(s) are you using?

Windows

Operating System Version

Windows 11

What arch are you using?

x64

Last Known Working Electron version

No response

Expected Behavior

I expect the output size to be 1800×1200 pixels on 6×4 inch photo paper.

Actual Behavior

I’m trying to print an image with webContents.print in Electron, and I expect the output size to be 1800×1200 pixels on 6×4 inch photo paper. However, the image is always overly enlarged when printed.

I’ve tried adjusting pageSize and dpi in the print options, but it doesn’t seem to have any effect.

Code Snippet

ipcMain.handle('print-photo', async (event, photoPath, copies = 1, printerOptions = {}) => {
  try {
    console.log('Receive print request:', { photoPath, copies, printerOptions })

    if (!photoPath || !fs.existsSync(photoPath)) {
      console.error('Print photo not exists:', photoPath)
      return { success: false, error: 'Photo not exists' }
    }

    const printWindow = new BrowserWindow({
      width: 1800,
      height: 1200,
      show: false,
      webPreferences: { nodeIntegration: false },
    })

    await printWindow.loadURL(file://${photoPath})

    await new Promise((resolve) => setTimeout(resolve, 1000))

    const printOptions = {
      silent: true,
      printBackground: true,
      color: true,
      margins: {
        marginType: 'custom',
        top: printerOptions.marginTop || 0,
        bottom: printerOptions.marginBottom || 0,
        left: printerOptions.marginLeft || 0,
        right: printerOptions.marginRight || 0,
      },
      landscape: printerOptions.landscape || false,
      deviceName: printerOptions.printerName || '',
    }

    let printResult = false
    for (let i = 0; i < copies; i++) {
      try {
        await new Promise((resolve, reject) => {
          printWindow.webContents.print(printOptions, (success, errorType) => {
            if (success) {
              console.log(Print success: copy ${i + 1} of ${copies})
              printResult = true
              resolve()
            } else {
              console.error('Print failed:', errorType)
              reject(new Error(Print failed: ${errorType}))
            }
          })
        })
      } catch (err) {
        console.error(Print error on copy ${i + 1}:, err)
      }
    }

    printWindow.close()

    return { success: printResult, error: printResult ? null : 'Print command failed' }
  } catch (error) {
    console.error('Print photo error:', error)
    return { success: false, error: error.message }
  }
})

Steps Taken

  1. Set `pageSize: { width: 1800, height: 1200 } or pageSize: { width: 152400, height: 101600 }
  2. Tried different DPI values (e.g., 300, 600)
  3. Experimented with different margin settings
  4. Used a hidden BrowserWindow to load the image before printing

Despite these attempts, the printed image is always too large and does not fit the expected 6×4-inch size.

Question

How can I ensure that webContents.print correctly scales the image to fit the 6×4-inch photo paper by silent print at the expected 1800×1200 resolution?

Any guidance would be greatly appreciated!


Why is my circle not moving after I run the function?

I am currently trying to code a circle that moves once I run a function. Here is my code:

function move(element, direction, distance=20, duration=1000) { //the move function var topOrLeft = (direction=="left" || direction=="right") ? "left" : "top"; var isNegated = (direction=="up" || direction=="left"); if (isNegated) { distance *= -1; } var elStyle = window.getComputedStyle(element); var value = elStyle.getPropertyValue(topOrLeft).replace("px", ""); var destination = Number(value) + distance; var frameDistance = distance / (duration / 10); function moveAFrame() { elStyle = window.getComputedStyle(element); value = elStyle.getPropertyValue(topOrLeft).replace("px", ""); var newLocation = Number(value) + frameDistance; var beyondDestination = ( (!isNegated && newLocation>=destination) || (isNegated && newLocation<=destination) ); if (beyondDestination) { element.style[topOrLeft] = destination + "px"; clearInterval(movingFrames); } else { element.style[topOrLeft] = newLocation + "px"; } } var movingFrames = setInterval(moveAFrame, 10); } function draw() //draws the circle { var canvas = document.getElementById('circle'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); var X = canvas.width / 2; var Y = canvas.height / 2; var R = 400; ctx.beginPath(); ctx.arc(X, Y, R, 0, 2 * Math.PI, false); ctx.lineWidth = 3; ctx.strokeStyle = '#000000'; ctx.stroke(); } } move(circle, "right", 20, 200) //move function

As you can see in the code, i first drew the circle (works) and made a function that moves the circle. However, when i run the function the circle does not move. Please help thanks

Why does audio play locally but not on liveserver or Github Pages?

For whatever reason no sound plays in my project https://github.com/Jocowl25/audioVisualiser.

There is no error message in the console, and the sound seems to still be loaded, just not audible.
Everything works perfectly when downloaded and run locally.
It has the ability to play preloaded files and uploaded files, and neither works.
The audio is becomes audible when the following code is commented out:
const source = audioCtx.createMediaElementSource(audio);
const analyser = audioCtx.createAnalyser();
source.connect(analyser);
source.connect(audioCtx.destination);
audio is connected to an html audio tag.

The audio is still inaudible when user input is provided.
It won’t have the sample audio loaded from here, but here is the full code:

//colors
const colorPallette=[
["#060647","#0209d1",(i)=>`rgb(105 25 ${(i/FreqBufferLength) * 115+(255-115)})`],
["#fadb61","#b00202",(i)=>`rgb(${(i/FreqBufferLength) * 15+(255-15)} 100 25)`],
]
let colorOption=0
//set up list of default songs
const audioMap = new Map();
audioMap.set("Sample1.mp3","Sample1.mp3")
audioMap.set("Sample2.mp3","Sample2.mp3")
//set up select and file input
const select=document.querySelector("select")
const fileInput = document.querySelector('input[type="file"]');
//set up audio
const audio=document.querySelector("audio")
const audioCtx = new AudioContext();
const source = audioCtx.createMediaElementSource(audio);
//set up analyser
const analyser = audioCtx.createAnalyser();
source.connect(analyser);
source.connect(audioCtx.destination);
//set up analyser arrays
const FreqBufferLength = analyser.frequencyBinCount;
const TimeBufferLength = analyser.fftSize;
const timeArray = new Uint8Array(TimeBufferLength);
const freqArray = new Uint8Array(FreqBufferLength);
//set up canvas
const canvas=document.querySelector("canvas")
canvas.width=600;
canvas.height=300;
const w=canvas.width;
const h=canvas.height;
const canvasCtx=canvas.getContext("2d");
canvasCtx.lineWidth = 2;
//set up document events
document.querySelector(".color").addEventListener("click",()=>
  {colorOption++
    colorOption=colorOption%colorPallette.length
  })
document.querySelector(".fileButton").addEventListener("click",()=>fileInput.click())
  fileInput.addEventListener('change', (event) => {
    for (const file of fileInput.files){
      const url = URL.createObjectURL(file);
      canvasCtx.fillStyle = colorPallette[colorOption][0];
      canvasCtx.fillRect(0, 0, w, h);
      select.innerHTML=`<option>${file.name}</option>`+select.innerHTML
      audio.src=url
      audioMap.set(file.name, url);
      select.value=file.name
    }
  })
//start
let val=select.value
requestAnimationFrame(draw)

function draw(){
  //set song
  if(val!=select.value){
  audio.src=audioMap.get(select.value)
  val=select.value
  }
  //pause visualizer if paused
    if(!audio.paused){
      analyser.getByteFrequencyData(freqArray);
      analyser.getByteTimeDomainData(timeArray);
    }
    //set up canvas colors
    canvasCtx.fillStyle = colorPallette[colorOption][0];
    canvasCtx.fillRect(0, 0, w, h);
let x=0
let skip=5
///////////////
///frequency///
///////////////
const barWidth = (w / FreqBufferLength)*1.5*skip;
let barHeight;
x = 0;
for (let i = 0; i < FreqBufferLength; i+=skip) {
    barHeight = freqArray[i];
    canvasCtx.fillStyle = colorPallette[colorOption][2](i);
    canvasCtx.fillRect(x, (h/2)-barHeight/2, barWidth, barHeight+1);
  
    x += (barWidth);
  }
  canvasCtx.strokeStyle = colorPallette[colorOption][1];
  canvasCtx.beginPath();
  x = 0;  
  ////////
  //time//
  ////////
  let timeSkip=1
  const sw = (w / TimeBufferLength)*timeSkip;
    for(let i=0;i<TimeBufferLength;i+=timeSkip){
    const v = timeArray[i] / 128.0;
  const y = v * (h / 2);

  if (i === 0) {
    canvasCtx.moveTo(x, y);
  } else {
    canvasCtx.lineTo(x, y);
  }
  x += sw;
    }
    canvasCtx.stroke();
    canvasCtx.closePath();
    requestAnimationFrame(draw)
}
body{
background-color: black;
overflow-x: hidden;
}
h1{
    color:white;
    font-size:70px;
    margin-bottom:30px;
    font-family:sans-serif;
}
canvas{
width:600px;
height:300px;
border: 2px solid rgb(255, 255, 255);
border-radius:20px;
position:relative;
z-index:0;
}
audio{
    height:50px;
    z-index:100;
    position:relative;
}
select{
    margin-bottom:5px;
    height:30px;
    font-size: 30px;
    width:300px;
    text-align:center;
    border-radius:5px;
}
.fileButton{
    margin-bottom:5px;
    font-size: 20px;
    width:300px;
    height:50px;
    align-items:center;
    border-radius:20px;
    border:none;
}
.color{
    margin-top:5px;
    font-size: 20px;
    height:50px;
    width:300px;
    align-items:center;
    border-radius:50px;
    border:none;
}

input{
    display:none;
}
.flex{
    display:flex;
    width:100vw;
    height:100%;
    align-items:center;
    justify-content: center;
    flex-flow:column;
}
button:hover{
    background-color:rgb(191, 187, 187);
}
button{
    background-color:rgb(255, 255, 255);
}
button:active{
    background-color:rgb(168, 161, 161);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="shortcut icon" href="#">
    <title>Audio Visualizer</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="flex">
      <h1>Audio Viewer</h1>
    <input multiple type="file" id="input"/>
    <button class="fileButton">Add Song</button>
    <select>
      <option>Sample1.mp3</option>
      <option>Sample2.mp3</option>
    </select>
    <canvas></canvas>
    <audio preload="auto" crossorigin="anonymous" controls src="Sample1.mp3"></audio>
    <button class="color">Change Theme</button>
  </div>
    <script src="index.js"></script>
  </body>
</html>