I want to link 2 websites with the onclick property

i made a login page and a content page. i made it so when i press the login button the content page will open in a new tab but i want it to open in the same tab i tried window.location.href but it dosent work for some reason.

function validate()
{
var username=document.getElementById("email").value;
var password=document.getElementById("password").value;
if(username=="marin" && password=="12345678") 
{
    
    window.open("file:///C:/Users/lukam/OneDrive/Radna%20povr%C5%A1ina/stranica/stranica1_1.html")
    return false;
}
else
{
    alert("login je pogresan")
}

}

How to use map function on object containing different key in select tag

need to show Movies in the select tag in which options are 2018,2019,2020 etc and when a year gets selected need to show corresponding Movies

const data = {
  2018: ["Avengers 1", "Now you see me", "Fast and Furious 7"],
  2019: ["Avengers 2", "Now you see me 2", "Fast and Furious 8"],
  2020: [
    "Final Avengers Movie(Iron man dies)",
    "Now you finally used Lenskart",
    "Covid Came",
  ],
  2021: ["Covid Returns"],
  2022: ["Adventures of Saiman", "Adventures of Shaktiman"],
};

const App = () => {
  const [option, setOption] = useState([]);
  
  return (
    <div id="main">
      <select name="select">
        {Object.keys(data).map((year) => (
          <option value={year}>{year}</option>
        ))}
      </select>
    </div>
  );
}

when do we need to put a parameter for the event handler

I am confused about events and event handlers, sometimes we call a function with an event handler and put a parameter for it and sometimes we do not. when do I put parameters and when is it necessay?

Here is an example:

<!DOCTYPE html>
<html>
<body>

<h2 onclick="showCoords(event)">Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer, relative to the screen, 
when it is clicked.</h2>

<p><strong>Tip:</strong> Try to click different places in the heading.</p>

<p id="demo"></p>

<script>
function showCoords(event) {
  var x = event.screenX;
  var y = event.screenY;
  var coords = "X coords: " + x + ", Y coords: " + y
  document.getElementById("demo").innerHTML = coords;
}
</script>

</body>
</html>

where the showCoords has a parameter called event. This code is from W3Schools.

What is the correct way of embedding tweets using twitter api

I am working on a website where I want to show the most recent 3 tweets from my Twitter profile. There is a way to embed the tweets by using the publish.twitter.com URL, the problem with this method is that I cannot style my embedded tweets and it doesn’t even show the number of likes and retweets. I want to get the recent tweets using the Twitter API where I am in control of the embedded tweets and can style them.
here is what I am using to embed tweets on my website.

<div class="twitter-feed" style="display:flex; align-items:center; justify-content:center;">
     <a class="twitter-timeline" href="https://twitter.com/dev_taimoor?ref_src=twsrc%5Etfw">Tweets by dev_taimoor</a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>

I need to know a way of using Twitter API through javascript so that I can fetch tweets. I did some research but none of the articles were helpful for me.

How to interact with JS-set cookies page by python

I’m trying to create the webparser for the .onion based resource, for which I need to pass some authorization logic. Usually the requests.Session object is enough, but this time I encountered the resource doing something like this:

At the first time you send the GET request, it opens a page with scripts only:
function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("d2ad7e1fdeadbe9fdeadbeefdefdbeef"),b=toNumbers("deade7efdecdbeefdebdbeefde9d3eef"),c=toNumbers("c660404a82c064124f667bfbe384c9b6");document.cookie="MON="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";location.href=/

Then it calculates cookies and attaches them to your session. After that it opens the website automatically. I can use this script within the console by hand, but I have no idea how to pass this via python.
I tried requests_html, but it couldn’t open an .onion link in html.render().

Is there a way to mimic this JS code inside python or run it with JS inside the request?

Why does filtering returned on a multi-level object behave differently if the object was only 1 level deep?

Filtering a multi-level object I was reading up on Array.prototype.filter() and ran across this answered one liner.

In testing if my object is one line, example:

const listToDelete = ['medium', 'large']

const pizzaObj = [
      {
        id: 'small',
        name: 'Small',
      },
      {
        id: 'medium',
        name: 'Medium',
      },
      {
        id: 'large',
        name: 'Large',
      },
      {
        id: 'xlarge',
        name: 'X Large',
      },
    ]

const result = pizzaObj.filter( el => (-1 == listToDelete.indexOf(el.id)) )
console.log(result)

my constant returned is correct but if I’m trying to filter out from a multi-level object, example:

const listToDelete = ['medium', 'large']

const pizzaObj = [
  {
    id: 'mon',
    name: 'Monday',
    subMenu: [],
  },
  {
    id: 'tues',
    name: 'Tuesday',
    subMenu: [
      {
        id: 'small',
        name: 'Small',
      },
      {
        id: 'medium',
        name: 'Medium',
      },
      {
        id: 'large',
        name: 'Large',
      },
      {
        id: 'xlarge',
        name: 'X Large',
      },
    ],
  },
  {
    id: 'wed',
    name: 'Wednesday',
    subMenu: [],
  },
]

const result = pizzaObj.filter(l => {
  return Object.keys(l).map(key => {
    if (l.id === 'tues' && key === 'subMenu') return l['subMenu'].filter(el => -1 == listToDelete.indexOf(el.id))
  })
})
console.log(result)

my filtered sub object is not changed.

Research

How should I be mapping over a sub level object and filter out what I do not want based on the passed array?

Javascript Array.Filter method not working

im do not understand why this filter call is not working? it should be returning the one item that has the 100 dollar invoice but it is instead sending an empty set. What am i doing wrong?

const express = require('express');
const app = express();

app.listen(3000);
app.use(express.static('public'));
app.set('view engine', 'ejs');

const invoices = [
    {
        INVOICE_AMOUNT: 50
    },
    {
        INVOICE_AMOUNT: 100
    },
    {
        INVOICE_AMOUNT: 200
    }
];

app.get('/', (req, res) => {
    res.send(invoices.filter(x=>{x.INVOICE_AMOUNT==100}));
});

useEffect is always running in React js (firebase firestore is used)

  const [bag, setBag] = useState([]);

  const bagRef = collection(db, "users", auth.currentUser.email, "bag");

  const updateBag = () => {
    onSnapshot(bagRef, (snapshot) => {
      // ...
      setBag(
        snapshot.docs.map((doc) => ({
          id: doc.id,
          data: doc.data(),
        }))
      );
      console.log("run");
    });
  };

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

my problem is that the useEffect is always running, i can see that since ‘run’ is showing in my console, and my firestore usage is increasing tried passing different arguments in ‘[]’ such as bag, bagRef, auth.currentUser.email and it didn’t work. thx in advanced 🙂

TypeError: Super expression must either be null or a function message when I’m trying to export named class

I’m trying to test components. I already have a default export and believe I have to use a named class for my next export. Here is the code:

export default Users;

import React from 'react';

export class UsersTest extends React.Users {
    updateState(event) {
      this.setState({
          input: event.target.value
      });
    }
    render() {
      return <div><input
        onChange={this.updateState.bind(this)}
        type="text" /></div>;
    }
  }

Return value from externally called fs.Readfile() in node

I am trying to get a value returned from a function where I read and write a file using fs.readFile/writeFile in Node.

In my main server.js file, a request comes in and I then want to send an email from another file called sendEmail.js:

const fs = require('fs')
const sendMail = require('./sendEmail')

async function sendAnEmail() {
    let resultOfSend = await sendMail.sendEmail()
    resultOfSend.then((result)=>{
      // return the result
    }        
}

sendAnEmail();

In sendEmail I first read a file to get the email to send to,
then write to a second file
then, if all is good, I send an email (from a separate function):

async function sendEmail() {
    // Check if user exists
    fs.readFile('./file.json', (err, data) => {
        if(err) {
            throw error
        }
        else {
            let users = JSON.parse(data)
            let dataToWrite = JSON.stringify(users)

            fs.writeFile('./file2.json', dataToWrite, (err) => {
                if(err) {
                    console.error(err)
                    throw error
                }
                else {
                    return generateEmail(users)
                        .then((info) => {
                           return info
                        })
                        .catch(console.log('err'))
                }
            })
        }
    })
}

async function generateEmail(user) {
        let msgText = 'hello world'

        // Set the mail options
        const mailOptions = {
           ...
        }
        
        // Send the mail
    let info = await transporter.sendMail(mailOptions)
    return info
}

module.exports = {sendEmail}

What I can’t get is a value for the resultOfSend variable. Keeps coming back undefined, I think because the promise hasn’t yet been fulfilled.

How do I get a value to return from the sendEmail function back to the server.js file where it’s called from?

I get an arror for map function(posts.map is not a function)

I get this error, while I don’t see any issue in that:

posts.map is not a function

import React from 'react'
import { useSelector } from 'react-redux'

export const PostsList = () => {
  const posts = useSelector(state => state.posts)

  const renderedPosts = posts.map(post => (
    <article className="post-excerpt" key={post.id}>
      <h3>{post.title}</h3>
      <p className="post-content">{post.content.substring(0, 100)}</p>
    </article>
  ))

  return (
    <section className="posts-list">
      <h2>Posts</h2>
      {renderedPosts}
    </section>
  )
}

This is my code Sandbox: https://codesandbox.io/s/wandering-darkness-6hi04d?file=/src/features/posts/PostsList.js

Array excersize in Javascript

I have a function that
receives as an argument an array of numbers called ‘numbers’ and must return an
array containing the smallest number in the ‘numbers’ array at position zero and the largest number in the array ‘numbers’ in position 1.

  maxValue = Math.max(numbers)
  minValue = Math.min(numbers)
  varResult = ([minValue, maxValue]);

  for (let i = 0; i < numbers.length; i++) {
  console.log (varResult);
  } 
} ```

Propuesta Talently Full Stack Developer -Salario en Dólares

Idiomas requeridos
EspañolHablado:Alto -Medio -BajoEscrito:Alto -Medio -Bajo
InglésHablado:Alto -Medio -BajoEscrito:Alto -Medio -Bajo
Descripción de la oferta
Lo que hacemos en Talently es capacitar a developers que tengan más de 2 años de experiencia mediante un programa de entrenamiento intensivo para que puedan conseguir un nuevo trabajo remoto en las mejores empresas tech de USA y Latam y duplicar su salario actual en USD.
Deberás pagar una matrícula inicial y cuando consigas tu nuevo empleo deberás pagar (por una única vez) el 50% de tu primer nuevo salario. En caso de no conseguir tu nuevo trabajo te devolvemos el 100% del valor de tu matrícula.
El programa de Talently está 100% orientado al resultado y ya hemos ayudado a miles de developers de todo LatAm a posicionarse en las mejores empresas de la región y de Estados Unidos.
Para ingresar al programa deberás tener una entrevista de admisión donde te diremos si eres apto o no para ingresar, ya que solo admitimos developers que estén buscando un cambio laboral/aumentar su salario actual en USD.

Les dejo el link para que completen (se completa en 1 minuto) y ya alguien de admisiones se contactará con ustedes. Por favor, avisenme cuando lo hayan completado así corroboro que haya llegado OK la información.
Perfil/Requerimientos del candidato
2 o + años de experiencia desarrollando en cualquier lenguaje de programación actual. Experiencia comprobable en empresas.
Estudios requeridos/titulaciones
Full Stack Developer
Front End Developer
Back End Developer
Data Scientist
Cloud Architect
Software Developer
Software Engineer