php file generating and reading data from a database

There is a function that generalize a php file:

require_once "connection.php";

// Módosítások elmentése vagy új termék hozzáadása
// Módosítások elmentése vagy új termék hozzáadása
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $new_name = isset($_POST["new_name"]) ? $_POST["new_name"] : "";
    $new_price = isset($_POST["new_price"]) ? $_POST["new_price"] : "";
    $new_image_url = isset($_POST["new_image_url"]) ? $_POST["new_image_url"] : "";

    if (isset($_POST["product_id"])) {
        /
        $product_id = $_POST["product_id"];
        updateProduct($product_id, $new_name, $new_price, $new_image_url);
    } else {
        
        $new_product_name = isset($_POST["new_product_name"]) ? $_POST["new_product_name"] : "";
        $new_price = isset($_POST["new_price"]) ? $_POST["new_price"] : "";
        $new_image_url = isset($_POST["new_image_url"]) ? $_POST["new_image_url"] : "";
        
        $new_product_id = generateSProductFile($new_product_name, $new_price, $new_image_url);
    }
}
function generateSProductFile($name, $price, $image_url) {
    global $conn;

   
    $insert_query = "INSERT INTO product (product_name, price, picture) VALUES (?, ?, ?)";
    $stmt = mysqli_prepare($conn, $insert_query);
    mysqli_stmt_bind_param($stmt, "sds", $name, $price, $image_url);
    mysqli_stmt_execute($stmt);

    /
    $new_product_id = mysqli_insert_id($conn);

    $file_path = "sproduct_" . $new_product_id . ".php";
    $file_content = "<?phpn";
    $file_content .= "$product_id = $new_product_id;n"; 
    $file_content .= "$product_name = "$name";n";
    $file_content .= "$product_price = "$price";n";
    $file_content .= "$product_picture = "$image_url";n";
    $file_content .= "?>n";
    $file_content .= file_get_contents("sproduct_template.php");
    
    
    file_put_contents($file_path, $file_content);

    return $new_product_id;
}

And there is the template file:


<?php
require_once "connection.php";




    
    $sql_product = "SELECT picture, product_name, price FROM product WHERE product_id = (SELECT MAX(product_id) FROM product)";
    $result_product = mysqli_query($conn, $sql_product);

    if ($result_product && mysqli_num_rows($result_product) > 0) {
        $row_product = mysqli_fetch_assoc($result_product);
        
        
        $product_name = $row_product['product_name'];
        $product_price = $row_product['price'];
        $product_picture = $row_product['picture'];
    } else {
        
        $product_name = "N/A"; 
        $product_price = "N/A";
        $product_picture = "default_image.jpg"; 
    
} else {
    
    $product_name = "N/A"; 
    $product_price = "N/A";
    $product_picture = "default_image.jpg"; 
}
?>

In addition, I also have a natural database, with the product table with manually entered products. The problem is that the newly generated php file shows incorrect product data. For some reason, it takes the data from the beginning of the database.
For example: I created a new product, and the database displayed the data of the product with ID 1 on the website.

Have VS Code execute a command line call when failing to save

My company uses Cliosoft for source control. If I do not check out a file in Cliosoft, it will fail to save in VS Code since the file will only have read access. I want to setup VS Code such that when it detects that a file failed to save, it runs a command line call (soscmd -co filename) and then tries to save again

I looked at the VS Code API, particularly onWillSaveTextDocument and onDidSaveTextDocument. I imagine through the combination of those two events I could make something up but I am not very familiar with how events and thenables work in Javascript

Why do only half of the values of my buttons get assigned their colors and not the other half?

I am creating a matching game and currently I am trying to get my buttons value assigned the color they were randomly assigned. However I can only get half of the buttons assigned their color while the others say “undefined.” I have tried multiple ways to get them to assign like assigning them numbers instead but they still won’t. Any thoughts?

const colors = ["blue", "green", "red", "yellow", "orange", "purple"];
let blue = 0;
let green = 0;
let red = 0;
let yellow = 0;
let orange = 0;
let purple = 0;


function runMatching(){
    let elements = document.querySelectorAll(".but");
    let num1 = [];
    let num2 = [];
    for (var i=0; i<elements.length; i++) {
        let ran = Math.floor(Math.random() * (6 - 0) + 0);
        if (num1.includes(ran)){
            if (num2.includes(ran)){
                i--;
            }
            else {
                elements[i].style.backgroundColor = colors[ran];
                num2.push(ran);
                elements[i].value = colors[i];
                console.log(elements[i].value);
            }
        }
        else {
            elements[i].style.backgroundColor = colors[ran];
            num1.push(ran);
            elements[i].value = colors[i];
            console.log(elements[i].value);
        }
    }
}

function runTitle(){
    const title = document.getElementById("header");
    title.style.animationPlayState = "running";
}

function runPlayBut(){
    const playBut = document.querySelector(".playButton");
    const grid = document.querySelector(".grid");
    const start = document.querySelector(".start");
    const stopwatch = document.querySelector(".stopwatch");
    playBut.style.animationPlayState = "paused, running";
    playBut.style.animationIterationCount = "unset";
    playBut.style.zIndex = "0";
    grid.style.animationPlayState = "running";
    start.style.animationPlayState = "running, paused";
    stopwatch.style.animationPlayState = "running";
}

function runStartBut(){
    const start = document.querySelector(".start");
    start.style.animationPlayState = "paused, running";
}

let startTime;
let running = false;

function startStopwatch() {
  if (!running) {
    startTime = new Date().getTime();
    running = true;
    updateStopwatch();
  }
}

function updateStopwatch() {
  if (running) {
    let currentTime = new Date().getTime();
    let elapsedTime = new Date(currentTime - startTime);
    let minutes = elapsedTime.getUTCMinutes().toString().padStart(2, '0');
    let seconds = elapsedTime.getSeconds().toString().padStart(2, '0');
    let milliseconds = Math.floor(elapsedTime.getMilliseconds() / 10).toString().padStart(2, '0');
    document.querySelector('.stopwatch').innerText = minutes + ":" + seconds + ":" + milliseconds;
    setTimeout(updateStopwatch, 10);
  }
}

let snow1 = document.querySelector('.snow:nth-child(1)');

function setProperty1(position) {
  snow1.style.left = position + "%";
}

function changeAnimationPos1() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty1(position);
}

setInterval(changeAnimationPos1, 6000)



let snow2 = document.querySelector('.snow:nth-child(2)');

function setProperty2(position) {
  snow2.style.left = position + "%";
}

function changeAnimationPos2() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty2(position);
}

setInterval(changeAnimationPos2, 8000)



let snow3 = document.querySelector('.snow:nth-child(3)');

function setProperty3(position) {
  snow3.style.left = position + "%";
}

function changeAnimationPos3() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty3(position);
}

setInterval(changeAnimationPos3, 12000)



let snow4 = document.querySelector('.snow:nth-child(4)');

function setProperty4(position) {
  snow4.style.left = position + "%";
}

function changeAnimationPos4() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty4(position);
}

setInterval(changeAnimationPos4, 7000)



let snow5 = document.querySelector('.snow:nth-child(5)');

function setProperty5(position) {
  snow5.style.left = position + "%";
}

function changeAnimationPos5() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty5(position);
}

setInterval(changeAnimationPos5, 7500)



let snow6 = document.querySelector('.snow:nth-child(6)');

function setProperty6(position) {
  snow6.style.left = position + "%";
}

function changeAnimationPos6() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty6(position);
}

setInterval(changeAnimationPos6, 5800)



let snow7 = document.querySelector('.snow:nth-child(7)');

function setProperty7(position) {
  snow7.style.left = position + "%";
}

function changeAnimationPos7() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty7(position);
}

setInterval(changeAnimationPos7, 10400)



let snow8 = document.querySelector('.snow:nth-child(8)');

function setProperty8(position) {
  snow8.style.left = position + "%";
}

function changeAnimationPos8() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty8(position);
}

setInterval(changeAnimationPos8, 6400)



let snow9 = document.querySelector('.snow:nth-child(9)');

function setProperty9(position) {
  snow9.style.left = position + "%";
}

function changeAnimationPos9() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty9(position);
}

setInterval(changeAnimationPos9, 7200)



let snow10 = document.querySelector('.snow:nth-child(10)');

function setProperty10(position) {
  snow10.style.left = position + "%";
}

function changeAnimationPos10() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty10(position);
}

setInterval(changeAnimationPos10, 8800)



let snow11 = document.querySelector('.snow:nth-child(11)');

function setProperty11(position) {
  snow11.style.left = position + "%";
}

function changeAnimationPos11() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty11(position);
}

setInterval(changeAnimationPos11, 11200)



let snow12 = document.querySelector('.snow:nth-child(12)');

function setProperty12(position) {
  snow12.style.left = position + "%";
}

function changeAnimationPos12() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty12(position);
}

setInterval(changeAnimationPos12, 7900)



let snow13 = document.querySelector('.snow:nth-child(13)');

function setProperty13(position) {
  snow13.style.left = position + "%";
}

function changeAnimationPos13() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty13(position);
}

setInterval(changeAnimationPos13, 9700)



let snow14 = document.querySelector('.snow:nth-child(14)');

function setProperty14(position) {
  snow14.style.left = position + "%";
}

function changeAnimationPos14() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty14(position);
}

setInterval(changeAnimationPos14, 6700)



let snow15 = document.querySelector('.snow:nth-child(15)');

function setProperty15(position) {
  snow15.style.left = position + "%";
}

function changeAnimationPos15() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty15(position);
}

setInterval(changeAnimationPos15, 8000)



let snow16 = document.querySelector('.snow:nth-child(16)');

function setProperty16(position) {
  snow16.style.left = position + "%";
}

function changeAnimationPos16() {
  let position = Math.random() * (95 - 5) + 5;
  setProperty16(position);
}

setInterval(changeAnimationPos16, 6400)
body {
    margin: 0;
    background: linear-gradient(white, skyblue);
    background-attachment: fixed;
}

#header {
    top: 80px;
    position: absolute;
    text-align: center;
    font-family: sans-serif;
    font-size: 100px;
    font-weight: 900;
    color: white;
    -webkit-text-stroke-color: black;
    -webkit-text-stroke-width: 0.8px;
    text-shadow: 0px 0px 10px black;
    width: 99.5vw;
    height: 5vh;
    z-index: 999;
    animation: exit 1.5s ease-in-out forwards;
    animation-play-state: paused;
}

@keyframes exit {
    0% {
        top: 80px;
    }
    20% {
        top: 110px;
    }
    100% {
        top: -200px;
    }
}

/*-----Snow-----*/

.snowfall {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 0;
}

.snow {
    background-color: snow;
    box-shadow: 0px 0px 10px snow;
    height: 10px;
    width: 10px;
    border-radius: 50%;
    animation: fall 9s linear infinite;
    position: absolute;
    top: -40px;
    left: 10%;
    z-index: 1;
}

.snow:nth-child(1) {
    animation-duration: 6s;
    position: absolute;
    top: -40px;
    left: 20%;
    opacity: 0.2;
}

.snow:nth-child(2) {
    animation-duration: 8s;
    position: absolute;
    top: -40px;
    left: 30%;
    height: 15px;
    width: 15px;
}

.snow:nth-child(3) {
    animation-duration: 12s;
    position: absolute;
    top: -40px;
    left: 43%;
    height: 7px;
    width: 7px;
    opacity: 0.4;
}

.snow:nth-child(4) {
    animation-duration: 7s;
    position: absolute;
    top: -40px;
    left: 50%;
    height: 25px;
    width: 25px;
}

.snow:nth-child(5) {
    animation-duration: 7.5s;
    position: absolute;
    top: -40px;
    left: 38%;
    height: 40px;
    width: 40px;
}

.snow:nth-child(6) {
    animation-duration: 5.8s;
    position: absolute;
    top: -40px;
    left: 84%;
    height: 13px;
    width: 13px;
}

.snow:nth-child(7) {
    animation-duration: 10.4s;
    position: absolute;
    top: -40px;
    left: 70%;
    height: 4px;
    width: 4px;
}

.snow:nth-child(8) {
    animation-duration: 6.4s;
    position: absolute;
    top: -40px;
    left: 90%;
    height: 34px;
    width: 34px;
    opacity: 0.7;
}

.snow:nth-child(9) {
    animation-duration: 7.2s;
    position: absolute;
    top: -40px;
    left: 7%;
    height: 17px;
    width: 17px;
}

.snow:nth-child(10) {
    animation-duration: 8.8s;
    position: absolute;
    top: -40px;
    left: 24%;
}

.snow:nth-child(11) {
    animation-duration: 11.2s;
    position: absolute;
    top: -40px;
    left: 56%;
}

.snow:nth-child(12) {
    animation-duration: 7.9s;
    position: absolute;
    top: -40px;
    left: 89%;
    height: 34px;
    width: 34px;
    opacity: 0.4;
}

.snow:nth-child(13) {
    animation-duration: 9.7s;
    position: absolute;
    top: -40px;
    left: 47%;
    opacity: 0.8;
}

.snow:nth-child(14) {
    animation-duration: 6.7s;
    position: absolute;
    top: -40px;
    left: 2%;
    opacity: 0.9;
}

.snow:nth-child(15) {
    animation-duration: 8s;
    position: absolute;
    top: -40px;
    left: 75%;
}

.snow:nth-child(16) {
    animation-duration: 6.4s;
    position: absolute;
    top: -40px;
    left: 97%;
    opacity: 0.6;
}

@keyframes fall{
    0% {
        transform: translateY(0);
    }
    100% {
        transform: translateY(110vh);
    }
}

/*-------PlayButton------*/

.playButton {
    font-weight: 300;
    position: absolute;
    left: 41.5%;
    top: 25%;
    background-color: white;
    box-shadow: 0px 0px 20px rgb(240, 240, 240);
    width: 300px;
    height: 150px;
    border: 1px solid grey;
    border-radius: 30px;
    z-index: 3;
    font-family: sans-serif;
    font-size: 40px;
    animation-name: float, disappear;
    animation-duration: 4s, 1s;
    animation-timing-function: ease-in-out, linear;
    animation-iteration-count: infinite;
    animation-fill-mode: forwards;
    animation-play-state: running, paused;
}

.playButton:hover {
    transform: scale(1.03);
    background-color: rgb(250, 250, 250);
    animation-play-state: paused;
}

@keyframes float {
    0% {
        margin-top: 120px;
    }
    50% {
        margin-top: 170px;
    }
    100% {
        margin-top: 120px;
    }
}

@keyframes disappear {
    0% {
        opacity: 1;
    }
    100% {
        opacity: 0;
    }
}

/*-----Grid-----*/

.grid {
    position: absolute;
    margin: 225px;
    left: 16.6%;
    display: flex;
    width: 700px;
    height: 500px;
    flex-wrap: wrap;
    justify-content: space-around;
    z-index: 2;
    opacity: 0;
    animation: appear 1s linear forwards;
    animation-delay: 1s;
    animation-play-state: paused;
}

.gridBut {
    height: 150px;
    width: 150px;
    background-color: white;
    border: 0.5px solid black;
    border-radius: 20px;
}

.gridBut:hover {
    background-color: rgb(240, 240, 240);
}

@keyframes appear {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

/*-----Start-----*/

.start {
    position: absolute;
    left: 41.5%;
    bottom: -10vh;
    background-color: rgb(0, 150, 0);
    color: white;
    box-shadow: 0px 0px 20px rgb(240, 240, 240);
    width: 300px;
    height: 70px;
    border: 5px solid snow;
    border-radius: 30px;
    z-index: 2;
    font-family: sans-serif;
    font-size: 40px;
    animation-name: raise1, drop1;
    animation-duration: 1.3s, 0.5s;
    animation-timing-function: ease-in-out, ease-in-out;
    animation-fill-mode: forwards;
    animation-delay: 1s, 1ms;
    animation-play-state: paused, paused;
}

.start:hover {
    background-color: rgb(0, 175, 0);
}

@keyframes raise1{
    0% {
        bottom: -10vh;
    }
    70% {
        bottom: 15%;;
    }
    100% {
        bottom: 12%;
    }
}

@keyframes drop1{
    0% {
        bottom: 12%;
    }
    100% {
        bottom: -10vh;
    }
}

/*-----Stopwatch-----*/

.stopwatch {
    font-family: sans-serif;
    font-size: 60px;
    position: absolute;
    left: 43.4%;
    margin-top: -100px;
    animation: drop2 1.3s ease-in-out forwards;
    animation-delay: 1s;
    animation-play-state: paused;
}

@keyframes drop2{
    0% {
        margin-top: -100px;
    }
    70% {
        margin-top: 95px;
    }
    100% {
        margin-top: 80px;
    }
}

/*-----Footer-----*/

#footer {
    background: linear-gradient(skyblue, white);
    border-top: 2px solid snow;
    width: 100vw;
    height: 8vh;
    position: absolute;
    bottom: -10vh;
    z-index: 4;
}

.container {
    margin: 15px auto;
    width: 200px;
    display: flex;
    justify-content: space-around;
}

.githubButton {
    width: 40px;
    height: 40px;
}

.githubButton:hover {
    transform: scale(1.2);
}

.linkedinButton {
    width: 40px;
    height: 40px;
}

.linkedinButton:hover {
    transform: scale(1.2);
}

.instagramButton {
    width: 40px;
    height: 40px;
}

.instagramButton:hover {
    transform: scale(1.2);
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="stylesheet.css">
        <title>Matching Game Project</title>
    </head>
    <body id="body">
        <header id="header">Matching Game</header>
        <div class="snowfall">
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
        </div>
        <script src="snow.js"></script>
        <div>
           <button class="playButton" type="button" onclick="runTitle(), runPlayBut()">Play</button>
        </div>
        <div class="grid">
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
            <button class="gridBut but" value="false"></button>
        </div>
        <div>
            <button class="start" type="button" onclick="runStartBut(), startStopwatch(), runMatching()">Start</button>
        </div>
        <div class="stopwatch">00:00:00</div>
        <script src="playbutton.js"></script>
        <script src="stopwatch.js"></script>
        <script src="matching.js"></script>
        <footer id="footer">
            <div class="footerBody">
                <div class="container">
                    <a href="https://github.com/aidanbh16" target="_blank"><img src="img/github.512x499.png" alt="github" class="githubButton"></a>
                    <a href="https://www.linkedin.com/in/aidan-holton/" target="_blank"><img src="img/linkedin-app-white-icon.png" alt="linkedin" class="linkedinButton"></a>
                    <a href="https://www.instagram.com/holton_aidan/" target="_blank"><img src="img/instagram-white-icon.png" alt="instagram" class="instagramButton"></a>
                </div>
            </div>
        </footer>
    </body>
</html>

Problem beim Discord.js Bot, mit scandir error, kann da jemand helfen? [closed]

 const result = binding.readdir(
                         ^

Error: ENOENT: no such file or directory, scandir 'C:UsersTobiasDesktoptcgsbotcommands'
    at Object.readdirSync (node:fs:1509:26)
    at Object.<anonymous> (C:UsersTobiasDesktoptcgsbotsrcindex.js:8:25)
    at Module._compile (node:internal/modules/cjs/loader:1378:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1437:10)
    at Module.load (node:internal/modules/cjs/loader:1212:32)
    at Module._load (node:internal/modules/cjs/loader:1028:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:142:12)
    at node:internal/main/run_main_module:28:49 {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'scandir',
  path: 'C:\Users\Tobias\Desktop


Wissen nicht weiter…

Haben schon einiges aus dem Internet probiert, hilft alles nicht.

Toggle between Front and Back camera not working

I have written a code in React js which toggles the front and back camera but it is not working properly.

import { useEffect,useRef } from "react"
import { useState } from "react"
export default function App(){
   const [strm,setStrm]=useState(null)
   const [cam,setCam]=useState(true)
   const myVdo=useRef(null)
   useEffect(()=>{
    navigator.mediaDevices.getUserMedia({video:{facingMode:'user'},audio:true})
    .then((stream)=>{
      setStrm(stream)
    })
   },[])
   useEffect(()=>{
    myVdo.current.srcObject=strm
   },[strm])
   const Flip=(e)=>{
    e.preventDefault()
    navigator.mediaDevices.getUserMedia({video:{facingMode:cam?'environment':'user'},audio:true})
    .then((s)=>{
      setStrm(s)
      setCam(!cam)
    })
   }
   return(
    <>
    <video autoPlay ref={myVdo}/>
    <button onClick={Flip}>Flip</button>
    </>
   )
}

Please help me to get rid of this issue.

Why can’t I get a list of all webcams of my pc in my app?

I’m new to javascript, and I’m trying to build a simple app that takes photos with the included webcam in my pc. I downloaded a library that makes the process much easier(Link: https://www.npmjs.com/package/webcam-easy). The good thing is that it has a “Webcam” object with a “webcamList” property that returns an array of all available webcams connected, when I log that property in the browser console with the app working, I get just that, but when I write the code to get it in VSCode, and then test it again, all I get is an empty array.

What could be happening?

Here’s the code in question:

const webCamElement = document.getElementById("webCam");
const canvasElement = document.getElementById("canvas");
const webcam = new Webcam(webCamElement, "user", canvasElement);
webcam.start();
const cameras = webcam.webcamList

console.log(cameras)

How to use Jexl to validate inputs in JavaScript/React?

I’m working on a project where I need to validate inputs using Jexl in a JavaScript/React application. I’m new to Jexl and I’m having trouble understanding how to use it for validation.

Specifically, I need to validate inputs against a set of rules defined in a Jexl expression. The inputs are dynamic and can change based on user interaction.

To give an example I have a form like this

form1

The visible if column is where I write the jexl syntax by opening a dialog as

dialogSave

What I’m writing here is that I have a mandatory string answer which should be always there.
Then is followed by the questionKey which is the key you see under the key column.
The == "yes" correspond on the items.

I know this way is valid as per jexl playground testing with a context as

{
  "answer": {
  "yes": "yes"
  }
}

What I need is to validate the input visibleIf by checking with jexl and show an error or a red borders when the syntax is invalid based on the context.

I’m not sure that is possible as I was unable to find any example of this.

What is the best way to generate unique user IDs at log in?

Google Analytics is now requiring us to pass a user_id protocol on our site, due to some changes they are making. We do not currently assign or collect unique IDs at log in, and I’m not sure how to even start doing that. We are a small company and I am our “developer”. I am by no means a professional at this, I just happen to be the one who understand the most out of anyone else here.

Is there an off-the-shelf code that we could paste that would assign unique IDs to users when they log in? I’ve spent all day trying to search for the answer but am coming up short.

If anyone could help point me in the right direction, it would be greatly appreciated.

React PageSpeed

I’m looking for a library to get 100% on performance on PageSpeed, our team have already made every thing that google asks for. And we still couldn’t get 100%. So we are looking for a library or a tool that works like wordpress plugins, to get 100% performance on PageSpeed.

We’ve done every thing that google ask’s for

Send value from Flask to Javascript variable in javascript file script [duplicate]

I am new to HTML and Javascript. I am having a Python dictionary from flask which I want to assign to javascript variable I tried the below systax but I am getting error.I looks like the value is not getting into javascript as my code is incorrect pls assist.

error = Uncaught TypeError: Cannot read properties of null (reading ‘value’)

Flask

@app.route('/data', methods=['POST'])
def get_d():
    pr_data = {'pr_data':['toyota','vw','GMC']}
    return jsonify(pr_data)

html

<div id="pr_data" data-pr_data={{pr_data}}></div>

javascript

var pr_data= JSON.parse(document.getElementById("pr_data").value)

I can’t handle all the possible viewports

Last time I tried to develop a website I started the layout from 0 to 280px because of the galaxy fold viewport, I don’t understand how experienced developers handle all the possible viewports.

Can someone tell me how can I handle viewports in a professional way?

I created a custom hook to create separate sites for mobile and desktop.

When creating my site I tested it using ngrok in my iPhone and bought an Android phone to test it but the safari search bar makes the layout horrible. I used dvh.

Why isn’t my nested route (Outlet -> index combo) working as expected?

I’m in the process of migrating my react-router from v5 to v6. There’s obviously some huge conceptual changes between how routes are handled between the two versions.

Previously, our authorization routes worked like this (code below): The root route ‘/’ rendered a component <AuthRoute />, which checked authentication and redirected to ‘/app’ if already authenticated, and otherwise rendered <AuthPage />, a layout route which rendered either AuthPageMobile or AuthPageWeb depending on the user’s device. From here, there was a new <Switch> component that showed either the login, signup, or reset routes depending on the URL provided, or redirect to ‘/login’ if the route was ‘/’. Here is the original setup:

App.js

<Switch>
      ...other routes
      <PrivateRoute exact path="/payment" component={PaymentScreen} />
      <AppContainerRoute path="/app" component={AppContainer} />
      <Route path="/reset/:token" component={ForgotPassWrapper} />
      <AuthRoute path="/" /> // Placed at bottom of tree so it matches all routes that aren't explicitly specified above.
    </Switch>

AuthRoute.js

const AuthRoute = props => {
  const mapState = state => ({
    isAuthenticated: state.currentUser.isAuthenticated,
  });
  const { isAuthenticated } = useSelector(mapState);
  return (
    <Route
      {...props}
      render={props =>
        isAuthenticated && localStorage.jwtToken && isMobile() ? (
          <Redirect
            to={{
              pathname: '/app/explore',
              state: { from: props.location },
            }}
          />
        ) : isAuthenticated && localStorage.jwtToken ? (
          <Redirect
            to={{
              pathname: '/app',
              state: { from: props.location },
            }}
          />
        ) : (
          <AuthPage {...props} />
        )
      }
    />
  );
};

AuthPage.js

<ContentContainer>
      <ScrollContainer>
        {isMobile() ? (
          <AuthPageMobile
            values={values}
            setValues={setValues}
            handleChange={handleChange}
            toggleValues={toggleValues}
            handleToggle={handleToggle}
            resetToken={resetToken}
          />
        ) : (
          <AuthPageWeb
            values={values}
            setValues={setValues}
            handleChange={handleChange}
            toggleValues={toggleValues}
            handleToggle={handleToggle}
            resetToken={resetToken}
          />
        )}
      </ScrollContainer>
    </ContentContainer>

AuthPageWeb.js

<Switch>
                <Route exact path="/">
                  <Redirect to="/login" />
                </Route>
                <Route
                  exact
                  path="/login"
                  render={props => (
                    <LoginForm
                      values={values}
                      setValues={setValues}
                      handleChange={handleChange}
                    />
                  )}
                />
                <Route
                  exact
                  path="/signup"
                  render={props => (
                    <SignupForm
                      values={values}
                      setValues={setValues}
                      handleChange={handleChange}
                      toggleValues={toggleValues}
                      handleToggle={handleToggle}
                    />
                  )}
                />
                <Route
                  path="/reset"
                  render={props => (
                    <ResetForm
                      values={values}
                      setValues={setValues}
                      handleChange={handleChange}
                      resetToken={resetToken}
                    />
                  )}
                />
              </Switch>

Now a couple big changes in v6 are that route order makes no difference, so I can’t capture the default at the bottom of the Switch statement, plus any middleware-style components like AuthRoute are no longer allowed. What I found through other research is the best way to replicate that type of functionality is to include it as the render element for the top-level Route and use Outlet to render the preferred sub-route. The issue I’m running into is when I type ‘www.oursite.com/login’ in the URL bar, I get a blank screen.

Here is my new reorganized approach:

App.js

<Routes>
          <Route path="/" element={<CheckAuth />}> // Also tried this with '/*'
            <Route index element={<AuthPage />} />
          </Route>
          <Route
            path="/please-verify"
            element={
              <RequireVerification>
                <VerificationPage />
              </RequireVerification>
            }
          ></Route>
          <Route
            path="/app/*"
            element={
              <RequireAuth>
                <RequireSubscribe>
                  <AppContainer />
                </RequireSubscribe>
              </RequireAuth>
            }
          ></Route>
          <Route path="/reset/:token" element={<ForgotPassWrapper />} />
        </Routes>

CheckAuth.js

const CheckAuth = () => {
  const mapState = (state) => ({
    isAuthenticated: state.currentUser.isAuthenticated,
  });
  const { isAuthenticated } = useSelector(mapState); 
  console.log(isAuthenticated, localStorage.jwtToken); // logs false, undefined
  return isAuthenticated && localStorage.jwtToken && isMobile() ? (
    <Navigate to="/app/explore" />
  ) : isAuthenticated && localStorage.jwtToken ? (
    <Navigate to="/app" />
  ) : (
    <Outlet /> // when a user is not logged in, I expect this to render the index child, <AuthPage/>
  );
};

AuthPage.js == same as before, except I added a console.log to see if it was actually being rendered, and this log is NOT firing, so somehow the index route is not being rendered.

AuthPageWeb.js

<Routes>
                <Route path="/" element={<Navigate to="/login" />} />
                <Route
                  path="/login"
                  element={
                    <LoginForm
                      values={values}
                      setValues={setValues}
                      handleChange={handleChange}
                    />
                  }
                />
                <Route
                  path="/signup"
                  element={
                    <SignupForm
                      values={values}
                      setValues={setValues}
                      handleChange={handleChange}
                      toggleValues={toggleValues}
                      handleToggle={handleToggle}
                    />
                  }
                />
                <Route
                  path="/reset"
                  element={
                    <ResetForm
                      values={values}
                      setValues={setValues}
                      handleChange={handleChange}
                      resetToken={resetToken}
                    />
                  }
                />
              </Routes>

What approach can I take to ensure that any routes that do not match one of the top level routes (/app, /payment, etc) would match on ‘/’ and then the sub-routes would be rendered in a lower-level component? (Note that I have tried using ‘/*’ on the top-level route).

Uncaught TypeError: Cannot read properties of undefined (reading ‘geometry’) – onPlaceChanged() triggering but getPlace() returns undefined

I am getting some errors when I click on any prediction from the google places autocomplete dropdown of predictions. From what I’ve discovered it getPlace() returns “undefined” the first time it’s triggered, but then it returns the address the second time around.
first click on a prediction from autocomplete dropdown

second click on the prediction

maps script
code for autocomplete

as can be seen in the code, I’m having a difficult time understanding why the getPlace doesn’t return a place even though the listener triggers the onPlaceChanged(), and I’m not sure if the errors are the root of the problem, but if anyone has any clues so that i can get a different error to work with that would be appreciated.

Ajax call fails when page change in Cordova app

With my pretty big Cordova app, I want to allow one page to kick off an Ajax Post message and allow the user to immediately leave the page. In some cases, I get an Ajax error even though the Ajax message has been sent. I’m having trouble detecting this case.

Background: Yes, I made a bad architectural decision and my Cordova app uses many separate pages. When the user changes pages quickly, the Ajax Post message throws an error (even though the Post message is always sent!). Unfortunately all the error variables (jqXHR.status, textStatus, errorThrown) are either blank or 0.

What I can do is use the cordova-plugin-network-information plugin to detect if there is a connection. If there is a connection and the Ajax Post message fails, I can assume the user has changed pages. But this does not seem like a robust solution.

Any advice?

Thanks much!

  • Jon

Converting Absolute path to Pre-Transform path

I have an svg element where I am applying transformation. Once the transformation is done, it is possible to calculate the absolute path which would have all the effects of the transformation; like below. These calculations are not easy as they would probably need complex calculations for different combinations of transform elements.

So for example, a path M650,300L650,150 that receives transform as rotate(45,650,300) becomes M650,300L756.0660171779821,193.93398282201787 as an absolute path.

My question is, if I start from the opposite M650,300L756.0660171779821,193.93398282201787 is there any API that can give me the path value of M650,300L650,150 which would turn to M650,300L756.0660171779821,193.93398282201787 with rotate(45,650,300) or a matrix(a,b,c,d,e,f).

To sumarize, how do I solve for x M650,300L650,150 from only y M650,300L756.0660171779821,193.9339828220178 and z rotate(45,650,300)/matrix(a,b,c,d,e,f)?

const data = [{ x: 650, y: 300 }, { x: 650, y: 150 }];

const d1 = data.reduce((acc, curr, index) => {
    if (index === 0) {
        return `M${curr.x},${curr.y}`;
    } else {
        return `${acc}L${curr.x},${curr.y}`;
    }
}, '');
const orgPath = document.querySelector('.original>path')
    .setAttribute('d', d1);

const rotatePath = document.querySelector('.originalWithTransform>path')
    .setAttribute('d', d1);

const pointOfRotation = { x: 650, y: 300 };

const angleOfRotationDeg = 45;

const angleOfRotationInRad = angleOfRotationDeg * Math.PI / 180;

const newData = [];

const fn = (d, x, y) => {
    // Translation to origin
    const translatedX = d.x - x;
    const translatedY = d.y - y;

    // Rotation matrix
    const newX = translatedX * Math.cos(angleOfRotationInRad) - translatedY * Math.sin(angleOfRotationInRad);
    const newY = translatedX * Math.sin(angleOfRotationInRad) + translatedY * Math.cos(angleOfRotationInRad);

    // Translation back to original position
    const rotatedX = newX + x;
    const rotatedY = newY + y;

    newData.push({ x: rotatedX, y: rotatedY });
}

data.forEach(d => fn(d, pointOfRotation.x, pointOfRotation.y));


const d2 = newData.reduce((acc, curr, index) => {
    if (index === 0) {
        return `M${curr.x},${curr.y}`;
    } else {
        return `${acc}L${curr.x},${curr.y}`;
    }
}, '');


//test to see if it aligns to the rotated path

const absPath = document.querySelector('.absolute>path')
absPath.setAttribute('d', d2);
absPath.setAttribute('stroke-dasharray', '4');
absPath.setAttribute('stroke-width', '4');
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Document</title>
  </head>
  <script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
  <body>
    <svg viewBox="0 0 1280 600">
      <rect width="1280" height="600" fill="#EFEFEF"></rect>
      <g class="original">
        <path fill="none" stroke="blue"></path>
      </g>
      <g class="originalWithTransform">
        <path fill="none" stroke="red" transform="rotate(45,650,300)"></path>
      </g>
      <g class="absolute">
        <path fill="none" stroke="brown"></path>
      </g>
      <line x1="240" x2="1040" y1="300" y2="300" stroke="green"></line>
    </svg>
  </body>
</html>