html2Canvas image pasting either blurry or extra large

I am working on a email signature creation website for my company. I have the background image of the email signature on the website, and am using the canvas to write the text over the image. The image I am using is 3x the size of what is displaying on the website. This is so when I scale it down to the correct size it is still high quality on the webpage.

The issue I’m running into is when I copy the canvas using html2canvas at scale: 1 it is way lower quality than the original canvas on the webpage when pasting into the email client.

I have tried using scale: 2 or scale: 3, but that makes the email signature 2x or 3x larger when pasting into my email client. I have also tried rendering the canvas at 2x or 3x then scaling it down to 1x when copying it, but it becomes a pixelated mess when I do that. I am new to this so I have been using a lot of outside resource because I don’t fully understand it all yet.

Code 1 – What I am using for image 1:

function copySignature() {
    const signatureElement = document.getElementById('signature-image-wrapper');
    
    html2canvas(signatureElement, { scale: 1 }).then(canvas => {
        canvas.toBlob(blob => {
            const item = new ClipboardItem({ "image/png": blob });
            navigator.clipboard.write([item]).then(() => {
                alert("Signature image copied to clipboard!");
            }, err => {
                alert("Failed to copy image to clipboard.");
                console.error(err);
            });
        });
    });
}

Code 2 – What I am using for image 3:

function copySignature() {
    const signatureElement = document.getElementById('signature-image-wrapper');
    
    html2canvas(signatureElement, { scale: 3 }).then(canvas => {
        // Resize to 450px wide, keeping aspect ratio
        const targetWidth = 450;
        const scaleFactor = targetWidth / canvas.width;
        const targetHeight = canvas.height * scaleFactor;

        const resizedCanvas = document.createElement('canvas');
        resizedCanvas.width = targetWidth;
        resizedCanvas.height = targetHeight;

        const ctx = resizedCanvas.getContext('2d');
        ctx.drawImage(canvas, 0, 0, targetWidth, targetHeight);

        resizedCanvas.toBlob(blob => {
            const item = new ClipboardItem({ "image/png": blob });
            navigator.clipboard.write([item]).then(() => {
                alert("Signature image copied to clipboard!");
            }, err => {
                alert("Failed to copy image to clipboard.");
                console.error(err);
            });
        });
    });
}

Image 1 – Canvas on the website:
enter image description here

Image 2 – All the Scales in email client:
enter image description here

Image 3 – Render the image at scale 3 but paste at smaller size:
enter image description here

How to fix the file upload bug?

I have a problem with the project, the thing is that when I click on the website to download the page, the browser tells me about the error “Check Internet connection”, after reloading the page and clicking on the button the file is downloaded

The project is written: React
OS: Centos 7
web server: Apache v2.4.62

The button is implemented as follows:

<button
  type="button"
  className="cb-btn btn-wide keep-lowercase"
  onClick={() => {
    const link = document.createElement('a');
    link.href = '/2025/pz/pzlink.zip'; 
    link.download = 'pzlink.zip'; 
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }}
>
  64 bit
</button>

Apache virtualhost config:

<VirtualHost *:443>
ServerName 10.10.10.10
ServerAlias pz-test.com
Redirect permanent /general https://pz-test.com/


RewriteEngine on

DocumentRoot /var/html/
<Directory /var/html/>
        Order allow,deny
        Allow from all
        Options FollowSymLinks
        Allowoverride All
        Require all granted
</Directory>
<Directory "/var/html/2025/pz/">
       Options Indexes FollowSymlinks
</Directory>
<Location "/server-status">
       SetHandler server-status
       Order deny,allow
       Require ip 10.10.10.251
</Location>



#Connecting SSL certificate
SSLEngine on
SSLCertificateFile /etc/ssl/certs/pz-selfsigned.crt
SSLCertificateKeyFile /etc/ssl/private/pz-selfsigned.key

#list of allowed ciphers
SSLCipherSuite "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!CAMELLIA"
#enabling TLSv1.2 and above
SSLProtocol -all +SSLv3 +TLSv1 +TLSv1.1 +TLSv1.2

SSLHonorCipherOrder on
SSLCompression off

#Strict Transport Security (HSTS)
Header always set Strict-Transport-Security max-age=31536000";includeSubDomains;upgrade-insecure-requests
Header always set X-XSS-Protection "1; mode=block"
Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://pz-test.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';"
Header edit Set-Cookie ^(.*)* $1;HttpOnly;Secure

</VirtualHost>

This is a local site that does not have global access to the network. I am using a self-signed certificate.

Maybe someone has encountered similar behavior?

I have also tried implementing buttons in various ways, including using the tag.

I have also tried implementing buttons in various ways, including using the tag.

Images on the website loads slowly. They load after the pages have been loaded

Please someone should help me on this website, the images load slowly, they load after the page has been loaded finish. The hompage transition images show blank after the page load, and later show the image afte a short blank space. Also the pages on the web show blank at first navigation to each page. I have reduced the sizes of the images to like 300kb and also I have changed the format to webp in order to make them load faster. If I can just make the images load after the pages load or a way to make the images load faster as the pages load.

This is the homepage

import React, { useEffect, useState } from "react";
import { Helmet } from "react-helmet-async";
import Styles from "./Home.module.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faGooglePlay, faApple } from "@fortawesome/free-brands-svg-icons";

const images = ["/carousel1.webp", "/carousel2.webp", "/carousel3.webp"];

const BASE_URL = process.env.REACT_APP_BASE_URL;

function Home() {
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentIndex((prevIndex) =>
        prevIndex === images.length - 1 ? 0 : prevIndex + 1
      );
    }, 7000);

    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    images.forEach((src) => {
      const img = new Image();
      img.src = src;
    });
  }, []);

  return (
    <div className={Styles.home_wrapper}>
      <Helmet>
        <title>PushEat - No Stress, Just Great Food!</title>
        <meta
          name="description"
          content="Order delicious meals fast and easy with PushEat. No stress, just great food!"
        />
        <meta
          name="keywords"
          content="PushEat, food delivery, fast food, order food online"
        />

        {/* Open Graph */}
        <meta
          property="og:title"
          content="PushEat - No Stress, Just Great Food!"
        />
        <meta
          property="og:description"
          content="Order delicious meals fast and easy with PushEat. Fresh meals delivered to your door."
        />
        <meta property="og:image" content={`${BASE_URL}/Logo.png`} />
        <meta property="og:url" content={BASE_URL} />
        <meta property="og:type" content="website" />

        {/* Twitter card */}
        <meta name="twitter:card" content="summary_large_image" />
        <meta
          name="twitter:title"
          content="PushEat - No Stress, Just Great Food!"
        />
        <meta
          name="twitter:description"
          content="Order delicious meals fast and easy with PushEat. Fresh meals delivered to your door."
        />
        <meta name="twitter:image" content={`${BASE_URL}/Logo.png`} />
      </Helmet>
      <section className={Styles.carousel_wrapper}>
        {images.map((src, index) => (
          <img
            key={index}
            src={src}
            loading="eager"
            alt="carousel"
            className={`${Styles.fade_image} ${
              index === currentIndex ? Styles.visible : ""
            }`}
          />
        ))}
        <div className={Styles.dots}>
          {images.map((_, index) => (
            <div
              key={index}
              className={`${Styles.dot} ${
                index === currentIndex ? Styles.activeDot : ""
              }`}
            ></div>
          ))}
        </div>

        <div className={Styles.home_content}>
          <div className={Styles.content}>
            <h1>
              No Stress,
              <br />
              Just Great Food!
            </h1>
            <div className={Styles.buttons}>
              <a href="https://google.com" className={Styles.google}>
                <FontAwesomeIcon
                  icon={faGooglePlay}
                  className={Styles.app_icon}
                />
                Download on Google Play
              </a>
              <a href="https://apple.com" className={Styles.apple}>
                <FontAwesomeIcon icon={faApple} className={Styles.app_icon} />
                Download on App Store
              </a>
            </div>
          </div>
        </div>
      </section>
      {/* <section>
        <div className={Styles.third_section_content}>
          <h1>Ready for the best food deals?</h1>
          <p>
            Scrolling through the exciting list of deals on Pusheat is so <br />
            much fun. Here are 3 steps to get the best food deals.
          </p>
        </div>
      </section> */}
    </div>
  );
}

export default Home;

This is the homepage style

.carousel_wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: black;
}

.fade_image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0;
  transition: opacity 3.5s ease-in-out;
  z-index: 0;
}

.visible {
  opacity: 1;
  z-index: 0;
}

.dots {
  position: absolute;
  bottom: 48px;
  right: 85px;
  display: flex;
  gap: 10px;
}

.dot {
  width: 8px;
  height: 5px;
  border: 2px solid #ccc;
  border-radius: 50%;
  transition: all 3s ease;
}

.activeDot {
  width: 32px;
  height: 3px;
  background-color: #fff;
  border: 2px solid #fff;
  border-radius: 999px;
}

.navbar {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding-top: 20px;
  padding-bottom: 20px;
  z-index: 10;
}

.home_content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1;
  padding-bottom: 60px;
  color: white;
  max-width: 90%;
  margin: auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 100%;
  box-sizing: border-box;
}

.content {
  margin-top: 50px;
  width: 786px;
}

.content h1 {
  text-align: left;
  font-size: 80px;
  line-height: 100.56px;
  letter-spacing: 4%;
  vertical-align: middle;
}


.buttons {
  display: flex;
  gap: 16px;
  margin-top: 20px;
  width: 567px;
}

.buttons a {
  display: inline-block;
  background-color: black;
  color: white;
  padding: 10px 20px;
  border-radius: 8px;
  text-decoration: none;
  font-weight: 600;
  font-size: 18px;
  line-height: 28px;
  text-align: center;
}

.app_icon {
  margin-right: 5px;
}

.buttons a.google {
  background-color: #000;
}

.buttons a.apple {
  background-color: #000;
}

.third_section_content {
  width: 816px;
  height: 179px;
  left: 231.5px;
  gap: 24px;
}

.third_section_content h1 {
  font-weight: 600;
  font-size: 60px;
  line-height: 72px;
}

.third_section_content p {
  font-size: 20px;
  line-height: 30px;
  text-align: center;
}

@media (min-width: 769px) and (max-width: 945px) {
  .content h1 {
  font-size: 60px;
 }
}


@media (max-width: 768px) {
  .navbar {
    padding: 10px 20px;
  }

  .home_content {
    padding-top: 120px;
    padding-bottom: 20px;
    max-width: 90%;
    margin: auto;
    text-align: center;
  }

  .content {
    width: 100%;
    margin-top: 20px;
  }

  .content h1 {
    font-size: 36px;
    line-height: 45px;
    text-align: center;
  }

  .buttons {
    flex-direction: column;
    width: 100%;
    align-items: center;
    gap: 12px;
  }

  .buttons a {
    width: 100%;
    font-size: 16px;
    padding: 12px 0;
  }

  .dots {
    bottom: 24px;
    right: 50%;
    transform: translateX(50%);
    gap: 8px;
  }

  .third_section_content h1 {
    font-size: 32px;
    line-height: 40px;
  }

  .third_section_content p {
    font-size: 16px;
    line-height: 24px;
  }
}

This is image for each page

import React from "react";
import { useState } from "react";
import Styles from "./ContentService.module.css";
import Navbar from "./Navbar";

function ContentService({ title, lastUpdated, titleClass, children }) {
  return (
    <div>
      <section className={Styles.service_wrapper}>
        <div className={Styles.services}>
          <picture>
            <source srcSet="/frame.webp" type="image/webp" />
            <img
              src="/frame.webp"
              alt="services"
              loading="eager"
              width="5760"
              height="1712"
            />
          </picture>
        </div>

        <div className={Styles.navbar}>
          <Navbar />
        </div>
        <div className={Styles.service_content}>
          <div className={Styles.content}>
            <h1
              className={[Styles.last_update, titleClass && Styles[titleClass]]
                .filter(Boolean)
                .join(" ")}
            >
              {title}
            </h1>

            {lastUpdated && (
              <p>
                Last Updated: <span>{lastUpdated}</span>
              </p>
            )}
          </div>
        </div>
      </section>
      {children}
    </div>
  );
}

export default ContentService;

This is the style for the each page image

html, body {
  margin: 0;
  padding: 0;
  overflow-x: hidden; 
}

.service_wrapper {
    position: relative;
    width: 100%;
    overflow: hidden;
    background-color: black;
  }
  
.services {
  position: relative;
  width: 100vw;
  height: auto; /* set a fixed height or based on aspect ratio */
}

.imagePlaceholder {
  width: 100vw;
  height: calc(100vw / 3.36); /* aspect ratio */
  background-image: url('../assets/frame-blur.webp');
  background-size: cover;
  background-position: center;
  background-color: #222; /* fallback color similar to blur */
  filter: blur(10px);
  transition: opacity 0.3s ease;
  position: relative;
  z-index: 1;
}


  .services img {
    width: 100vw;
    height: auto;
    object-fit: cover;
    display: block;
  }
  
  .navbar {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    padding-top:20px;
    padding-bottom:20px;
    z-index: 10;
  }
  
  
  .service_content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 20; /* Increase z-index */
    padding-bottom: 60px;
    color: white;
    max-width: 90%;
    margin: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 100%;
    box-sizing: border-box;
    margin-bottom: 0;
    margin-top: 0;
    align-items: center;
    text-align: center;

  }

  .content {
    margin-top: 160px;
  }
  
  .content .last_update {
    font-weight: 800;
    font-size: 80px;
    line-height: 120%;
    letter-spacing: 4%;
    text-align: center;
    vertical-align: middle;
    margin-top: 0;
    margin-bottom: 0;
  }

  .content p {
    font-size: 18px;
    line-height: 18px;
    letter-spacing: 0%;
    text-align: center;
    margin-top: 0;
  }

  .content span {
    font-style: italic;
    font-weight: 200;
  }

  .smallTitle {
  font-size: 1.4rem; /* or smaller */
  line-height: 1.2;
}

  
  @media (max-width: 1130px) {
    /* .content {
      margin-top: 210px;
    } */

    .content .last_update {
      font-size: 30px;
    }
  
    .content p {
      font-size: 13px;
    }
  }

  @media (min-width: 1001px) and (max-width: 1054px) {

    .content .last_update {
      font-size: 27px;
    }
  
    .content p {
      font-size: 16px;
    }
  }


  @media (max-width: 1048px) {
    .content {
      margin-top: 200px;
    }

    .content .last_update {
      font-size: 27px;
      margin-bottom: 3px;
    }

    .content p {
      font-size: 16px;
      margin-bottom: 13px;
    }
  }


  @media (min-width: 1001px) and (max-width: 1130px) {
 .content .smallTitle,
  .content .last_update {
    font-size: 1.4rem !important;
    line-height: 1.2 !important;
    margin-bottom: 5px !important;
  }
  }

  @media (min-width: 1001px) and (max-width: 1048px) {
 .content .smallTitle,
  .content .last_update {
    font-size: 2rem !important;
     line-height: 1.3 !important;
  }
   .content {
      margin-top: 150px;
    }
  }

  @media (min-width: 1049px) and (max-width: 1130px) {
 .content .smallTitle,
  .content .last_update {
    font-size: 2.5rem !important;
    line-height: 1.2 !important;
  }
  }


   @media (min-width: 1131px) and (max-width: 1378px) {
 .content .smallTitle,
  .content .last_update {
    font-size: 3.3rem !important;
    line-height: 1.2 !important;
  }
  }


  @media (max-width: 1000px) {
    .services img {
      width: 100vw;
      height: 500px;
      object-fit: cover;
      display: block;
    }

    .content .last_update {
      font-size: 50px;
      margin-bottom: 10px;
    }
  
    .content p {
      font-size: 16px;
    }
  }



  @media (max-width: 768px) {
    .content .last_update {
      font-size: 60px;
    }

    .content {
      margin-top: 100px;
    }
    .last_update {
      display: block;
      white-space: pre-line;
      line-height: 1.2;
    }
  
    .content p {
      font-size: 14px;
      margin-top: 20px;;
    }
  }
  
  @media (max-width: 480px) {
    /* .content .last_update {
      font-size: 30px;
    } */
  
    .content p {
      font-size: 12px;
    }
  }

This is the index.js

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />

    <link rel="preload" as="image" href="/Logo.png" />
    <link rel="preload" as="image" href="/frame.png" type="image/png">


    <meta
      name="description"
      content="PushEat - Order your favorite meals fast and easily. Reliable. Delicious. Simple."
    />
    <title>PushEat</title>


    <link rel="icon" type="image/png" href="%PUBLIC_URL%/favicon.png" />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />


   
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />


    <meta property="og:type" content="website" />
    <meta property="og:url" content="https://pusheat1.netlify.app/" />
    <meta property="og:title" content="PushEat - Get Food Deals Near You" />
    <meta
      property="og:description"
      content="PushEat lets you order your favorite meals easily and reliably. Fresh, fast, and always delicious."
    />
    <meta name="twitter:image" content="/Logo.png" />


   
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:url" content="https://pusheat1.netlify.app/" />
    <meta name="twitter:title" content="PushEat - Get Food Deals Near You" />
    <meta
      name="twitter:description"
      content="Order meals seamlessly with PushEat. Reliable. Delicious. Simple."
    />
    <meta name="twitter:image" content="/Logo.png" />

  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

Why are my touch events in an iframe preventing the webpage from scolling? [iOS]

I have a iFrame on a webpage and it contains a div element, which I will call the gestureZone, which has some touch events listeners, just like this: Webpage Layout

The iFrame itself is never scrollable, it always resizes to the content it contains but the webpage it sits on is vertically scrollable. There are touchstart, touchmove and touchend event listeners on the gestureZone that allow the image in the gesture zone to move left and right freely.

My issue is that I still want the webpage to scroll vertically at the same time. This works perfectly on android across all browsers but doesn’t work at all on iOS.

gestureZone.addEventListener("touchmove", function(e) {
    let myDiff = e.changedTouches[0].screenX - gestureStartX;
    let s=1;
    if(myDiff<0){
        s=-1
    }
    this.style.left = s*Math.min(200, Math.abs(myDiff)) + "px";
    this.style.rotate = s*Math.min(8, Math.abs(myDiff)/25)+ "deg";

}, { capture: false, passive: true });

Has anyone had a similar issue?

How to use Vite in Laravel to compile and bundle existing CSS/JS assets located in the public folder (Metronic Admin Panel)?

I’m working on a Laravel project where I’m using the Metronic Admin Panel. All my CSS and JavaScript files are currently stored inside the public directory:

CSS: public/cms/assets/css/ —
JS: public/cms/assets/js/

In my main layout Blade file, I include these assets in the traditional way like this:

<head>
    ....
    ....
    <link href="{{ asset('cms/assets/plugins/global/plugins.bundle.css') }}" rel="stylesheet" type="text/css" />
    <link href="{{ asset('cms/assets/css/style.bundle.css') }}" rel="stylesheet" type="text/css" />
    ....
    ....
</head>
<body>
    ....
    ....
    <script src="{{ asset('cms/assets/js/common/js/kh_general.js') }}"></script>
    <script src="{{ asset('cms/assets/js/axios.min.js') }}"></script>
    ....
    ....
<body>

Now I want to switch to using Vite to optimize and bundle these assets

now this is my vite.config.js:

import { defineConfig } from 'vite';
import laravel, { refreshPaths } from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
            ],
            refresh: [
                ...refreshPaths,
                'app/Http/Livewire/**',
            ],
        }),
    ],
});

My Questions:

How do I migrate the CSS and JS files from public/cms/assets/ to resources/ so Vite can compile them?

Should I copy everything manually? What about dependencies and third-party libraries that come with Metronic?

How do I include Metronic’s assets in resources/js/app.js or resources/css/app.css properly for Vite to build them?

How do I modify my Blade layout to use Vite’s @vite() directive instead of the old asset() helper?

Is there a way to use @vite([‘cms/assets/css/style.bundle.css’]) if I keep the structure?

React Native: TurboModule method “installTurboModule” called with 1 argument (expected 0) — Hermes JS Engine Error

I’m encountering an error in my React Native app when using the Hermes engine:

ERROR Error: Exception in HostFunction: TurboModule method "installTurboModule" called with 1 arguments (expected argument count: 0)., js engine: hermes

This happens on a specific screen that is using reanimate. I’m not explicitly calling installTurboModule anywhere in my code, so I suspect it’s related to a library or incorrect native integration.

My setup:
React Native version: [0.79.2]

Has anyone else faced this? Could it be related to an incompatible native module or a misconfigured TurboModule? How do I trace what’s triggering this?

Any help would be appreciated!

Things I’ve tried:

  • Clearing Metro bundler cache and reinstalling node_modules
  • Rebuilding the app
  • Searching for installTurboModule in my codebase and dependencies

select2 Laravel – Always Showing JSON

I’ve been playing with this setup for a while now but I can’t get the results to return to the select box. always showing JSON

Result

public function autocomplete(Request $request)
    {
       $data = Pegawai::where('nama', 'LIKE', '%'.request('q').'%')->paginate(10);

        return response()->json($data);
    }
<script>
    $(document).ready(function(){

    $("#pegawais").select2({
        placeholder:'Pilih Provinsi',
        ajax: {
            url: "{{route('autocomplete')}}",
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.nama,
                            id: item.id
                        }
                    })
                };
            },
            cache: true

        }
    });
});
</script>



<div class='mb-2'>
    <label> Regencies</label>
    <select id="pegawais" class="form-select" aria-label="Default select example">

    </select>
</div>

How to find a current index of array in js

I need to find a current audio index that is played when I click on it. I tried using findIndex(), but it displays an error: ‘GET http://127.0.0.1:5500/undefined 404 (Not Found)’ and ‘index.html:1 Uncaught (in promise) NotSupportedError: Failed to load because no supported source was found’.

const allSongs = [                 //Array of objects
    {
    id: 0,
    title: "Scratching The Surface",
    artist: "Quincy Larson",
    duration: "4:25",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/scratching-the-surface.mp3",
  },
  {
    id: 1,
    title: "Can't Stay Down",
    artist: "Quincy Larson",
    duration: "4:15",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/can't-stay-down.mp3",
  },
  {
    id: 2,
    title: "Still Learning",
    artist: "Quincy Larson",
    duration: "3:51",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/still-learning.mp3",
  },
  {
    id: 3,
    title: "Cruising for a Musing",
    artist: "Quincy Larson",
    duration: "3:34",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/cruising-for-a-musing.mp3",
  },
  {
    id: 4,
    title: "Never Not Favored",
    artist: "Quincy Larson",
    duration: "3:35",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/never-not-favored.mp3",
  },
  {
    id: 5,
    title: "From the Ground Up",
    artist: "Quincy Larson",
    duration: "3:12",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/from-the-ground-up.mp3",
  },
  {
    id: 6,
    title: "Walking on Air",
    artist: "Quincy Larson",
    duration: "3:25",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/walking-on-air.mp3",
  },
  {
    id: 7,
    title: "Can't Stop Me. Can't Even Slow Me Down.",
    artist: "Quincy Larson",
    duration: "3:52",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/cant-stop-me-cant-even-slow-me-down.mp3",
  },
  {
    id: 8,
    title: "The Surest Way Out is Through",
    artist: "Quincy Larson",
    duration: "3:10",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/the-surest-way-out-is-through.mp3",
  },
  {
    id: 9,
    title: "Chasing That Feeling",
    artist: "Quincy Larson",
    duration: "2:43",
    src: "https://cdn.freecodecamp.org/curriculum/js-music-player/chasing-that-feeling.mp3",
  },
];

const songs = allSongs.sort((a, b) => a.title.localeCompare(b.title));  //Sorted array
const audio = new Audio();


const renderSongs = () => {               //Render songs

  songs.forEach(data => {
playlist.innerHTML +=`
<li class="flex flex-row items-center gap-2 border-b border-b-yellow-600 border-b-2 border-dashed px-3 py-4">
<div id="playlistBtn${playlist.children.length}" onclick="playSongs(this)" class="flex flex-row items-center gap-3 cursor-pointer">
<div class="flex-1 flex-wrap">${data.title}</div>
<div class="text-[13px] flex-none mr-2">${data.artist}</div>
<div>${data.duration}</div>
</div>
<button id="removeBtn${playlist.children.length}">
    <svg width="30" height="25" fill="white" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512">
</button>
</li>
`;
  });

}
renderSongs();


const playSongs = () => {              
  const index = songs.findIndex(ind => ind === songs.id); //the problem
  audio.src = songs[index];
  audio.play();
}

Taking row by row data from Excel and putting it in a payload

I’m currently working on a project where I read an excel file with row by row monthly data here is the current code

const handleFileUpload = async (e) => {


        // converting excel date value 
        const excelEpoch = 25568; 
        const millisecondsInDay = 86400000;
        const jsTime = (jsonData[7][6] - excelEpoch) * millisecondsInDay;
        const date = new Date(jsTime);


        const file = e.target.files[0];
        setFileName(file.name);

        const data = await file.arrayBuffer();
        const workbook = XLSX.read(data);

        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        console.log(worksheet);
        const jsonData = XLSX.utils.sheet_to_json(worksheet, {
            header: 1,
            defval: "",
        });

        let waterExcel = []
        let elecExcel = []
        let gasExcel = []

        console.log(jsonData);

        const waterUnits = jsonData[6][2].toLowerCase();
        const gasUnits = jsonData[6][9].toLowerCase();
        const elecUnits = jsonData[6][14].toLowerCase();
        const demandUnits = jsonData[6][16].toLowerCase();
        
        for (var i = 7; i < jsonData.length; i++){

            let waterCost;
            if (jsonData[i][3] != ""){waterCost=jsonData[i][3]}else{waterCost=0}
            let wasteWater;
            if (jsonData[i][4] != ""){wasteWater=jsonData[i][4]}else{wasteWater=0}
            let wasteWaterCost;
            if (jsonData[i][5] != ""){wasteWaterCost=jsonData[i][3]}else{wasteWaterCost=0}
            
            //water payload 
            if (jsonData[i][1] != "" && jsonData[i][2] != "") {
                
                const payload = {
                    site_id: site_id,
                    units: waterUnits,
                    total_water: parseFloat(jsonData[i][2]),
                    water_cost: parseFloat(waterCost),
                    total_wastewater: parseFloat(wasteWater),
                    wastewater_cost: parseFloat(wasteWaterCost),
                    total_bill_cost: parseFloat(jsonData[i][1]),
                    //month: parseInt(month),
                    //year: parseInt(year),
                    // start_date: "2025-04-01",
                    // end_date: "2025-05-02",
                };
                waterExcel.push(payload)
            }

            //gas payload
            let gasCost;
            if (jsonData[i][10] != ""){gasCost=jsonData[i][10]}else{gasCost=0}

            if (jsonData[i][8] != "" && jsonData[i][9] != "") {
                const payload = {
                    site_id: site_id,
                    gas_units:gasUnits,
                    total_gas: parseFloat(jsonData[i][9]),
                    gas_cost: parseFloat(gasCost),
                    total_bill_cost: parseFloat(jsonData[i][8]),
                    // month: parseInt(month),
                    // year: parseInt(year),
                    // start_date: "2024-04-01",
                    // end_date: "2024-05-02",
                };

                gasExcel.push(payload)
            }

            // electricity payload

            let elecCost;
            if (jsonData[i][15] != ""){elecCost=jsonData[i][15]}else{elecCost=0}
            let demandCost;
            if (jsonData[i][17] != ""){demandCost=jsonData[i][17]}else{demandCost=0}
            let globalAdjust;
            if (jsonData[i][18] != ""){globalAdjust=jsonData[i][18]}else{globalAdjust=0}


            if (jsonData[i][13] != "" && jsonData[i][14] != "" && jsonData[i][16] != "") {
                
                const payload = {
                    site_id: site_id,
                    electricity_units: elecUnits,
                    total_electricity: parseFloat(jsonData[i][14]),
                    electricity_cost: parseFloat(elecCost),
                    demand_units: demandUnits,
                    total_demand: parseFloat(jsonData[i][16]),
                    demand_cost: parseFloat(demandCost),
                    total_bill_cost: parseFloat(jsonData[i][13]),
                    global_adjustment: parseFloat(globalAdjust),
                    // month: parseInt(month),
                    // year: parseInt(year),
                    // start_date: "2024-04-01",
                    // end_date: "2024-05-02",
                };
                elecExcel.push(payload)
            }
             
        }

        console.log("water payloads")
        console.log(waterExcel);
        console.log("gas payloads")
        console.log(gasExcel);
        console.log("electricity payloads")
        console.log(elecExcel);
    }

and the output comes out as expect with 3 different payloads. However I’m trying to restructure the payload so that it is more similar to this

enter image description here

where month-year “mar-2024” is the first column of the excel sheet. Im not sure how to accomplish this, any help would be appreciated. Here is an example of the excel spreadsheet enter image description here

What is the most concise way to provide and consume context values?

I am looking for the most concise way, in React, to provide context to a component (say a “page”) and all its subcomponents. For now, the most concise way I have found includes 6 files (!), plus one file per subcomponent that needs the context.

Important notice: I am separating a lot of stuff instead of putting everything in the same file because I want to avoid the following warning:

Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components.

Here is my MWE in the case where our main component FooPage has 2 subcomponents FooButton and FooText, so, in this case, we have 8 files in total:

File #1: define the type of the context value.

// types.ts

// define the type of the value provided by the context,
// it depends on which stuff we want to provide to the subcomponents
export type FooContextType = {
  foo: number;
  setFoo: React.Dispatch<React.SetStateAction<number>>;
};

File #2: the actual outer component that we will use in our web page.

// FooPageWrapper.tsx
// This component is the one we actually use, it wraps
// the FooPage inside the context provider.
import FooProvider from "./context/FooProvider";
import FooPage from "./FooPage";

export default function FooPageWrapper() {
  return (
    <FooProvider>
      <FooPage />
    </FooProvider>
  );
}

File #3: the actual content (which needs to be wrapped in the context provider).

// FooPage.tsx
// This component is the one with the actual content.
// It must be used inside the context provider FooProvider.
import FooButton from "./components/FooButton";
import FooText from "./components/FooText";

export default function FooPage() {
  return (
    <div>
      <h1>Foo Page</h1>
      <FooButton />
      <FooText />
    </div>
  );
}

File #4: the definition of the context itself.

// context/FooContext.tsx
// defines the context.
import { createContext } from "react";

import { FooContextType } from "../types";

export const FooContext = createContext<FooContextType | undefined>(undefined);

File #5: the context provider, in which we will put all our logic (this is the most important one).

// context/FooProvider.tsx
// This is the actual context provider component.
// Here we provide the context value using useState,
// but we could provide a more complex value if needed,
// using useReducer or other state management solutions.
import { useState } from "react";

import { FooContext } from "./FooContext";
export default function FooProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [foo, setFoo] = useState(0);
  return (
    <FooContext.Provider value={{ foo, setFoo }}>
      {children}
    </FooContext.Provider>
  );
}

File #6: a custom hook to easily access the context value in our subcomponents.

// context/useFoo.tsx
// Custom hook to use the context FooContext
// when we are in a component that is wrapped by the FooProvider.
import { useContext } from "react";

import { FooContext } from "./FooContext";
export default function useFoo() {
  const c = useContext(FooContext);
  if (c === undefined) {
    throw new Error("FooContext is undefined");
  }
  return c;
}

File #7: a first subcomponent that uses the context.

// components/FooButton.tsx
// Example of a component that uses the context FooContext
// (via the custom hook useFoo).
import useFoo from "../context/useFoo";

export default function FooButton() {
  const { foo, setFoo } = useFoo();
  return (
    <button onClick={() => setFoo(foo + 1)}>
      Foo is {foo}, click to increment it!
    </button>
  );
}

File #8: a second subcomponent that uses the context.

// components/FooText.tsx
// Example of a component that uses the context FooContext
// (via the custom hook useFoo).
import useFoo from "../context/useFoo";
export default function FooText() {
  const { foo } = useFoo();
  return (
    <span>
      Foo is {foo}, this is a text component that uses the Foo context!
    </span>
  );
}

The example works as expected: we obtain a page with a button and a text, which both can read and write the value of foo in the context. However, this is very verbose.

Is there any way to make it more concise?

Why do jest tests fail with a stacktrace pointing to very first character of the test declaration?

I have a collection of Jest tests that run in CI. They normally pass, and when they fail, jest normally shows the error location and stack trace and failures are easy to fix.

However, occasionally, seemingly random tests fail with a mysterious stacktrace that gives no indication what the actual issue is. Instead, Jest just points to the actual test declaration function and gives no other helpful info.

What sort of failure does this indicate in Jest? I’m struggling to understand the class of issue that this indicates.

Example failure:

 FAIL  __test__/server/api/v1/externalApi.test.ts (338.997 s, 790 MB heap size)
  ● external API v1 › with base project › Should be able to get all runs for a project



      372 |     });
      373 |
    > 374 |     it("Should be able to get all runs for a project", async () => {
          |     ^
      375 |       //simulate the project being published
      376 |       await hexVersionRepo.update(hexVersion.id, {
      377 |         published: true,

      at it (__test__/server/api/v1/externalApi.test.ts:374:5)
      at describe (__test__/server/api/v1/externalApi.test.ts:125:3)
      at Object.describe (__test__/server/api/v1/externalApi.test.ts:63:1)

And then a separate log of the stacktrace shows the following:

Error: 
    at it (/home/circleci/project/packages/integration-tests/__test__/server/api/v1/externalApi.test.ts:374:5)
    at _dispatchDescribe (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/jestAdapterInit.js:596:26)
    at describe (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/jestAdapterInit.js:564:44)
    at describe (/home/circleci/project/packages/integration-tests/__test__/server/api/v1/externalApi.test.ts:125:3)
    at _dispatchDescribe (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/jestAdapterInit.js:596:26)
    at describe (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/jestAdapterInit.js:564:44)
    at Object.describe (/home/circleci/project/packages/integration-tests/__test__/server/api/v1/externalApi.test.ts:63:1)
    at Runtime._execModule (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:1247:24)
    at Runtime._loadModule (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:909:12)
    at Runtime.requireModule (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:812:12)
    at jestAdapter (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/runner.js:92:13)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at runTestInternal (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runner/build/testWorker.js:262:16)
    at runTest (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runner/build/testWorker.js:326:7)
    at Object.worker (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runner/build/testWorker.js:480:12)

Find when pattern appear in memory with Frida

I have peace of code that search pattern in memory with Frida

let pattern = "aa bb cc dd ee ff 11 22 33 44 55 66 77 88 99 00"
Process.enumerateRanges('--rw-')  
    .forEach(range => {
        Memory.scan(range.base, range.size, pattern, {
            onMatch(address, size) {
                const mod = Process.findModuleByAddress(address);
                console.log("Found at: " + address + " in module: " + (mod ? mod.name : "unknown"));
            },
            onComplete() { }
        });
    });

How can I edit that code to search every time when that code appear in memory?

I want to know which code insert that pattern to memory?
Maybe read/memory/recv I don’t know

How do I add options to my bootstrap select statement? [closed]

I want to use bootstrap-select, specifically the selectpicker class with data-live-search. But I wanted to dynamically create the select dropdown, which should take an array of options and input those options into the HTML.

This can be done very easily without bootstrap, like this…

HTML:

<select id="options">
  <option>One</option>
</select>

JavaScript:

var select = document.getElementById("options");
select.innerHTML += "<option>Two</option>"

Resulting HTML:

<select id="options">
  <option>One</option>
  <option>Two</option>
</select>

But if you try that code in a snippet like this, it doesn’t work. There is even documentation saying it is very difficult to do.

<head>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta2/css/bootstrap-select.min.css">
</head>

<body>
  <select id="options" class="selectpicker" multiple aria-label="Default select example" data-live-search="true">
    <option value="1">One</option>
  </select>
</body>

<footer>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta2/js/bootstrap-select.min.js"></script>
</footer>