How to extract text from an html page to insert in another?

I would like to extract some text, which is changing every 30 min, from a weather website (METAR for pilots) and integrate it on a self made html page (i’m doing a summary of many weather informations on one page).
The text is in a class on this website : https://metar-taf.com/LFBO

and it is the text in the dark blue rounded box, above the “donate” button.
looks like this when i inspect :
METAR LFBO 011700Z AUTO 29020KT CAVOK 08/M05 Q1010 TEMPO 32020G35KT

i don’t really like iframes as they slow down the page loading a lot, is there another way ?

thank you

I tried to use some part of code here Extract the text out of HTML string using JavaScript but it is not adapted to my use.
I just need the text “extracted” and usable on another page.

Why the errror if semicolon not available?

It is a very simple IIFE situation in JavaScript.
But the semicolon at the end of the first line will make a huge difference whether it is over there or not.

Here is the error version and no semicolon in the first line:

const obj = {}
(function () { })()

If we add semicolon at the end of that line, error dismissed:

const obj = {};
(function () { })()

I was told that semicolon is not necessary in JavaScript but it apparently is wrong in this situation. Why?

When is it okay/appropriate to use logical assignment in javascript?

I used logical assignments like b = a || [] in Javascript before, and there are many questions on SO about it.
To mention some:

And from what I read, b = a || [] is legit code.

However, I noticed in a recent case (checking for a variable set by another script), that this code does not work as I expected.
I assumed the code would check whether a is falsy, and if so [] would be assigned to b. Since undefined is falsy, I excepted the code to work and assign [] in the case when a was not defined.

But this code causes an error:

let b;

b = a || [];
console.log(b);

a = ["1", "2", "3"];
b = a || [];
console.log(b);

wheras

let b;

b = typeof a == "undefined" ? [] : b;
console.log(b);

a = ["1", "2", "3"];
b = a || [];
console.log(b);

does not.
And why is it causing an error, when the error says Uncaught ReferenceError: a is not defined, which implies a is undefined?

When can I use the logical assignment? Only when it is guaranteed that the variable (a) is at least declared?

Send HTML data to PHP and post back the result to HTML page with ajax

I am trying to send an input text value “Username” to a php script which is giving a result. That result I want it back on the html page.

    <input type="name" id="user" name="id" placeholder="Username">
    <button type="button" id="fetchBtn">Click Me!</button>
    <p id="txt"></p>

sssss

<script>
let fetchBtn = document.getElementById('fetchBtn');
let user = document.getElementById('user');
fetchBtn.addEventListener('click', buttonClickHandler);

function buttonClickHandler() {
    
    // Instantiate an xhr object
    var xhr = new XMLHttpRequest();
    
    // What to do when response is ready  
    xhr.onreadystatechange = () => {
        if(xhr.readyState === 4) {
            if(xhr.status === 200) {
                document.getElementById("txt").innerHTML = 
                xhr.responseText;
            } else {
                console.log('Error Code: ' + xhr.status);
                console.log('Error Message: ' + xhr.statusText);
            }
        }
    }
    xhr.open('GET', 'data.php');
    
    // Send the request
    xhr.send();
}
</script>

Now I am trying to get the PHP variable $title back to HTML page after it’s processed by the php script. I can’t figure out how to display it properly

<?php 
function file_get_contents_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

// $para = $_GET['id'];
// $para =
$html = file_get_contents_curl("http://website.com/$para");

//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');

//get and display what you need:
$title = $nodes->item(0)->nodeValue;
?>

<html>
<body>
   <?php echo '<h1>Welcome to GfG</h1>'; ?>  
    <?php echo "$title"?>

SubString using regex

I am trying to find last occurrence of word in a given string and delete all data from that position.

Let say I have data like below I have to search last occurrence of <!-- Temp -->
and delete all character from that position using Javascript.

let data ="This is a test data <!-- Temp --> to be continue";
//Expected Output
"This is a test data"

let data1 ="This is <!-- Temp --> a test data <!-- Temp --> to be continue";
//Expected Output
"This is <!-- Temp --> a test data"

Is there a way that we can use attribute selectors in Material-UI using makeStyles?

I am trying to extract all the div’s having some specific Mui classenames say access-MuiPickersCalendarHeader-switchHeader,access-MuiPickersDay-day etc. Here the actual class names are
MuiPickersCalendarHeader-switchHeader,MuiPickersDay-day as per Material-ui. As I am seeding my components using StylesProvider it is adding access infront of the classes as prefix.
Is there anyway that i can fetch all the div’s whose class names includes “MuiPickersDay-day”,”MuiPickersCalendarHeader-switchHeader” and style them using makeStyles in material-ui?

For Example:
Component 1 is having some elements with classnames : aboutpage-MuiPickersDay-day
Component 2 is having some elements with classnames : homepage-MuiPickersDay-day

Create a makeStyles where i can style both of the component’s elements whose classname includes
‘MuiPickersDay-day’

I tried using attribute selectors in makeStyles but i am not able to do that. It is not allowing me to use that approach
For eample:

const useStyles = makeStyles((theme) => createStyles((theme) => {
               div[class^='MuiPickersDay-day]:{backgroundColor:'black'}
});

Sort list in descending alphabetical order

I have a list of Tasks and each task contains the property ‘fromPriority’. This property is a string and its values can only be ‘HIGH’, ‘AVERAGE’, ‘LOW’ or a numeric string. I need to order this list by this property, but I need that the numeric strings are ordered first in desceding order. For example, if I have the following values:

‘1’, ’99’, ’10’, ‘HIGH’, ‘5’, ‘LOW’

I want the order to be

’99’, ’10’, ‘5’, ‘1’, ‘HIGH’, ‘LOW’

How to store local storage value as a JavaScript array [duplicate]

so I have this in my local storage at the moment.
enter image description here

I would like to store these objects into an array, so that it looks like this.
Do you guys have any ideas? Ive been stuck on this for so long…

let brickArr = [
  {brick0: { id: '0', name: 'brick0', price: 0.50}},
  {brick1: { id: '1', name: 'brick1', price: 0.50}},
  {brick2: { id: '2', name: 'brick2', price: 0.50}}
]

How to load script that uses `window` object in jsdom (jest)

I am a beginner to jest, not sure how do I test a script that’s suppossed to be run in the dom, if possible I don’t want to load the dom, just app.env.js

  • app.env.test.js
/**
 * @jest-environment jsdom
 */

test("Contains environment", () => {
  console.log(window.APP_ENV);
  expect(process.env.NODE_ENV).toBe("local");
});
  • app.env.js
window.APP_ENV = Object.freeze({
  env: "local",
});

FirebaseError: Function setDoc() called with invalid data. Unsupported field value: undefined

I want to save order details to my firestore db,Here my orderDetails:

const orderDetails=[{
                      id:"ID1",
                      name:"foo"
                     },
                     {
                     id:"ID2",
                     name:"foo-foo"
                     },
                     ]

Here is the code for adding this order Details to fire store:

setDoc(userOrderRef,{
     
      orders: orderDetails,
      created :1213,
      amount :13132
   

   },{merge:true})

But this throw an error :

 FirebaseError: Function setDoc() 
 called with invalid data. Unsupported
 field value: undefined

Can anyone help me with this?

How to get episode name where the character appeared for the first time? (Rick&Morty api)

I’m trying to create Rick&Morty page like the original Rick&Morty-api

But I have problems with the First seen in: line , where you can see on which episode the character appeared for the first time.

My code below, I’ve used useEffect to get all characters and rendered them. It was the easest part, but I don’t understand how to get name of episodes , where character appears for the 1st time. And It should work on each page, when I change my page by my pagination. Maybe I should match episodes id with characters id. I really want to work out this problem.
So please direct me somehow:)

import {
  Card,
  CardContent,
  CardMedia,
  Container,
  Pagination,
  Typography,
} from "@mui/material";
import { Box } from "@mui/system";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

export function RickAndMorty() {
  const [characters, setCharacters] = useState([]);
  const [episodes, setEpisodes] = useState([]);
  const [totalPages, setTotalPages] = useState(0);
  let [page, setPage] = useState(1);
  let [episodePage, setEpisodePage] = useState(1);

  useEffect(() => {
    getAllCharacters();
  }, [page]);

  useEffect(() => {
    getAllEpisodes();
  }, []);


  function getAllEpisodes() {
    fetch(`https://rickandmortyapi.com/api/episode/?page=${episodePage}`)
      .then((res) => res.json())
      .then((data) => setEpisodes(data.info));
  }

 /*  function changeEpisodesPage() {
    if(episodes.next !== null) setEpisodePage(episodes.next);
    else if(episodes.prev !== null) setEpisodePage(episodes.prev);
  } */

  function getAllCharacters() {
    fetch(`https://rickandmortyapi.com/api/character/?page=${page}`)
      .then((res) => res.json())
      .then((data) => {
        setCharacters(data.results);
        setTotalPages(data.info.pages);
      });
  }

  
  
  return (
    <Container style={{ padding: 40 }} maxWidth="xl">
      <Container style={{ maxWidth: 1280 }}>
        <div>
          <h1
            style={{
              margin: 0,
              marginBottom: 40,
              fontSize: 100,
              fontWeight: 800,
              textAlign: "center",
              color: "rgb(32, 35, 41)",
            }}
          >
            The Rick and Morty
          </h1>
          <ul className="characters_list">
            {characters.map((character, index) => (
              <Card
                sx={{
                  display: "flex",
                  maxWidth: 600,
                  height: 220,
                  flexGrow: 1,
                }}
                key={index}
              >
                <CardMedia
                  component="img"
                  sx={{ width: 230 }}
                  image={character.image}
                  alt="Live from space album cover"
                />
                <Box
                  sx={{ display: "flex", flexDirection: "column", flexGrow: 1 }}
                >
                  <CardContent
                    className="character_card_content"
                    sx={{
                      flex: "1 0 auto",
                      backgroundColor: "rgb(60, 62, 68)",
                    }}
                  >
                    <Typography component="div" variant="h5">
                      <Link to={"/movies/"}>
                        <h2 className="character_title">{character.name}</h2>
                      </Link>
                    </Typography>
                    <Typography
                      fontFamily="Segoe UI"
                      color="white"
                      component="div"
                    >
                      <span className="character_status">
                        <span
                          className="status_icon"
                          style={{
                            backgroundColor:
                              character.status === "Alive"
                                ? "rgb(85, 204, 68)"
                                : character.status === "Dead"
                                ? "rgb(214, 61, 46)"
                                : "rgb(158, 158, 158)",
                          }}
                        ></span>
                        {character.status} - {character.species}
                      </span>
                      <Typography
                        fontFamily="Segoe UI"
                        fontWeight={500}
                        color="rgb(158, 158, 158)"
                        component="div"
                        marginTop={2}
                      >
                        <span>Last known location:</span>
                        <h3 className="character_location">
                          {character.location.name}
                        </h3>
                        <div style={{ marginTop: 16 }}>
                          <span>First seen in:</span>
                            <h3 className="character_location">
                             {character.episode[0].match(/d+/)}
                            </h3>
                        </div>
                      </Typography>
                    </Typography>
                  </CardContent>
                </Box>
              </Card>
            ))}
          </ul>
        </div>
        <Pagination
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
          count={totalPages}
          page={page}
          shape="rounded"
          onChange={(e, page) => setPage(page)}
        />
      </Container>
    </Container>
  );
}

My result

Node.js: ECONNRESET when making multipart/form-data post request?

I am getting the following error:

(node:12268) [https://github.com/node-fetch/node-fetch/issues/1167] DeprecationWarning: form-data doesn't follow the spec and requires special treatment. Use alternative package
(Use `node --trace-deprecation ...` to show where the warning was created)
FetchError: request to https://api.nordigen.com/v2/report failed, reason: socket hang up
    at ClientRequest.<anonymous> (file:///home/doejohn/www/work/johndoe/backend/Scripts/nordigen-scripts/node_modules/node-fetch/src/index.js:108:11)
    at ClientRequest.emit (node:events:539:35)
    at TLSSocket.socketCloseListener (node:_http_client:427:11)
    at TLSSocket.emit (node:events:539:35)
    at node:net:709:12
    at TCP.done (node:_tls_wrap:582:7) {
  type: 'system',
  errno: 'ECONNRESET',
  code: 'ECONNRESET',
  erroredSysCall: undefined
}

When I do the following request:

  const data = new FormData();
  data.append("input", file);
  const init = {
    method: "POST",
    headers: {
      Authorization: `Bearer ${oauthToken}`,
    },
    body: data,
  };
  fetch("https://api.nordigen.com/v2/report", init)
    .then((res) => res.json())

I got it working perfectly with Python. But somehow when converting it to Node.js I seem to be doing something wrong.

resReport = requests.post("https://api.nordigen.com/v2/report", files={'input': open('test2.json', 'rb')}, headers={"Authorization": f"Bearer {token}"})

The file input at node.js and python are same file on disk. I also checked the auth token and it is correct.

The docs at the API have the following curl request as example:

curl -X POST 
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' 
-F [email protected] 
https://api.nordigen.com/v2/report

How to solve this?

I want to be able to change the content of modal each time the map function iterates

I want to use the map function to show on the same modal different content and update them when necessary, I decided to go with props and I don’t get why it isn’t working.

This is my Parent component

<div
      style={{
        display: "flex",
        justifyContent: "space-between",
        fontWeight: 600,
      }}
    >
      {Res.AdmissionsRes.slice(0, 3).map((admission, index) => (
        <S.BackCardGuIn
          bR="16px"
          bg="#f8f9fa"
          bS="0 1px 2px 0 rgb(60 64 67 / 30%), 0 1px 3px 1px rgb(60 64 67 / 15%)"
          style={{ textAlign: "center" }}
          height="32rem"
          width="calc(100% - 190px)"
          padding="0"
          margin="2%"
        >
          <S.BackCardGuInCir
            border="none"
            // bR="20px"
            // bBL="0"
            // bBR="0"
            bPos="center"
            bg={admission.programImg}
            bSize="cover"
            position="relative"
            top="30px"
            width="9rem"
            height="9rem"
          />
          <p
            style={{
              textAlign: "center",
              fontSize: "20px",
              lineHeight: "28px",
              fontWeight: 600,
              marginTop: "35px",
            }}
          >
            {admission.programType}
          </p>
          <p
            style={{
              fontWeight: 500,
              textAlign: "center",
              minHeight: "40px",
            }}
          >
            Accelerate your growth in the medical domain with the fully
            managed RHIBMS school which stands at {admission.programFee}
          </p>
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <S.ApplyForThis  onClick={()=> {
              setProgramInstance(admission)
              handleShow();
              }}>
              View All {admission.programType.slice(0, 3)}
            </S.ApplyForThis>
            <Modal
              title={admission.programType}
              programImg={admission.programImg}
              programFee={admission.programFee}
              onClose={() => setShow(false)}
              show={show}
            />

            
          </div>

My Modal component is below

<E.Modal onLoad={()=>setProgramType(`${props.title}`)} onClick={props.onClose}>
 
  <E.ModalContent
    className="animate__animated animate__bounceInUp"
    onClick={(e) => e.stopPropagation()}
  >
    <E.ModalHeader>
      <E.ModalTitle></E.ModalTitle>
    </E.ModalHeader>
    <E.ModalBody>
    <S.BackCardGuInCir
            border="none"
            // bR="20px"
            // bBL="0"
            // bBR="0"
            bPos="center"
            bg={props.programImg}
            bSize="cover"
            position="relative"
            top="0"
            width="22rem"
            height="22rem"
          />
      <ProgramTable tuition={props.programFee} title={props.title}/>
    </E.ModalBody>
    <E.ModalFooter>
      <E.ModalBtn onClick={props.onClose}>Close!</E.ModalBtn>
    </E.ModalFooter>
  </E.ModalContent>
</E.Modal>

So far, only the last object is rendering on the modal always and not updating. I’m really stuck!

Animation on form React

I am stuck, I am adding amination on form on every radio button click, next question should Slide Up , but this is not happening sliding is happening only on first question.

<CSSTransition classNames="fade"
    in={expanded}
    timeout={300}
    
    unmountOnExit
  >   
        <Card variant="outlined" sx={{ bgcolor: "#bea"}} elevation={0}>
            <CardContent>
           
            <form onSubmit= {handleSubmit}>
                    <CardActions>
                  <Button type="submit" color="warning" variant="outlined" className={classes.button} onClick={previousQuestion}>
                      Previous</Button>
                  </CardActions>
                 
                  <FormControl component='fieldset' className={classes.formControl}
    data-hidden={questions[currentQuestion].number !==
      currentQuestion[questions[currentQuestion].number]}>
    <FormLabel component='legend'>
      {questions[currentQuestion].question}
    </FormLabel>
    <FormLabel component='legend'>
      {questions[currentQuestion].description}
    </FormLabel>
    <RadioGroup
      aria-label='quiz'
      name='quiz'
      value={questions[currentQuestion].value}
      onChange={(e)=> handleRadioChange(questions[currentQuestion].number, e)}
      sx={{
        color: pink[800],
        '&.Mui-checked': {
          color: pink[600],
        },
      }}>
      {options.map((option) => (
        <FormControlLabel
          key={option.score}
          value={option.score}
          control={<Radio  sx={{
            color: pink[800],
            '&.Mui-checked': {
              color: pink[600],
            },
          }}/>}
          label={option.label}
        />
      ))}
    </RadioGroup>
  </FormControl>

                    <CardActions>
                    <Button type="submit" variant="outlined" color="primary" className={classes.button} onClick={handleSubmit}>
                    Submit
                </Button>
              </CardActions>

                </form>
          
             
                </CardContent>
                </Card>
                </CSSTransition>

The css is

.fade-enter {
    opacity: 0;
  }
  
  .fade-enter.fade-enter-active {
    opacity: 1;
    transition: opacity 0.5s ease-in-out 0.3s;
  }
  
  .fade-leave {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    opacity: 1;
  }
  
  .fade-leave.fade-leave-active {
    opacity: 0;
    transition: opacity 0.5s ease-in-out;
  }

The animation is not working. Please help in finding out. I want every question to fade Out on radio button click. But this occurs only on the first but after that there is no transition.

puppeteer selector works for .querySelectorAll() but not .$$()

I’m trying to run the following selector through puppeteer page.$$(".paging:not(.ng-hide) button.paging-button")
This returns an empty array, but when I go to the page and run document.querySelectorAll(".paging:not(.ng-hide) button.paging-button") I get two elements (which is what I want) It’s my understanding that puppeteer uses document.querySelectorAll() under the hood but I don’t know why my selector is broken in puppeteer. Could it be my use of :not()? My query won’t work without that selector since there’s n amount of elements that match my selector without it but only 2 that don’t have the .ng-hide class

Here’s my code

async function advancePage(page)
{
    const pagingButton = await page.$$(PAGING_BUTTON)[1];
    console.log(pagingButton)
    let adHocs = await getCalcsOnPage(page);
    const isButtonDisabled = await page.evaluate(el=>el.disabled,pagingButton)
    if(isButtonDisabled)
    {return adHocs}
    else{
        console.log(chalk.bgBlue("ADVANCING PAGE"))
        await pagingButton.click();
        const nextPageCalcs = await advancePage()
        adHocs.concat(nextPageCalcs)
        return adHocs
    }
    
}

and I have my selectors declared in another file

export const PAGING_BUTTON = ".paging:not(.ng-hide) button.paging-button"