How to i play notification sound on HTML5 after getting response from webscoket request

I made a function in my HTML 5 using Howler and wants to play the sound when I receive a response from the socket but the sound doesn’t play, but the same sound plays when I tried using a button click. This is the function I made for sound

<script>
   var PlayNotificationSound = new Howl ({
     src : ['http://localhost/rystore/resources/assets/sound/notification.ogg'],
     html5: true
});
</script>

And the below code is when I receive a response from the socket

Socket.on("delivery-boy-notification", () =>{
    PlayNotificationSound.play();
    Snackbar.show({text: "You Have Received A New Delivery Order Check Your Inventory"})
})

The message is being shown but the sound is not being played

Debounce values but return all non unique elements instead of just one element in javascript

I have a use case where I have multiple functions firing simultaneously.
Each function can be called multiple times but I need to pick out only one return value. Im using debounce and it does work as intended. Even if I have 10 return values, I get only 1 return at the end. However if there are unique values, I want all the unique values returned

What is happening

-----1----2-----2---2----2----2----3-----3---3---3---3---3------>
(Only 1 value is returned)
-------------------3--------------------------------------------->

What I want

-----1----2-----2----2----2----2----3-----3---3---3---3---3------>
(Return all unique values)
-------------------1-------------------2--------------------2---->

What I have tried (Example)

var _ = require('lodash');

function printOne () {
  handleSearch(1);
}

function printTwo () {
  handleSearch(2);
}

function printThree () {
  handleSearch(3);
}


const handleSearch = _.debounce((msg) => {
  console.log(msg)
}, 2000, );


printOne();
printTwo();
printTwo();
printTwo();
printThree();
printThree();
printThree();

Output -> 3

Expected Output -> 1 2 3

Should I use a set to have a form of local cache and then get unique values? Any pointers would be welcome

State won’t change in “keydown” event in React

I am making a an app where I need to register the keys the user presses. To do that I am using keydown and keyup events. However, I don’t want to register the same key multiple times when the user holds it down.

I want to make it so the downHandler function won’t run multiple times whenever you hold down a key. I only want it to run once. I try to use an if statement for that and setting keyPressed to true so it won’t run again. I try to log keyPressed right after I set it to true, but it logs as false, and the function still runs again.

I tried to remove setKeyPressed(false) in the downHandler function, but keyPressed was still false no matter what.

Here is my app.js:

import { useState, useEffect } from "react";


function App() {
  const key = useKeyPress();

  function useKeyPress(targetKey) {

    const [keyPressed, setKeyPressed] = useState(false);

    function downHandler(key) {
      if (keyPressed === false) {
        setKeyPressed(true);
        console.log(keyPressed)
      }
    }

    const upHandler = (key) => {
      console.log("up")
      setKeyPressed(false);
    };

    useEffect(() => {
      window.addEventListener("keydown", downHandler);
      window.addEventListener("keyup", upHandler);

      return () => {
        window.removeEventListener("keydown", downHandler);
        window.removeEventListener("keyup", upHandler);
      };
    }, []);
    return keyPressed;
  }

  return (
    <div>

    </div>
  )
}

export default App;

setLocalStorage is not working on cypress test

I have a problem with token.

I have loginCommand.

Cypress.Commands.add('login', (user, password) => {
  cy.request('POST', `${Cypress.env('API')}/auth/login`, {
    email: Cypress.env(user),
    password: Cypress.env(password),
  })
    .its('body')
    .then(res => {
      cy.log('res:', res);
      cy.setLocalStorage('token', res.token);
    });
});

I am trying to add new offer. And this is the test case.

it('can create an projectOffer C232 C233 C234 C235 C236', () => {
  //cy.seed(token);
  cy.fixture('offerA').as('offerA');
  cy.login('testEmail', 'testPwd');
  cy.visit(base);
  const customerRef = `create offer test ${new Date().toISOString()}`;
  cy.fixture('offerA').then(offerA => {
    cy.createOffer(offerA, customerRef);
  });
});

and also this is the related part of my code.

Cypress.Commands.add('createOffer', (offer, offerName) => {
  cy.get('[data-testid=app-toolbar-item]').click();

The error is

[data-testid=app-toolbar-item], but never found it.

In the application tab I see that my token is not there

What can I do for fixing this?

Regex fails if there are `()` small brackets present in text

I am trying to build a regular expression that detects the presence of header tags in HTML, and then captures the textual content of the header tag. I have also tried to make it a little robust by also taking care of nested tags present inside the header tags.

Here is the regular expression that I am currently working with.

<h1.*?>s*(<.*?>)*s*(</.*?>)*s*(<.*?>)*s*b(.+)bs*(</.*?>)*s*</h1>

It works pretty well with many test examples. However, for some reason which I am not able to understand, this expression fails if there are brackets, e.g, small brackets present inside the textual content area.

Following is a sample tag, which I am trying to parse, my specified expression fails to properly work with it.

<h1><span id="Civil_rights_activist_in_South_Africa_.281893.E2.80.931914.29"></span><span class="mw-headline" id="Civil_rights_activist_in_South_Africa_(1893–1914)">Civil rights activist in South Africa (1893–1914)</span></h1>

Interestingly, it works just fine if I remove the small brackets from the textual area which I am trying to capture. The following example works just fine.

<h1><span id="Civil_rights_activist_in_South_Africa_.281893.E2.80.931914.29"></span><span class="mw-headline" id="Civil_rights_activist_in_South_Africa_(1893–1914)">Civil rights activist in South Africa 1893–1914</span></h1>

The textual area in both samples is Civil rights activist in South Africa (1893–1914)
with and without the small brackets surroundings the years.

The textual content can be anything, so I can not always look for the presence of brackets. e.g, I also want to make sure that my regex does not miss the following cases.

<h1> Hello World</h1>

<h1 id="main_heading"> Hello World</h1>

<h1><span class="bold"> Hello World </span></h1>

How can I map Elements size and position to other Elements size and position on resize

So I’ve run into a problem trying to make objects on a image clickable.
I have an Image with 3 Objects that I want to link to 3 different pages / execute 3 different functions onclick.

Now my problem occurs when I resize my window. The Image having the following style to always display the objects, even if I resize the window and fill up the entire screen.

img {
    object-fit: cover;
    object-position: center;
    width: 100%;
    height: calc(100vh - 90px);
}

Since the objects are pretty big and when I resize, to let’s say mobile view, the links will overlap and be bigger then the screen itself.

Now my question is, would it be possible to kinda map the buttons sizes and positions to the image, that the rescale automatically, or would i need to use media-queries to achieve that?

I was thinking of tracking the initial scale of the image someone and applying that to the links with transform: scale();, maybe?

Using JS is fine, since it is a vue 3 application.

How can I write useEffect in test code (jest)?

// MyCode.tsx
const MyCode = (props) => {
    const { useEffect, useRef } = React;
    const { count, setCount } = useState(0)
    const elementRef = useRef(null);

    useEffect(() => {
        setCount(1);
    }, [elementRef]);

    const getFunc() {
        return {
            name: 'Mike',
        }
    }

    return (
        <React.Fragment>
            <div className="section" ref={elementRef}>
                ....
            </div>
        </React.Fragment>
    );
}
// MyCode.test.js
import * as React from 'react';
import { render, mount, shallow, shallowWrapper } from 'enzyme';
import MyCode from '../MyCode';

describe('TEST START', function() {
    let wrapper;

    beforeEach(() => {
        wrapper = shallow(
            <MyCode />,
        );
    });

    it('TEST1', () => {
        expect(wrapper.find('.section').length).toEqual(1);
    });

    it('TEST2', () => {
        // useEffect(() => {
        //     setCount(1);
        // }, [elementRef]);
    });

    it('TEST3', () => {
        // const getFunc() {
        //     return {
        //         name: 'Mike',
        //     }
        // }
    });
});

I have some questions.
It is difficult to write a test code.

Q1. How can I write useEffect in test code (jest)? I want to get the changed state value.
Q2. How can I get the return value of the getFunc function?
I can’t do it like this.

expect(wrapper.getFunc()).toBe({ name: 'Mike' })

help me…

How can I change the text of a button based on click if is looped inside a map function?

I am mapping over a series of cards in a form component like this :

```

{links?.map((i,j) => (
  <main className={styles["card-container"]} key={j}>
    <Card
        url={i?.url}
        shortenUrl={i?.shorten}
    />
  </main>
))}

```

That Card renders a URL link, a shortened link and a button that says “click”

<div>
  <div>{url}</div>
  <div>{shortenUrl}</div>
  <Button>Copy</Button>

</div>

The Button too is a reusable component,

  return (
    <>
      <button>{children}</button>
    </>
  )

What I want to do:

  • I want to click the button on any of the mapped cards, and the button text should be changed to “copied”

what I have tried :

  • I have tried using a state to change the text, but it changes “copy” -> “copied” on all the mapped cards.
  • I also tried passing props from the form component using prop drilling to the Button component, but it doesn’t work as expected.
  • I looked at other answers here on SO, one answer was to use button text as an array itself, but I’m not sure how to implement it in this context.

Any solution to this?

Thanks for reading this far

JavaScript array map return multiple value

Now I have array like this

let arr = [{
    name: 'Tony', age: 17, love: [1, 2, 4]
}, {
    name: 'David', age: 12, love: [6, 6, 6]
}, {
    name: 'John', age: 10, love: [0, 0, 0]
}]

And I want to map this array and get result

const a1 = arr.map(man => {
    if(man.name === 'Tony') {
        for(let i = 0; i < man.love.length; i++) {
            return man.love[i]
        }
    }
    else {
        return man.name
    }
})

The result I Want is [ 1, 2, 4, 'David', 'John' ].

But I got [ 1, 'David', 'John' ]

How can I achieve that? Thanks in advanced!

Why it value does not send in to ajax post?

I’m a newbie working with ajax. I have a problem while sending the data into ajax post.
The output of console.log(obj.Id) and console.log(oke) is 2. Then I tried to send it through data in ajax, but it end up 0 in the controller.

$(function () {
            $("body").on('click', '#btnEdit', function () {
                alert("clicked ok");
                $("#addRowModal").modal("hide");
                var obj = {};
                obj.Id = $(this).attr('data-id');
                oke = $(this).data("id");
                console.log(obj.Id)
                console.log(oke)
 
                $.ajax({
                    url: '@Url.Action("Details", "InvoicePPh")',
                    data: oke,
                    type: 'POST',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        alert("sukses");
                    },
                    error: function(response) { 
                        alert("error") 
                    }
                });
            });
        });

And my controller looks like this

[HttpPost]
        public JsonResult Details(int id)
        {
            var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
            InvoicePPh pph = new InvoicePPh();
            pph2326.TaxForm = obj.TaxForm;              
            return Json(pph);
        }

I want the ‘2’ value that passes into my controller, how can I do that? Thank you for your help.

How do I fix CORS error for thumbnails.roblox.com? Please do not downvote I’m trying to find an answer like the rest of you

Every single CORS fix that I have seen on overflow has not worked for me yet so I am hoping someone has a .htaccess fix that allows me to execute a curl request to https://thumbnails.roblox.com/v1/batch. I am trying to send a request there to get the thumbnail of a game on ROBLOX but it is not working whatsoever because of CORS policy. Is there a .htaccess fix for this? Please send me if so.

Access to XMLHttpRequest at 'https://thumbnails.roblox.com/v1/batch' from origin 'mysite' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.