node.js puppeteer “document is not defined”

I am attempting to try click a button using code without an id or class, but my terminal always responds with:

document.getElementsByTagName("Accept Cookies");
    ^

ReferenceError: document is not defined

This is my code:

const puppeteer = require('puppeteer');

const product_url = "https://www.nike.com/launch"

async function givePage() {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    return page;
}

async function acceptCookies(page) {
    await page.goto(product_url);
    const btn = await page.waitForSelector('#cookie-settings-layout > div > div > div > 
div:nth-child(3) > div.ncss-col-md-6.ncss-col-sm-12.mb5-sm > button')
    await btn.click()
}

async function notifyMe(page) {
    await page.goto(product_url);
    document.querySelector("button[type="submit"]").click("Notify Me");
}

async function checkout() {
    var page = await givePage();
    await acceptCookies(page);
    await notifyMe(page);
}

checkout();

What did I do wrong and how can I fix this?

Firebase createUserProfileDocument() is returning undefined

As the title says, the createUserProfileDocument() method from firebase is returning undefined for some reason, therefore, it’s throwing an error on my broswer’s console.

The error that is being thrown is: App.js:23 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onSnapshot') at App.js:23:1

Please find the code below:

import './App.css';
import { connect } from 'react-redux';
import { Switch, Route } from 'react-router-dom';
import HomePage from './pages/homepage/homepage.component';
import ShopPage from './pages/shop/shop.component';
import Header from './components/header/header.componet';

import { auth, createUserProfileDocument } from './firebase/firebase.utils';
import SignInAndSignUpPage from './pages/sign-in-and-sign-up/sign-in-and-sign-up.component';
import { setCurrentUser } from './redux/user/user.actions';

class App extends React.Component {
    unsubscribeFromAuth = null;

    componentDidMount() {
        const { setCurrentUser } = this.props;

        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
                console.log(userRef);
                userRef.onSnapshot((snapshot) => {
                    setCurrentUser({
                        id: snapshot.id,
                        ...snapshot.data(),
                    });
                });
            }
            setCurrentUser(userAuth);
        });
    }

    componentWillUnmount() {
        this.unsubscribeFromAuth();
    }

    render() {
        return (
            <div className='App'>
                <Header />
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route exact path='/shop' component={ShopPage} />
                    <Route
                        exact
                        path='/signin'
                        component={SignInAndSignUpPage}
                    />
                </Switch>
            </div>
        );
    }
}

const mapDispatchToProps = (dispatch) => ({
    setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});

export default connect(null, mapDispatchToProps)(App);

The portion of code related to my error is the following:

componentDidMount() {
        const { setCurrentUser } = this.props;

        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
                console.log(userRef);
                userRef.onSnapshot((snapshot) => {  // This is Line 23......
                    setCurrentUser({
                        id: snapshot.id,
                        ...snapshot.data(),
                    });
                });
            }
            setCurrentUser(userAuth);
        });
    }

I console.logged(userRef) as you can see, and it returns undefined. This is my first experience with firebase so I am not sure where the error is.

I googled and found an answer here in stackoverflow which is alike to my issue: TypeError: Cannot read properties of undefined (reading ‘onSnapshot’)

However, that problem is specifically related to how the developer was passing the method as an array and not a method, which does not help my situation.

Please don’t downvote my question in case of finding it wrong, please suggest edits instead, since I am kind of new to stackoverflow and a complete noob to firebase.

Thanks a lot in advance for your help!

Attempting to make Ray Tracing inside of p5.js but function recursion is acting weird

So, I found a source online that went over ray tracing for c++ (https://www.scratchapixel.com/code.php?id=3&origin=/lessons/3d-basic-rendering/introduction-to-ray-tracing)

I decided to go into p5.js and attempt to replicate what they have in their source code, but ran into an error when I got to function recursion. To add reflections they used recursion and ran the same function again, but when I attempt the same thing I get all sorts of incorrect outputs… This is my code:
https://editor.p5js.org/20025249/sketches/0LcyoY8yS

function trace(rayorig, raydir, spheres, depth) {
  let tnear = INFINITY;
  let sphere;
  
  // find intersection of this ray with the spheres in the scene
  for (let i = 0; i < spheres.length; i++) {
    t0 = INFINITY;
    t1 = INFINITY;
    if (spheres[i].intersect(rayorig, raydir)) {
      if (t0 < 0) t0 = t1;
      if (t0 < tnear) {
        tnear = t0;
        sphere = spheres[i];
      }
    }
  }
  
  // if there's no intersection return black or background color
  if (!sphere) return createVector(2, 2, 2);
  
  let surfaceColor = createVector(0); // color of the ray/surfaceof the object intersected by the ray
  let phit = createVector(rayorig.x, rayorig.y, rayorig.z).add(createVector(raydir.x, raydir.y, raydir.z).mult(tnear)); // point of intersection
  let nhit = createVector(phit.x, phit.y, phit.z).sub(sphere.center); // normal at the intersection point
  nhit.normalize(); // normalize normal direction
  
  // If the normal and the view direction are not opposite to each other
  // reverse the normal direction. That also means we are inside the sphere so set
  // the inside bool to true. Finally reverse the sign of IdotN which we want
  // positive.
  let bias = 1e-4; // add some bias to the point from which we will be tracing
  let inside = false;
  if (createVector(raydir.x, raydir.y, raydir.z).dot(nhit) > 0) {
    nhit = -nhit;
    inside = true;
  }
  
  if ((sphere.transparency > 0 || sphere.reflection > 0) && depth < MAX_RAY_DEPTH) {
    let facingratio = createVector(-raydir.x, -raydir.y, -raydir.z).dot(nhit);
    // change the mix value to tweak the effect
    let fresneleffect = mix(pow(1 - facingratio, 3), 1, 0.1);
    // compute reflection direction (not need to normalize because all vectors
    // are already normalized)
    let refldir = createVector(raydir.x, raydir.y, raydir.z).sub(createVector(nhit.x, nhit.y, nhit.z).mult(2).mult(createVector(raydir.x, raydir.y, raydir.z).dot(nhit)));
    refldir.normalize();


    // Here is the error:
    let reflection = trace(createVector(phit.x, phit.y, phit.z).add(createVector(nhit.x, nhit.y, nhit.z).mult(bias)),
                           refldir,
                           spheres,
                           depth+1
                          );


    let refraction = createVector(0);
    // // if the sphere is also transparent compute refraction ray (transmission)
    // if (sphere.transparency) {
    //   let ior = 1.1
    //   let eta = (inside) ? ior : 1 / ior; // are we inside or outside the surface?
    //   let cosi = createVector(-nhit.x, -nhit.y, -nhit.z).dot(raydir);
    //   let k = 1 - eta * eta * (1 - cosi * cosi);
    //   let refrdir = createVector(raydir.x, raydir.y, raydir.z).mult(eta).add(createVector(nhit.x, nhit.y, nhit.z).mult(eta *  cosi - sqrt(k)));
    //   refrdir.normalize();
    //   refraction = trace(createVector(phit.x, phit.y, phit.z).sub(createVector(nhit.x, nhit.y, nhit.z).mult(bias)),
    //                      refrdir,
    //                      spheres,
    //                      depth + 1
    //                     );
    // }
    // the result is a mix of reflection and refraction (if the sphere is transparent)
    surfaceColor = (
      createVector(reflection.x, reflection.y, reflection.z)
        .mult(fresneleffect)
        .add(
          createVector(refraction.x, refraction.y, refraction.z).mult(1 - fresneleffect).mult(sphere.transparency)
        )
    )
    .mult(sphere.surfaceColor);
  }
  return createVector(surfaceColor.x, surfaceColor.y, surfaceColor.z).add(sphere.emissionColor);
}

The error is that the reflections don’t give me the same output as the c++ script and seems to be wonky. I cannot for the love of me figure out why the recursive function just doesn’t work.

I have attempted to run it without the recursion and it worked perfectly fine but the recursion is where is breaks

The way I found the error was by printing on the original c++ script and printing on the one I was making and it all works up until the recursive reflections. I get the correct first output but then it all goes down hill.

Their outputs:

[-0.224259 3.89783 -19.1297]
[-0.202411 3.88842 -19.0835]
[-0.180822 3.88236 -19.0538]

My outputs:

[-0.224259 3.89783 -19.1297] // correct
[-0.000065 0.001253 -0.005654] // incorrect
[-0.000064 0.00136 -0.00618] // incorrect

Summary: I made a function that works but the recursion breaks it and I cannot figure out why

Unable to assign a variable as a arithmetic operator in javascript while making a calculator

Hello I was making a calculator
But i am unable to play arithmetic operators in it please solve it. because it was not checking it as a arithmetic operator it was checking it as string. And if i assisgn + like this var a = + ; it gives me an error that unexpected token }

Html code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <ulnk rel="stylesheet" href="css/index.css">
  <script src="js/index.js"></script>
  <title>CALCULATOR </title>
</head>
<body>
<!------------------------------------------->

<input readonly="true" type="text" id="value"></input>
<button id="result" ></button>

<ul><button onclick="one()" >1</button></ul>    
<ul><button onclick="four()" type="submit">4</button></ul>
<ul><button onclick="seven()" type="submit">7</button></ul>
<ul><button onclick="zero()" type="submit">0</button></ul>
<ul><button onclick="Add()" type="submit">+</button></ul>
<ul><button onclick="RESULT()" type="submit">=</button></ul>
<!------------------------------------------->
</body>
</html>

Js code

function one() {
var value = document.getElementById("value")
var input = value.value +="1"

}
function RESULT() {
var value = document.getElementById("value")
var input = value.value
var result = value.value
}
function Add() {
var value = document.getElementById("value")
var input = value.value +='+'
}
function four() {
var value = document.getElementById("value")
var input = value.value +=4
}
function seven() {
var value = document.getElementById("value")
var input = value.value +=7
}
function zero() {
var value = document.getElementById("value")
var input = value.value +=0
}
function RESULT() {
var result = document.getElementById("result")
var value = document.getElementById("value").value
var results_value =parseInt(value);
var results_value2 = result.innerHTML=results_value
}

HTML JS trigger button enter

Was trying to get this working that I saw from another post here. I got it working but I can get the enter to work. I tried to tie in https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter but for the life of me cant get both to work.

Hope someone can help!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

    $('#button').click(function(e) {  
        var inputvalue = $("#input").val();
        window.location.replace(" http://www.example.com/page/"+inputvalue);

    });
});
</script> 
</head>
<body>

       <input type="text" value="11" id="input"> 
       <button type="button" id="button">Click Me!</button>
</body>
</html>

Get value from few Select in Material-UI

I have two MUI Select components on my page. I’m trying to set values depends on id of Select. I’ve checked (id === “breed-select”) in console and (at first) it’s true, but immediately after that it become false, and i cant understand why. Where i made a mistake? May be there is a better way to set values of two Select components?

import React from 'react';
import './AddCatPopup.css';
import {Box, Button, FormControl, InputLabel, MenuItem, Select, TextField} from '@mui/material';
import {theme} from '../../theme';
import {ThemeProvider} from '@mui/material/styles';

function AddCatPopup({ breeds, isOpen, onClose, onAddCat }) {

  const breedsName = breeds.map(item => item.nameBreed);

  const colorsArray = [
    'black',
    'white',
    'grey',
    'red',
    'multicolor'
  ];

  const [name, setName] = React.useState('');
  const [price, setPrice] = React.useState(0);
  const [color, setColor] = React.useState('');
  const [age, setAge] = React.useState(0);
  const [breed, setBreed] = React.useState('');

  function handleChange(event) {
    const {
      target: { value, id }
    } = event;
    id === "breed-select" ? setBreed(value) : setColor(value);
  }

  function handleSubmit(e) {
    e.preventDefault();
  }

  return(
    <section className={`popup ${isOpen && 'popup_opened'}`}>
      <div className={'popup__container'}>
        <button type="button" className={'popup__close-btn'} onClick={onClose}></button>
        <p className={'popup__title'}>Enter info about cat</p>
        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Name"
                   required />

        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Price"
                   required />

        <FormControl sx={{ mt: 1, mb: 1 }}
                     variant="standard"
                     required>
          <InputLabel id="breed-label">Breed</InputLabel>
          <Select
            labelId="filter-breed"
            id="breed-select"
            label="Breed"
            value={breed}
            onChange={handleChange}
          >
            {breedsName.map((item) => (
              <MenuItem
                key={item}
                value={item}
                id="breed-select"
                onClick={handleChange}
              >
                {item}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <FormControl sx={{ mt: 1, mb: 1 }}
                     variant="standard"
                     required>
          <InputLabel id="color-label">Color</InputLabel>
          <Select
            labelId="filter-color"
            id="color-select"
            label="Color"
            value={color}
          >
            {colorsArray.map((item) => (
              <MenuItem
                key={item}
                value={item}
                id="color-select"
                onClick={handleChange}
              >
                {item}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Age"
                   required />

        <ThemeProvider theme={theme}>
          <Button sx={{ mt: 1, mb: 1 }}
                  variant="contained"
                  color={'secondary'}
                  onClick={handleSubmit}>
            Add
          </Button>
        </ThemeProvider>

      </div>
    </section>
  );
}

export default AddCatPopup;

How Can I target single item by map button in React Typescript?

So I have a functional components here:

export default function Test() {
    const [products, setProduct] = useState<any>([]);
    const [image, setImage] = useState<any>([""]);
    const [prices, setPrice] = useState<any>([]);
    const [showPrice, setShowPrice] = useState<boolean>(false);
    const [PhonePrice, setPhonePrice] = useState<any>("");


    useEffect(() => {
        async function loadProducts() {
            const res = await fetch("http://raw.githubusercontent.com/reborn094/Practice/main/data.json", {
                method: "GET",
            });
            const json = await res.json();
            const data = json.products;

            setProduct(data);

    return (
        <div>
                    {products.map((product: any, index: number) => {
                        return (
                            <Col>
                                <Card key={index} style={{ width: "20rem" }}>
                                    <Card.Body>
                                        <Card.Title>
                                        </Card.Title>
                                        <Card.Title>
                                            <Child ProductImage={image[index]} name={product.name} code={product.code}  onSelectProduct={()=>{  
                                             

> 

what should I write here????
------------------------

   
                                            }}
                                            ></Child>
                                           
                                        </Card.Title>
                                        <Card.Text></Card.Text>
                                    </Card.Body>
                                </Card>
                            </Col>
                        );
                    })}
        </div>
    );
}

And here is my Child components :

export default function Child(props:{
    onSelectProduct?:()=> void;
}) {
  return (
      <div>
        <Button onClick={props.onSelectProduct}></Button>
    </div>
  )
}

My question is What if I want to set button in Test components to target single item in list, what should I do? Because Now If I set Button that Button would trigger all item.What should I do in the function onSelectProduct?

JSON parse in Javascript with [ [duplicate]

I am trying to parse this JSON file. I was able to get temp easy but I am not able to get main from the weather. I assume this is due to the “weather”: [ than normal JSON file.

Does anyone know how to parse this correctly to be able to access the weather.main data.

JSON file:

{
  "coord": {
    "lon": -4.5063,
    "lat": 55.6787
  },
  "weather": [
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 3.72,
    "feels_like": 1.32,
    "temp_min": 3.07,
    "temp_max": 4.94,
    "pressure": 1024,
    "humidity": 75
  }

Here is my current parser:

async function getWeather(lat, lon) {
  const params = new URLSearchParams({
    lat,
    lon,
    units: "metric",
    appid: API_KEY,
  })
  return fetch(`https://api.openweathermap.org/data/2.5/weather?${params}`)
  .then(function (response) {
    return response.json()
  }).then(function (obj) {
    console.log(obj.main.temp)
    weatherTemp = obj.main.temp;
    console.log("OBJ" + obj.weather.main) // does not work, return undefined. Not able to access
    //weatherType = obj.weather.main;
    // print();
    // ContextMerge();
  }).catch(function (error) {
    console.log("Something went wrong" + error)
  });
  }

Nodejs Require is not defined while using reverse shell

If require is not available, to obtain the require by:

process = this.constructor.constructor(‘return (function(){return process})()’)();
var require = process.mainModule.require;

used

shell = ‘process = this.constructor.constructor(‘return (function(){return process})()’)();’

shell += ‘var require = process.mainModule.require;’

Errors: process is not defined
if we add const before process
Errors: mainModule is not defined

How do we import process without Require , and how do we process the code to server

Destructuring object with inner array without all keys

I have an object like this:

const objBefore: 
{
    "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1",
    "number": "5000",
    "enabled": true,
    "classes": [
        {
            "id": "2fc87f64-5417-4562-b3fc-2c963f66afa4",
            "name": "General"
        },
        {
            "id": "7ffcada8-0215-4fb0-bea9-2266836d3b18",
            "name": "Special"
        },
        {
            "id": "6ee973f7-c77b-4738-b275-9a7299b9b82b",
            "name": "Limited"
        }
    ]
}

Using es6, I want to grab everything in the object except the name key of the inner classes array to pass it to an api.

So:

{
    "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1",
    "number": "5000",
    "enabled": true,
    "classes": [
        {"id": "2fc87f64-5417-4562-b3fc-2c963f66afa4"},
        {"id": "7ffcada8-0215-4fb0-bea9-2266836d3b18"},
        {"id": "6ee973f7-c77b-4738-b275-9a7299b9b82b"}
    ]
}

The closest I got was: let {id, number, enabled, classes: [{id}]} = objBefore;

But it only gets me one id in classes. I’ve tried spreading above using [...{id}] or [{...id}]. Same thing.

I find it challenging to get the right mental model for how to think about this when it’s on multiple levels. In my mind, when I say [...{id}] I’m thinking, “I want the id property as an object in the outer classes array, but give me every id in the array!”

Clearly I’m not thinking about this correctly.

I’ve tried it using map to get that part but I’m still having trouble combining it back to the original to produce the desired result. for example:

let classIds = objBefore.classes.map(({id}) => {
    return {
        id 
    }
})

(Using the map syntax, how can I destructure in the function the other keys that are one level higher?)

To combine them I started trying anything and everything, :

let {id, number, enabled, classIds} = {objBefore, [...classIds]} // returns undefined for all

I’d prefer to do it in one statement. But if that’s not possible, then what’s a clean way to do it using map?.

How do you avoid an SQL injection vulnerability without a query builder or an ORM?

Suppose I have a function that looks like the following (ignore any syntax errors here unless they are relevant to the question, I’m new to SQL):

// This function updates the database using the command passed as a parameter
const execute = async (command) => {
    open({
        filename: "test.db",
        driver: sqlite3.Database,
    }).then((db) => {
        db.exec(command);
    });
};

// Takes the user ID and their input and adds it to the database
const createBlogPost = async (userId, text) => {
    await execute(`INSERT INTO posts (user_id, post) VALUES ("${userId}", "${text}");`)
}

There is nothing stopping the user from injecting their own SQL into the blog post text field. Wouldn’t they be able to execute any command they want as long as the syntax is correct? I’m wondering if there’s anything extra you’re supposed to do in order to prevent this, or if it’s best practice to just use an ORM rather than building your own SQL statements.

Many thanks.

Disconnect MutationObserver wrapped in self invoking function

I have created a JavaScript that uses MutationObserver to watch for changes to a website in the console. The script would retrieve some values from a div, log the accumulated sum and also create some elements on the page (omitted in the code below for simplicity).

I wrap the MutationObserver in a self Invoking function to prevent the variables from colliding with the ones used by the website.

Occasionally the script may fail (the script is not robust enough to deal with some differences in pages) and what I am doing is to log out of the page, paste a different script onto the console to make it work again. Or else the sum would be incorrect and the elements would be created in the wrong place.

I understand that the MutationObserver is on its own scope so observer.disconnect(); would not work. Is there other way to disconnect the MutationObserver in the console without having to refresh/log out of the page?

Here is the simplified version of my code:

(function () {  
    const targetNode = document.querySelector('div.content')
    const observerOptions = { childList: true, attributes: false, subtree: false }
    const callback = function (mutationsList, observer) {
      for (const mutation of mutationsList) {
        if (mutation.removedNodes.length > 0 && (mutation.removedNodes[0].classList.contains('some-view'))) {
            // do something here
        }
        if (mutation.addedNodes.length > 0 && (mutation.addedNodes[0].classList.contains('some-view'))) {
            // do something here
        }
      }
    }
  
    const observer = new MutationObserver(callback)
    observer.observe(targetNode, observerOptions)
  })()

Thank you.

Why Instagram “shortcode_media” is undefined?

I was trying to use a library to download videos from instagram, and it uses graphql, but it only downloads videos every now and then, other times it returns an error. The error:

TypeError: Cannot read properties of undefined (reading 'shortcode_media')

The code:

    async function downloadMetaData(url) {
      try {
        const metaData = await axios({
          method: "get",
          url: url,
        });
        return metaData.data.graphql;
      } catch (error) {
        throw error;
      }
    }
    
    function getMediaType(mediaData) {
      if (mediaData.shortcode_media.is_video === true) {
        return "video";
      }
      return "image";
    }

The link of library (if you need local tests)

Could anyone give me a suggestion on how to solve it or recommend another lib?