SOLVED: Triggering this file input with a button click doesn’t allow images to attach

I am sure it is something simple that I am not understanding but I don’t see the issue here.

In the code below I am using a button (#clickme) to trigger the file input (#image-input) to open a dialogue box to choose a file. I am doing this so I can style the button. That works. But because of what I am doing inside the change event (converting files and creating a new formData object), it doesn’t actually upload an image. It only works if you click on the actual file input (#file-input).

What am I missing here? How do I allow the use of a button to open the dialogue box but still get my file to upload via AJAX? I get no errors, just no file upload.

I believe the change event isn’t firing.

$("#clickme").on("click", function () {
  $("#image-input").trigger("click");
});

$("#image-input").on("change", function (ev) {
  var originalFile = ev.target.files[0];

  if (
    originalFile.type === "image/heic" ||
    originalFile.name.toLowerCase().endsWith(".heic")
  ) {
    heic2any({
      blob: originalFile,
      toType: "image/jpeg",
    })
      .then(function (resultBlob) {
        var convertedFile = new File(
          [resultBlob],
          originalFile.name.replace(/.heic$/i, ".jpg"),
          { type: "image/jpeg" },
        );

        var formData = new FormData();

        formData.append("image-input", convertedFile, convertedFile.name);

        // formData.append('otherField', 'value');

        uploadFile(formData);
      })
      .catch(function (x) {
        var error = "Error code: " + x.code + " " + x.message;
        console.log(error);
      });
  } else {
    var formData = new FormData();
    formData.append("image-input", originalFile, originalFile.name);
    uploadFile(formData);
  }
});

function uploadFile(formData) {
  $.ajax({
    url: base_url + "home/upload",
    type: "POST",
    data: formData,
    dataType: "json",
    mimeType: "multipart/form-data",
    contentType: false,
    cache: false,
    processData: false,
    success: function (response) {
      console.log(response);
    },
    error: function (error) {
      console.log(error);
    },
  });
}

make dark mode can be still dark mode when i reload browser

I wanna make a website with dark mode, i want this website can still with dark mode, but i dont know to fix it, can anyone to help me?

i’ve been try with this code

const checkbox = document.getElementById("checkbox")
checkbox.addEventListener("change", () => {
  document.body.classList.toggle("dark")
  localStorage.setItem("checkbox", checkbox)
})


const inputType = () => {
  let fullName = document.getElementById("fname").value
  let email = document.getElementById("email").value
  let messege = document.getElementById("messege").value
}

<form action="" method="post" id="formInput">
            <label for="fname">Fullname: </label><br>
            <input type="text" id="fname" name="fname"><br><br>
            <label for="email">E-Mail: </label><br>
            <input type="email" id="email" name="email"><br><br>
            <label for="messege">Messege: </label><br>
            <textarea name="messege" id="messege"></textarea><br>
            <input type="submit" value="Submit" onclick="inputType()">
        </form> 

Facing problem with re-renders in react (or anything else?)

I am working on creating a mccabe thiele plotter (a chemical engineering topic) which will take some parameters as input and show a plot (using chartjs)

For this, I need to select one among two options ‘vol’ or ‘datapts’.
In vol mode (relative volatility mode), equilibrium data equi will be calculated from a equation and for datapts mode (equilibrium data), i need to provide equi data:

For toggling selection and automatically updating equi data:

useEffect(() => {
        if (vol === 'datapts') addEqui([{x: 0, y: 0}, {x: 1, y: 1}])
        else if (vol === 'vol' && alpha > 1) equi_rel_from_alpha();
    }, [vol, alpha]);
function equi_rel_from_alpha() {
        try {
            let newEqui = []
            let x
            let y_eq
            for (let i = round(0); round(i) <= 1; i += 0.1) {
                x = round(i)
                y_eq = (alpha * x) / (1 + (alpha - 1) * x)
                newEqui.push({ x: x, y: Number(y_eq.toFixed(4)) })
            }
            addEqui(newEqui)
        } catch (err) {
            setErr('Error in finding equilibrium curve from alpha')
        }
    }
 function round(el) {
        return Math.round(el * 100) / 100
    }

Azeo is a random function as to calculate how many times the equi data lines will cross y=x line:

    const [azeo, setAzeo] = useState([])    
    
    function check_azeo(){
    
        const xy = {a: 1, b: -1, c: 0}
        const len = equi.length
        let azeo_temp = []
        let pos = 1
        if(len>2){
            let p1
            let p2
            let ln
            while(pos+1!=len-1){
                p1 = equi[pos]
                p2 = equi[pos+1]
                if((xy.a*p1.x + xy.b*p1.y + xy.c) == 0){
                    azeo_temp.push(p1.x)
                }
                else if((xy.a*p1.x + xy.b*p1.y + xy.c)*(xy.a*p2.x + xy.b*p2.y + xy.c)<0){
                    ln = line_from_2points(p1, p2)
                    azeo_temp.push(intersection_of_2lines(xy, ln).x)
                }
                pos += 1
            }   
        }
        setAzeo(azeo_temp)
    }    

Now once I have selected the mode, there will be parameters provided (D, F, etc.) and mccabe_thiele function will be called based on criteria and mode as below:

useEffect(() => {
        if (D && F && xD && xF && q && op_ratio && q && vol && alpha && equi.length > 1) {
            if (D > 0 && F > 0 && F > D && xF < 1 && xD < 1 && xF > 0 && xD > 0 && alpha > 1 && F * xF > D * xD && xD > xF && op_ratio > 1) {
                if (vol === 'vol') {
                    setErr('')
                    mcCabe_thiele()
                }
                else if (vol === 'datapts') {
                    
                    if(azeo.length > 0){
                        setErr('Cant plot for azeotropes')
                    }
                    else if (equi.length >= 5) {
                        setErr('')
                        mcCabe_thiele()
                    }
                    else setErr('Atleast 5 equilibrium points must be provided')
                }
            }
            else if (alpha <= 1) setErr('Relative volatility must be greater than 1')
            else if (D <= 0) setErr('Distillate rate must be greater than 0')
            else if (F <= 0) setErr('Feed rate must be greater than 0')
            else if (F < D) setErr('Feed rate must be greater than distillate rate')
            else if (F * xF < D * xD) setErr('You are expecting more than you are feeding')
            else if (xD <= xF) setErr('Distillate purity must be more than feed purity')
            else if (op_ratio <= 1) setErr('Optimum ratio must be greater than 1')
            else if (xD <= 0) setErr('Distillate purity cannot be zero')
            else if (xD >= 1) setErr('Distillate cannot be completely pure')
            else if (xF <= 0) setErr('Feed cannot be single component')
            else if (xF >= 1) setErr('Feed cannot be single component')
        }
    }, [alpha, D, F, xD, xF, q, op_ratio, equi, azeo])

Here, D, F, xD, xF, q, opt_ratio are parameters and need not be worried about.

I am facing a very very weird issue:

  1. When I am using vol mode, its working completely fine but mccabe thiele is being called twice.

  2. When I am switching to datapts mode and entering valid equi data (5 points), its working fine but again mccabe thiele is called twice.

  3. In case when I am intentionally using points in datapts mode where azeo is non-empty array, weirdly still mccabe_thiele function is being called (which shouldnt be the case when azeo.length>0) and stages are being drawn according to mccabe thiele method (but using equi data of vol mode). So system is using vol mode equi data for calculation when azeo is non-empty, I want the plot to not execute the mccabe thiele function in this case.

I know the problem is too long, but I want the solution. I am not using any strict mode, please help!!! (all parameter inputs are working fine)

McCabe_math.jsx

import { useEffect } from "react"

export default function McCabe_math({ D, F, xF, xD, q, vol, alpha, op_ratio, setW, setxW, addEqui, setR, setErr, equi, setSteps, setfdInter, setRm, setStages, azeo, setAzeo }) {

    function round(el) {
        return Math.round(el * 100) / 100
    }

    useEffect(() => {
        setErr('')
    }, [vol, D, F, xD, xF, q, op_ratio])

    useEffect(() => {
        if (vol === 'datapts') addEqui([{x: 0, y: 0}, {x: 1, y: 1}])
        else if (vol === 'vol' && alpha > 1) equi_rel_from_alpha();
    }, [vol, alpha]);


    // useEffect(() => {
    //     if (azeo.length > 0) setErr('Azeotrope formation')
    // }, [azeo])


    useEffect(() => {
        if (D && F && xD && xF && q && op_ratio && q && vol && alpha && equi.length > 1) {
            if (D > 0 && F > 0 && F > D && xF < 1 && xD < 1 && xF > 0 && xD > 0 && alpha > 1 && F * xF > D * xD && xD > xF && op_ratio > 1) {
                if (vol === 'vol') {
                    setErr('')
                    mcCabe_thiele()
                }
                else if (vol === 'datapts') {
                    
                    if(azeo.length > 0){
                        setErr('Cant plot for azeotropes')
                        setStages([])
                    }
                    else if (equi.length >= 5) {
                        setErr('')
                        mcCabe_thiele()
                    }
                    else setErr('Atleast 5 equilibrium points must be provided')
                }
            }
            else if (alpha <= 1) setErr('Relative volatility must be greater than 1')
            else if (D <= 0) setErr('Distillate rate must be greater than 0')
            else if (F <= 0) setErr('Feed rate must be greater than 0')
            else if (F < D) setErr('Feed rate must be greater than distillate rate')
            else if (F * xF < D * xD) setErr('You are expecting more than you are feeding')
            else if (xD <= xF) setErr('Distillate purity must be more than feed purity')
            else if (op_ratio <= 1) setErr('Optimum ratio must be greater than 1')
            else if (xD <= 0) setErr('Distillate purity cannot be zero')
            else if (xD >= 1) setErr('Distillate cannot be completely pure')
            else if (xF <= 0) setErr('Feed cannot be single component')
            else if (xF >= 1) setErr('Feed cannot be single component')
        }
    }, [alpha, D, F, xD, xF, q, op_ratio, equi, azeo])

    function equi_rel_from_alpha() {
        try {
            let newEqui = []
            let x
            let y_eq
            for (let i = round(0); round(i) <= 1; i += 0.1) {
                x = round(i)
                y_eq = (alpha * x) / (1 + (alpha - 1) * x)
                newEqui.push({ x: x, y: Number(y_eq.toFixed(4)) })
            }
            addEqui(newEqui)
        } catch (err) {
            setErr('Error in finding equilibrium curve from alpha')
        }
    }

    function line_from_2points(p1, p2) {
        let x1 = p1.x
        let y1 = p1.y
        let x2 = p2.x
        let y2 = p2.y
        let m = (y2 - y1) / (x2 - x1)
        return { a: m, b: -1, c: y1 - m * x1 }
    }

    function closestPoint(a, b, c) {
        let init = Math.abs(c / (Math.pow(a * a + b * b, 0.5)))
        let min = { val: init, pt: { x: 0, y: 0 } }

        for (let el of equi) {
            let xi = el.x
            let yi = el.y
            let dist = Math.abs((a * xi + b * yi + c) / (Math.pow(a * a + b * b, 0.5)))
            if (dist == 0) return { x: xi, y: yi, ptr: 'exact', dist: 0 }  //when the intersection is an actual data point
            else if (dist < min.val) {
                min.val = dist
                min.pt = { x: xi, y: yi }
            }
        }
        return { x: min.pt.x, y: min.pt.y, ptr: 'non-exact', dist: min.val }
    }

    function sideofPoint(xi, yi, a, b, c) {
        let s_origin = a * 0 + b * 0 + c
        let s_point = a * xi + b * yi + c
        if (s_origin * s_point < 0) return 'right'
        else if (s_origin * s_point > 0) return 'left'
    }

    function complementaryPoint(xi, side) {
        const index = equi.findIndex(el => el.x === xi)
        if (side === 'right') return equi[index - 1]
        else if (side === 'left') return equi[index + 1]
    }

    function intersection_of_2lines(l1, l2) {
        let a1 = l1.a
        let b1 = l1.b
        let c1 = l1.c
        let a2 = l2.a
        let b2 = l2.b
        let c2 = l2.c

        return { x: (b1 * c2 - b2 * c1) / (a1 * b2 - a2 * b1), y: (a2 * c1 - a1 * c2) / (a1 * b2 - a2 * b1) }
    }

    function q_line() {
        try {
            if (Number(q) === 1) return { a: 1, b: 0, c: Number(-xF) }
            else {
                let feed_slope = (-1) * (q / (1 - q))
                return { a: (-1) * feed_slope, b: 1, c: xF * (feed_slope - 1) }
            }
        } catch (err) {
            setErr('Error in finding q line')
        }
    }

    function feed_intersection() {
        try {
            let feed_slope
            let closestPt
            let side
            let compPt
            if (Number(q) === 1) {
                //feed line eqn: x + 0*y - xF = 0
                closestPt = closestPoint(1, 0, -1 * (xF))
                if (closestPt.ptr === 'exact') return { x: closestPt.x, y: closestPt.y }
                else {
                    side = sideofPoint(closestPt.x, closestPt.y, 1, 0, -1 * (xF))
                }
            }
            else {
                //feed line eqn: (-feed_slope)x + y + xF(feed_slope - 1) = 0
                feed_slope = (-1) * (q / (1 - q))
                closestPt = closestPoint((-1) * feed_slope, 1, xF * (feed_slope - 1), equi)
                if (closestPt.ptr === 'exact') return { x: closestPt.x, y: closestPt.y }
                else {
                    side = sideofPoint(closestPt.x, closestPt.y, (-1) * feed_slope, 1, xF * (feed_slope - 1))
                }
            }
            compPt = complementaryPoint(closestPt.x, side)
            let comp_line = line_from_2points(closestPt, compPt)

            if (Number(q) === 1) return intersection_of_2lines(comp_line, { a: 1, b: 0, c: (-1) * Number(xF) })
            else return intersection_of_2lines(comp_line, { a: (-1) * feed_slope, b: 1, c: xF * (feed_slope - 1) })
        } catch (err) {
            setErr('Error in finding feed intersection with curve')
        }
    }

    function step_intersection(yi) {
        let snap = -1;

        for (let i = 0; i < equi.length; i++) {
            if (equi[i].y === yi) return { x: equi[i].x, y: equi[i].y }; // Exact match
            if (equi[i].y > yi) {
                snap = i;
                break; // Stop at the first point where y > yi
            }
        }

        // If `yi` is outside the range, return null
        if (snap === -1 || snap === 0) return null; // No valid intersection

        let p1 = equi[snap - 1];
        let p2 = equi[snap];

        let l1 = line_from_2points(p1, p2);
        let l2 = { a: 0, b: 1, c: -yi };

        return intersection_of_2lines(l1, l2);
    }

    function mcCabe_thiele() {

        console.log('mct called')

        //top_composition
        let top_compo = { x: xD, y: xD }

        //to find out the intersection point of feed line with equilibrium curve after finding closest and complementary eq. data points and interpolation
        const feed_equi = feed_intersection()

        //q-line
        let q_ln = q_line()

        //pinch calculations
        let pinch_slope = (feed_equi.y - top_compo.y) / (feed_equi.x - top_compo.x)

        let Rmin = pinch_slope / (1 - pinch_slope)
        setRm(Rmin)
        let Ropt = Rmin * op_ratio
        setR(Ropt)

        let rect_slope = Ropt / (Ropt + 1)
        let rect = { a: (-1) * rect_slope, b: 1, c: xD * (rect_slope - 1) }

        //intersection of feed and rectifying line
        let feed_rect_intersection = intersection_of_2lines(q_ln, rect)

        try {
            setfdInter(feed_rect_intersection)
        } catch (err) {
            setErr('Error in finding feed and rectification line intersection')
        }

        //stripping line
        let W = F - D
        setW(W)
        let xW = (F * xF - D * xD) / W
        setxW(xW)
        let bottom_compo = { x: xW, y: xW }
        let strip = line_from_2points(feed_rect_intersection, bottom_compo)

        //steps calculation
        let step_pts = []
        let x_curr = xD
        let y_curr
        let stage = 'rect'
        let check
        let next

        try {
            while (true) {
                //rectifying area
                if (stage === 'rect') {
                    //horizontal step
                    y_curr = (-1) * (rect.a * x_curr + rect.c) / (rect.b)

                    //check if stripping zone is reached after last vertical dip
                    check = sideofPoint(x_curr, y_curr, q_ln.a, q_ln.b, q_ln.c)
                    if (check === 'left') {
                        stage = 'strip'
                        continue
                    }
                    step_pts.push({ x: x_curr, y: y_curr })

                    //if stripping zone is not reached
                    next = step_intersection(y_curr)
                    x_curr = next.x
                    y_curr = next.y
                    check = sideofPoint(x_curr, y_curr, q_ln.a, q_ln.b, q_ln.c)
                    if (check === 'left') {
                        step_pts.push({ x: x_curr, y: y_curr })
                        stage = 'strip'
                        continue
                    }
                    step_pts.push({ x: x_curr, y: y_curr })

                    //vertical step
                    next = intersection_of_2lines(rect, { a: 1, b: 0, c: -1 * x_curr })
                    x_curr = next.x
                }

                if (stage === 'strip') {
                    //horizontal step
                    y_curr = (-1) * (strip.a * x_curr + strip.c) / (strip.b)

                    if (x_curr < xW) {
                        step_pts.push({ x: x_curr, y: x_curr })
                        break
                    }
                    step_pts.push({ x: x_curr, y: y_curr })

                    next = step_intersection(y_curr, equi)
                    x_curr = next.x
                    y_curr = next.y
                    step_pts.push({ x: x_curr, y: y_curr })

                    //vertical step
                    next = intersection_of_2lines(strip, { a: 1, b: 0, c: -1 * x_curr })
                    x_curr = next.x
                }
            }
            setSteps(step_pts)
            setStages(() => Math.floor(step_pts.length / 2))
        }
        catch (err) {
            console.log(err)
            setErr('Error in step calculation')
        }
    }

    return (
        <>

        </>
    )
}

Mccabe_plot.jsx

import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js';
import { useState, useEffect } from 'react';

export default function Mccabe_plot({ xW, xD, xF, fdInter, equi, steps, err, vol }) {

    ChartJS.register(
        CategoryScale,
        LinearScale,
        PointElement,
        LineElement,
        Title,
        Tooltip,
        Legend
    );

    const [x_eq, addx_eq] = useState([]);
    const [y_eq, addy_eq] = useState([]);
    const [x_steps, addx_steps] = useState([]);
    const [y_steps, addy_steps] = useState([]);
    const [chartData, setChartData] = useState(null);

    useEffect(() => {
        if (xD < 1 && xD>0 && xW > 0 && xW<1 && xF > 0 && xF < 1 && xD>xF && xF>xW) {
            if((vol==='vol' && err === '')||(vol==='datapts')){
    
                setChartData(equi.length>=5?{
                    datasets: [
                        {
                            label: 'x_eq vs y_eq',
                            data: equi.map((point) => ({
                                x: Number(point.x).toFixed(4),
                                y: Number(point.y).toFixed(4),
                            })),
                            fill: false,
                            borderColor: 'rgba(75, 192, 192, 1)',
                            tension: 0.1,
                        },
                        {
                            label: 'Steps',
                            data: steps.map((point) => ({
                                x: Number(point.x).toFixed(4),
                                y: Number(point.y).toFixed(4),
                            })),
                            fill: false,
                            borderColor: 'brown',
                            tension: 0.1,
                        },
                        {
                            label: 'Enriching Line',
                            data: [
                                { x: xD, y: xD },
                                { x: fdInter.x, y: fdInter.y },
                            ],
                            fill: true,
                            borderColor: 'red',
                            tension: 0.1,
                        },
                        {
                            label: 'Stripping Line',
                            data: [
                                { x: xW, y: xW },
                                { x: fdInter.x, y: fdInter.y },
                            ],
                            fill: true,
                            borderColor: 'blue',
                            tension: 0.1,
                        },
                        {
                            label: 'Feed Line',
                            data: [
                                { x: xF, y: xF },
                                { x: fdInter.x, y: fdInter.y },
                            ],
                            fill: true,
                            borderColor: 'grey',
                            tension: 0.1,
                        },
                        {
                            label: 'x=y',
                            data: [
                                { x: 0, y: 0 },
                                { x: 1, y: 1 },
                            ],
                            fill: true,
                            borderColor: 'black',
                            tension: 0.1,
                        }
                    ]
                }:
                {
                    datasets: [
                        {
                            label: 'x_eq vs y_eq',
                            data: equi.map((point) => ({
                                x: Number(point.x).toFixed(4),
                                y: Number(point.y).toFixed(4),
                            })),
                            fill: false,
                            borderColor: 'rgba(75, 192, 192, 1)',
                            tension: 0.1,
                        },
                        {
                            label: 'Enriching Line',
                            data: [
                                { x: xD, y: xD },
                                { x: fdInter.x, y: fdInter.y },
                            ],
                            fill: true,
                            borderColor: 'red',
                            tension: 0.1,
                        },
                        {
                            label: 'Stripping Line',
                            data: [
                                { x: xW, y: xW },
                                { x: fdInter.x, y: fdInter.y },
                            ],
                            fill: true,
                            borderColor: 'blue',
                            tension: 0.1,
                        },
                        {
                            label: 'Feed Line',
                            data: [
                                { x: xF, y: xF },
                                { x: fdInter.x, y: fdInter.y },
                            ],
                            fill: true,
                            borderColor: 'grey',
                            tension: 0.1,
                        },
                        {
                            label: 'x=y',
                            data: [
                                { x: 0, y: 0 },
                                { x: 1, y: 1 },
                            ],
                            fill: true,
                            borderColor: 'black',
                            tension: 0.1,
                        }
                    ]
                });
            }
            }
    }, [equi, steps, err, xD, xW, xF, vol]);

    const options = {
        responsive: true,
        scales: {
            x: {
                type: 'linear',
                position: 'bottom',
                title: {
                    display: true,
                    text: 'X',
                    font: {
                        size: 15,
                        weight: 'normal',
                    },
                    grid: {
                        borderColor: 'black',
                        borderWidth: 5,
                    },
                }
            },
            y: {
                beginAtZero: true,
                title: {
                    display: true,
                    text: 'Y',
                    font: {
                        size: 15,
                        weight: 'normal',
                    },
                },
            },
        },
    };

    return (
        <div>
            {chartData ? (
                <Line data={chartData} options={options} width={600} height={570} />
            ) : (
                <p>Invalid input values. Chart not updated.</p>
            )}
        </div>
    );
}

PowerShell Select-String fails with “Illegal at end of pattern” when searching for directory

I’m using PowerShell to find ignored files in my Git repository that belong to a specific directory, company_logos. I’m running the following command in my project folder:

powershell
Copy
Edit
git ls-files –ignored –others –exclude-standard | Select-String “company_logos”
However, I get this error:

vbnet
Copy
Edit
Select-String : The string company_logos is not a valid regular
expression: parsing “company_logos” – Illegal at end of pattern.
At line:1 char:54

  • … ignored –others –exclude-standard | Select-String “company_logos”
  •                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidArgument: (:) [Select-String], ArgumentException
    • FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand
      It seems like PowerShell is interpreting company_logos as a regex pattern, and the backslashes () in the path are causing an issue.

What I’ve tried:
Escaping the backslashes:

powershell
Copy
Edit
git ls-files –ignored –others –exclude-standard | Select-String “company_logos”
But I still get the same issue.

Using single quotes:

powershell
Copy
Edit
git ls-files –ignored –others –exclude-standard | Select-String ‘company_logos’
This also didn’t work.

Using -SimpleMatch:

powershell
Copy
Edit
git ls-files –ignored –others –exclude-standard | Select-String -SimpleMatch “company_logos”
This worked, but I want to understand why the original command failed and how to properly escape it.

Question:
Why does Select-String throw the “Illegal at end of pattern” error in my original command?
What is the correct way to search for a directory name like company_logos in this context?
Any insights would be appreciated!

Animated dashed css circulating border

I want to create div with dashed border all round and once the user hovers over it it dashed borders move around / circulates in the same way they’re they just move round the edges not leaving their position.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style> 
   .animated-border {
  width: 200px;
  height: 100px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  border: 4px dashed transparent;
}

.animated-border::before {
  content: "";
  position: absolute;
  top: -4px;
  left: -4px;
  right: -4px;
  bottom: -4px;
  border: 4px dashed black;
  clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
  animation: borderMove 2s linear infinite paused;
}

.animated-border:hover::before {
  animation-play-state: running;
}

@keyframes borderMove {
  0% {
    clip-path: inset(0 0 90% 0);
  }
  25% {
    clip-path: inset(0 90% 0 0);
  }
  50% {
    clip-path: inset(90% 0 0 0);
  }
  75% {
    clip-path: inset(0 0 0 90%);
  }
  100% {
    clip-path: inset(0 0 90% 0);
  }
}

</style>
<body>
    <div class="animated-border">Your Content</div>
</body>
</html>

The code above is working a bit well but the only issue is that the borders are not round it its just half but they’re going round though.

React native navigation error with .replace() and .reset()

<TouchableOpacity
style={styles.button}
onPress={() => {
navigation.reset({
index: 0,
routes: [{ name: 'ProfilePage' }],
});
}}
>
<Text style={styles.buttonText}>Test Navigation</Text>
</TouchableOpacity>

This code crashes my app whenever I click on the Test Navigation button. I’ve read on multiple posts on reddit, github and stackexchange that the fix is to install react-native-reanimated, and to add

import react-native-reanimated;

to the top of the App.js file. I did both those things and it doesn’t work. I’ve got no clue what to do

After open bootstrap modal and close i can’t reopen again why?

I open bootstrap modal and close it without any issue

when I try to reopen again for second time after closing it

it not open so how to fix issue

so how to solve this issue

I can open bootstrap modal for display data and can close it without any issue

but when try to reopen again it not accept and not open bootstrap modal

<button id="BtnAddDisplay" class="btn custom-button col-12" type="button" onclick="INSERT_REQUEST_DEGREE_EQUATION_MODAL(); return false;">
        ارسال الى جهه جديده
    </button>
<div class="modal fade" id="INSERT_REQUEST_DEGREE_EQUATIONModal" tabindex="-1" aria-labelledby="INSERT_REQUEST_DEGREE_EQUATIONModalLabel" aria-hidden="true">
  <div class="modal-dialog custom-modal-dialog">
    <div class="modal-content">
      <div class="modal-header btn-dark text-center w-100">
        <h5 class="modal-title text-white w-100" id="INSERT_REQUEST_DEGREE_EQUATIONModalLabel">اضافه جهه جديده</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
               <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="card-subtitle line-on-side text-muted text-center font-small-4 pt-1">دراسة مواد للشهادة ذاتها بجامعات أخرى</h6>
                            </div>
                            <div class="card-body">
          
                                <div id="dvTransfersInputs" class="row transfers">
                                    <div class="col-12 col-md-4">
                                        <div class="form-group">
                                            <label class="control-label">
                                                <asp:Literal Text="<%$ Resources:Resource1, P_COUNTRY_ID %>" runat="server" />
                                            </label>
                                              <asp:DropDownList ID='ddlP_COUNTRY_ID_equation' runat='server' 
                                    CssClass='chosen-select chosen-rtl form-control' 
                                    data-placeholder="<%$ Resources:Resource1, ddl-placeholder %>" 
                                    ClientIDMode='Static' 
                                    onchange="handleDropdownChange_country(this)">
                                    <asp:ListItem Value="" Text="" Selected="True"></asp:ListItem>
                                </asp:DropDownList>
                                        </div>
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <div class="form-group">
                                            <label class="control-label">
                                                <asp:Literal Text="<%$ Resources:Resource1, P_UNIVERSITY_ID %>" runat="server" />
                                            </label>
                                            <asp:DropDownList ID='ddlP_UNIVERSITY_ID_equation' runat='server' CssClass='chosen-select chosen-rtl form-control' data-placeholder="<%$ Resources:Resource1, ddl-placeholder %>" ClientIDMode='Static'  onchange="handleDropdownChange_university(this)">
                                                <asp:ListItem Value="" Text="" Selected="True"></asp:ListItem>
                                            </asp:DropDownList>
                                        </div>
                                    </div>
                                    <div class="col-12 col-md-4">
                                        <div class="form-group">
                                            <label class="control-label">
                                                <asp:Literal Text="<%$ Resources:Resource1, P_OFFICE_ID %>" runat="server" />
                                            </label>
                                            <asp:DropDownList ID='ddlP_OFFICE_ID_equation' runat='server' CssClass='chosen-select chosen-rtl form-control' data-placeholder="<%$ Resources:Resource1, ddl-placeholder %>" ClientIDMode='Static' onchange="handleDropdownChange_office(this)">
                                                <asp:ListItem Value="" Text="" Selected="True"></asp:ListItem>
                                            </asp:DropDownList>
                                        </div>
                                    </div>
                          
                                </div>
                            </div>
                 
                        </div>

                    </div>
                </div>
      </div>
      <div class="modal-footer justify-content-center">
       <button type="button" onclick="INSERT_UPD_E_TRANS_REQUEST_DEGREE_EQUATION_TRANSFARED()" class="btn btn-success">اضافه</button>
       <button type="button" class="btn btn-danger" data-dismiss="modal">الغاء</button>
      </div>
    </div>
  </div>
</div>
i open it using 
function INSERT_REQUEST_DEGREE_EQUATION_MODAL() {
    debugger;
    //$('.chosen-select').chosen({
    //    no_results_text: "No results matched",
    //    width: "100%"
    //});
    // check values of country
    $('#ddlP_OFFICE_ID_equation').val('').trigger('chosen:updated');
    $('#ddlP_UNIVERSITY_ID_equation').val('').trigger('chosen:updated');
    $('#ddlP_COUNTRY_ID_equation').val('').trigger('chosen:updated');
    var hiddenCountryValue = $('#HiddenCountry').val();
    var countries = JSON.parse(hiddenCountryValue);

    // Clear the dropdown and add a default empty option
    var $ddlCountry = $('#ddlP_COUNTRY_ID_equation');
    $ddlCountry.empty();
    $ddlCountry.append($('<option>', {
        value: '',
        text: 'اختر من القائمه'
    }));

    // Populate the dropdown with the JSON data
    $.each(countries, function (index, country) {
        $ddlCountry.append($('<option>', {
            value: country.COUNTRY_ID,
            text: country.COUNTRY_NAME
        }));
    });

    // Set the selected index to 0 (default option)
    $ddlCountry.prop('selectedIndex', 0);

    // Trigger the chosen update if you are using the chosen plugin
    $ddlCountry.trigger('chosen:updated');

    //========== Check university
    // Get the JSON data from the hidden field for Universities
    var hiddenUniversityValue = $('#HiddenUniversity').val();
    var universities = JSON.parse(hiddenUniversityValue);

    // Clear the University dropdown and add a default empty option
    var $ddlUniversity = $('#ddlP_UNIVERSITY_ID_equation');
    $ddlUniversity.empty();
    $ddlUniversity.append($('<option>', {
        value: '',
        text: 'اختر من القائمه'
    }));

    // Populate the University dropdown with the JSON data
    $.each(universities, function (index, university) {
        $ddlUniversity.append($('<option>', {
            value: university.UNIVERSITY_ID,
            text: university.UNIVERSITY_DESC
        }));
    });

    // Set the selected index to 0 (default option)
    $ddlUniversity.prop('selectedIndex', 0);

    // Trigger the chosen update for University dropdown
    $ddlUniversity.trigger('chosen:updated');

    //=========== Check office
    var hiddenOfficeValue = $('#HiddenOffice').val();
    var offices = JSON.parse(hiddenOfficeValue);

    // Clear the Office dropdown and add a default empty option
    var $ddlOffice = $('#ddlP_OFFICE_ID_equation');
    $ddlOffice.empty();
    $ddlOffice.append($('<option>', {
        value: '',
        text: 'اختر من القائمه'
    }));

    // Populate the Office dropdown with the JSON data
    $.each(offices, function (index, office) {
        $ddlOffice.append($('<option>', {
            value: office.OFFICE_ID,
            text: office.OFFICE_NAME
        }));
    });

    // Set the selected index to 0 (default option)
    $ddlOffice.prop('selectedIndex', 0);

    // Trigger the chosen update for Office dropdown
    $ddlOffice.trigger('chosen:updated');

    //============
    $('#INSERT_REQUEST_DEGREE_EQUATIONModal').find('input:text, select').val('').trigger('chosen:updated');

    // Optionally, if you are using other plugins or components, reset their states here

    // Show the modal
    $('#INSERT_REQUEST_DEGREE_EQUATIONModal').modal('show').on('hidden.bs.modal', function () {
        // Perform any clean-up if necessary when the modal is hidden
        // Reset dropdowns or other inputs here if needed
        populateDropdown($('#ddlP_COUNTRY_ID_equation'), countries, 'اختر من القائمه');
        populateDropdown($('#ddlP_UNIVERSITY_ID_equation'), universities, 'اختر من القائمه');
        populateDropdown($('#ddlP_OFFICE_ID_equation'), offices, 'اختر من القائمه');
    });
    //if ($.fn.chosen) {
    //    $ddlCountry.chosen('destroy'); // Destroy previous instance if any
    //    $ddlCountry.chosen({
    //        // Custom Chosen Options if required
    //        'width': '100%', // adjust as needed
    //        'no_results_text': 'لا توجد نتائج' // Example
    //    });

    //    $ddlUniversity.chosen('destroy'); // Destroy previous instance if any
    //    $ddlUniversity.chosen({
    //        // Custom Chosen Options if required
    //        'width': '100%', // adjust as needed
    //        'no_results_text': 'لا توجد نتائج' // Example
    //    });

    //    $ddlOffice.chosen('destroy'); // Destroy previous instance if any
    //    $ddlOffice.chosen({
    //        // Custom Chosen Options if required
    //        'width': '100%', // adjust as needed
    //        'no_results_text': 'لا توجد نتائج' // Example
    //    });
    //}
/*    $('#INSERT_REQUEST_DEGREE_EQUATIONModal').modal('hide');*/

    // Reset input fields (optional, since they'll be reset when hidden)
    //$('#ddlP_OFFICE_ID').val('').trigger('chosen:updated');
    //$('#ddlP_UNIVERSITY_ID').val('').trigger('chosen:updated');
    //$('#ddlP_COUNTRY_ID').val('').trigger('chosen:updated');
    //$('#INSERT_REQUEST_DEGREE_EQUATIONModal').modal('show');
    return false; 
}
and i close it using 
         $('#INSERT_REQUEST_DEGREE_EQUATIONModal').modal('hide');

Why do I get value: 1 trying to control generator with parameter?

Here is a code:

function* counter() {
  let counter = 0;
  while (true) {
    counter++;
    const restart = yield counter;
    if (restart === true) {
      counter = 0;
    }
  }
}

const counter1 = counter();
console.log(counter1.next()); //{value: 1, done: false}
console.log(counter1.next()); //{value: 2, done: false}
console.log(counter1.next()); //{value: 3, done: false}
console.log(counter1.next(true)); //{value: 1, done: false}
console.log(counter1.next()); //{value: 2, done: false}
.as-console-wrapper { max-height: 100% !important; }

Logically, the value should be 0 when the ‘true’ parameter is passed, isn’t it? As a counter increment and then it gets reset.

Trying to ask chatGPT it tells me that value is supposed to be 3 or 4 which is incorrect for sure. I can’t get the truth from it.

How can I get rid of the initial delay when I hold down WASD?

So my code most probably isn’t the most optimal way to do this, but if it ain’t broke don’t fix it, right? Anyway, whenever I hold down any of the WASD keys it has a second or so of initial delay before moving the character (currently rectangle) So, how could I fix this?

Here’s my code:

const p1 = document.getElementById("p1");
const p1Height = p1.offsetHeight;
const p1Width = p1.offsetWidth;
const p2 = document.getElementById("p2");
const speed = 20;

if (!p1.style.top) {
  p1.style.top = `${window.innerHeight * 0.4}px`;
}

if (!p1.style.left) {
  p1.style.left = `${window.innerWidth * 0.005}px`;
}

let targetX = parseInt(p1.style.left, 10);
let targetY = parseInt(p1.style.top, 10);
let currentX = targetX;
let currentY = targetY;

let isMoving = false;

document.addEventListener("keypress", function(event) {
  switch (event.key) {
    case 'w':
      if (parseInt(p1.style.top) > 0) {
        targetY -= speed;
      } else {
        p1.style.top = "0px";
      }
      break;
    case 'a':
      if (parseInt(p1.style.left) > 0) {
        targetX -= speed;
      } else {
        p1.style.left = "0px";
      }
      break;
    case 's':
      if (parseInt(p1.style.top) + p1Height < window.innerHeight) {
        targetY += speed;
      } else {
        p1.style.top = `${window.innerHeight - p1Height}px`;
      }
      break;
    case 'd':
      if (parseInt(p1.style.left) + p1Width < window.innerWidth) {
        targetX += speed;
      } else {
        p1.style.left = `${window.innerWidth - p1Width}px`;
      }
      break;
  }

  if (!isMoving) {
    isMoving = true;
    requestAnimationFrame(move);
  }
})

function move() {
  const dx = targetX - currentX;
  const dy = targetY - currentY;

  const moveX = dx * 0.1;
  const moveY = dy * 0.1;

  currentX += moveX;
  currentY += moveY;

  p1.style.left = `${currentX}px`;
  p1.style.top = `${currentY}px`;

  if (Math.abs(dx) > 1 || Math.abs(dy) > 1) {
    requestAnimationFrame(move);
  } else {
    isMoving = false;
  }
}

requestAnimationFrame(move);
@font-face {
  font-family: 'Komikaze', monospace;
  src: url('path-to-your-font/Komikaze.ttf') format('truetype');
}

body {
  background-color: azure;
  overflow: hidden;
}

#p1 {
  position: absolute;
  background-color: red;
  height: 10vh;
  width: 5vh;
  top: 45%;
}

#p2 {
  position: absolute;
  background-color: dodgerblue;
  height: 10vh;
  width: 5vh;
  top: 45%;
  left: 97.2%;
}
<div id="p1"></div>
<div id="p2"></div>

It’s probably way simpler than my brain is trying to make it, but thanks for taking a look!

Shepherd.js: Add Padding Between Tour Step and Screen Edge Without Shifting Arrow?

Current Behavior

I am using shepherdjs to build an app tour. Shepherdjs in turn uses floating-ui under the hood.

My problem is that the tour step is positioned too close to the screen edge, making it look unpolished.

Example (Current Behavior):

Image

    {
      attachTo: {
        element: '#top-menu-account-settings-menu-icon',
        on: 'left',
      },
      buttons: [
        {
          action: addLocationTour.next,
          text: 'Next',
        },
      ],
      floatingUIOptions: {
        middleware: [
          offset(12), // Offset from the highlighted element
        ],
      },
      modalOverlayOpeningRadius: 5,
      text: 'This step is attached to the bottom of the <code>.example-css-selector</code> element.',
    },

Attempted Fix

I tried adding shift({ padding: 16 }) to floatingUIOptions. This successfully prevented the step from touching the screen edge but also misaligned the arrow, shifting it downward and away from the icon center.

Example (Misaligned Arrow Issue):

Image

    {
      attachTo: {
        element: '#top-menu-account-settings-menu-icon',
        on: 'left',
      },
      buttons: [
        {
          action: addLocationTour.next,
          text: 'Next',
        },
      ],
      floatingUIOptions: {
        middleware: [
          offset(12), // Offset from the highlighted element
          shift({ padding: 16 }), // Prevents tour from touching screen edges but shifts the arrow
        ],
      },
      modalOverlayOpeningRadius: 5,
      text: 'This step is attached to the bottom of the <code>.example-css-selector</code> element.',
    },

Question

How can I prevent the step from touching the screen edge without affecting the arrow alignment?

How to play the audio automatically at the start of the page in React/Vite?

I am trying to play the audio automatically at the start of the page without the user interaction(click, tap, keypress..). But I am getting this error when I try to play the audio without it.
I know that this error happens because browsers block audio playback unless there has been user interaction with the page.
Is there any way to play the audio automatically at the start of the page without the user interaction? The website is built with React/Vite.

NotAllowedError: play() failed because the user didn’t interact with the document first.

Adding an image blog to the file form element

I am using the Heic2Any javascript library to convert .heic files into JPG like this:

$('#image-input').on('change', function(ev) {
    var blob = ev.target.files[0];
    heic2any({
        blob: blob,
        toType: "image/jpeg",
    })
    .then(function (resultBlob) {
        
    })
    .catch(function (x) {
        var error = "Error code: " + x.code + " " + x.message;
        console.log(error);
    });
});

But how do I insert the new jpg image into the input form element or otherwise make it available so I can upload it to a PHP script and access it in $_FILES?

Using Nextjs (latest version) and MUI (latest version) and getting Uncaught Error: Cannot read properties of undefined (reading ‘appBar’)

I am trying to figure out the issue as to why I am getting the undefined error below.

Uncaught Error: Cannot read properties of undefined (reading ‘appBar’)

I’m doing a simple setup for testing purposes and running into this error has put a halt on progress.

Here is the code snippets below.

Layout.tsx

import type { Metadata } from "next";
import { Roboto } from "next/font/google";
import "./globals.css";
import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
import { ThemeProvider } from "@mui/material";
import {themeOptions} from '../theme/theme';
import NavAppBar from "@/components/header/header";

const roboto = Roboto({
  variable: "--font-roboto",
  subsets: ["latin"],
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({children,}: Readonly<{
  children: React.ReactNode;
}>) {


  return (
    <html lang="en">
      <body className={`${roboto.className}`}>
        <AppRouterCacheProvider>
          <ThemeProvider theme={themeOptions}>
            <NavAppBar />
            {/* <CssBaseline /> */}
            {children}
          </ThemeProvider>
        </AppRouterCacheProvider>
      </body>
    </html>
  );
}

header.tsx file

"use client";
import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Menu from '@mui/material/Menu';
import MenuIcon from '@mui/icons-material/Menu';
import Container from '@mui/material/Container';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import Tooltip from '@mui/material/Tooltip';
import MenuItem from '@mui/material/MenuItem';
import AdbIcon from '@mui/icons-material/Adb';

const pages = ['Products', 'Pricing', 'Blog'];
const settings = ['Profile', 'Account', 'Dashboard', 'Logout'];

export default function NavAppBar() {
  const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(null);
  const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(null);

  const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorElNav(event.currentTarget);
  };
  const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorElUser(event.currentTarget);
  };

  const handleCloseNavMenu = () => {
    setAnchorElNav(null);
  };

  const handleCloseUserMenu = () => {
    setAnchorElUser(null);
  };

  return (
    <AppBar position='static' sx={{ bgcolor: 'primary.main' }}>
      <Container maxWidth="xl">
        <Toolbar disableGutters>
          <AdbIcon sx={{ display: { xs: 'none', md: 'flex' }, mr: 1 }} />
          <Typography
            variant="h6"
            noWrap
            component="a"
            href="#app-bar-with-responsive-menu"
            sx={{
              mr: 2,
              display: { xs: 'none', md: 'flex' },
              fontFamily: 'monospace',
              fontWeight: 700,
              letterSpacing: '.3rem',
              color: 'inherit',
              textDecoration: 'none',
            }}
          >
            LOGO
          </Typography>

          <Box sx={{ flexGrow: 1, display: { xs: 'flex', md: 'none' } }}>
            <IconButton
              size="large"
              aria-label="account of current user"
              aria-controls="menu-appbar"
              aria-haspopup="true"
              onClick={handleOpenNavMenu}
              color="inherit"
            >
              <MenuIcon />
            </IconButton>
            <Menu
              id="menu-appbar"
              anchorEl={anchorElNav}
              anchorOrigin={{
                vertical: 'bottom',
                horizontal: 'left',
              }}
              keepMounted
              transformOrigin={{
                vertical: 'top',
                horizontal: 'left',
              }}
              open={Boolean(anchorElNav)}
              onClose={handleCloseNavMenu}
              sx={{ display: { xs: 'block', md: 'none' } }}
            >
              {pages.map((page) => (
                <MenuItem key={page} onClick={handleCloseNavMenu}>
                  <Typography sx={{ textAlign: 'center' }}>{page}</Typography>
                </MenuItem>
              ))}
            </Menu>
          </Box>
          <AdbIcon sx={{ display: { xs: 'flex', md: 'none' }, mr: 1 }} />
          <Typography
            variant="h5"
            noWrap
            component="a"
            href="#app-bar-with-responsive-menu"
            sx={{
              mr: 2,
              display: { xs: 'flex', md: 'none' },
              flexGrow: 1,
              fontFamily: 'monospace',
              fontWeight: 700,
              letterSpacing: '.3rem',
              color: 'inherit',
              textDecoration: 'none',
            }}
          >
            LOGO
          </Typography>
          <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}>
            {pages.map((page) => (
              <Button
                key={page}
                onClick={handleCloseNavMenu}
                sx={{ my: 2, color: 'white', display: 'block' }}
              >
                {page}
              </Button>
            ))}
          </Box>
          <Box sx={{ flexGrow: 0 }}>
            <Tooltip title="Open settings">
              <IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
                <Avatar alt="Remy Sharp" src="/static/images/avatar/2.jpg" />
              </IconButton>
            </Tooltip>
            <Menu
              sx={{ mt: '45px' }}
              id="menu-appbar"
              anchorEl={anchorElUser}
              anchorOrigin={{
                vertical: 'top',
                horizontal: 'right',
              }}
              keepMounted
              transformOrigin={{
                vertical: 'top',
                horizontal: 'right',
              }}
              open={Boolean(anchorElUser)}
              onClose={handleCloseUserMenu}
            >
              {settings.map((setting) => (
                <MenuItem key={setting} onClick={handleCloseUserMenu}>
                  <Typography sx={{ textAlign: 'center' }}>{setting}</Typography>
                </MenuItem>
              ))}
            </Menu>
          </Box>
        </Toolbar>
      </Container>
    </AppBar>
  );
}

Simply put I am trying to see the ends and outs of using MUI with Nextjs.