Bypass javascript multi-tap prevention [closed]

I’m using a membership site as long as multiple tabs are blocked.

Blocking multi-tap is hurting productivity, so I want to bypass it.

I want to solve it by entering the command in the console window. Any help would be appreciated.

There is an upload limit on the length of the code, so please refer to the shared document.

https://docs.google.com/document/d/1TPCmU9DzqCfUsQwa7A4v4igRnGSNQqvbWyigLqzr0CQ/edit?usp=sharing

How can I map the state?

This is how I am getting the state, but how can I map through coin inside the JSX

For some reason I cant map through the coin array :

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getstats } from '../Redux/stocks/stockreducer';

export const Stats = () => {
  const dispatch = useDispatch();
  useEffect(() => dispatch(getstats('Qwsogvtv82FCd')), []);
  const stats = useSelector((state) => state.stocks);

  console.log(stats);

  return (
    <div className="main">
      <h1>Stats Page</h1>

      {stats.map((item) => (
        <>
          <p key={item.uuid}>name: {item.name}</p>
        </>
      ))}
    </div>
  );
};

This expression is not callable … type has no call signatures [ts 2349] error

I’m trying to use functions from Observable Plot example with marimekko chart in my project with typescript and got this error on this string:

   setXz(I.map((i) => sum.get(X[i])))

The code is:

function marimekko({ x, y, z, inset = 0.5, ...options }) {
    const [Xz, setXz] = lazyChannel(z)
    const {
        y1,
        y2,
        transform: stackY,
    } = Plot.stackY({ offset: "expand", x, y: z })
    const {
        x1,
        x2,
        transform: stackX,
    } = Plot.stackX({ offset: "expand", y, x: Xz })
    return {
        x1,
        x2,
        y1,
        y2,
        transform: (data, facets) => {
            const I = d3.range(data.length)
            const X = Plot.valueof(data, x)
            const Z = Plot.valueof(data, z)
            const sum = d3.rollup(
                I,
                (I) => d3.sum(I, (i) => Z[i]),
                (i) => X[i]
            )
            setXz(I.map((i) => sum.get(X[i])))
            stackX(data, facets)
            stackY(data, facets)
            return { data, facets }
        },
        inset,
        ...options,
    }
}

function lazyChannel(source) {
    let value
    return [
        {
            transform: () => value,
            label:
                typeof source === "string"
                    ? source
                    : source
                    ? source.label
                    : undefined,
        },
        (v) => (value = v),
    ]
}

Any ideas how to fix it?

How to create gaps when using group / groupX / groupY in Observable Plot?

On line charts “if some of the x or y channel values are undefined (or null or NaN), gaps will appear between adjacent points”.

If my dataset contains such undefined values, how can I achieve that these also remain when I use group / groupX / groupY?

The below plot is created (some settings removed for brevity) using a dataset where all x values (timestamp) are set and some y values (temp) are undefined.

marks: [
  Plot.frame(),
  Plot.line(data, { x: "timestamp", y: "temp", stroke: "sensor_id" }),
  Plot.line(data,  Plot.groupX({ y: "mean" }, { x: d => new Date(d.timestamp.getTime()).setSeconds(0, 0), y: "temp", stroke: "black" }))
]

enter image description here

The grouping groups all measurements per minute and plots the average in black.
In the data, there is a minute that only has a single entry, and its y value (temp) is undefined.
How can I achieve that this aggregates to undefined? Is there a setting how group behaves when a single value / all values are undefined?

I managed to make it work by providing a custom aggregation function that takes care of undefined values, but I think there should be an easier way to achieve this. It seems like I am missing something.

Plot.line(data, 
          Plot.groupX(
            // Here I check if the grouping consists of a single falsy value
            { y: data => (data.length == 1 && !data[0]) ? undefined : data.reduce((a,b) => a + b, 0) / data.length }, 
            { x: d => new Date(d.timestamp.getTime()).setSeconds(0, 0), y: "temp", stroke: "black"
))

enter image description here

While creating item from parent to child component, going to infinite loop in React

This is my home page and getting list data then creating List component as much as need.
Then going to List component and creating list item. so creating new component using map function. I tried different ways for it but I can’t figure out. It goes infinite loop whatever I did.

Home.jsx

const [lists, setLists] = useState([]);

  useEffect(() => {
    const getRandomList = async () => {
      try {
        const res = await axios.get(`/lists${type ? "?type=" + type : ""}`, {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            token: token,
          },
        });
        setLists(res.data);
      } catch (error) {
        console.log(error);
      }
    };
    getRandomList();
  }, [type]);
  return (
    <div className="home">
      <Navbar />
      <Featured type={type} />
      {lists.map((list, index) => {
        return <List key={index} list={list}/>;
      })}
    </div>
  );
}

in List component, creating List item component as much as need.

List.jsx

export default function List({ list }) {
  const [isMoved, setIsMoved] = useState(false);
  const [slideNumber, setSlideNumber] = useState(0);
  const [clickLimit, setClickLimit] = useState(window.innerWidth / 230);
  const [lists, setLists] = useState([])  
  const listRef = useRef();

  useEffect( () =>{
    const getList = ()=>{
      setLists(list.content)
    }
    getList()
  },[list])


  const handleClick = (direction) => {
    setIsMoved(true);
    let distance = listRef.current.getBoundingClientRect().x - 50;
    if (direction === "left" && slideNumber > 0) {
      setSlideNumber(slideNumber - 1);
      listRef.current.style.transform = `translateX(${230 + distance}px)`;
    }
    if (direction === "right" && slideNumber < 10 - clickLimit) {
      setSlideNumber(slideNumber + 1);
      listRef.current.style.transform = `translateX(${-230 + distance}px)`;
    }
  };
  return (
    <div className="list">
      <span className="listTitle">Continue to watch</span>
      <div className="listWrapper">
        <ArrowBackIosOutlined
          className="sliderArrow left"
          onClick={() => handleClick("left")}
          style={{ display: !isMoved && "none" }}
        />
        <div className="listContainer" ref={listRef}>
          {lists.map((item, index) => {
            return <ListItem key={index} index={index} item={item} />;
          })} 
        </div>
        <ArrowForwardIosOutlined
          className="sliderArrow right"
          onClick={() => handleClick("right")}
        />
      </div>
    </div>
  );
}

last component here.

ListItem.jsx

export default function ListItem({ index, item }) {
  const [isHovered, setIsHovered] = useState(false);
  const [movie, setMovie] = useState({});

  useEffect(() => {
    const getMovie = async (item) => {
      try {
        const res = await axios.get("/movies/find/" + item, {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            token: token,
          },
        });
        setMovie(res.data);
      } catch (error) {
        console.log(error);
      }
    };  
    getMovie()
    
  }, [item]);

  
  return (
    <div
      className="listItem"
       style={{
        left:
          isHovered &&
          Object.values(index) * 225 - 50 + Object.values(index) * 2.5,
      }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)} 
    >
      <img src={movie.img} alt="" />
      {isHovered && (
        <>
          <video src={movie.trailer} autoPlay loop></video>
          <div className="itemInfo">
            <div className="itemIcons">
              <PlayArrow className="itemIcon" />
              <Add className="itemIcon" />
              <ThumbUpAltOutlined className="itemIcon" />
              <ThumbDownAltOutlined className="itemIcon" />
            </div>
            <div className="itemInfoTop">
              <span>1 hour 14 mins</span>
              <span className="limit">{movie.limit}</span>
              <span>{movie.year}</span>
            </div>
            <div className="itemDescription">{movie.description}</div>
            <div className="itemGenre">{movie.genre}</div>
          </div>
        </>
      )}
    </div>
  );
}

Apply border-radius to ECharts heatmap

Taking this ECharts example https://echarts.apache.org/examples/en/editor.html?c=heatmap-cartesian, I was wondering if it would be somehow possible to apply a border-radius to each square of the heatmap. My goal was that make these squares appear as rounded elements, like that: https://9elements.com/blog/content/images/border-radius-1.png.

I have tried using the series-heatmap.itemStyle.borderRadius property, but that does not seem available.

Any ideas?

Logging in before items are set in localStorage – JS

I am trying to make an app with firebase but when I click log in, it does everything except setting the localStorage items. Tried awaiting and everything else I could think of

signInWithEmailAndPassword(auth, email, password)
            .then(async (userCredential) => {
                const user = userCredential.user;
                localStorage.setItem("access_token", user.stsTokenManager.accessToken);
                localStorage.setItem("uid", user.uid);

                const devices = collection(db, "users", user.uid, "devices");
                const devicesSnap = await getDocs(devices);
                if(devicesSnap.docs.length >= 1) {
                    localStorage.setItem("first_charger", devicesSnap.docs[0].id);
                    localStorage.setItem("first_charger_name", devicesSnap.docs[0].data().deviceName + "/" + devicesSnap.docs[0].id);
                    const formattedChargers = formatChargers(devicesSnap.docs);
                    setChargers(formattedChargers);
                } else {
                    setChargers([]);
                }

                const cars = collection(db, "users", localStorage.getItem("uid"), "vehicles");
                const carsSnap = await getDocs(cars);
                if(carsSnap.docs.length >= 1) {
                    const formattedCars = formatCars(carsSnap.docs);
                    setCars(formattedCars);
                } else {
                    setCars([]);
                }

                setLoading(false);
                setLoggedIn(true);
            })
            .catch((error) => {
                console.log(error);
            });

DOMContentLoaded doesn’t fire at all

I’m new to Typescript/JavaScript and tried out the DOMContentLoaded event. In one ts document it works but now I split my code into two ts documents and now DOMContentLoaded doesn’t work anymore.

This is my code:

document.addEventListener('DOMContentLoaded', (event) => {
alert('Text');
});

This is my html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="build/order-System.js"></script>
</head>
<body>

</body>
</html>

Why I don’t get the alert

filtering data if it has a key value from an array to store in a useState

I have this data:

subsInfo =
[
0: {username: "One", subId: 001, address: 123,},
1: {username: "Two", subId: 002, address: 456,},
2: {username: "Three", subId: 003, address: 789,},
]

I store the value of subId and stored it in a useState:

const [subIdsArray, setSubIdsArray] = useState([]);
const [addressArray, setAddressArray] = useState([]);

var subIdKey = [001, 002, 003]
setSubIdsArray(subsIdKey);

var addressKey = [123, 456, 789]
setAddressArray(addressKey);

I want to filter the subsInfo that has the value of subIdsArray and addressArray

I am using functional component in javascript.

I tried the .filter + .map but didn’t work.

How can I pass null from react native to java when I develop a module

I’m developing a native module for Android in React Native. I have two method with the same name but I can’t use them in React Native because Java Script has not overloading directly. So I write a function which can get null as a paramater in React Native and try to handle it in Java.

React Native side:

    function a(arg=null){
       moduleName.b(arg)
    }

Java side:

public void wrapper(@Nullable Boolean arg, final Promise promise){
  if(arg == null){
    c()
  }else{
    c(arg)
  }
}

Then I have not problem when I pass true or false to function a but when I pass nothing to funtion a I get an error on my phone like that:

error

What is the problem?

Need help understanding how this JS code is generating UUID [duplicate]

I got this piece of code for generating UUID in case the browser doesn’t support crypto.randomUUID.

I need help understanding how this works. A step by step process would be much appreciated. Would also like to know the official term that is used to define this kind of process.

var random_string = (
    Math.random().toString(16) +
    Math.random().toString(16) +
    Math.random().toString(16) +
    Math.random().toString(16) +
    Math.random().toString(16)
  ).replace(/0./g, ""),
  random_y_bit = [8, 9, "a", "b"][~~(Math.random() * 4)],
  template_uuid = /.*(........)..(....)..(...)..(...)..(............).*/,
  replace_pattern = "$1-$2-4$3-" + random_y_bit + "$4-$5";

return random_string.replace(template_uuid, replace_pattern);

How can I use template literals next to a button?

I’m rendering a template literal with a placeholder inside my conditional operator, but it seems there is an issue I can’t identify. Any clue as to what this may be?

function scoreQuiz() {
    let totalCorrect = 0;
    allCorrectAnswers.forEach((answer, index) => {
    if(answer === selections[index]) {
        totalCorrect++;
    }
    
})
}
{finished === false ? 
        <button
            
            onClick={() => {
                    //checkSelectedAnswer();
                    scoreQuiz();
                    finishQuiz()
                    }
                }>
            Check answers
        </button>
        : 
        `You scored ${totalCorrect}/5  correct` <button>Play again</button>
      }

How can I aggregate the values from my repeating form components?

I have this component named Component.js with input fields for the user to enter the required values. I created another component where I could repeat all of these input fields by repeating the Component.js. How can I aggregate the values entered in the Component.js and submit these values in the parent component? Any help would be appreciated. Thank you.

Link: https://codesandbox.io/s/form-order-working-4f6g2?file=/demo.js:0-329

Component.js

export default function BasicSelect() {
  const [prod, setProd] = useState("");
  const [qty, setQty] = useState(0);
  const [productArr, setProductArr] = useState([]);
  const [design, setDesign] = useState("");
  const [size, setSize] = useState("");

  const handleChange = (event) => {
    setProd(event.target.value);
  };

  const handleChangeSize = (e, p) => {
    if (e && p) {
      p.size = e.target.value;
      const updatedObject = productArr.map((product) =>
        product.key === p.key ? p : product
      );
      setProductArr(updatedObject);
    }
  };

  const handleChangeDesign = (e, p) => {
    if (e && p) {
      p.design = e.target.value;
      const updatedObject = productArr.map((product) =>
        product.key === p.key ? p : product
      );
      setProductArr(updatedObject);
    }
  };

  const handleChangeColor = (e, p) => {
    if (e && p) {
      p.color = e.target.value;
      const updatedObject = productArr.map((product) =>
        product.key === p.key ? p : product
      );
      setProductArr(updatedObject);
    }
  };

  const handleChangeQty = (event) => {
    setQty(event.target.value);
    while (productArr.length > 0) {
      productArr.pop();
    }
    let updateProductArr = [...productArr];
    for (let i = 0; i < event.target.value; i++) {
      updateProductArr.push({
        key: i + 1,
        size: "",
        design: "",
        color: ""
      });
    }
    setProductArr(updateProductArr);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    // console.log(prod, qty, size, design);
    console.log(productArr);
  };

  //for removing the textfields
  const handleRemove = (e) => {
    const reducedArr = productArr.filter((product) => product.key !== e);
    setProductArr(reducedArr);
    console.log(e);
    setQty(qty - 1);
  };

  const handleAdd = (e) => {
    const addArr = productArr.filter((product) => product.key !== e);
    setProductArr(addArr);
    console.log(addArr);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <form onSubmit={handleSubmit}>
        <FormControl fullWidth>
          <InputLabel id="demo-simple-select-label">Product</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={prod}
            label="Product"
            onChange={handleChange}
          >
            <MenuItem value="Item1">Item1</MenuItem>
            <MenuItem value="Item2">Item2</MenuItem>
            <MenuItem value="Item3">Item3</MenuItem>
          </Select>
        </FormControl>
        <br />
        <br />
        <TextField
          type="number"
          label="Quantity"
          variant="outlined"
          value={qty}
          onChange={handleChangeQty}
          fullWidth
        />
        <br />
        <br />
        {productArr.map((product) => (
          <div key={"div-" + product.key}>
            <p>{product.key}</p>

            <FormControl fullWidth>
              <InputLabel id="demo-simple-select-label-{product.key}">
                Size
              </InputLabel>
              <Select
                labelId={"demo-simple-select-label-" + product.key}
                id={"demo-simple-select-" + product.key}
                value={product.size}
                label="Product"
                onChange={(e) => handleChangeSize(e, product)}
              >
                <MenuItem value="S">Small</MenuItem>
                <MenuItem value="M">Medium</MenuItem>
                <MenuItem value="L">Large</MenuItem>
              </Select>
            </FormControl>

            <br />
            <br />
            <FormControl fullWidth>
              <InputLabel id="demo-simple-select-label-{product.key}">
                Choose Design
              </InputLabel>
              <Select
                labelId={"demo-simple-select-label-" + product.key}
                id={"demo-simple-select-" + product.key}
                value={product.design}
                label="Product"
                onChange={(e) => handleChangeDesign(e, product)}
              >
                <MenuItem value="Design1">Design1</MenuItem>
                <MenuItem value="Design2">Design2</MenuItem>
                <MenuItem value="Design3">Design3</MenuItem>
              </Select>
            </FormControl>

            <br />
            <br />
            <FormControl fullWidth>
              <InputLabel id="demo-simple-select-label-{product.key}">
                Choose Color
              </InputLabel>
              <Select
                labelId={"demo-simple-select-label-" + product.key}
                id={"demo-simple-select-" + product.key}
                value={product.color}
                label="Color"
                onChange={(e) => handleChangeColor(e, product)}
              >
                <MenuItem value="Red">Red</MenuItem>
                <MenuItem value="Blue">Blue</MenuItem>
                <MenuItem value="Yellow">Yellow</MenuItem>
              </Select>
            </FormControl>
            <br />
            <br />

            {product.length !== 1 && (
              <Button
                variant="contained"
                onClick={() => handleRemove(product.key)}
                // onClick={() => handleColorRemove(index)}
              >
                Remove
              </Button>
            )}
            <br />
            {product.length <= 1 && (
              <Button onClick={handleAdd(product.key)}>
                Add more Product{" "}
              </Button>
            )}
          </div>
        ))}

        <br />
        <br />
        {/* <Button type="submit">Submit </Button> */}
      </form>
    </Box>
  );
}

Too add more component:

ButtonAdd.js

import React, { useState } from "react";
import Component from "./component";

const ButtonAdd = () => {
  const [inputList, setInputList] = useState([]);

  const onAddBtnClick = (event) => {
    setInputList(inputList.concat(<Component key={inputList.length} />));
  };
  return (
    <>
      <button onClick={onAddBtnClick}>Add a product</button>
      {inputList}
    </>
  );
};

export default ButtonAdd;

Parent component or the Demo.js

const Demo = () => {
  return (
    <>
      <Component />
      <br />
      <ButtonAdd />
      <br />
      <Button>Submit</Button>
    </>
  );
};

export default Demo;

Create and embed repl environment in React webpage

I am trying to create a site for my coding students to do practice problems. The problems would be for basic javascript (primary use), html and css, and React components. To do this I believe I would need a REPL embedded in my React components (not sure if my terminology is correct here; by REPL I mean an environment to write code, execute it, and see any output in a console). I also need to be able to run tests on their code.

I know repl.it (the website) has an API for this, but I would like to learn how to create it from scratch. Furthermore, I can’t find any resources on how to implement something like this in a React app specifically.

All I’ve been able to find so far is vague references to Linux containers and some mentions of Docker. I have no experience with either of these. If someone could point me to a resource to help me learn how to set this up and integrate it in my React app I would be very appreciative.

A good example of what I want would be the REPL in codewars. You can write code, then run tests and get specific feedback on that code.