Autoplay the text-to-speech response on mobile browser after I receive message from the server

I have this web application where I exchange messages with an AI model. Every time I want to say the response out loud when I receive a new one. In the browser this works fine, but it seems my solution doesn’t work on mobile browsers because they don’t allow autoplay.

Anyone got a crafty solution to this? It’s a vital part of the experience of my app and I don’t know how to proceed. I do not want the user to have to click a play button every time they receive a response. I want the sound to be played automatically.

function playAudio(audioUrl: any) {
  fetch(audioUrl)
      .then(response => response.arrayBuffer())
      .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
      .then(audioBuffer => {
          const source = audioContext.createBufferSource();
          source.buffer = audioBuffer;
          source.connect(audioContext.destination);
          source.start();
      })
      .catch(error => console.error(error));
}

enter image description here

Single Word City name like “California” shows result but double word “New York” dosn’t

This is a PHP , JS based web page that represents a weather website. But when I enter any Any string that contained one word whether it is a valid city name or not it provides a result. But when I input in the form any double worded string it shows nothing. But if I manually input the city name like New York in the api link url it shows all Jason data accurately.

Where in the following is my code:

<?php
$status = "";
$msg = "";
$city = "";
if (isset($_POST['submit'])) {
   $city = $_POST['city'];
   $url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=92b2d5275d8ce6c94cd0a72ffc7bd208";
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   $result = curl_exec($ch);
   curl_close($ch);
   $result = json_decode($result, true);
       if ($result['cod'] == 200) {
      $status = "yes";
   } else {
      $msg = $result['message'];
   }

}
?>

<html lang="en" class=" -webkit-">

<head>
    <meta charset="UTF-8">
    <title>Weather</title>
    <style>
    @import url(https://fonts.googleapis.com/css?family=Poiret+One);
    @import url(https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.9/css/weather-icons.min.css);

    body {
        background-image: url("weather.png");
        background-size: cover;
        background-repeat: no-repeat;
        font-family: Poiret One;
        background-blend-mode: screen;
    }

    .widget {
        position: absolute;
        top: 50%;
        left: 50%;
        display: flex;
        height: 300px;
        width: 600px;
        transform: translate(-50%, -50%);
        flex-wrap: wrap;
        cursor: pointer;
        border-radius: 20px;
        box-shadow: 0 27px 55px 0 rgba(0, 0, 0, 0.3), 0 17px 17px 0 rgba(0, 0, 0, 0.15);
    }

    .widget .weatherIcon {
        flex: 1 100%;
        height: 60%;
        border-top-left-radius: 20px;
        border-top-right-radius: 20px;
        background: #FAFAFA;
        font-family: weathericons;
        display: flex;
        align-items: center;
        justify-content: space-around;
        font-size: 100px;
    }

    .widget .weatherIcon i {
        padding-top: 30px;
    }

    .widget .weatherInfo {
        flex: 0 0 70%;
        height: 40%;
        background: darkslategray;
        border-bottom-left-radius: 20px;
        display: flex;
        align-items: center;
        color: white;
    }

    .widget .weatherInfo .temperature {
        flex: 0 0 40%;
        width: 100%;
        font-size: 65px;
        display: flex;
        justify-content: space-around;
    }

    .widget .weatherInfo .description {
        flex: 0 60%;
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
        justify-content: center;
        margin-left: -15px;
    }

    .widget .weatherInfo .description .weatherCondition {
        text-transform: uppercase;
        font-size: 35px;
        font-weight: 100;
    }

    .widget .weatherInfo .description .place {
        font-size: 15px;
    }

    .widget .date {
        flex: 0 0 30%;
        height: 40%;
        background: #70C1B3;
        border-bottom-right-radius: 20px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        color: white;
        font-size: 30px;
        font-weight: 800;
    }

    p {
        position: fixed;
        bottom: 0%;
        right: 2%;
    }

    p a {
        text-decoration: none;
        color: #E4D6A7;
        font-size: 10px;
    }

    .form {
        position: absolute;
        top: 42%;
        left: 50%;
        display: flex;
        justify-content: center;
        align-items: start;
        height: 300px;
        width: 600px;
        transform: translate(-50%, -50%);
    }

    .text {
        width: 65%;
        padding: 10px;
        border-radius: 15px;
        border: 0px;
        -webkit-box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
    }


    .conmain {
        margin-right: 45px;
    }

    button {
        padding: 9px;
        width: 30%;
        border: unset;
        border-radius: 15px;
        color: #212121;
        z-index: 1;
        background: #e8e8e8;
        position: relative;
        font-weight: 1000;
        font-size: 17px;
        -webkit-box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        transition: all 250ms;
        overflow: hidden;
    }

    button::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        width: 0;
        border-radius: 15px;
        background-color: darkslategray;
        z-index: -1;
        -webkit-box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        box-shadow: 4px 8px 19px -3px rgba(0, 0, 0, 0.27);
        transition: all 250ms
    }

    button:hover {
        color: #e8e8e8;
    }

    button:hover::before {
        width: 100%;
    }

    #getLocation {
        width: 40%;
    }
    </style>
</head>

<body>
    <div class="form">
        <p><?php
         var_dump($ch)
         ?></p><br>
        <p><?php
         var_dump($result)
         ?></p><br>

        <p><?php var_dump($status)?></p>
        <form style="width:100%;" method="post">
            <input type="text" class="text" placeholder="Enter country or city name" name="city"
                value="<?php echo $city ?>" />
            <button type="submit" value="Submit" class="button" name="submit">submit</button>
            <?php echo $msg ?>
        </form>
        <button id="getLocation">My Location</button>

    </div>

    <?php if ($status == "yes") { ?>
    <article class="widget">
        <div class="weatherIcon">
            <img src="http://openweathermap.org/img/wn/<?php echo $result['weather'][0]['icon'] ?>@4x.png" />
        </div>
        <div class="weatherInfo">
            <div class="temperature">
                <span><?php echo round($result['main']['temp'] - 273.15) ?>°</span>
            </div>
            <div class="description conmain">
                <div class="weatherCondition"><?php echo $result['weather'][0]['main'] ?></div>
                <div class="place"><?php echo $result['name'] ?></div>
            </div>
            <div class="description">
                <div class="weatherCondition">Wind</div>
                <div class="place"><?php echo $result['wind']['speed'] ?> M/H</div>
            </div>
        </div>
        <div class="date">
            <?php echo date('d M', $result['dt']) ?>

        </div>
    </article>
    <?php } ?>

    <script>
    const getLocationButton = document.getElementById("getLocation");
    getLocationButton.addEventListener("click", () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
                const latitude = position.coords.latitude;
                const longitude = position.coords.longitude;

                // Use the latitude and longitude to fetch the location data
                fetchLocationData(latitude, longitude);
            });
        } else {
            alert("Geolocation is not supported by your browser.");
        }
    });

    function fetchLocationData(latitude, longitude) {
        const locationUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`;
        fetch(locationUrl)
            .then((response) => response.json())
            .then((data) => {
                const city = data.address.city || data.address.town || data.address.village;
                if (city) {
                    document.querySelector('input[name="city"]').value = city;
                    // Auto-submit the form by simulating a click on the submit button
                    document.querySelector('[name="submit"]').click();
                }
            })
            .catch((error) => {
                console.error("Error fetching location data:", error);
            });
    }
    </script>
</body>

</html>

I’m expecting to get results in no matter how many words I input in the form. Would really appreciate and help thank you.

I want to add a dynamic graph to my project

I want to create an automatically updating graph in my project using HTML, CSS, and JavaScript that appears as soon as users access the page. Is there a problem with my code? If not, will adding the correct API make the graph appear?

enter image description here

here is my html,css,javascript code.

Como cambiar valor de 1000 a 1k? [closed]

esta es mi primera pregunta en el foro.
Encontré un código para realizar lo siguiente: “Pasar el numero 1000 a 1k”.
El código es el siguiente:

<script>
function numberto(n){
    x=(''+n).length;
    p=Math.pow;
    d=p(10,true);
    x-=x%3;
    return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3];
    }</script>
<input type="number" placeholder="Ingresa un numero" id="num">
<input type="submit" value="Convertir" onclick="document.getElementById('res').innerHTML = numberto(document.getElementById('num').value)">
<br/>
<strong id="res"></strong>

Como debería modificar el código para que lo realice cuando yo le pase una variable devuelta de myqsl, y que modifique una parte del código del html sin presionar el botón.

Cambiar de 1000 a 1k php y javascript

Touchscreen equivalent for Mousedrag for a painting grid in HTML/CSS/JS

I’m trying to build a paint like program (Etch-a-Sketch of The Odin Project) where when I drag the mouse across the paint grid, it colours them black.

enter image description here

I am basing my function hold() from how to implement mousemove while mouseDown pressed js. and the code works for a mouse on a pc.

The code:

   //FUNCTION TO DRAG AND PAINT 
   function hold(){
        var items = document.querySelectorAll(".grid");
              
    
       items.forEach(item => {
            item.addEventListener('mousemove', function (event){
                 if(event.buttons == 1){
                     event.preventDefault();      

                     item.style.backgroundColor = "black";
                 }
                
           });
       });
    
    }

However, when I try the same for mobile/touch devices, using the code as mentioned in the same page for touch enabled devices, it does not work. The user has to tap everytime to colour the grids black instead of tap and drag like it was in the case of using the mousepointer for click and drag.

The code:

    //FUNCTION TO DRAG AND PAINT 
    function hold(){
        var items = document.querySelectorAll(".grid");
              
    
       items.forEach(item => {
               item.addEventListener('touchmove', function (event){
                     if(event.touches.length == 1){
                         event.preventDefault();    
                     item.style.backgroundColor = "black";
                 }
               
           });
       });

Can someone please help me with this? I will be grateful if someone can point out what would be the equivalent of mousedrag for a touch device?

Thank you!

I tried changing the code as mentioned above but it did not work.

Getting null value when passing ID from req.banker to MongoDB query but works with hardcoded ID

I’m encountering an issue where I’m getting a null value when passing the bankerId from the req.banker object to a MongoDB query. However, when I hardcode the ID, the query works as expected. I’ve checked the data type of the bankerId and confirmed it’s a string, but I’m still getting null. I’ve also verified that the Banker object with the provided bankerId exists in the MongoDB database.

Here is how I connected DB from my connection.js file:

require('dotenv').config();
const mongoose = require("mongoose");

async function connectToDatabase() {
  try {
    await mongoose.connect(process.env.MONGODB_URL);
    console.log("Db Connected Successfully");
  } catch (error) {
    console.error(error);
  }
}

connectToDatabase();

Here is my code:

// Authenticate token middleware
async function authenticateToken(req, res, next) {
  const token = req.cookies.jwt;
  if (!token) {
    return res.status(401).send("No token found");
  }

  try {
    const banker = await jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);
    req.banker = banker;
  } catch (e) {
    console.log(e);
    return res.status(403).send("Invalid token");
  }

  next();
}

// Banker check middleware
async function bankerCheck(req, res, next) {
  if (!req.banker || !req.banker.id) {
    return res.send("Invalid banker ID");
  }

  const bankerId = req.banker.id.toString();

  try {
    Banker.findById(bankerId)
      .then((bankerData) => {
        console.log("bankerData: ", bankerData);

        if (!bankerData) {
          return res.send("Invalid banker id");
        }

        req.banker = bankerData;
        next();
      })
      .catch((err) => {
        console.error("Error in Banker.findById: ", err);
        res.status(500).send("Internal Server Error");
      });
  } catch (err) {
    console.error(err);
    res.status(500).send("Internal Server Error");
  }
}

// Dashboard route
router.get("/dashboard", authenticateToken, bankerCheck, (req, res) => {
  res.render("DashBoard/BankerHomeDashBoard");
});

I’ve tried adding logging to the Banker.findById query to further investigate the issue, but I can’t seem to pinpoint the exact cause.

Steps to reproduce:

Start your Node.js application.
Make a request to the /banker/dashboard route.

Expected behavior:

The bankerData object should be populated with the banker’s data.

Actual behavior:

The bankerData object is null.

Amadeus Self Service API making a post request

I am trying to make a post request to Amadeus Self Service API but I am receiving the error below. I hope someone can help me.

Uncaught (in promise) FetchError: [POST] "http://localhost:2801/flight-offers/upselling": <no response> Failed to fetch at async $fetch2 (ofetch.00501375.mjs?v=b3021059:261:15) at async submitBrandedOffers (upselling.vue:25:20)

Server

app.post(`/flight-offers/upselling`, (req, res) => {
  const flight = req.body.flight;
  amadeus.shopping.flightOffers.upselling
    .post(
      JSON.stringify({
        data: {
          type: 'flight-offers-upselling',
          flightOffers: [flight],
        },
      })
    )
    .then(function (response) {
      res.send(response.result);
    })
    .catch(function (response) {
      res.send(response);
    });
});

Template

const offer = route.query.offer_id;
async function submitBrandedOffers() {
  const response = await $fetch(
    'http://localhost:2801/flight-offers/upselling',
    {
      method: 'POST',
      mode: 'cors',
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json',
      },
      redirect: 'follow',
      referrerPolicy: 'no-referrer',
      body: JSON.stringify(offer), 
    }
  );
  // console.log(response.json());
  return await response.json();
}
submitBrandedOffers();

I am unable to get a response and I think I am not accessing the server.

Querying multiple rows of a table shows an [object] [object] instead of the actual data. How to fix?

I have this query:

  const {data, error} = await supabase  
        .from('profiles')
        .select(`
          *,
          station (
            station_name, user_id
          ),
          type (
            *
          )
        `)
        .eq('id', searchParams.id)

I can see the data already, however, for the type I can only see the: [ [Object], [Object], [Object] ]

The types here may have multiple rows:

Sample output of the data:

[
  {
    id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
    email: '[email protected]',
    full_name: 'Raven',
    `station: {
      station_name: 'Water Station 1',
      user_id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f'
    },
    type: [ [Object], [Object], [Object] ]
  }
]

This is the sample data for the type when I query it:

 const {data, error} = await supabase  
      .from('type')
      .select(`
        *,
        profiles(
          *
        )
      `)
      .eq('user_id', searchParams.id)

Output:

[
  {
    id: 'c12c5e82-c569-48d9-ae25-4c68f0ac2935',
    name: 'Distilled Water',
    price: 20,
    user_id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
    profiles: {
      id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
      email: '[email protected]',
      full_name: 'Raven'
    }
  },
  {
    id: 'f6759420-8ae7-485f-99da-0f248a964d63',
    name: 'Mineral Water',
    price: 50,
    user_id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
    profiles: {
      id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
      email: '[email protected]',
      full_name: 'Raven'
    }
  },
  {
    id: '70e2e497-37b0-4294-a3b3-94bbd95c989a',
    name: 'Sparkling Water',
    price: 500,
    user_id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
    profiles: {
      id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
      email: '[email protected]',
      full_name: 'Raven'
    }
  }
] 

Expected Data is to show the list of types on this data:

[
  {
    id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
    email: '[email protected]',
    full_name: 'Raven',
    station: {
      station_name: 'Water Station 1',
      user_id: '2d6c72a1-175c-4c08-823e-10e35c0d1d7f',
    },
    type: [
      {
        id: 'c12c5e82-c569-48d9-ae25-4c68f0ac2935',
        name: 'Distilled Water',
        price: 20,
      },
      {
        id: 'f6759420-8ae7-485f-99da-0f248a964d63',
        name: 'Mineral Water',
        price: 50,
      },
      {
        id: '70e2e497-37b0-4294-a3b3-94bbd95c989a',
        name: 'Sparkling Water',
        price: 500,
      },
    ],
  },
];

Find a value in side a associated array

I have a array like this

[{"name":"Typical value Sydney (SUA) Houses", "value":"Bar" },
 {"name":"Days on market Sydney (SUA) Houses", "value":"Bar" },
 {"name":"Typical value Melbourne (SUA) Houses", "value":"Line" },
 {"name":"Days on market Brisbane (SUA) Houses", "value":"Bar" }]

I have another variable that I receive the name “Days on market Sydney (SUA) Houses”
I want to find the the name in the array and get the corresponded value like “Bar”

how do I achieve this in javascript

    for (var j = 0; j < arr.length; j++){
        if (arr[j].name == seri){
             value= arr[j].value;
             return true;
        }}

it is not going into the if condition .

How to access variable value in vscode extension API

I am working on a custom vscode extension and creating a hover provider. Say I have a json file example.json:

{
 exampleOne: ["one", "two"]
}

and exampleProxy.js:

import exampleMap from "./example.json"

export const ExampleObject = exampleMap;

And then in various js files in the project imports like”

import { ExampleObject } from "../exampleProxy.js";

const varValue = ExampleObject.exampleOne;

In my hover provider I want to get the actual value associated with that object key when the user hovers over the key. So like when user hovers over “exampleOne” in the above example I will get [“one”, “two”]. How do I do that?

Heres my hover provider so far:

    vscode.languages.registerHoverProvider(
        'javascript',
        new (class implements vscode.HoverProvider {
            provideHover(
                _document: vscode.TextDocument,
                _position: vscode.Position,
                _token: vscode.CancellationToken
            ): vscode.ProviderResult<vscode.Hover> {
                const range = _document.getWordRangeAtPosition(_position, /(?<=ExampleObject.)w+/);
                if (!range) {
                    return;
                }
                const word = _document.getText(range);
                console.log('word', word);
            
            }
        })()
    );

I can get the name of the key like “exampleOne” but how can i get the value it resolves to?

Trying to create an html box around the letters rendered on the webpage

I am trying to measure the real height of the text rendered on my webpage, and then wrapping the text inside a box with no whitespaces. I used the method to calculate height provided by markE in this post Calculate exact characterstring height in javascript. However when I draw the box around the letter, the box’s initial position is at the same position as where the letter’s span element starts. Is there a way that the box starts from the real position at which the letter actually starts. The red box is the html element – letterBox which I want to start from where H letter starts not where the span for letterElement starts.

My code looks like this:

function measureCustomTextHeight(fontSizeFace, customText) {
    var width = 1000;
    var height = 60;
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");

    var text = customText;
    
    ctx.save();
    ctx.font = fontSizeFace;

    var m = ctx.measureText(customText);
    var textWidth = m.width;

    ctx.clearRect(0, 0, width, height);
    ctx.fillText(text, 0, 40);
    ctx.restore();

    // Get the pixel data from the canvas
    var data = ctx.getImageData(0,0,width,height).data,
        first = false, 
        last = false,
        r = height,
        c = 0;

    // Find the last line with a non-transparent pixel
    while(!last && r) {
        r--;
        for(c = 0; c < width; c++) {
            if(data[r * width * 4 + c * 4 + 3]) {
                last = r;
                break;
            }
        }
    }

    // Find the first line with a non-transparent pixel
    while(r) {
        r--;
        for(c = 0; c < width; c++) {
            if(data[r * width * 4 + c * 4 + 3]) {
                first = r;
                break;
            }
        }

        // If we've got it then return the height
        if(first != r) return [last - first, textWidth];
    }

    // error condition if we get here
    return 0;
}
for (let letter of text) {
        const letterBox = document.createElement("span");
        letterElement = document.createElement("span");

        if (letter !== ' ') {
            const computedStyle = window.getComputedStyle(letterElement);
            const fontSizeFace = computedStyle.getPropertyValue("font");
            var currLetter = letter;
            var dimensions = measureCustomTextHeight(fontSizeFace, currLetter);
            var textHeight = dimensions[0] + "px";
            var textWidth = dimensions[1] + "px";

            letterElement.textContent = letter;
            letterBox.appendChild(letterElement);
            letterElement.style.display = "inline-block";

            letterBox.style.height = textHeight;
            letterBox.style.width = textWidth;
            letterBox.style.position = "relative";
            measurable_content.appendChild(letterBox);
            letterElement.classList.add("letter-element");
            
            letterBox.classList.add("letter-box");
            letterBox.style.border = "1px solid red";
            letterBox.style.display = "inline-block";
           
        } else {
            letterBox.innerText = letter; // Add a non-breaking space character
            measurable_content.appendChild(letterBox);
        }
    }

React vite google maps libraries

Am using google map in react vite. When the map loads it doesnt load the libraries too. That is not the case when I use CRA. What should I do to make the libraries too load alongside the map?

I tried to use timeout but it did not load. I was hoping that that could make the libraries load if they load slower. I also used condition rendering that too did not work.

Useeffect

How to add text to a readonly input display for a calculator project?

I am attempting to add numbers to the display area of my html/css calculator on the click of a button but it does not work.
`

C
7
8
9
/
4
5
6
*
1
2
3

0
.
=
+

const display = document.getElementById(“display”);

function appendToDisplay(val) {
    display.value = display.value + val;
}

function clearDisplay () {
    display.value = "";
}

`

I tried using a innerHTML property instead of value property on the display variable.

Is the callback queue of javascript works in multithreaded manner?

I want to print numbers i= 1,2,3,4,5 each after i seconds of delay, but all the numbers are printing after 1 second of delay, it feels like js is multithreaded.

function x()
{
    for(var i=1; i<=5; i++)
    {
        setTimeout(()=>{
            console.log(i);
        }, i*1000);
    }
    console.log("namaste js");
}

console.log("calling x");
x();   

According to me the total time to execute this should be 15 seconds, but it is comming out to be 5 seconds. Why?

Iterating through a non-associative array in Java script

I have this non associative array:

var cars = [ 'Lambo', 'Ferrari', 'Jeep' ];

I am trying to iterate throug the items:

for( var key in cars ){
    alert( cars[key] );
}

But it does not work. It’s like the key is not being recognized. The for loop works with associative arrays but not with non associative. I am running out of ideas. How can I iterate through a non associative array in Java script?

Please don’t flag my questions. Let me know what is wrong and I will fix it as soon as possible.