Performant way to generate PNG from HTML?

I’m creating a PoC where the end-goal is to generate a PNG from a HTML page.
I’ve found many solutions, but the problem is the performance. My current implementation using headless chrome takes around 500ms to generate the PNG.
The goal is to replace an existing system which manages to generate a PNG in around 7ms.
I’m not sure if that kind of performance is possible with HTML, but if i can get to around 100ms, i could most likely reach the desired performance by horizontal scaling and load balancing.

Things i’ve tried:
Generate PNG using headless chrome
Generate PNG using Python (Selenium, Pillows etc.)

I’ve only got experience in Web technologies, but i’m open to any approach.

Some more (optional) context:
The system that i plan to replace takes batch requests of JSON data, generates a layout using this data and ultimately generates/saves a png. These request can range from anywhere between a few hundreds at a time to a million or more in extreme cases, so the system is very performant.
However, that performance comes at some cost. Creating new Layouts is a huge pain. There is no proper way to visualize the layout other than creating a png every time. Configurations like font, font-size, etc. are a pain. Handling edge-cases (what to do if text exceeds length, image is too big etc.) is a pain.
Basically, the current system is very performant, but it’s absolutely not suited for implementing new layouts, which we have to do.

How to determine the drop zone for a multi drag-and-drop file uploader?

Question

How do I accurately determine which drop zone the file was dropped into?

Background

I’m creating an HTML page with vanilla JavaScript that has 2 drop zones for 2 different file types, and depending on which drop zone the file is sent to, the files should ultimately be sent to a different endpoint.

Drop Zone HTML

  <div class="drop-area" id="drop-area-1" >
    <form class="my-form" id="form-1">
      <p id="p-1">Drop Area 1</p>
    </form>
  </div>

  <div class="drop-area" id="drop-area-2" >
    <form class="my-form" id="form-2">
      <p id="p-2">Drop Area 2</p>
    </form>
  </div>

Javascript

I won’t put in all the boilerplate stuff like preventDefaults, but I’ll show the drop handler function

  function handleDrop(e) {
    var dt = e.dataTransfer;
    var files = dt.files;
    let fileType = e.target.innerText;
    handleFiles(files, fileType)
  }

Problem

Depending on if I release the drag in the div, the form, or the p, I get different values for e.target.id

For example, if I add a console.log(e.target.id), I can get the following values depending on where I do the actual drop:

  • drop-area-1 / drop-area-2
  • form-1 / form-2
  • p-1 / p-2

So what value in the event can I use to say regardless of where the drop occurs that it happened in drop?

Current solution

The only way I’ve managed to get it to work consistently is by using e.target.innerText which feels like a hack.

Interview question: Develop a pseudo Front End Application which would let the users login and display a message [closed]

Design (Try to replicate the wireframe as closely as possible. Ideally pixel perfect)
Use of Web API to
• Authenticate an User https://reqres.in/api/login
• Pass two parameters in the (POST) request body i.e email and password.
“email”: “[email protected]”,
“password”: “cityslicka”
After Successful User Login, In Api response you will be able to get user details including auth token. you will use this token for calling a secure API to get the list of users.
https://reqres.in/api/unknown

How to redirect another page after button on click method react js

This is the my login.js page code I want redirect the new page after click the button. I tried several methods but problem not solve. All things are work correctly. but I don’t know how to link the page after the api return result in loginClick function. I Added this line in the code refer some tutorial but its not work.

this.props.history.push('/add');

I am new to the react js, I don’t know about the react well. please help me.

import React,{Component} from 'react';
import { variables } from '../../Variables';



export class Login extends Component{

constructor(props){
    super(props);
    this.state={
        login:[],
        name:"",
        password:"",
        redirect: false
    }
}

changelogindetailsname = (e)=>{
    this.setState({name:e.target.value})
}

changelogindetailspass = (e)=>{
    this.setState({password:e.target.value})
}

loginClick(){

        fetch(variables.API_URL+'login',{
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({
                name:this.state.name,
                password:this.state.password
            })
        })
        .then(res=>res.json())
        .then((result)=>{
            alert(result);
            this.props.history.push('/add');
             
        },(error)=>{
            alert('Faild');
        })
    }


render(){
    const{
        name,
        password
    }=this.state;
    return(
            <div>
                <center>
                    <h1></h1>
                    <hr/>
                    <h3>Welcome Back !</h3>
                    <p></p>
                    <div className="container">
                        <br/>
                        <br/>
                        <br/>
                        <div className="row">
                            <div className="col">

                            </div>
                            <div className="col">

                            </div>
                            <div className="col-4">
                            <style>{" .rr{ float:left; } "} </style>
                            <style>{" .bb{ float:right; } "} </style>
                                <div className="mb-3">
                                    <label className="form-label rr d-flex"> Username</label>
                                    <div className="input-group input-group-lg">
                                        <input type="text" className="form-control " id="formGroupExampleInput" placeholder="Username"
                                        value={name}
                                        onChange={this.changelogindetailsname}/>
                                    </div>
                                </div>
                                <div className="mb-3">
                                    <label className="form-label rr d-flex">Password</label>
                                    <div className="input-group input-group-lg">
                                        <input type="password" className="form-control" id="formGroupExampleInput2" placeholder="Password"
                                        value={password}
                                        onChange={this.changelogindetailspass}/>
                                    </div>
                                </div>
                                <div className="d-flex mb-3">
                                    <a href="#" className="form-label rr"> Forgot your password?</a>
                                </div>
                                <div className="col">
                                        <div className="form-check rr">
                                            <input className="form-check-input" type="checkbox" value="" id="flexCheckDefault"/>
                                            <label className="form-check-label" htmlFor="flexCheckDefault">
                                                Remember me
                                            </label>
                                        </div>
                                </div>
                                   
                                <div className="col">
                                    <button type="button" className="btn btn-success bb"
                                    onClick={()=>this.loginClick() } >Login</button>
                                </div>
                                   
                                <br/>
                                <br></br>
                                <hr/>
                                <p>Don't have an account?</p>
                                <div className="mb-3">
                                    
                                     <button type="button" className="btn btn-light d-flex"
                                     >Sign up for Muessoze</button>
                           
                                  </div>
                            </div>
                            <div className="col">
                                
                            </div>
                            <div className="col">
                                
                            </div>
                        </div>

                      
                   
                    </div>
                   
                </center>
            </div>
    )
}

}

express-session/cors/Axios returns 401 (unauthorized)

I’m building an app with Vue, connecting through Axios to an API made with express.

I’m trying to use express-session to manage login sessions and auth. On my localhost it works great, but when I tried to use it from the site hosted on heroku, it breaks. The middleware that checks whether the session has an usuario property blocks the call.

I’m pretty sure it has to do with https instead of http. I tested it on localhost https with some generated credentials and it broke the same way.

The endpoint for login is quite long, but basically checks if the password you gave it is correct, and if it is, it sets req.session.usuario to an object with some user data. After that, when I check again for the session, usuario is not set.

The CORS middleware:

const cors = require("cors");

const whitelist = ["https://localhost:8080", "https://hosted-client.herokuapp.com"];
const corsOptions = {
    credentials: true,
    origin: (origin, callback) => {
        if (whitelist.includes(origin))
            return callback(null, true);

        //callback(new Error("CORS error"));
        callback(null, true);
    },
};

module.exports = cors(corsOptions);

The session middleware:

const Redis        = require("ioredis");
const connectRedis = require("connect-redis");
const session      = require("express-session");

const RedisStore = connectRedis(session);
const redisClient = new Redis(
    process.env.REDIS_PORT,
    process.env.REDIS_HOST,
    {password: process.env.REDIS_PASSWORD}
);

module.exports = session({
    store: new RedisStore({ client: redisClient }),
    secret: process.env.SECRET,
    saveUninitialized: false,
    resave: process.env.STATE_ENV === "production",
    proxy: true,
    cookie: {
        secure: process.env.STATE_ENV === "production",
        httpOnly: true,
        sameSite: "none",
        // maxAge: 1000 * 60 * 30, // 30 minutos
    },
});

A simple test auth middleware:

module.exports = function (req, _, next) {
    if (!req.session || !req.session.usuario) {
        const err = new Error("No se encontró una sesión");
        err.statusCode = 401;

        next(err);
    }
    next();
}

The Axios instance on the client:

require("dotenv").config();
import axios from "axios";

export default axios.create({
    baseURL: process.env.VUE_APP_API,
    headers: {
        "Content-type": "application/json",
    },
    withCredentials: true,
});

I’m not sure if that’s enough info, if not let me know.

React Plotly JS apply dark (plotly_dark) theme

Using React Plotly Js library. Need robust solution instead of passing plot_bgcolor and paper_bgcolor for creating dark-themed chart. Can’t find doc related to theming for javascript.

I am aware of creating dark-themed Plotly charts by changing the plot_bgcolor, paper_bgcolor and other internal attributes.

However, the outcome of this method doesn’t look as good as the chart produced using the default dark theme available in plotly python version.

As per Plotly python doc passing the theme name to the figure object is enough to change the theme.

import plotly.express as px

df = px.data.gapminder()
df_2007 = df.query("year==2007")

for template in ["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white", "none"]:
    fig = px.scatter(df_2007,
                     x="gdpPercap", y="lifeExp", size="pop", color="continent",
                     log_x=True, size_max=60,
                     template=template, title="Gapminder 2007: '%s' theme" % template)
    fig.show()

As per the above doc, the python version ships with inbuilt themes ('ggplot2', 'seaborn', 'simple_white', 'plotly','plotly_white', 'plotly_dark', 'presentation', 'xgridoff','ygridoff', 'gridon').

I was hoping, I could use one of these themes(plotly_dark) inside my website.

I tried searching for a similar feature in Plotly javascript. The closest I got is Javascript layout template. But there is no mention of using inbuilt themes.

I am looking for something similar to the python theme template, which I can use through React Plotly js library.

Here is the blog link Introducing plotly.py Theming discussing the theming feature for python, which came out in 2018.

Here is the github link to the python file that generates the theme template for plotly.py definitions.py

Here is a link to codesandbox https://codesandbox.io/s/react-plotly-y9ifj9?file=/src/App.js containing the example code available on react plotly website.

Kindly help me by pointing me in the right direction

Buscar dados de um elemento de array em outro arquivo Js

Olá, sou iniciante em programação e estou tentando me entender com o react, quando me deparei com um problema que não acho solução a dias ..

Eu quero passar as datas em negrito armazenadas na array do arquivo Lists.js, do trecho separado 1, para serem usadas no trecho 2 no arquivo contador.js, exibindo na tela junto com os elementos do trecho separado 3, respeitando o ID e usando a data de cada grupo de elementos da array Lists

1 - data_final: '2022-4-12'
2 - const timeRemaining = new Date('***2022-5-2***') - new Date();
3 - <a href={sorteios.referral}><img src={sorteios.image_url} alt={sorteios.title}/></a>

Eu gostaria um codigo em java que usasse a data de cada elemento do array e exibisse o contador de acordo com a data informada de cada lista do array

const timeRemaining = new Date({codigo aqui}) - new Date(); 

Abaixo os trechos dos códigos que estou usando, sem as importações e outros elementos que não interagem com o contador , desde ja agradeço a atenção e o help! Obrigado!

export const Lists = [
    {
        id: '1',
        referral: '',
        title: '',
        data_final: '22-4-12',
        image_url: ''

    },
    {
        id: '2',
        referral: '',
        title: '', 
        data_final: '22-4-11',
        image_url: ''
        
    },
    {
        id:'3' ,
        referral: '',
        title: '',
        data_final: '22-4-2',
        image_url: ''
        
    },

function Grid() {
    return (
        <Container>
            <h1>Logo</h1>
            <RedesSociais>
                <a href="https://www.google.com/" target="_blank" rel="noreferrer"><img src={Twitter} alt="twitter" width="28px" height="28px"></img></a>
                <a href="https://www.google.com/" target="_blank" rel="noreferrer"><img src={Telegram} alt="telegram" width="28px" height="28px"></img></a>
            </RedesSociais>
            <List>
                {lists.map(sorteios => {
                    return (
                        <Sorteios>
                            <Elemento key={sorteios.id}>
                                <a href={sorteios.referral} target="_blank" rel="noreferrer"><img src={sorteios.image_url} alt={sorteios.title}/></a>
                            </Elemento>
                            <Contador/> // Aqui exibe direitinho a data, porém a mesma em todos!
                        </Sorteios>
                    )
                })}
           </List>
        </Container> 
    )
}

export default Grid;

Código do countdown que acaba aparecendo em todos os elemento exibidos pelo array

const Contador = () => {
    
    const getCountdown = () => {
    const timeRemaining = new Date(`2022-5-2`) - new Date();
    let countdown = {};
    if (timeRemaining > 0) {
      countdown = {
        Days: Math.floor(timeRemaining / (1000 * 60 * 60 * 24)),
        Hours: Math.floor((timeRemaining / (1000 * 60 * 60)) % 24),
        Minutes: Math.floor((timeRemaining / 1000 / 60) % 60),
      };
    }
    return countdown;
  };
  const [countdown, setCountdown] = useState(getCountdown());

  useEffect(() => {
    setTimeout(() => {
      setCountdown(getCountdown());
    }, 1000);
  });

  const data = [];
  Object.entries(countdown).forEach(([unit, value]) => {
    data.push(
      <li key={Math.random().toString(16)}>
        <strong>{value}</strong> {unit}
      </li>
    );
  });

  return (
    <div>
      <Visor>{data}</Visor>
    </div>
  );
  
};

export default Contador;

Can’t perform a React state update on an unmounted component.React useEffect Error

I want to dispatch orderDetails from firestore. This code works when page load first time,but if i refresh page i got an error.

    useEffect(() => {
    const getUserOrders=()=>{
     const shopdbRef=doc(db,"shopDB",user?.uid);
     const userOrderRef=getDocs( collection(shopdbRef,"userOrderInfo"))
     .then(response=>(
       response.docs.map((doc)=>{
         dispatch({
           type:"ADD_TO_ORDERS",
           item:{
             id:doc.id,
             data:doc.data()
           }
         })
       })
     )).catch(error=>{
         console.log(error.message)
     })
    }
    getUserOrders();
  }, []);

error>>>>>>>>>>>>>

 Warning: Can't perform a React state
 update on an unmounted component. 
 This is a no-op, but it indicates a 
 memory leak in your application.
 To fix, cancel all subscriptions 
 and asynchronous tasks in a useEffect
 cleanup function.

I am new to react.js can anyone help me
as shown in the error what actually cleanup means,And how can i implement cleanup in my case.

How to structure my vue 3 app to use an Intersecting Observer?

I am trying to change my header’s background whenever it passes some DOM elements (like <section>).

For this I am using the Intersection Observer. But the vanilla JS version from a lot of examples is not working correctly in my app (in the examples document.querySelectorAll is used which, as in other SO questions is considered as antipattern).

But let’s start from the beginning.
My App.vue structure look’s like:

<template>
  <Header />
  <RouterView />
</template>

Since I am using vue-router, I have a Home.vue view which is structured as:

<template>
  <Hero />
  <NotRelevant Content />
  <NotRelevantContent />
  <NotRelevantContent />
  <Footer />
</template>

So the header is visible on each route (but as of now I only have one).

My should change its background color whenever it intersects with the <Hero /> or the <Footer /> component. Both components have a class="observer" which should trigger the Intersection Observer.

The problem is, that in the <Header /> component the document.querySelectorAll('observer') is undefined. I assume, that not all DOM elements are loaded and that’s why my querySelectorAll is undefined.

My question is, what could I do in this case to solve my problem?

I tried to use this.$nextTick() on the Intersection Observer but with no effect.

I was suggested to use $ref with emmit and props, but how to achieve my desired result, when there are multiple components?

Would like to avoid using vuex to not make this project more complicated.

I found this solution: vue-intersection-observer. Maybe it is worth trying? (As a last resort).

My <Header /> looks like:

<template>
  <header
    class="header fade-in-bg"
    :class="{
      header__scroll: isContrastActive,
    }"
  >
    Logo
  </header>
</template>

<script>

export default {
  data() {
    return {
      isContrastActive: false,
      observer: null,
    }
  },
methods: {
  async activateObserver() {
      this.observer = new IntersectionObserver(
        ([entry]) => {
          if (!entry.isIntersecting) {
            this.isContrastActive = true
          } else {
            this.isContrastActive = false
          }
        },
        { rootMargin: '-5% 0px 0px 0px' }
      )
    const myQuerySelector = 
      document.querySelectorAll('.observer')
        .forEach(el => this.observer.observe(el))

        console.log("myQuerySelector: ", myQuerySelector)
    },
  },
  this.activateObserver()
  },
}
</script>

Hero.vue component:

<template>
  <article class="hero observer">
    HERO
  <article />
<template />

Footer.vue component:

<template>
  <article class="footer observer">
    Footer
  <article />
<template />

Are we supposed to initialize variables in JS, regardless of a “value” being set in HTML?

I started using HTML and CSS a while back, but I started implementing JS only about a couple of weeks ago. I understand JS independently, along with HMTL and CSS. Now that I have to put them together, I don’t understand the implementation of JS– specifically with variables and manipulating them.

I want to increase, decrease, or represent the changes (e.g., Moves left = 10 => Moves left = 9), but my code doesn’t work. Are there specific concepts I need to understand besides “knowing JS basics?” Leaving the code below.

HTML, which only includes the main section:

<section class="game">
        <!--Title -->
        <div class="title">Rock Paper Scissor</div>

        <!--Display Score of player and computer -->
        <div class="score">
          <div class="playerScore">
            <h2>Player</h2>
            <p class="p-count count">0</p>
          </div>
          <div class="computerScore">
            <h2>Computer</h2>
            <p class="c-count count">0</p>
          </div>
        </div>

        <div class="move">Choose your move</div>

        <!--Number of moves left before game ends -->
        <div class="movesleft">Moves Left: 10</div>

        <!--Options available to player to play game -->
        <div class="options">
          <button class="rock">Rock</button>
          <button class="paper">Paper</button>
          <button class="scissor">Scissors</button>
        </div>

        <!--Final result of game -->
        <div class="result"></div>

        <!--Reload the game -->
        <button class="reload">Reload Game?</button>
      </section>

JS, which includes where I want my HTML values to update:

const game = () => {
    let playerScore = document.getElementsByClassName('p-count count'); // At the start of the game the player & computer scores will = 0
    let computerScore = document.getElementsByClassName('c-count count');
    let moves = 0; // Start of gaming... total moves will equal 0, so this will initialize it since both the scores are already initalized at 0.

    playGame();
};

const playGame = () => {
    let playerOptions = [document.getElementsByClassName('rock'), document.getElementsByClassName('paper'), document.getElementsByClassName('scissors')];
    let computerOptions = [document.getElementsByClassName('rock'), document.getElementsByClassName('paper'), document.getElementsByClassName('scissors')];

    playerOptions.forEach(addEventListener("click", function(){
        moves++; // This says "we will add 1 to the total moves made." This will affect the moves variable in the game function.
        let movesLeft = document.getElementById('movesleft'); // Calls the movesleft div-class
        return movesLeft - moves; // Begins the subtraction of moves from the starting amount
    }));
    
    let computerSelection = computerOptions[Math.floor((Math.random) * computerOptions.length)] // Within the shared options, this will generate a random number between 0 -
    // - & 2 to represent the options within the array (rock, paper, scissors)

    winner();
    gameOver();

};

const winner = (playerOptions, computerOptions) => {
    if (playerOptions[0] & computerOptions[2]) {
        playerScore++; // Rock beats scissors
    } else if (playerOptions[1] && computerOptions[0]) {
        playerScore++; // Paper beats rock
    } else if (playerOptions[2] && computerOptions[2]) {
        playerScore++; // Scissors beats paper
    } else {
        computerScore++;
    } // Checking player's input to see if was a round-winnable move. 
};

How to create an algorithm which creates a word search puzzle?

I would love to create a word search puzzle on the web where I can input the words in an array, and then the puzzle will be generated with those words placed randomly in a grid.

Something like this:
enter image description here

I found a tutorial, but it was not exactly what my problem described: Word Search

Because you had to put the words in the table yourself by changing the html.

If anyone has any ideas to create this word search puzzle, please tell me.