Capture text inside multiple header tags with regex [duplicate]

Given a string with multiple html tags inside (headers and other), I’d like to extract all text inside multiple header tags.

A given string : '<h1>Header 1</h1> <p>blabla</p> <h2>Header 2</h2>'

Expected result : ['Header 1', 'Header 2']

I came up with this : /<h[1-9]>(.*)</h[1-9]>/g; but it works only for a single occurrence.

Javascript arrow funtions with a function as parameter

I am trying to understand this arrow function declaration but I can’t. Someone can explain what is getFooOfImpl in this funtion and why there’s several async declarations? Thank you

const getFooOfId = (getFooOfIdImpl = async (fooId) => { throw new Error(`Can't retrieved foo of id ${fooId} : missing implementation`) }) => async fooId => {
 try {
    const fooData = await getFooOfIdImpl(fooId);
    return FooData(fooData);
  } catch (err) {
    throw new Error(`Unable to retrieve Foo with id ${fooId}`);
  }
}

Chrome extension – storage change listener in popup

I’m creating both web app and react chrome extension. I want the extension to show current web app auth status (stored in cookies). The following code below works (background script listens to cookies changes and store current value in storage, and popup script pulls every 1s the current value from storage), but I wonder whether this pulling is a right way to do it. I tried using chrome.storage.onChanged in popup script, but it was fired only once.

background.js

const domainName = 'localhost' // address of my web app
const cookieName = 'user'

chrome.cookies.onChanged.addListener(({ cookie, removed: isBeingRemoved }) => {
    if (cookie.domain === domainName && cookie.name === cookieName) {
        chrome.storage.sync.set({
            [cookieName]: !isBeingRemoved
                ? cookie.value
                : null,
        })
    }
})

popup.jsx

const [user, setUser] = useState(null)

const pullVariablesFromStorage = () => {
        chrome.storage.sync.get(['user'], function ({ user }) {
            setUser(user)
        })
}

 useEffect(() => {
        pullVariablesFromStorage()

        const intervalId = setInterval(() => {
            pullVariablesFromStorage()
        }, 1000)

        return () => clearInterval(intervalId)
 }, [])

return (
   <div>{user ? `Hi ${user}` : 'sign in using web app'}</div>
)

Test if Child components exist and render correctly inside Parent component in react native

I’m trying to test a Parent component that contains three child components

my parent component look like this:

<SafeAreaView
        testID="welcome-screen"
        edges={['left', 'right', 'top']}
        style={[styles(colors).container]}>
        <StatusBar barStyle={'light-content'} backgroundColor={'black'} />
        <Animatable.View
            animation={isAnimationsFinish ? upTopBar : absoluteScreen}>
            <ShowInitialUserDetails />
        </Animatable.View>
        <View style={styles(colors).scroll_and_button}>
            <ScrollView
                contentContainerStyle={styles(colors).userDetailsContainer}>
                <RegularTextStyle color={colors.SOFT_BLACK} size={14}>
                    To proceed, Please fill up the following fields.
                </RegularTextStyle>
                <Animatable.View
                    animation={upUserDetailsScreen}
                    style={styles(colors).userDetailsViewContainer}>
                    {}
                    <TitleAndTextInput
                        title="Your phone number"
                        placeHolder="Phone number"
                        inputType=""
                    />
                </Animatable.View>
            </ScrollView>
            <SimpleButton
                title="Continue"
                isVisible={isAnimationsFinish ? true : false}
                onPress={() => resetTo(HOME_NAVIGATOR)}
            />
        </View>
    </SafeAreaView>

and my test file look like this:

import { render, waitFor } from '@testing-library/react-native';
import { Provider } from 'react-redux';
import store from '../../../state/store';
import React from 'react';
import WelcomeScreen from '../WelcomeScreen';
import RegularTextStyle from '../../../components/texts/RegularTextStyle';
import { View } from 'react-native';
import TitleAndTextInput from '../../../components/TitleAndTextInput';
import ShowInitialUserDetails from '../components/ShowInitialUserDetailsComponent';
import * as Animatable from 'react-native-animatable';
import { shallow } from 'enzyme';
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
Enzyme.configure({ adapter: new Adapter() });

jest.mock('react-native-animatable', () => {
   const ReactRef = jest.requireActual('react');
   return {
       // ...actual,
       View: class extends ReactRef.Component {
           render() {
               return <></>;
           }
       },
   };
});

jest.mock('../../../components/texts/RegularTextStyle', () =>
   jest.fn().mockReturnValue(null),
);
jest.mock('../../../components/TitleAndTextInput', () =>
   jest.fn().mockReturnValue(null),
);
jest.mock('../components/ShowInitialUserDetailsComponent', () =>
   jest.fn().mockReturnValue(null),
);

describe('Welcome Screen test', () => {
   //TEST NUMBER 1 -WORKING
   it('Should render currectly', async () => {
       const { getByTestId } = render(
           <Provider store={store}>
               <WelcomeScreen />
           </Provider>,
       );
       await waitFor(() => {
           const welcomeContainer = getByTestId('welcome-screen');
           expect(welcomeContainer).toBeDefined();
       });
   });
    //TEST NUMBER 2 - WORKING
   it('should render RegularTextStyle currectly ', () => {
       (RegularTextStyle as jest.Mock).mockReturnValue(
           <View testID="mock-regular-textStyle" />,
       );

       const { getByTestId } = render(
           <Provider store={store}>
               <WelcomeScreen />
           </Provider>,
       );
       getByTestId('mock-regular-textStyle');
   });

    //TEST NUMBER 3 -  NOT WORKING!
   it('should render TitleAndTextInput  currectly ', async () => {
       (TitleAndTextInput as jest.Mock).mockReturnValue(
           <Animatable.View testID="test" />,
       );
       const { getByTestId } = render(
           <Provider store={store}>
               <WelcomeScreen />
           </Provider>,
       );
       getByTestId('test');
   });

    //TEST NUMBER 4 -  NOT WORKING!
   it('should render ShowInitialUserDetails currectly', () => {
   const wrapper = shallow(
       <Provider store={store}>
           <WelcomeScreen />
       </Provider>,
   );
   expect(wrapper.find(<ShowInitialUserDetails />)).toHaveLength(1);
});

as you can see test number 1 and 2 working fine
but test number 3 that look the same as test number 2 exepct that he is insdie Animated.View, throw Error:

    Unable to find an element with testID: test

For test number 4 I received this error when I used the Enzyme library

expect(received).toHaveLength(expected)

Expected length: 1
Received length: 0
Received object: {}

Could someone please tell me what I am doing wrong with this test or how I should test my child component?
thanks!

UI automation with Protractor – promise handling with async await

We have taken Page Object Model (POM) approach. It works perfectly fine when ‘Control Flow’ is enabled.
But when we disable ‘Control Flow’ in conf.js file by flag SELENIUM_PROMISE_MANAGER: false
and apply Async/Await we are getting following error message:-

    S D:oldcode> protractor Conf.js
    [15:37:02] I/launcher - Running 1 instances of WebDriver
    [15:37:02] I/direct - Using ChromeDriver directly...
     DevTools listening on ws://127.0.0.1:64832/devtools/browser/1d68c5dc-5b58-495a-9db9- 
     c1d45c531723
     Started
     .
     
     1 spec, 0 failures       
     Finished in 0.018 seconds
     
     [15:37:07] E/launcher - Error while waiting for Protractor to sync with the page: "both 
     angularJS testability and angular testability are undefined.  This could be either 
     because this is a non-angular page or because your test involves client-side navigation, 
     which can interfere with Protractor's bootstrapping.  See http://git.io/v4gXM for 
     details"
     [15:37:07] E/launcher - Error: Error while waiting for Protractor to sync with the page: 
     "both angularJS testability and angular testability 
     are undefined.  This could be either because this is a non-angular page or because your 
     test involves client-side navigation, which can interfere with Protractor's 
     bootstrapping.  See http://git.io/v4gXM for details"
     at C:UsersDbindalAppDataRoamingnpmnode_modulesprotractorbuiltbrowser.js:461:23
     at processTicksAndRejections (node:internal/process/task_queues:96:5)Error
     at ElementArrayFinder.applyAction_ 
     (C:UsersDbindalAppDataRoamingnpmnode_modulesprotractorbuiltelement.js:459:27)
     at ElementArrayFinder.<computed> [as click] 
     (C:UsersDbindalAppDataRoamingnpmnode_modulesprotractorbuiltelement.js:91:29)        
    at ElementFinder.<computed> [as click] 
    (C:UsersDbindalAppDataRoamingnpmnode_modulesprotractorbuiltelement.js:831:22)
    at demoPage.submit (D:oldcodepage.js:34:18)
    at UserContext.<anonymous> (D:oldcodedemo13_spec.js:13:16)
    at 

C:UsersDbindalAppDataRoamingnpmnode_modulesprotractornode_modulesjasminewd2index.js:112:25
at new Promise ()
at SimpleScheduler.promise
(C:UsersDbindalAppDataRoamingnpmnode_modulesprotractornode_modulesselenium-
webdriverlibpromise.js:2242:12)
at schedulerExecute

(C:UsersDbindalAppDataRoamingnpmnode_modulesprotractornode_modulesjasminewd2index.js:95:18)
at C:UsersDbindalAppDataRoamingnpmnode_modulesprotractornode_modulesselenium-
webdriverlibpromise.js:2232:22
[15:37:07] E/launcher – Process exited with error code 199
PS D:oldcode> [7160:14332:0111/153709.074:ERROR:device_event_log_impl.cc(214)]
[15:37:09.074] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node
connection: A device attached to the system is not functioning. (0x1F)
[7160:14332:0111/153709.077:ERROR:device_event_log_impl.cc(214)] [15:37:09.077] USB:
usb_device_handle_win.cc:1048 Failed to read descriptor
from node connection: A device attached to the system is not functioning. (0x1F)
[7160:21072:0111/153709.120:ERROR:chrome_browser_main_extra_parts_metrics.cc(226)]
crbug.com/1216328: Checking Bluetooth availability started. Please report if there is no
report that this ends.
[7160:21072:0111/153709.128:ERROR:chrome_browser_main_extra_parts_metrics.cc(229)]
crbug.com/1216328: Checking Bluetooth availability ended.
[7160:21072:0111/153709.129:ERROR:chrome_browser_main_extra_parts_metrics.cc(232)]
crbug.com/1216328: Checking default browser status started. Please report if there is no
report that this ends.
[7160:21072:0111/153709.143:ERROR:chrome_browser_main_extra_parts_metrics.cc(236)]
crbug.com/1216328: Checking default browser status ended.
[2632:18876:0111/153905.755:ERROR:gpu_init.cc(457)] Passthrough is not supported, GL is
disabled, ANGLE is

We have used two .js files. One for locators and action methods is page.js and its code is as below
let demoPage = function () {

      let prefix = element(by.xpath("//input[@value = 'Mr']"));
      let firstname = element(by.id('first-name'));
      let lastname = element(by.id('last-name'));
      let subject = element(by.xpath("//input[@value = 'Computers']"));
      let street = element(by.id('street'));
      let city = element(by.cssContainingText('option', 'Delhi'));
      let zip = element(by.id('zip'));
      let submit = element(by.xpath("//button[@type = 'submit']"));
      let link = element(by.partialLinkText('Link'));
      let hover = element(by.xpath('//*[contains(text(), "Mouse Over")]'))

      this.get= async function(url){
           await browser.get(url);
           await browser.manage().window().maximize();
           expect(await browser.getCurrentUrl()).toBe('http://localhost:4200/');
         }

     this.submit= async function(fn, ln, str, zp){
     await prefix.click();
     await firstname.click().sendKeys(fn);
     await lastname.click().sendKeys(ln);
     await subject.click();
     await street.click().sendKeys(str);
      await city.click();
     await zip.click().sendKeys(zp);
    await browser.actions().mouseMove(hover).perform();
    text= await browser.driver.switchTo().alert().getText();
    console.log(text);
    await browser.driver.switchTo().alert().accept();
    await submit.click();
    }
    };
    module.exports = new demoPage();

The other test file is testspec.js and its code is as follow –

       let demoPage = require('./page');
      describe('mySuite', function () {
     it('Test case', function () {
       demoPage.get("http://localhost:4200/");
       demoPage.submit("John", "Smith", "CP", "110001");
      });
    });

It would be great if the community here guide me in finding a solution. I am thankful in advance for the invaluable advice from fellow members.

How to fetch Amazon Cognito Identity ID (user_identity_id) for the user from the lambda function?

In the Amplify documentation, under the Storage/File access levels section there is a paragraph that states:

Files are stored under private/{user_identity_id}/ where the user_identity_id corresponds to the unique Amazon Cognito Identity ID for that user.

How to fetch user_identity_id from the lambda function?

Request to the lambda is authorized, the event.requestContext.authorizer.claims object is available, I can see the user data, but not the user_identity_id.

Not able to save object value in Angular component

This is component class for example:

export class AppComponent {

  categories = {
     country: [],
     author: []
  }

  constructor(){}

  getOptions(options) {
     options.forEach(option => {
        const key = option.name;
        this.categories[key].push(option.value);
     })
  }
  
}

On clicking a button, I am calling getOptions(options) from different component. The structure of options looks like:

options = [
  {name: 'country', value: 'Germany'},
  {name: 'author', value: 'Franz Kafka'}
]

So now the value of this.categories will get updated, so now:

this.categories[country] = ["Germany"]
this.categories[author] = ["Frank Kafka"]

Value of options changes every time on clicking the button. When I am sending new options value such as:

options = [
  {name: 'country', value: 'Japan'},
  {name: 'author', value: 'Masashi Kishimoto'}
]

Old value for this.categories[country] is not getting saved for some reason. The new value for this.categories[country] should be ["Germany, "Japan"] but I am getting only ["Japan"] in the array.

What is the purpose of @next/react-dev-overlay

I am working on a NextJs project. In it, I have found this piece of code inside next.config.js:

const withTM = require('next-transpile-modules')([
    'some package',
    'some package',
    'emittery',
    '@next/react-dev-overlay'
]);

I was wondering what is the purpose of this @next/react-dev-overlay and was not able to find anything online. The only thing was this unanswered question in the nextjs github issues. When I remove it, it seems that the project is working as expected. My question is what is the purpose of this @next/react-dev-overlay package and should I remove it?

How to add array of videos links into code

How do I add this:

videoPlayer.init([
    "0dgNc5S8cLI",
    "mnfmQe8Mv1g",
    "CHahce95B1g",
    "2VwsvrPFr9w"
]);

Into here?

videoPlayer.init({
  afterPlayerReady: function initCover() {
    manageCover.init(function playVideo() {
      videoPlayer.play();
    });
  }
});

That is what I am needing to do.

https://jsfiddle.net/x4qs50wz/

Currently, there is this error:

 Cannot read properties of undefined (reading 'join')"

That is because, I have not added the array to the code because I am stuck.

LocalStorage Quasar Storing a Checkbox

This really just doesn’t make sense to me why it’s such a pain storing a value of a q-checkbox and keeping it after reloading the page. I had no issues doing this with jQuery but I really need help understanding this for Quasar.

https://quasar.dev/quasar-plugins/web-storage

I need just a working example of how to do this correctly. I love Quasar because of the preset styles and just how easy it is to implement things usually. Thanks everyone!

Enumerating sliced array using original indices

I need to slice an array and enumerate the values but I also need the reference to the original index because I’m doing an async operation that needs to be mapped back to the original index in the original array when complete.

const array = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'];
const slicedArray = array.slice(0, 3).map((v, i) => ({ v, i }));
// Returns: [{ "v": "foo", "i": 0 }, { "v": "bar", "i": 1 }, { "v": "baz", "i": 2 }]
// Required: [{ "v": "foo", "i": 0 }, { "v": "bar", "i": 1 }, { "v": "baz", "i": 2 }]
const slicedArray2 = array.slice(3, 6).map((v, i) => ({ v, i }));
// Returns: [{ "v": "qux", "i": 0 }, { "v": "quux", "i": 1 }, { "v": "corge", "i": 2 }]
// Required: [{ "v": "qux", "i": 3 }, { "v": "quux", "i": 4 }, { "v": "corge", "i": 5 }]

How can I achieve this?

Is it ok to declare variables inside of if statements?

Today I’m refactoring someone’s code from var to let which should be used in modern JS and declared variables inside of if statements occur a lot in the code. So this made me wonder is it ok to declare variables inside of if statements or should it be avoided in JS?

var Example1 = "test";

if (Example1 == "test") {
   var test1 = true;
}

if (test1) {
   console.log("Test 1 works!");
}

// Refactored code do not work with let

let Example2 = true;

if (Example2 == "test") {
   let test2 = true;
}

if (test2) {
   console.log("Test 2 works!");
}

Get point projection on line defined by two points

How can I get a point projection on a line in the two following cases:

enter image description here

I have A, B, and P points defined by the x and y values in the 2D coordinating system. How can I get P’ point coordinates using javascript?
Every point is defined by the following values:

{
   x: number;
   y: number;
}

change and text color onmouseover an js

in that html

        <article id="art">
            <h1 class="hstyle">1</h1>
            <p class="pstyle">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, sed.</p>
        </article>

        <article id="art">
            <h1 class="hstyle">2</h1>
            <p class="pstyle">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iste, cumque!</p>
        </article>

        <article id="art">
            <h1 class="hstyle">3</h1>
            <p class="pstyle">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Blanditiis, officia!</p>
        </article>

        <article id="art">
            <h1 class="hstyle">4</h1>
            <p class="pstyle">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nobis, consequatur!</p>
        </article>

        <article id="art">
            <h1 class="hstyle">5</h1>
            <p class="pstyle">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Vero, sed.</p>
        </article>

        <article id="art">
            <h1 class="hstyle">6</h1>
            <p class="pstyle">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Officia, asperiores?</p>
        </article>
    </div>

in javascript i want to change backgroundcolor of all articles onmouseover and in the same time change h1 and p text color onmouseover the articles
i can do backgroundcolor change in js :

a = document.getElementsByTagName("article");
h = document.getElementsByClassName("hstyle");
p = document.getElementsByClassName("pstyle");
console.log(a);
console.log(h);
console.log(p);
for (i in a) {
    a[i].onmouseover = function () {
        this.style.backgroundColor = "black";
    };
    a[i].onmouseout = function () {
        this.style.backgroundColor = "white";
    };
};

but as you can see i could’nt go any further
some help would be appreciated .