Resetting volume state of multiple Audio components from parent component

In the following code, in the Audio component, I have state called volume, which stores the value of each Slider:

import {
  useRef,
  useState,
  createRef,
  forwardRef,
  MutableRefObject,
} from 'react';

import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';

const audios = [
  {
    src: 'https://onlinetestcase.com/wp-content/uploads/2023/06/100-KB-MP3.mp3',
  },
  {
    src: 'https://onlinetestcase.com/wp-content/uploads/2023/06/500-KB-MP3.mp3',
  },
];

interface Props {
  src: string;
}

const Audio = forwardRef<HTMLAudioElement, Props>(
  (props: Props, ref: MutableRefObject<HTMLAudioElement>) => {
    const { src } = props;
    const [volume, setVolume] = useState(50);

    function handleVolumeChange(value) {
      ref.current.volume = value / 100;
      setVolume(value);
    }

    return (
      <>
        <audio ref={ref} loop>
          <source src={src} type="audio/mpeg" /> Your browser does not support
          the audio element.
        </audio>
        <Slider
          min={0}
          max={100}
          step={1}
          value={volume}
          onChange={handleVolumeChange}
        />
      </>
    );
  }
);

export const App = ({ name }) => {
  const [isPlayingAudio, setIsPlayingAudio] = useState(false);
  const defaultVolume = 50;

  const audioRefs = useRef(
    audios.map((audio) => ({
      ...audio,
      ref: createRef<HTMLAudioElement>(),
    }))
  );

  function playAudio() {
    audioRefs.current?.forEach((audioRef) => audioRef.ref.current.play());
    setIsPlayingAudio(true);
  }

  function resetAudio() {
    audioRefs.current?.forEach((audioRef, index) => {
      if (audioRef.ref.current) {
        audioRef.ref.current.volume = defaultVolume / 100;
      }
      // I need to use `setVolume` here to reset the volume of each audio
    });
  }

  return (
    <>
      {audioRefs.current?.map((audioRef, index) => (
        <>
          <Audio key={audioRef.src} {...audioRef} ref={audioRef.ref} />
        </>
      ))}
      <button onClick={playAudio}>Play Audio</button>
      <button onClick={resetAudio}>Reset Audio</button>
      <div>
        {isPlayingAudio ? <p>Audio is playing</p> : <p>Audio is not playing</p>}
      </div>
    </>
  );
};

But since volume (and setVolume) are in the Audio component, I can’t use it in App, in the resetAudio function.

I could move volume to App, turn it into an array, and use index to match each state to its corresponding audioRef in Audio. Is this the only way? Or there’s a better one?

Live code at StackBlitz

Function continues despite of await [duplicate]

I’ve got a function with async param. Inside it I make fetch with await.

async function getChallenge() {
 await fetch(myUrl, {
headers and body})
.then(function (response) {
      if (response.status !== 200) {
        console.log(
          'Looks like there was a problem. Status Code: ' + response.status
        );
        return 0;
      }
      response.json()
      .then(function (data) {
        registrationResponse = data;
      });
    })

After this function finish, the next starts to execute, but it gives me an error that registrationResponse is undefined. But when I start the procedure again, the second function read registrationResponse correctly. registrationResponse is defined using var at the top of the file. Do you maybe know what could I do, to not trigger the sequence twice?

Changing website favicon dynamically without it being requested each time it is appended to the DOM

I’m trying to write a feature where if a user has unread messages and navigates away from the app in the current tab, the app would then blink with an indicator at an interval every 1000ms. So if the user has 4 unread messages and opens a new tab, in the previous tab that they were just on, they’d see:

App | Home
* New messages (4)
App | Home
* New messages (4)
App | Home
// and so on every 1000ms until they navigate back to the tab

I found this question and got it working as I want it to, but I noticed that each time I append the favicon to the document, it is re-requested in the Network tab.

Yes it’s cached, but I was wondering if there was a way to do this without the favicon being requested every interval loop?

Why is it faster to process a sorted array than an unsorted array? [closed]

I’m currently working on a JavaScript project and have encountered a puzzling issue with one of my functions. Despite my efforts to troubleshoot, I haven’t been able to pinpoint the problem, so I’m turning to this knowledgeable community for assistance.

I’ve checked for syntax errors, reviewed the documentation, and even tried a few alternative approaches, but the issue persists. If anyone could take a look at my code and offer some guidance or insights into what might be causing this behavior, I would be extremely grateful.

Here’s a condensed version of the code:

// Your code snippet here
function myProblematicFunction() {
  // Function logic causing issues
}

// Additional context or code if needed

Any suggestions, explanations, or even questions to help me better understand the problem would be immensely appreciated. I’m eager to learn and improve my coding skills.

I have Seen everywhere but didn’t fix it and I’m expecting to get solved my issue.

Is there any other way to test the Javascript Stimulus using rails Rspec

I am using this code of stimulus in want to make test cases using Rspec

 update(){
    this.submitForm()
  }
  async submitForm(){
    const organizationId = this.organizationTarget.value;

    var endpoint = this.updateInvoiceTarget.value
    var invoiceId = this.updateInvoiceTarget.getAttribute("data-invoice-id")
    console.log("invoice_path "+ endpoint)
    try {
      const result = await fetch(endpoint, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json",
          "X-CSRF-Token": this.getMetaValue("csrf-token"),
        },
        body: JSON.stringify({ "invoice_id": invoiceId, "organization_id": organizationId }),
      });
      const data = await result.json();
      console.log(data)
      if (data.code == 200) {
          console.log("SUCCES")
          var row = document.getElementById("invoices_list_"+invoiceId);
          if (row) {
            row.parentNode.removeChild(row);
          }
      }
    } catch (error) {
      console.log(error)
    }
  }

I want to get the expected result data using Rspec rails.

i have error in iframe contents html getiing

i am trying to get iframe html but returning undefined why?

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>
<body>
    <iframe src="http://opsukrat.in/iframe.html" id="iframe"></iframe>
    <button onclick="check_html()">Hit me</button>
    <div id="contents">HTML</div>

    <script>
        function check_html() {
            var iframeContents = $('#iframe').contents().find('html').html();
            console.log(iframeContents);
            $('#contents').html('HTML: ' + iframeContents);
        }
    </script>
</body>
</html>

if i am creating file in my server than trying to get than working <iframe src="myfile.html" id="iframe"></iframe>

Create my own language from xml in Monaco editor

I want to create my own language in Monaco Editor for use in my site.
My language is made from XML and I’d like to know if I have to code everything by hand or if there’s a way to complete Monaco’s code for XML to add my specific features.

I’m currently trying to do everything by hand, or if I can just modify what Monaco has for XML to suit my taste. It would take me far too long to do everything by hand

ReactJS and Cloudscape component Date conversion resulting in error

We are trying to add the initial date as 12/01/2023 for the startDate field, however while converting it in the cloudscape DatePicker component we get the following error:
Any help is greatly appreciated.

We have the below code which results into the following error:

Uncaught RangeError: date value is not finite in
DateTimeFormat.format()

import React, {Fragment, useEffect, useContext, useState} from 'react';
import DatePicker from "@cloudscape-design/components/date-picker";
import TimeInput from "@cloudscape-design/components/time-input";
import FormField from "@cloudscape-design/components/form-field";
import { Paper } from '@material-ui/core';
import './ReportTracker.scss';
import {Box} from '@material-ui/core';
import 'date-fns';
import { KeyboardTimePicker, KeyboardDatePicker , MuiPickersUtilsProvider,DateTimePicker } from '@material-ui/pickers';
import DateFnsUtils from '@date-io/date-fns';
import Button from '@material-ui/core/Button';
//import { useHistory } from 'react-router-dom';
import {Select,MenuItem} from '@material-ui/core';
import { AppLayout } from '@amzn/awsui-components-react';
import moment from 'moment-timezone';
import { Navigation } from 'src/components/common/AlfredSideNav/Navigation'
import { ComponentsRoutesContext } from '../../context/ComponentsRoutesContext';


const ReportTracker = () =>{
const { org , idToken, alias } = useContext(ComponentsRoutesContext);
const [navigationOpen , setNavigationOpen] = useState(false);
const [currentStartDate,setCurrentStartDate]=useState(true);
const [currentEndDate,setCurrentEndDate]=useState(true);
const [selectedStartDate, setSelectedStartDate] = React.useState(new Date());
const [selectedEndDate, setSelectedEndDate] = React.useState(new Date());
const [endDate, setEndDate] = React.useState(new Date());
const [startDate ,setStartDate] =  useState(React.useState(new Date()));
//const history = useHistory();
const [peak,setPeak]=useState("PD Peak");
const [status,setStatus]=useState("Green");
const [startDateError,setStartDateError] = useState(false);
const [endDateError,setEndDateError] = useState(false);
const peakdropdownValues = ["PD Peak","Q4 Peak","PBDD Peak"];
const statusdropdownValues = ["Green","Red"];


const handleStartDateChange = (date) => {
if(currentEndDate){
  if(moment(date).isAfter(endDate)){
    setStartDateError(true);
  }else{
    setStartDateError(false);
    setEndDateError(false);
  }
  setCurrentStartDate(false);
  setSelectedStartDate(date);
}else{
  if(moment(date).isAfter(selectedEndDate)){
    setStartDateError(true);
  }else{
    setStartDateError(false);
    setEndDateError(false);
  }
  setCurrentStartDate(false);
  setSelectedStartDate(date);
}
};

  const handleEndDateChange = (date) => {
    if(currentStartDate){
      if(moment(date).isBefore(startDate)){
        setEndDateError(true);
      }else{
        setEndDateError(false);
        setStartDateError(false);
      }
      
      setCurrentEndDate(false);
      setSelectedEndDate(date);
    }else{
      if(moment(date).isBefore(selectedStartDate)){
        setEndDateError(true);
      }else{
        setEndDateError(false);
        setStartDateError(false);
      }
      setCurrentEndDate(false);
      setSelectedEndDate(date);
    }
    
  };

  const  getCurrentTime = () => {
    var date = new Date();
    var pstDate = date.toLocaleString("en-US", {
      timeZone: "America/Los_Angeles"
    })
    setEndDate(pstDate);
    var curr = new Date(pstDate);
    setStartDate(curr.setHours(curr.getHours() - 4));

  }

  const handlepPeakTypeChange = (event) => {
    setPeak(event.target.value);
  };

  const handleStatusChange = (event) => {
    setStatus(event.target.value);
  };

  useEffect(() => {
    getCurrentTime();
    const interval=setInterval(()=>{
      getCurrentTime();
    },1000);
    return()=>clearInterval(interval);
  }, []);
console.log("FP: startDate "+ startDate);
const startDateSlice = startDate.toString().slice(0, -3);
console.log("FP: startDate "+ startDateSlice);
console.log("FP: selectedStartDate "+ selectedStartDate);
console.log("FP: currentStartDate "+ currentStartDate);

let formattedStartDate = new Intl.DateTimeFormat("en-US", {
  year: "numeric",
  month: "2-digit",
  day: "2-digit"
}).format(startDateSlice);
console.log("FP: current formatted Date"+formattedDate)

return(
<div>
        <AppLayout
          navigationOpen={navigationOpen}
          onNavigationChange={() => {setNavigationOpen(!navigationOpen)}}
          content={<>
          <div style={{ minHeight: "500vh" }}
    className='col-md-7'>
        <Paper className='mt-4 ml-4 paper-component-container' >
            <div className='mt-4 ml-4 font-weight-bold'>Hi {alias}, Welcome to Alfred Peak Report!</div>
            <div className='mt-5 d-flex flex-row'>

            <FormField      
              label="Start Date"      
              constraintText="Use MM/DD/YYYY format."    
              >      
              <DatePicker        
                onChange={handleStartDateChange} 
                margin="normal"  
                    
                value={currentStartDate ? formattedStartDate : selectedStartDate.toString()}
                
                openCalendarAriaLabel={selectedDate =>
                  "Select Start Date" +          
                (selectedDate            
                ? `, selected date is ${selectedDate}`            
                : "")       
                }
                       
              placeholder="MM/DD/YYYY"      
              /> 
            </FormField>   
           </div>
        {/* <div className='mt-5 d-flex flex-row'>
            <Box component="span" sx={{ p: 1}} className='ml-5 label-box'>
              <div className='p-2 label-text'>END TIME</div>
            </Box>
            <Box component="span" sx={{ p: 1}} className='ml-5 date-time'>
                <div className='mt-2'>
                    <MuiPickersUtilsProvider utils={DateFnsUtils}>
                        <KeyboardDatePicker data-test="timeline-date-change"
                        margin="normal"
                        id="date-picker-dialog"
                        className='m-0'
                        format="MM/dd/yyyy"
                        value={currentEndDate ? endDate : selectedEndDate}
                        onChange={handleEndDateChange}
                        popperPlacement = "top"
                        KeyboardButtonProps={{
                            'aria-label': 'change date',
                        }}
                        disableFuture={true}
                        error={endDateError}
                        />
                        <KeyboardTimePicker data-test="timeline-time-change"
                        margin="normal"
                        className='my-0 ml-3'
                        id="time-picker"
                        value={currentEndDate ? endDate : selectedEndDate }
                        views={['hours']}
                        format="hh aa"
                        onChange={handleEndDateChange}
                        KeyboardButtonProps={{
                        'aria-label': 'change time',
                        }}
                        error={endDateError}
                        
                        />
                    </MuiPickersUtilsProvider>
                </div>
            </Box>
        </div>
        <div className='mt-5 d-flex flex-row'>
            <Box component="span" sx={{ p: 1}} className='ml-5 label-box'>
              <div className='p-2 label-text'>PEAK TYPE</div>
            </Box>
            <Select sx={{ p: 1}}
            id="peak-event-dropdown"
            value={peak}
            className='ml-5 pl-4 peak-event'
            onChange={handlepPeakTypeChange}
            MenuProps={{
              anchorOrigin: {
                vertical: "bottom",
                horizontal: "left"
              },
              transformOrigin: {
                vertical: "top",
                horizontal: "left"
              },
              getContentAnchorEl: null
            }}
        >
          {peakdropdownValues.map((val) => <MenuItem value={val}>{val}</MenuItem>)}
          </Select>
        </div>
        <div className='mt-5 d-flex flex-row'>
            <Box component="span" sx={{ p: 1}} className='ml-5 label-box'>
              <div className='p-2 label-text'>STATUS</div>
            </Box>
            <Select sx={{ p: 1}}
            id="peak-status-dropdown"
            value={status}
            className='ml-5 pl-4 peak-event'
            onChange={handleStatusChange}
            MenuProps={{
              anchorOrigin: {
                vertical: "bottom",
                horizontal: "left"
              },
              transformOrigin: {
                vertical: "top",
                horizontal: "left"
              },
              getContentAnchorEl: null
            }}
        >
          {statusdropdownValues.map((val) => <MenuItem value={val}>{val}</MenuItem>)}
          </Select>
        </div> */}

        <div className='mt-5 d-flex flex-row'>
            <Button  className='ml-5 mt-5' disabled={startDateError || endDateError} variant="contained" color="primary" 
            // onClick = {() => history.push({
            //    pathname: "/alfred/report-template",
            //    state: { 
            //     end: currentEndDate ? endDate : selectedEndDate,
            //     peakType: peak,
            //     start: currentStartDate ? startDate: selectedStartDate,
            //     status: status
            //    }
            // })} 
            >
                <div className='label-text'>GENERATE REPORT</div>
            </Button>
            </div>
            
    </Paper>
      
    </div>
          <div>
        </div>
      </>} 
          navigation={<Navigation navigationType={"all"}/>}
          headerSelector={"#topNav"}
          footerSelector={"#bottomNav"}
        /> 
    
</div>
        );
};

export default ReportTracker;

Azure Maps label text that scales with the zoom level

Is it possible to create a text label that stays the same relative size compared to the map when zooming in or out? Reading the docs and looking at the symbol layer sample, it seems that this is not possible and that the label will always have the same absolute size (appearing larger when zooming out), but I’m curious whether it is possible to achieve this somehow, using some sort of undocumented feature. If not, is it possible to request this feature somewhere; or is this out of scope?

How to style certain parts of template literal

I have a template literla in my method (vue.js):

methodNameDisplay(m) {
            let nameToDisplay = ''
            if (m.friendlyName === m.methodName) {
                nameToDisplay = m.friendlyName
            } else {
              nameToDisplay = `${m.friendlyName} - ${m.methodName}`
            }
            return nameToDisplay
        },

This method is used to return the value of a title here:

<MethodRepeaterTitle
            :title="showMName ? methodNameDisplay(m) : m.friendlyName"
/>

The issue I am facing is that I need to style the second part of the template literal after the hyphen. How can I go about doing this?

I have tried adding a span to the template literal but this just renders as a string, Vue does not recognize the tag.

Inputs reset after making copy of row

Im trying to do a copy of a row to add another line of inputs but every time i click the button the value of every input resets.

Here is what ive written so far:

<div style="margin-left: 2em;margin-right: 2em;">
            <table class="table table-bordered">
                <thead>
                  <tr>
>!                   th`s
                  </tr>
                </thead>
                <tbody id="aditional">
                  <tr id="template">
>!                    inputs and blank td`s
                  </tr>
                  <script>

                    const temp = document.getElementById("template").innerHTML;
                    const adit = document.getElementById("aditional");

                    function add() {
                        adit.innerHTML+='<tr>'+temp+'</tr>';
                        renum();
                    }

                    function renum() {
                        const lp = document.getElementsByClassName("lp"); 
                        for(let i=0;i<lp.length;i++) {
                            lp[i].innerHTML = i+1;
                        }
                    }
                    
                  </script>
                </tbody>
              </table>
              <button class="btn btn-success" type="button" onclick="add()">Dodaj</button>
        </div>

Ive tried:
const temp = (document.getElementById("template").innerHTML).toString()

Uploading image to cloudinary using Express.js, throws an error

The error

enter image description here

I am having an issue when trying to upload the image to cloudinary using Express.js. I have seen similar questions here, but NONE of the answers worked for me. Could assist me with this issue?

here is my code

const cloudinary = require('cloudinary').v2
const dotenv = require('dotenv')

dotenv.config()

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET
})

exports.uploads = async (file, folder) => {
  // eslint-disable-next-line no-useless-catch
  try {
    const result = await cloudinary.uploader.upload(file, {
      use_filename: true,
      folder
    })

    return {
      url: result.url,
      id: result.public_id
    }
  } catch (error) {
    throw error
  }
}

multer.js

const multer = require('multer')
const fs = require('fs')

const UPLOADS_DIR = './uploads'

if (!fs.existsSync(UPLOADS_DIR)) {
  fs.mkdirSync(UPLOADS_DIR)
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, UPLOADS_DIR)
  },
  filename: (req, file, cb) => {
    const timestamp = new Date().toISOString().replace(/:/g, '-')
    const originalname = file.originalname || 'unknown'
    cb(null, `${timestamp}-${originalname}`)
  }
})

const fileFilter = (req, file, cb) => {
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true)
  } else {
    // reject file
    cb({ message: 'Unsupported file format' }, false)
  }
}

const upload = multer({
  storage,
  limits: { fileSize: 1024 * 1024 },
  fileFilter
})

module.exports = upload

here is my ProductController.js, where I upload the image then push the link to the database

const createProduct = async (req, res) => {
  const { name, price, description } = req.body

  console.log('Received request with data:', { name, price, description })

  const uploader = async (path) => await cloudinary.uploads(path, 'Images')

  try {
    if (req.method === 'POST') {
      const urls = []
      const files = req.files
      for (const file of files) {
        const { path } = file
        const newPath = await uploader(path)
        urls.push(newPath)
        fs.unlinkSync(path)
      }

      console.log('Cloudinary Upload URLs:', urls)
      // creating the product
      const product = await new Product({
        name,
        description,
        price,
        files: urls
      })

      await product.save()
      return res.status(200).json({
        success: true,
        message: 'product created sucessfully',
        data: product
      })
    } else {
      return res.status(405).json({
        err: `${req.method} method not allowed`
      })
    }
  } catch (error) {
    console.error('Error creating product:', error)
    return res.status(412).send({
      success: false,
      message: error.message
    })
  }
}

Google re-Captcha is not completely visible on Mobile Screen

In my application i found google recaptcha is not visible properly on mobile view , i am trying to set some css setting but its not fixed for all mobile screen.

skip and verify button is hide from the screen , i am attaching a screenshot of mobile view. where you will find in the below section of the image, the buttons are missing.

enter image description here

npm start TypeError Cannot Detect node version

I am trying to run a react app using npm start. I’m using node js 10.24.1 and cannot upgrade it as the project is a legacy project.
I tried clear the cache with force, removing node_modules and package-lock.json, nothing worked. I also tried using gulp tasks as the porject requires running backend tasks using gulp run:backend. After that, I use gulp run:dar-360. dar-360 being the name of my app.
There are no errors in the console, however the application doesn’t start in the browser and the chrome devtools show:

index.js:57 Uncaught TypeError: Unable to determine current node version
   at versionIncluded (index.js:57:1)
   at isCore (index.js:76:1)
   at ../../node_modules/resolve/lib/core.js (core.js:12:1)
   at __webpack_require__ (bootstrap:784:1)
   at fn (bootstrap:150:1)
   at ../../node_modules/resolve/index.js (index.js:3:1)
   at __webpack_require__ (bootstrap:784:1)
   at fn (bootstrap:150:1)
   at ../../node_modules/tslint/lib/utils.js (utils.js:25:1)
   at __webpack_require__ (bootstrap:784:1)
   at fn (bootstrap:150:1)
   at ./src/modules/maps/pages/map-page/components/help-modal.component.js (geo.helper.js:122:1)
   at __webpack_require__ (bootstrap:784:1)
   at fn (bootstrap:150:1)
   at ./src/modules/maps/pages/map-page/map.page.js (map.page.css:45:1)
   at __webpack_require__ (bootstrap:784:1)
   at fn (bootstrap:150:1)
   at ./src/components/app/app.component.js (app.component.css:45:1)
   at __webpack_require__ (bootstrap:784:1)
   at fn (bootstrap:150:1)
   at ./src/index.js (index.css:45:1)
   at __webpack_require__ (bootstrap:784:1)
   at fn (bootstrap:150:1)
   at 1 (service-worker.utils.js:56:1)
   at __webpack_require__ (bootstrap:784:1)
   at checkDeferredModules (bootstrap:45:1)
   at Array.webpackJsonpCallback [as push] (bootstrap:32:1)
   at main.chunk.js:1:67

can you make the checkbox boolean state and the input value interact with each other?

I’m struggling with a checkbox and input logic.
This is the diagram:
enter image description here
here, when the user inputs three, three of the data in the list should be true, like this.
enter image description here

But when the user clicks “open modal” it will show the modal that the user can choose the data from. like this:
enter image description here
then, only the selected data from the list should be true.
Also, when the user clicks the up/down button, the checkboxes should check in chronological order, like this:
enter image description here
the opposite should be the same.

I have done each features separately, but I am having trouble combining both and I think my state structure is wrong so I’m thinking of planning the whole thing from blank.
I’m using Zustand as state management, and React/typescript.

Could you please recommend how many states I should use and how they interact with one another? Thank you!

for reference, the “sweep” feature in opensea is similar but it doesn’t do the exact thing I am trying to achieve.